Consolidate SQL backends into persistence modules

This commit is contained in:
2026-11-30 03:43:47 +08:00
parent 55d66d5d9b
commit 2f2a39621c
14 changed files with 13 additions and 71 deletions
+1 -1
View File
@@ -6,5 +6,5 @@ rust-version.workspace = true
[dependencies]
serde_json.workspace = true
sqlx.workspace = true
sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] }
thiserror.workspace = true
+5 -1
View File
@@ -1,4 +1,8 @@
//! Shared storage contract for Bedrock's SQL backends.
//! Shared storage contract and SQL backends for Bedrock.
pub mod mysql;
pub mod postgres;
pub mod sqlite;
use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration};
+211
View File
@@ -0,0 +1,211 @@
//! MySQL storage, writer leases and deployment cleanup.
use std::{sync::Arc, time::Duration};
use crate::{
Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment,
pool,
};
use sqlx::AnyPool;
const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
deployment VARBINARY(128) PRIMARY KEY,
revision BIGINT NOT NULL DEFAULT 0,
retired BIGINT NOT NULL DEFAULT 0,
lease_epoch BIGINT NOT NULL DEFAULT 0,
lease_until BIGINT NOT NULL DEFAULT 0
) ENGINE=InnoDB",
"CREATE TABLE IF NOT EXISTS bedrock_documents (
deployment VARBINARY(128) NOT NULL,
collection VARBINARY(128) NOT NULL,
document_id VARBINARY(128) NOT NULL,
revision BIGINT NOT NULL,
payload LONGBLOB,
PRIMARY KEY (deployment, collection, document_id, revision),
FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment)
) ENGINE=InnoDB",
];
#[derive(Clone)]
pub struct MySql {
store: Store,
pool: AnyPool,
deployment: Vec<u8>,
identity: Arc<()>,
}
/// The monotonically increasing epoch fences off holders whose lease expired.
#[derive(Debug)]
pub struct Lease {
epoch: i64,
issuer: Arc<()>,
}
impl Lease {
pub fn epoch(&self) -> i64 {
self.epoch
}
}
impl MySql {
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Self> {
let pool = pool(Dialect::Mysql, url, max_connections, false)?;
let store = Store::initialize(
pool.clone(),
Dialect::Mysql,
deployment,
SCHEMA,
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
ON DUPLICATE KEY UPDATE revision = revision",
)
.await?;
Ok(Self {
store,
pool,
deployment: deployment.as_bytes().to_vec(),
identity: Arc::new(()),
})
}
pub fn reader(&self) -> Reader {
self.store.reader()
}
/// An ordinary write is allowed while no lease is active.
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
self.store.commit(expected, mutations).await
}
pub async fn commit_with_lease(
&self,
lease: &Lease,
expected: Revision,
mutations: &[Mutation],
) -> Result<Revision> {
let epoch = self.epoch(lease)?;
self.store
.commit_with_fence(expected, mutations, Some(epoch))
.await
}
/// Acquires an expired or unheld lease using the database clock.
pub async fn acquire_lease(&self, ttl: Duration) -> Result<Option<Lease>> {
let ttl = lease_millis(ttl)?;
let update = format!(
"
UPDATE bedrock_deployments
SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ?
WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}"
);
let mut transaction = self.pool.begin().await?;
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
let changed = sqlx::query(&update)
.bind(ttl)
.bind(self.deployment.as_slice())
.execute(&mut *transaction)
.await?;
if changed.rows_affected() != 1 {
return Ok(None);
}
let epoch =
sqlx::query_scalar("SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?")
.bind(self.deployment.as_slice())
.fetch_one(&mut *transaction)
.await?;
transaction.commit().await?;
Ok(Some(Lease {
epoch,
issuer: self.identity.clone(),
}))
}
/// Extends an active lease from the current database time without shortening it.
pub async fn renew_lease(&self, lease: &Lease, ttl: Duration) -> Result<()> {
let epoch = self.epoch(lease)?;
let ttl = lease_millis(ttl)?;
let update = format!(
"
UPDATE bedrock_deployments
SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?)
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
);
let mut transaction = self.pool.begin().await?;
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
let changed = sqlx::query(&update)
.bind(ttl)
.bind(self.deployment.as_slice())
.bind(epoch)
.execute(&mut *transaction)
.await?;
if changed.rows_affected() != 1 {
return Err(Error::LeaseLost);
}
transaction.commit().await?;
Ok(())
}
pub async fn release_lease(&self, lease: &Lease) -> Result<bool> {
let epoch = self.epoch(lease)?;
let changed = sqlx::query(
"
UPDATE bedrock_deployments SET lease_until = 0
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
)
.bind(self.deployment.as_slice())
.bind(epoch)
.execute(&self.pool)
.await?;
Ok(changed.rows_affected() == 1)
}
/// Removes only this deployment's documents and retires its identity in one transaction.
/// The retained deployment row prevents a restart from recreating the deleted deployment.
pub async fn delete_deployment(&self, lease: &Lease) -> Result<u64> {
let epoch = self.epoch(lease)?;
let update = format!(
"
UPDATE bedrock_deployments SET retired = 1, lease_until = 0
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
);
let mut transaction = self.pool.begin().await?;
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
let changed = sqlx::query(&update)
.bind(self.deployment.as_slice())
.bind(epoch)
.execute(&mut *transaction)
.await?;
if changed.rows_affected() != 1 {
return Err(Error::LeaseLost);
}
let removed = sqlx::query("DELETE FROM bedrock_documents WHERE deployment = ?")
.bind(self.deployment.as_slice())
.execute(&mut *transaction)
.await?;
transaction.commit().await?;
Ok(removed.rows_affected())
}
fn epoch(&self, lease: &Lease) -> Result<i64> {
if !Arc::ptr_eq(&self.identity, &lease.issuer) {
return Err(Error::LeaseLost);
}
Ok(lease.epoch)
}
}
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<Reader> {
Reader::new(
pool(Dialect::Mysql, url, max_connections, true)?,
Dialect::Mysql,
deployment,
)
}
fn lease_millis(ttl: Duration) -> Result<i64> {
let millis = ttl.as_millis();
if millis == 0 || millis >= i64::MAX as u128 / 2 {
return Err(Error::Invalid("lease duration"));
}
Ok(millis as i64)
}
+40
View File
@@ -0,0 +1,40 @@
//! PostgreSQL connection pools and the Bedrock document layout.
use crate::{Dialect, Reader, Result, Store, pool};
const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
deployment BYTEA PRIMARY KEY,
revision BIGINT NOT NULL DEFAULT 0,
retired BIGINT NOT NULL DEFAULT 0
)",
"CREATE TABLE IF NOT EXISTS bedrock_documents (
deployment BYTEA NOT NULL REFERENCES bedrock_deployments(deployment),
collection BYTEA NOT NULL,
document_id BYTEA NOT NULL,
revision BIGINT NOT NULL,
payload BYTEA,
PRIMARY KEY (deployment, collection, document_id, revision)
)",
];
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Store> {
let pool = pool(Dialect::Postgres, url, max_connections, false)?;
Store::initialize(
pool,
Dialect::Postgres,
deployment,
SCHEMA,
"INSERT INTO bedrock_deployments (deployment) VALUES ($1)
ON CONFLICT (deployment) DO NOTHING",
)
.await
}
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<Reader> {
Reader::new(
pool(Dialect::Postgres, url, max_connections, true)?,
Dialect::Postgres,
deployment,
)
}
+41
View File
@@ -0,0 +1,41 @@
//! File-backed Bedrock storage for self-hosted deployments.
use crate::{Dialect, Reader, Result, Store, pool};
const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
deployment BLOB PRIMARY KEY NOT NULL,
revision INTEGER NOT NULL DEFAULT 0,
retired INTEGER NOT NULL DEFAULT 0
)",
"CREATE TABLE IF NOT EXISTS bedrock_documents (
deployment BLOB NOT NULL,
collection BLOB NOT NULL,
document_id BLOB NOT NULL,
revision INTEGER NOT NULL,
payload BLOB,
PRIMARY KEY (deployment, collection, document_id, revision),
FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment)
)",
];
pub async fn connect(url: &str, deployment: &str) -> Result<Store> {
let pool = pool(Dialect::Sqlite, url, 1, false)?;
Store::initialize(
pool,
Dialect::Sqlite,
deployment,
SCHEMA,
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
ON CONFLICT (deployment) DO NOTHING",
)
.await
}
pub fn reader(url: &str, deployment: &str) -> Result<Reader> {
Reader::new(
pool(Dialect::Sqlite, url, 1, true)?,
Dialect::Sqlite,
deployment,
)
}