From 6c51e6881747369302c0568c7b29dcba4f5af364 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 04:35:54 +0800 Subject: [PATCH] Separate shared database implementation from crate exports --- README.md | 2 +- crates/db/src/connection.rs | 2 +- crates/db/src/lib.rs | 391 +--------------------------------- crates/db/src/mysql.rs | 2 +- crates/db/src/postgres.rs | 2 +- crates/db/src/sqlite.rs | 2 +- crates/db/src/store.rs | 386 +++++++++++++++++++++++++++++++++ deploy/bedrock-deployment.svg | 2 +- 8 files changed, 398 insertions(+), 391 deletions(-) create mode 100644 crates/db/src/store.rs diff --git a/README.md b/README.md index 259e9f2..2aaed51 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i ## Storage boundaries -`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. +`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share the connection pools and transaction implementation in `store.rs`. Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index 33afeaf..0fa87d0 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -6,9 +6,9 @@ use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeploymen use thiserror::Error; use crate::{ - Error as StorageError, Mutation, Reader, Revision, Snapshot, Store, mysql::{self, MySql}, postgres, sqlite, + store::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store}, }; #[derive(Debug, Error)] diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 887d9a4..b5cb6b1 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -4,393 +4,14 @@ mod connection; pub mod mysql; pub mod postgres; pub mod sqlite; +mod store; -pub use Error as StorageError; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; pub use connection::{ConnectError, Connection, ReadPreference, connect}; pub use mysql::{Lease, MySql}; -use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; - -use serde_json::Value; -use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions}; -use thiserror::Error; - -pub type Revision = i64; -pub type Result = std::result::Result; - -#[derive(Debug, Error)] -pub enum Error { - #[error("invalid {0}")] - Invalid(&'static str), - #[error("the database connection failed")] - Connection, - #[error("SQL operation failed: {0}")] - Sql(#[from] sqlx::Error), - #[error("document encoding failed: {0}")] - Encoding(#[from] serde_json::Error), - #[error("the connection is read-only")] - ReadOnly, - #[error("the deployment is missing or retired")] - MissingDeployment, - #[error("database is at revision {available}, requested revision {requested}")] - Behind { - requested: Revision, - available: Revision, - }, - #[error("the write conflicts with the current revision or lease")] - WriteConflict, - #[error("lease is missing, expired, or belongs to another store")] - LeaseLost, -} - -impl Error { - pub fn retry_on_primary(&self) -> bool { - match self { - Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true, - Self::Sql(error) => match error { - sqlx::Error::Io(_) - | sqlx::Error::Tls(_) - | sqlx::Error::PoolTimedOut - | sqlx::Error::PoolClosed - | sqlx::Error::WorkerCrashed => true, - sqlx::Error::Database(db) => db.code().is_some_and(|code| { - code.starts_with("08") - || matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146") - }), - _ => false, - }, - _ => false, - } - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct Document { - pub revision: Revision, - pub value: Value, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct Snapshot { - pub revision: Revision, - pub document: Option, -} - -#[derive(Clone, Debug)] -pub struct Mutation { - pub collection: String, - pub id: String, - /// None writes a tombstone. Some(Value::Null) stores a JSON null. - pub value: Option, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Dialect { - Sqlite, - Postgres, - Mysql, -} - -/// Opened SQL reader. Its pool is private so callers cannot bypass the read API. -#[derive(Clone)] -pub struct Reader { - pool: AnyPool, - dialect: Dialect, - deployment: Vec, -} - -#[derive(Clone)] -pub struct Store { - reader: Reader, -} - -/// Returns a lazily connected pool. The writer initializes schema before use. -#[doc(hidden)] -pub fn pool(dialect: Dialect, url: &str, connections: u32, read_only: bool) -> Result { - if connections == 0 { - return Err(Error::Invalid("database pool size")); - } - sqlx::any::install_default_drivers(); - let mut options = AnyPoolOptions::new() - .max_connections(connections) - .acquire_timeout(Duration::from_secs(5)); - let read_only_statement = match dialect { - Dialect::Sqlite => "PRAGMA query_only = ON", - Dialect::Postgres => "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", - Dialect::Mysql => "SET SESSION TRANSACTION READ ONLY", - }; - if read_only { - options = options.after_connect(move |connection, _| { - Box::pin(async move { - sqlx::query(read_only_statement).execute(connection).await?; - Ok(()) - }) - }); - } - options.connect_lazy(url).map_err(|_| Error::Connection) -} - -impl Reader { - #[doc(hidden)] - pub fn new(pool: AnyPool, dialect: Dialect, deployment: &str) -> Result { - validate_id(deployment)?; - Ok(Self { - pool, - dialect, - deployment: deployment.as_bytes().to_vec(), - }) - } - - pub async fn revision(&self) -> Result { - let statement = statement( - self.dialect, - "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0", - ); - sqlx::query_scalar(&statement) - .bind(self.deployment.as_slice()) - .fetch_optional(&self.pool) - .await - .map_err(connection_error)? - .ok_or(Error::MissingDeployment) - } - - /// Fetch at the latest revision or at an exact, previously committed snapshot. - pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { - validate_id(collection)?; - validate_id(id)?; - if at.is_some_and(|at| at < 0) { - return Err(Error::Invalid("snapshot revision")); - } - // A single statement keeps the revision and document on the same database snapshot. - let statement = statement( - self.dialect, - " - SELECT d.revision AS available, v.revision AS document_revision, v.payload - FROM bedrock_deployments d - LEFT JOIN bedrock_documents v - ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ? - AND v.revision <= COALESCE(?, d.revision) - WHERE d.deployment = ? AND d.retired = 0 - ORDER BY v.revision DESC LIMIT 1", - ); - let row = sqlx::query(&statement) - .bind(collection.as_bytes()) - .bind(id.as_bytes()) - .bind(at) - .bind(self.deployment.as_slice()) - .fetch_optional(&self.pool) - .await - .map_err(connection_error)? - .ok_or(Error::MissingDeployment)?; - let available = row.try_get("available")?; - let revision = at.unwrap_or(available); - if revision > available { - return Err(Error::Behind { - requested: revision, - available, - }); - } - let document_revision: Option = row.try_get("document_revision")?; - let payload: Option> = row.try_get("payload")?; - let document = match (document_revision, payload) { - (Some(revision), Some(payload)) => Some(Document { - revision, - value: serde_json::from_slice(&payload)?, - }), - _ => None, - }; - Ok(Snapshot { revision, document }) - } -} - -impl Store { - #[doc(hidden)] - pub async fn initialize( - pool: AnyPool, - dialect: Dialect, - deployment: &str, - schema: &[&str], - insert_deployment: &str, - ) -> Result { - let reader = Reader::new(pool, dialect, deployment)?; - if dialect == Dialect::Postgres { - // PostgreSQL catalog inserts can race even with IF NOT EXISTS. - let mut transaction = reader.pool.begin().await.map_err(connection_error)?; - sqlx::query("SELECT pg_advisory_xact_lock(1694199371)") - .execute(&mut *transaction) - .await?; - initialize_schema( - &mut transaction, - schema, - insert_deployment, - &reader.deployment, - ) - .await?; - transaction.commit().await?; - } else { - let mut connection = reader.pool.acquire().await.map_err(connection_error)?; - initialize_schema( - &mut connection, - schema, - insert_deployment, - &reader.deployment, - ) - .await?; - } - reader.revision().await?; - Ok(Self { reader }) - } - - pub fn reader(&self) -> Reader { - self.reader.clone() - } - - pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { - self.commit_with_fence(expected, mutations, None).await - } - - #[doc(hidden)] - pub async fn commit_with_fence( - &self, - expected: Revision, - mutations: &[Mutation], - fence: Option, - ) -> Result { - let revision = expected - .checked_add(1) - .filter(|_| expected >= 0) - .ok_or(Error::Invalid("expected revision"))?; - if mutations.is_empty() { - return Err(Error::Invalid("empty write batch")); - } - let mut seen = HashSet::new(); - let mut rows = Vec::with_capacity(mutations.len()); - for mutation in mutations { - validate_id(&mutation.collection)?; - validate_id(&mutation.id)?; - if !seen.insert((&mutation.collection, &mutation.id)) { - return Err(Error::Invalid("duplicate document in write batch")); - } - let payload = mutation - .value - .as_ref() - .map(serde_json::to_vec) - .transpose()?; - rows.push(( - mutation.collection.as_bytes(), - mutation.id.as_bytes(), - payload, - )); - } - - let store = &self.reader; - let mut transaction = store.pool.begin().await.map_err(connection_error)?; - let mut advance = "UPDATE bedrock_deployments SET revision = ? WHERE deployment = ? AND revision = ? AND retired = 0".to_owned(); - if store.dialect == Dialect::Mysql { - lock_mysql_deployment(&mut transaction, &store.deployment).await?; - if fence.is_some() { - advance.push_str(" AND lease_epoch = ? AND lease_until > "); - } else { - advance.push_str(" AND lease_until <= "); - } - advance.push_str(MYSQL_NOW); - } else if fence.is_some() { - return Err(Error::Invalid("lease on a database without lease support")); - } - let advance = statement(store.dialect, &advance); - let mut query = sqlx::query(&advance) - .bind(revision) - .bind(store.deployment.as_slice()) - .bind(expected); - if let Some(fence) = fence { - query = query.bind(fence); - } - if query.execute(&mut *transaction).await?.rows_affected() != 1 { - return Err(Error::WriteConflict); - } - let insert = statement( - store.dialect, - " - INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) - VALUES (?, ?, ?, ?, ?)", - ); - for (collection, id, payload) in rows { - sqlx::query(&insert) - .bind(store.deployment.as_slice()) - .bind(collection) - .bind(id) - .bind(revision) - .bind(payload) - .execute(&mut *transaction) - .await?; - } - transaction.commit().await?; - Ok(revision) - } -} - -/// MySQL server time in milliseconds, shared by lease management and fenced writes. -#[doc(hidden)] -pub const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)"; - -/// Lock before reading the database clock. MySQL timestamps are fixed at statement start. -#[doc(hidden)] -pub async fn lock_mysql_deployment( - connection: &mut AnyConnection, - deployment: &[u8], -) -> Result<()> { - sqlx::query_scalar::<_, Revision>( - "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE", - ) - .bind(deployment) - .fetch_optional(connection) - .await? - .ok_or(Error::MissingDeployment)?; - Ok(()) -} - -fn validate_id(value: &str) -> Result<()> { - if value.is_empty() || value.len() > 128 || value.contains('\0') { - return Err(Error::Invalid( - "identifier (expected 1–128 bytes without NUL)", - )); - } - Ok(()) -} - -async fn initialize_schema( - connection: &mut AnyConnection, - schema: &[&str], - insert_deployment: &str, - deployment: &[u8], -) -> Result<()> { - for ddl in schema { - sqlx::query(ddl).execute(&mut *connection).await?; - } - sqlx::query(insert_deployment) - .bind(deployment) - .execute(connection) - .await?; - Ok(()) -} - -fn statement(dialect: Dialect, sql: &str) -> Cow<'_, str> { - if dialect != Dialect::Postgres { - return Cow::Borrowed(sql); - } - let mut parts = sql.split('?'); - let mut translated = parts.next().unwrap_or_default().to_owned(); - for (index, part) in parts.enumerate() { - let _ = write!(translated, "${}", index + 1); - translated.push_str(part); - } - Cow::Owned(translated) -} - -fn connection_error(error: sqlx::Error) -> Error { - match error { - sqlx::Error::Configuration(_) => Error::Connection, - other => Error::Sql(other), - } -} +pub use store::Error as StorageError; +pub use store::{ + Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store, + lock_mysql_deployment, pool, +}; diff --git a/crates/db/src/mysql.rs b/crates/db/src/mysql.rs index e1a1e6d..20c3024 100644 --- a/crates/db/src/mysql.rs +++ b/crates/db/src/mysql.rs @@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration}; -use crate::{ +use crate::store::{ Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment, pool, }; diff --git a/crates/db/src/postgres.rs b/crates/db/src/postgres.rs index 612dad9..1164b90 100644 --- a/crates/db/src/postgres.rs +++ b/crates/db/src/postgres.rs @@ -1,6 +1,6 @@ //! PostgreSQL connection pools and the Bedrock document layout. -use crate::{Dialect, Reader, Result, Store, pool}; +use crate::store::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/crates/db/src/sqlite.rs b/crates/db/src/sqlite.rs index ee3ce1e..88a0592 100644 --- a/crates/db/src/sqlite.rs +++ b/crates/db/src/sqlite.rs @@ -1,6 +1,6 @@ //! File-backed Bedrock storage for self-hosted deployments. -use crate::{Dialect, Reader, Result, Store, pool}; +use crate::store::{Dialect, Reader, Result, Store, pool}; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( diff --git a/crates/db/src/store.rs b/crates/db/src/store.rs new file mode 100644 index 0000000..ca2c37c --- /dev/null +++ b/crates/db/src/store.rs @@ -0,0 +1,386 @@ +//! Shared SQL connection pools, documents, snapshots and write transactions. + +use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration}; + +use serde_json::Value; +use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions}; +use thiserror::Error; + +pub type Revision = i64; +pub type Result = std::result::Result; + +#[derive(Debug, Error)] +pub enum Error { + #[error("invalid {0}")] + Invalid(&'static str), + #[error("the database connection failed")] + Connection, + #[error("SQL operation failed: {0}")] + Sql(#[from] sqlx::Error), + #[error("document encoding failed: {0}")] + Encoding(#[from] serde_json::Error), + #[error("the connection is read-only")] + ReadOnly, + #[error("the deployment is missing or retired")] + MissingDeployment, + #[error("database is at revision {available}, requested revision {requested}")] + Behind { + requested: Revision, + available: Revision, + }, + #[error("the write conflicts with the current revision or lease")] + WriteConflict, + #[error("lease is missing, expired, or belongs to another store")] + LeaseLost, +} + +impl Error { + pub fn retry_on_primary(&self) -> bool { + match self { + Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true, + Self::Sql(error) => match error { + sqlx::Error::Io(_) + | sqlx::Error::Tls(_) + | sqlx::Error::PoolTimedOut + | sqlx::Error::PoolClosed + | sqlx::Error::WorkerCrashed => true, + sqlx::Error::Database(db) => db.code().is_some_and(|code| { + code.starts_with("08") + || matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146") + }), + _ => false, + }, + _ => false, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Document { + pub revision: Revision, + pub value: Value, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Snapshot { + pub revision: Revision, + pub document: Option, +} + +#[derive(Clone, Debug)] +pub struct Mutation { + pub collection: String, + pub id: String, + /// None writes a tombstone. Some(Value::Null) stores a JSON null. + pub value: Option, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Dialect { + Sqlite, + Postgres, + Mysql, +} + +/// Opened SQL reader. Its pool is private so callers cannot bypass the read API. +#[derive(Clone)] +pub struct Reader { + pool: AnyPool, + dialect: Dialect, + deployment: Vec, +} + +#[derive(Clone)] +pub struct Store { + reader: Reader, +} + +/// Returns a lazily connected pool. The writer initializes schema before use. +#[doc(hidden)] +pub fn pool(dialect: Dialect, url: &str, connections: u32, read_only: bool) -> Result { + if connections == 0 { + return Err(Error::Invalid("database pool size")); + } + sqlx::any::install_default_drivers(); + let mut options = AnyPoolOptions::new() + .max_connections(connections) + .acquire_timeout(Duration::from_secs(5)); + let read_only_statement = match dialect { + Dialect::Sqlite => "PRAGMA query_only = ON", + Dialect::Postgres => "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", + Dialect::Mysql => "SET SESSION TRANSACTION READ ONLY", + }; + if read_only { + options = options.after_connect(move |connection, _| { + Box::pin(async move { + sqlx::query(read_only_statement).execute(connection).await?; + Ok(()) + }) + }); + } + options.connect_lazy(url).map_err(|_| Error::Connection) +} + +impl Reader { + #[doc(hidden)] + pub fn new(pool: AnyPool, dialect: Dialect, deployment: &str) -> Result { + validate_id(deployment)?; + Ok(Self { + pool, + dialect, + deployment: deployment.as_bytes().to_vec(), + }) + } + + pub async fn revision(&self) -> Result { + let statement = statement( + self.dialect, + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0", + ); + sqlx::query_scalar(&statement) + .bind(self.deployment.as_slice()) + .fetch_optional(&self.pool) + .await + .map_err(connection_error)? + .ok_or(Error::MissingDeployment) + } + + /// Fetch at the latest revision or at an exact, previously committed snapshot. + pub async fn get(&self, collection: &str, id: &str, at: Option) -> Result { + validate_id(collection)?; + validate_id(id)?; + if at.is_some_and(|at| at < 0) { + return Err(Error::Invalid("snapshot revision")); + } + // A single statement keeps the revision and document on the same database snapshot. + let statement = statement( + self.dialect, + " + SELECT d.revision AS available, v.revision AS document_revision, v.payload + FROM bedrock_deployments d + LEFT JOIN bedrock_documents v + ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ? + AND v.revision <= COALESCE(?, d.revision) + WHERE d.deployment = ? AND d.retired = 0 + ORDER BY v.revision DESC LIMIT 1", + ); + let row = sqlx::query(&statement) + .bind(collection.as_bytes()) + .bind(id.as_bytes()) + .bind(at) + .bind(self.deployment.as_slice()) + .fetch_optional(&self.pool) + .await + .map_err(connection_error)? + .ok_or(Error::MissingDeployment)?; + let available = row.try_get("available")?; + let revision = at.unwrap_or(available); + if revision > available { + return Err(Error::Behind { + requested: revision, + available, + }); + } + let document_revision: Option = row.try_get("document_revision")?; + let payload: Option> = row.try_get("payload")?; + let document = match (document_revision, payload) { + (Some(revision), Some(payload)) => Some(Document { + revision, + value: serde_json::from_slice(&payload)?, + }), + _ => None, + }; + Ok(Snapshot { revision, document }) + } +} + +impl Store { + #[doc(hidden)] + pub async fn initialize( + pool: AnyPool, + dialect: Dialect, + deployment: &str, + schema: &[&str], + insert_deployment: &str, + ) -> Result { + let reader = Reader::new(pool, dialect, deployment)?; + if dialect == Dialect::Postgres { + // PostgreSQL catalog inserts can race even with IF NOT EXISTS. + let mut transaction = reader.pool.begin().await.map_err(connection_error)?; + sqlx::query("SELECT pg_advisory_xact_lock(1694199371)") + .execute(&mut *transaction) + .await?; + initialize_schema( + &mut transaction, + schema, + insert_deployment, + &reader.deployment, + ) + .await?; + transaction.commit().await?; + } else { + let mut connection = reader.pool.acquire().await.map_err(connection_error)?; + initialize_schema( + &mut connection, + schema, + insert_deployment, + &reader.deployment, + ) + .await?; + } + reader.revision().await?; + Ok(Self { reader }) + } + + pub fn reader(&self) -> Reader { + self.reader.clone() + } + + pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { + self.commit_with_fence(expected, mutations, None).await + } + + #[doc(hidden)] + pub async fn commit_with_fence( + &self, + expected: Revision, + mutations: &[Mutation], + fence: Option, + ) -> Result { + let revision = expected + .checked_add(1) + .filter(|_| expected >= 0) + .ok_or(Error::Invalid("expected revision"))?; + if mutations.is_empty() { + return Err(Error::Invalid("empty write batch")); + } + let mut seen = HashSet::new(); + let mut rows = Vec::with_capacity(mutations.len()); + for mutation in mutations { + validate_id(&mutation.collection)?; + validate_id(&mutation.id)?; + if !seen.insert((&mutation.collection, &mutation.id)) { + return Err(Error::Invalid("duplicate document in write batch")); + } + let payload = mutation + .value + .as_ref() + .map(serde_json::to_vec) + .transpose()?; + rows.push(( + mutation.collection.as_bytes(), + mutation.id.as_bytes(), + payload, + )); + } + + let store = &self.reader; + let mut transaction = store.pool.begin().await.map_err(connection_error)?; + let mut advance = "UPDATE bedrock_deployments SET revision = ? WHERE deployment = ? AND revision = ? AND retired = 0".to_owned(); + if store.dialect == Dialect::Mysql { + lock_mysql_deployment(&mut transaction, &store.deployment).await?; + if fence.is_some() { + advance.push_str(" AND lease_epoch = ? AND lease_until > "); + } else { + advance.push_str(" AND lease_until <= "); + } + advance.push_str(MYSQL_NOW); + } else if fence.is_some() { + return Err(Error::Invalid("lease on a database without lease support")); + } + let advance = statement(store.dialect, &advance); + let mut query = sqlx::query(&advance) + .bind(revision) + .bind(store.deployment.as_slice()) + .bind(expected); + if let Some(fence) = fence { + query = query.bind(fence); + } + if query.execute(&mut *transaction).await?.rows_affected() != 1 { + return Err(Error::WriteConflict); + } + let insert = statement( + store.dialect, + " + INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload) + VALUES (?, ?, ?, ?, ?)", + ); + for (collection, id, payload) in rows { + sqlx::query(&insert) + .bind(store.deployment.as_slice()) + .bind(collection) + .bind(id) + .bind(revision) + .bind(payload) + .execute(&mut *transaction) + .await?; + } + transaction.commit().await?; + Ok(revision) + } +} + +/// MySQL server time in milliseconds, shared by lease management and fenced writes. +#[doc(hidden)] +pub const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)"; + +/// Lock before reading the database clock. MySQL timestamps are fixed at statement start. +#[doc(hidden)] +pub async fn lock_mysql_deployment( + connection: &mut AnyConnection, + deployment: &[u8], +) -> Result<()> { + sqlx::query_scalar::<_, Revision>( + "SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE", + ) + .bind(deployment) + .fetch_optional(connection) + .await? + .ok_or(Error::MissingDeployment)?; + Ok(()) +} + +fn validate_id(value: &str) -> Result<()> { + if value.is_empty() || value.len() > 128 || value.contains('\0') { + return Err(Error::Invalid( + "identifier (expected 1–128 bytes without NUL)", + )); + } + Ok(()) +} + +async fn initialize_schema( + connection: &mut AnyConnection, + schema: &[&str], + insert_deployment: &str, + deployment: &[u8], +) -> Result<()> { + for ddl in schema { + sqlx::query(ddl).execute(&mut *connection).await?; + } + sqlx::query(insert_deployment) + .bind(deployment) + .execute(connection) + .await?; + Ok(()) +} + +fn statement(dialect: Dialect, sql: &str) -> Cow<'_, str> { + if dialect != Dialect::Postgres { + return Cow::Borrowed(sql); + } + let mut parts = sql.split('?'); + let mut translated = parts.next().unwrap_or_default().to_owned(); + for (index, part) in parts.enumerate() { + let _ = write!(translated, "${}", index + 1); + translated.push_str(part); + } + Cow::Owned(translated) +} + +fn connection_error(error: sqlx::Error) -> Error { + match error { + sqlx::Error::Configuration(_) => Error::Connection, + other => Error::Sql(other), + } +} diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index 2c7feab..73c2a2c 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -76,7 +76,7 @@ 配置由 BEDROCK_DB_CONFIG 指定。 在已有 PostgreSQL 数据库内初始化 -postgres 模块提供 SQL,db 在事务里执行。 +postgres.rs 提供 SQL,store.rs 在事务里执行。 创建 Bedrock 表并登记 production 部署。 进入 Store::initialize() 成功