Merge pull request '实现 Bedrock SQL 存储与部署配置' (#24) from codex/sql-persistence into main
Deploy Rust Bedrock / deploy (push) Failing after 31m4s

Reviewed-on: #24
Reviewed-by: Zayden-Jung <zayden.jung@entroia.com>
This commit was merged in pull request #24.
This commit is contained in:
2026-11-29 20:47:50 +00:00
25 changed files with 3706 additions and 3 deletions
+29
View File
@@ -0,0 +1,29 @@
name: Deploy Rust Bedrock
on:
push:
branches: [main]
concurrency:
group: bedrock-rust-deploy
cancel-in-progress: false
jobs:
deploy:
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
runs-on: ces-control
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Build the Rust release
run: bash deploy/build-release.sh
- name: Publish and initialize Bedrock storage
env:
BEDROCK_PG_HOST: ${{ vars.BEDROCK_PG_HOST }}
BEDROCK_PG_PORT: ${{ vars.BEDROCK_PG_PORT }}
BEDROCK_PG_DATABASE: ${{ vars.BEDROCK_PG_DATABASE }}
BEDROCK_PG_USER: ${{ vars.BEDROCK_PG_USER }}
BEDROCK_PG_PASSWORD: ${{ secrets.BEDROCK_PG_PASSWORD }}
run: bash deploy/release.sh target/bedrock-release/bedrock "$GITHUB_SHA"
+2
View File
@@ -1 +1,3 @@
/target /target
/bedrock.sqlite3
/bedrock.sqlite3-*
Generated
+1875
View File
File diff suppressed because it is too large Load Diff
+24 -1
View File
@@ -1,6 +1,29 @@
[workspace]
members = ["crates/*"]
resolver = "3"
[workspace.package]
edition = "2024"
rust-version = "1.91"
[workspace.dependencies]
clusters = { path = "crates/clusters" }
db = { path = "crates/db" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] }
tempfile = "3"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
url = "2"
[package] [package]
name = "bedrock" name = "bedrock"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition.workspace = true
rust-version.workspace = true
[dependencies] [dependencies]
db.workspace = true
serde_json.workspace = true
tokio.workspace = true
+36
View File
@@ -0,0 +1,36 @@
# Bedrock storage
Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `db` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start.
## 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. The backend modules share the connection pools and transaction implementation in `common.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)
## Database configuration
Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example:
```json
{
"deployment": "production",
"cluster": "east",
"clusters": {
"east": {
"driver": "postgres",
"primary": "postgres://bedrock@primary.example.net/bedrock",
"replicas": ["postgres://bedrock_reader@replica.example.net/bedrock"],
"max_connections": 5
}
}
}
```
The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file.
Applications connect with `db::connect`. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value.
For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database.
See [deployment configuration](deploy/README.md) for the PostgreSQL configuration renderer and deployment-only variables.
+5
View File
@@ -0,0 +1,5 @@
# Manual SQL verification
`ci/check-sql.sh` runs storage checks against SQLite and temporary PostgreSQL and MySQL containers. Run it from the workspace root on an approved remote runner. It removes its test containers and network on exit.
![Bedrock deployment and manual SQL verification flow](../deploy/bedrock-deployment.svg)
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
set -euo pipefail
prefix="bedrock-sql-$(openssl rand -hex 8)"
password="$(openssl rand -hex 16)"
cleanup() {
docker rm -f "$prefix-rust" "$prefix-mysql" "$prefix-postgres" >/dev/null 2>&1 || true
docker network rm "$prefix" >/dev/null 2>&1 || true
}
trap cleanup EXIT
docker network create "$prefix" >/dev/null
docker run -d --name "$prefix-postgres" --network "$prefix" --network-alias postgres \
-e POSTGRES_PASSWORD="$password" -e POSTGRES_DB=bedrock postgres:17-alpine >/dev/null
docker run -d --name "$prefix-mysql" --network "$prefix" --network-alias mysql \
-e MYSQL_RANDOM_ROOT_PASSWORD=1 -e MYSQL_USER=bedrock -e MYSQL_PASSWORD="$password" \
-e MYSQL_DATABASE=bedrock mysql:8.4 >/dev/null
wait_for() {
for _ in {1..90}; do
if "$@" >/dev/null 2>&1; then return; fi
sleep 2
done
"$@"
}
wait_for docker exec "$prefix-postgres" pg_isready -h 127.0.0.1 -U postgres -d bedrock
docker exec -e PGPASSWORD="$password" "$prefix-postgres" \
createdb -h 127.0.0.1 -U postgres bedrock_replica
wait_for docker exec -e MYSQL_PWD="$password" "$prefix-mysql" \
mysql -h 127.0.0.1 -u bedrock -D bedrock -e 'SELECT 1'
docker run --rm --name "$prefix-rust" --network "$prefix" \
--mount "type=bind,src=$PWD,dst=/work,readonly" -w /work \
-e CARGO_TARGET_DIR=/tmp/bedrock-target \
-e BEDROCK_REQUIRE_SQL_TESTS=1 \
-e BEDROCK_TEST_POSTGRES="postgres://postgres:$password@postgres/bedrock" \
-e BEDROCK_TEST_POSTGRES_REPLICA="postgres://postgres:$password@postgres/bedrock_replica" \
-e BEDROCK_TEST_MYSQL="mysql://bedrock:$password@mysql/bedrock" \
rust:1.91.1-bookworm sh -ec '
rustup component add rustfmt
cargo fmt --all --check
cargo test --locked --workspace
cargo build --locked --workspace
cd "$(mktemp -d)"
/tmp/bedrock-target/debug/bedrock
test -f bedrock.sqlite3
'
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "clusters"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
serde.workspace = true
thiserror.workspace = true
url.workspace = true
+229
View File
@@ -0,0 +1,229 @@
use std::{collections::BTreeMap, fmt, path::Path};
use serde::Deserialize;
use thiserror::Error;
use url::Url;
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Driver {
#[default]
Sqlite,
Postgres,
Mysql,
}
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Tls {
#[default]
VerifyFull,
Disabled,
}
/// A database address may contain credentials.
#[derive(Clone, Deserialize)]
#[serde(transparent)]
pub struct Address(String);
impl From<&str> for Address {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for Address {
fn from(value: String) -> Self {
Self(value)
}
}
impl fmt::Debug for Address {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Address([redacted])")
}
}
impl Address {
pub fn connection_string(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Cluster {
pub driver: Driver,
pub primary: Address,
#[serde(default)]
pub replicas: Vec<Address>,
#[serde(default)]
pub tls: Tls,
#[serde(default = "default_pool_size")]
pub max_connections: u32,
}
const fn default_pool_size() -> u32 {
5
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DeploymentConfig {
pub deployment: String,
pub cluster: Option<String>,
pub clusters: BTreeMap<String, Cluster>,
pub read_only: bool,
pub sqlite_path: Address,
}
impl Default for DeploymentConfig {
fn default() -> Self {
Self {
deployment: "default".into(),
cluster: None,
clusters: BTreeMap::new(),
read_only: false,
sqlite_path: "bedrock.sqlite3".into(),
}
}
}
#[derive(Debug)]
pub struct ResolvedDeployment {
pub deployment: String,
pub cluster: Option<String>,
pub driver: Driver,
pub primary: Address,
pub replicas: Vec<Address>,
pub read_only: bool,
pub max_connections: u32,
}
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("invalid {0} name")]
Name(&'static str),
#[error("the selected database cluster is not configured")]
UnknownCluster,
#[error("a cluster must be selected when clusters are configured")]
ClusterRequired,
#[error("the database pool size must be greater than zero")]
PoolSize,
#[error("SQLite does not support a replica list")]
SqliteReplicas,
#[error("invalid SQLite file path")]
SqlitePath,
#[error("invalid {0} database URL")]
Url(&'static str),
}
impl DeploymentConfig {
pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> {
validate_name(&self.deployment, "deployment")?;
let local = Cluster {
driver: Driver::Sqlite,
primary: self.sqlite_path.clone(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 1,
};
let cluster = match &self.cluster {
Some(name) => {
validate_name(name, "cluster")?;
self.clusters.get(name).ok_or(ConfigError::UnknownCluster)?
}
None if self.clusters.is_empty() => &local,
None => return Err(ConfigError::ClusterRequired),
};
if cluster.max_connections == 0 {
return Err(ConfigError::PoolSize);
}
if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() {
return Err(ConfigError::SqliteReplicas);
}
let primary = resolve_address(cluster, &cluster.primary, self.read_only)?;
let replicas = cluster
.replicas
.iter()
.map(|address| resolve_address(cluster, address, true))
.collect::<Result<_, _>>()?;
Ok(ResolvedDeployment {
deployment: self.deployment.clone(),
cluster: self.cluster.clone(),
driver: cluster.driver,
primary,
replicas,
read_only: self.read_only,
max_connections: cluster.max_connections,
})
}
}
fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
if value.is_empty()
|| value.len() > 128
|| !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
{
return Err(ConfigError::Name(kind));
}
Ok(())
}
fn resolve_address(
cluster: &Cluster,
address: &Address,
read_only: bool,
) -> Result<Address, ConfigError> {
let address = address.connection_string();
let (driver, tls_key, tls_enabled, tls_disabled) = match cluster.driver {
Driver::Sqlite => return sqlite_url(address, read_only),
Driver::Postgres => ("postgres", "sslmode", "verify-full", "disable"),
Driver::Mysql => ("mysql", "ssl-mode", "VERIFY_IDENTITY", "DISABLED"),
};
let mut url = Url::parse(address).map_err(|_| ConfigError::Url(driver))?;
let compatible = url.scheme() == driver || driver == "postgres" && url.scheme() == "postgresql";
if !compatible
|| url.host_str().is_none()
|| url.username().is_empty()
|| url.path().trim_matches('/').is_empty()
|| url.fragment().is_some()
|| url.query_pairs().any(|(key, _)| {
matches!(
key.as_ref(),
"sslmode"
| "ssl-mode"
| "host"
| "hostaddr"
| "port"
| "socket"
| "dbname"
| "options"
)
})
{
return Err(ConfigError::Url(driver));
}
let tls_mode = match cluster.tls {
Tls::VerifyFull => tls_enabled,
Tls::Disabled => tls_disabled,
};
url.query_pairs_mut().append_pair(tls_key, tls_mode);
Ok(Address(url.into()))
}
fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> {
if path.is_empty() || path == ":memory:" || path.contains('\0') {
return Err(ConfigError::SqlitePath);
}
let absolute = std::path::absolute(Path::new(path)).map_err(|_| ConfigError::SqlitePath)?;
let file = Url::from_file_path(absolute).map_err(|_| ConfigError::SqlitePath)?;
let file = file
.as_str()
.strip_prefix("file:")
.ok_or(ConfigError::SqlitePath)?;
let mode = if read_only { "ro" } else { "rwc" };
Ok(Address(format!("sqlite:{file}?mode={mode}")))
}
@@ -0,0 +1,41 @@
use std::collections::BTreeMap;
use clusters::{Cluster, ConfigError, DeploymentConfig, Driver, Tls};
#[test]
fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
let mut config = DeploymentConfig {
cluster: Some("regional".into()),
clusters: BTreeMap::from([(
"regional".into(),
Cluster {
driver: Driver::Postgres,
primary: "postgres://user:secret@primary/bedrock".into(),
replicas: vec!["postgresql://reader:secret@replica/bedrock".into()],
tls: Tls::VerifyFull,
max_connections: 5,
},
)]),
..DeploymentConfig::default()
};
let resolved = config.resolve().unwrap();
assert!(
resolved
.primary
.connection_string()
.ends_with("sslmode=verify-full")
);
assert!(
resolved.replicas[0]
.connection_string()
.ends_with("sslmode=verify-full")
);
assert!(!format!("{resolved:?}").contains("secret"));
config.clusters.get_mut("regional").unwrap().replicas[0] =
"mysql://user:secret@replica/bedrock".into();
assert!(matches!(
config.resolve(),
Err(ConfigError::Url("postgres"))
));
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "db"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
clusters.workspace = true
serde_json.workspace = true
sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] }
thiserror.workspace = true
[dev-dependencies]
tempfile.workspace = true
tokio.workspace = true
+386
View File
@@ -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<T> = std::result::Result<T, Error>;
#[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<Document>,
}
#[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<Value>,
}
#[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<u8>,
}
#[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<AnyPool> {
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<Self> {
validate_id(deployment)?;
Ok(Self {
pool,
dialect,
deployment: deployment.as_bytes().to_vec(),
})
}
pub async fn revision(&self) -> Result<Revision> {
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<Revision>) -> Result<Snapshot> {
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<Revision> = row.try_get("document_revision")?;
let payload: Option<Vec<u8>> = 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<Self> {
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<Revision> {
self.commit_with_fence(expected, mutations, None).await
}
#[doc(hidden)]
pub async fn commit_with_fence(
&self,
expected: Revision,
mutations: &[Mutation],
fence: Option<i64>,
) -> Result<Revision> {
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),
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Deployment bootstrap and read routing.
use std::sync::atomic::{AtomicUsize, Ordering};
use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeployment};
use thiserror::Error;
use crate::{
common::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store},
mysql::{self, MySql},
postgres, sqlite,
};
#[derive(Debug, Error)]
pub enum ConnectError {
#[error(transparent)]
Config(#[from] ConfigError),
#[error(transparent)]
Storage(#[from] StorageError),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ReadPreference {
/// Read from the primary endpoint.
#[default]
Primary,
/// Try configured replicas in round-robin order, then fall back to the primary.
/// Without an explicit snapshot revision a replica may return stale data.
PreferReplica,
}
enum Writer {
Sql(Store),
MySql(MySql),
}
pub struct Connection {
driver: Driver,
writer: Option<Writer>,
primary: Reader,
replicas: Vec<Reader>,
next_replica: AtomicUsize,
}
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
let config = config.resolve()?;
let writer = if config.read_only {
None
} else {
let url = config.primary.connection_string();
let name = &config.deployment;
let max = config.max_connections;
Some(match config.driver {
Driver::Sqlite => Writer::Sql(sqlite::connect(url, name).await?),
Driver::Postgres => Writer::Sql(postgres::connect(url, name, max).await?),
Driver::Mysql => Writer::MySql(MySql::connect(url, name, max).await?),
})
};
let primary = match &writer {
Some(Writer::Sql(store)) => store.reader(),
Some(Writer::MySql(store)) => store.reader(),
None => {
let reader = reader(&config, &config.primary)?;
reader.revision().await?;
reader
}
};
let replicas = config
.replicas
.iter()
.map(|address| reader(&config, address))
.collect::<Result<_, _>>()?;
Ok(Connection {
driver: config.driver,
writer,
primary,
replicas,
next_replica: AtomicUsize::new(0),
})
}
fn reader(config: &ResolvedDeployment, address: &Address) -> Result<Reader, StorageError> {
let url = address.connection_string();
let name = &config.deployment;
match config.driver {
Driver::Sqlite => sqlite::reader(url, name),
Driver::Postgres => postgres::reader(url, name, config.max_connections),
Driver::Mysql => mysql::reader(url, name, config.max_connections),
}
}
impl Connection {
pub fn driver(&self) -> Driver {
self.driver
}
pub fn is_read_only(&self) -> bool {
self.writer.is_none()
}
pub async fn revision(&self) -> Result<Revision, StorageError> {
self.primary.revision().await
}
pub async fn get(
&self,
collection: &str,
id: &str,
at: Option<Revision>,
preference: ReadPreference,
) -> Result<Snapshot, StorageError> {
if preference == ReadPreference::PreferReplica && !self.replicas.is_empty() {
let count = self.replicas.len();
let start = self.next_replica.fetch_add(1, Ordering::Relaxed) % count;
for replica in self.replicas.iter().cycle().skip(start).take(count) {
match replica.get(collection, id, at).await {
Ok(snapshot) => return Ok(snapshot),
Err(error) if error.retry_on_primary() => {}
Err(error) => return Err(error),
}
}
}
self.primary.get(collection, id, at).await
}
pub async fn commit(
&self,
expected: Revision,
changes: &[Mutation],
) -> Result<Revision, StorageError> {
match &self.writer {
Some(Writer::Sql(store)) => store.commit(expected, changes).await,
Some(Writer::MySql(store)) => store.commit(expected, changes).await,
None => Err(StorageError::ReadOnly),
}
}
pub fn mysql_writer(&self) -> Option<&MySql> {
match &self.writer {
Some(Writer::MySql(store)) => Some(store),
_ => None,
}
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Bedrock's transactional document storage for SQL databases.
mod common;
mod connection;
pub mod mysql;
pub mod postgres;
pub mod sqlite;
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
pub use connection::{ConnectError, Connection, ReadPreference, connect};
pub use mysql::{Lease, MySql};
pub use common::Error as StorageError;
pub use common::{
Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store,
lock_mysql_deployment, pool,
};
+211
View File
@@ -0,0 +1,211 @@
//! MySQL storage, writer leases and deployment cleanup.
use std::{sync::Arc, time::Duration};
use crate::common::{
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::common::{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::common::{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,
)
}
+272
View File
@@ -0,0 +1,272 @@
use std::{collections::BTreeMap, env, time::Duration};
use db::{
Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls,
connect,
};
use serde_json::json;
fn change(id: &str, text: &str) -> Mutation {
Mutation {
collection: "notes".into(),
id: id.into(),
value: Some(json!({ "text": text })),
}
}
fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig {
DeploymentConfig {
deployment: deployment.into(),
cluster: Some("test".into()),
clusters: BTreeMap::from([(
"test".into(),
Cluster {
driver,
primary: url.into(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 4,
},
)]),
..DeploymentConfig::default()
}
}
fn test_url(variable: &str) -> Option<String> {
match env::var(variable) {
Ok(url) => Some(url),
Err(_) if env::var_os("BEDROCK_REQUIRE_SQL_TESTS").is_some() => {
panic!("{variable} is required for the remote storage checks")
}
Err(_) => None,
}
}
async fn check_document_contract(db: &Connection) {
assert_eq!(db.revision().await.unwrap(), 0);
let original = change("doc", "first");
assert_eq!(db.commit(0, &[original]).await.unwrap(), 1);
let duplicate = [
change("other", "never written"),
change("other", "duplicate"),
];
assert!(matches!(
db.commit(1, &duplicate).await,
Err(StorageError::Invalid(_))
));
assert!(matches!(
db.commit(0, &[change("other", "stale")]).await,
Err(StorageError::WriteConflict)
));
let second = [change("doc", "second")];
let alternative = [change("doc", "alternative")];
let (one, two) = tokio::join!(db.commit(1, &second), db.commit(1, &alternative));
assert!(matches!(
(&one, &two),
(Ok(2), Err(StorageError::WriteConflict)) | (Err(StorageError::WriteConflict), Ok(2))
));
let old = db
.get("notes", "doc", Some(1), ReadPreference::Primary)
.await
.unwrap();
assert_eq!(old.document.unwrap().value, json!({ "text": "first" }));
assert!(matches!(
db.get("notes", "doc", Some(3), ReadPreference::Primary)
.await,
Err(StorageError::Behind {
requested: 3,
available: 2
})
));
assert!(
db.get("notes", "other", None, ReadPreference::Primary)
.await
.unwrap()
.document
.is_none()
);
let tombstone = Mutation {
collection: "notes".into(),
id: "doc".into(),
value: None,
};
let null_document = Mutation {
collection: "notes".into(),
id: "null".into(),
value: Some(json!(null)),
};
assert_eq!(db.commit(2, &[tombstone, null_document]).await.unwrap(), 3);
assert!(
db.get("notes", "doc", None, ReadPreference::Primary)
.await
.unwrap()
.document
.is_none()
);
let null_document = db
.get("notes", "null", None, ReadPreference::Primary)
.await
.unwrap();
assert_eq!(null_document.document.unwrap().value, json!(null));
}
#[tokio::test]
async fn sqlite_persists_across_reopening_and_enforces_read_only() {
let folder = tempfile::tempdir().unwrap();
let filename = folder.path().join("bedrock +?#%.sqlite");
let mut config = DeploymentConfig {
sqlite_path: filename.to_str().unwrap().into(),
..DeploymentConfig::default()
};
let db = connect(&config).await.unwrap();
assert_eq!(db.driver(), Driver::Sqlite);
check_document_contract(&db).await;
drop(db);
config.read_only = true;
let db = connect(&config).await.unwrap();
assert_eq!(db.revision().await.unwrap(), 3);
assert!(db.is_read_only());
assert!(matches!(
db.commit(3, &[change("doc", "invalid")]).await,
Err(StorageError::ReadOnly)
));
}
#[tokio::test]
async fn postgres_reads_replicas_and_falls_back_when_behind() {
let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else {
return;
};
let replica_url = test_url("BEDROCK_TEST_POSTGRES_REPLICA").unwrap();
let mut config = sql_config(Driver::Postgres, &url, "pg_contract");
config
.clusters
.get_mut("test")
.unwrap()
.replicas
.push(replica_url.clone().into());
let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract"))
.await
.unwrap();
let (db, concurrent) = tokio::join!(connect(&config), connect(&config));
let db = db.unwrap();
assert_eq!(concurrent.unwrap().revision().await.unwrap(), 0);
check_document_contract(&db).await;
replica
.commit(0, &[change("doc", "replica")])
.await
.unwrap();
let stale = db
.get("notes", "doc", None, ReadPreference::PreferReplica)
.await
.unwrap();
assert_eq!(stale.revision, 1);
assert_eq!(stale.document.unwrap().value, json!({ "text": "replica" }));
let fresh = db
.get("notes", "null", Some(3), ReadPreference::PreferReplica)
.await
.unwrap();
assert_eq!(fresh.revision, 3);
assert_eq!(fresh.document.unwrap().value, json!(null));
config.read_only = true;
let db = connect(&config).await.unwrap();
assert!(db.is_read_only());
assert_eq!(db.revision().await.unwrap(), 3);
}
#[tokio::test]
async fn mysql_fences_writers_and_cleans_only_one_deployment() {
let Some(url) = test_url("BEDROCK_TEST_MYSQL") else {
return;
};
let config = sql_config(Driver::Mysql, &url, "mysql_contract");
let db = connect(&config).await.unwrap();
check_document_contract(&db).await;
let other = connect(&sql_config(Driver::Mysql, &url, "mysql_other"))
.await
.unwrap();
other.commit(0, &[change("doc", "keep")]).await.unwrap();
let mysql = db.mysql_writer().unwrap();
let lease = mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(
mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.is_none()
);
assert!(matches!(
db.commit(3, &[change("doc", "blocked")]).await,
Err(StorageError::WriteConflict)
));
assert!(matches!(
other
.mysql_writer()
.unwrap()
.delete_deployment(&lease)
.await,
Err(StorageError::LeaseLost)
));
mysql
.renew_lease(&lease, Duration::from_secs(30))
.await
.unwrap();
assert_eq!(
mysql
.commit_with_lease(&lease, 3, &[change("doc", "leased")])
.await
.unwrap(),
4
);
assert!(mysql.release_lease(&lease).await.unwrap());
let next = mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(next.epoch() > lease.epoch());
assert!(matches!(
mysql
.commit_with_lease(&lease, 4, &[change("doc", "stale")])
.await,
Err(StorageError::WriteConflict)
));
assert!(mysql.delete_deployment(&next).await.unwrap() > 0);
assert!(matches!(
db.revision().await,
Err(StorageError::MissingDeployment)
));
assert!(connect(&config).await.is_err());
assert_eq!(
other
.get("notes", "doc", None, ReadPreference::Primary)
.await
.unwrap()
.document
.unwrap()
.value,
json!({ "text": "keep" })
);
let mut other_config = sql_config(Driver::Mysql, &url, "mysql_other");
other_config.read_only = true;
assert_eq!(
connect(&other_config)
.await
.unwrap()
.revision()
.await
.unwrap(),
1
);
}
+17
View File
@@ -0,0 +1,17 @@
# Deployment configuration
Deployments pass the path of a JSON configuration file to the Bedrock executable using `BEDROCK_DB_CONFIG`. The Rust libraries accept structured configuration.
- **SQLite** uses `deploy/sqlite.json` as a template. Set `sqlite_path` to a persistent, writable volume path.
- **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address.
- **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint.
Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `db` use only SQL configuration.
Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner.
## Release on the existing deployment host
Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs the current one-shot Rust storage initializer on the existing `endoleap-dev_default` network. It publishes releases under `/opt/endoleap-infra/bedrock-rust/releases` and switches `/opt/endoleap-infra/bedrock-rust/current` after successful initialization. The Go service retains its own containers and routes.
![Bedrock deployment and manual SQL verification flow](./bedrock-deployment.svg)
+105
View File
@@ -0,0 +1,105 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1160" height="1000" viewBox="0 0 1160 1000" role="img" aria-labelledby="title description">
<title id="title">Bedrock 的部署与手动验证流程</title>
<desc id="description">main 提交触发 Gitea CD。release.sh 调用配置渲染器并启动临时容器。容器内 Rust Bedrock 初始化已有 PostgreSQL 数据库中的 Bedrock 表。另有独立手动检查路径。</desc>
<defs>
<marker id="arrow" viewBox="0 0 9 9" refX="8" refY="4.5" markerWidth="9" markerHeight="9" orient="auto" markerUnits="userSpaceOnUse"><path d="M0 0 9 4.5 0 9z" fill="#557866"/></marker>
<marker id="arrow-red" viewBox="0 0 9 9" refX="8" refY="4.5" markerWidth="9" markerHeight="9" orient="auto" markerUnits="userSpaceOnUse"><path d="M0 0 9 4.5 0 9z" fill="#976752"/></marker>
<pattern id="grid" width="16" height="16" patternUnits="userSpaceOnUse"><circle cx="2" cy="2" r=".7" fill="#a4b2a3" opacity=".28"/></pattern>
</defs>
<style>
text{font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;fill:#1e3328}
.title{font-size:37px;font-weight:720;letter-spacing:-.4px}
.kicker,.code{font-family:ui-monospace,"SF Mono",Consolas,monospace}
.kicker{font-size:13px;letter-spacing:2px;font-weight:650;fill:#426251}
.lane{font-size:23px;font-weight:700}
.headline,.code{font-size:17px;font-weight:700}
.detail{font-size:14px;fill:#475d50}
.badge{font-size:14px;font-weight:650;fill:#325541}
.result{font-size:15px;font-weight:700;fill:#38624b}
.failed{fill:#8b5642}
.flow{fill:none;stroke:#557866;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;marker-end:url(#arrow)}
.flow-fail{fill:none;stroke:#976752;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;marker-end:url(#arrow-red)}
.side{stroke-dasharray:4 4}
</style>
<rect width="1160" height="1000" rx="23" fill="#f8f8f1"/>
<rect x=".5" y=".5" width="1159" height="999" rx="22.5" fill="none" stroke="#d9dfd3"/>
<path d="M34 103H1126" stroke="#d9dfd3"/>
<rect x="34" y="123" width="738" height="842" rx="17" fill="#eef2e9" stroke="#d9e1d5"/>
<rect x="34" y="123" width="738" height="842" rx="17" fill="url(#grid)"/>
<rect x="792" y="123" width="334" height="842" rx="17" fill="#f1f1e9" stroke="#dfe1d6"/>
<text x="34" y="36" class="kicker">BEDROCK / DEPLOYMENT</text>
<text x="34" y="81" class="title">Bedrock 的部署与手动验证流程</text>
<text x="55" y="159" class="lane">CD · 原部署机</text>
<text x="813" y="159" class="lane">手动验证</text>
<path d="M310 215 V235" class="flow"/>
<path d="M310 298 V318" class="flow"/>
<path d="M310 381 V414" class="flow"/>
<path d="M310 477 V497" class="flow"/>
<path d="M310 560 V580" class="flow"/>
<path d="M310 643 V663" class="flow"/>
<path d="M310 740 V821" class="flow"/>
<path d="M564 447 H536" class="flow side"/>
<path d="M310 896 V906 H224 V919" class="flow"/>
<path d="M310 896 V906 H568 V919" class="flow-fail"/>
<path d="M959 215 V235" class="flow"/>
<path d="M959 298 V318" class="flow"/>
<path d="M959 396 V416" class="flow"/>
<path d="M959 494 V522" class="flow"/>
<rect x="84" y="171" width="452" height="44" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
<path d="M93 183v20" stroke="#8bac94" stroke-width="2" stroke-linecap="round"/>
<text x="104" y="199.0" class="headline">main 收到提交</text>
<rect x="84" y="235" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="264" class="code">deploy.yml</text>
<text x="104" y="285" class="detail">Gitea 在 ces-control 上检出代码并编排部署。</text>
<rect x="84" y="318" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="347" class="code">build-release.sh</text>
<text x="104" y="368" class="detail">在 Rust 容器内编译 release,输出 Bedrock 二进制。</text>
<text x="327" y="402" class="detail">二进制路径与 Git SHA 交给发布脚本</text>
<rect x="84" y="414" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="443" class="code">release.sh</text>
<text x="104" y="464" class="detail">建立暂存目录,放入二进制。</text>
<rect x="564" y="412" width="185" height="70" rx="9" fill="#edf1e8" stroke="#c1ccbf"/>
<text x="584" y="441" class="headline">Gitea 部署配置</text>
<text x="584" y="462" class="detail">PostgreSQL Variables</text>
<text x="584" y="481" class="detail">和密码 Secret</text>
<rect x="84" y="497" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="526" class="code">render-postgres.py</text>
<text x="104" y="547" class="detail">由 release.sh 调用,生成权限为 0600 的 bedrock.json。</text>
<rect x="84" y="580" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="609" class="headline">release.sh 启动临时容器</text>
<text x="104" y="630" class="detail">挂载二进制和配置,运行 Rust bedrock。</text>
<rect x="84" y="663" width="452" height="77" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
<path d="M93 675v53" stroke="#8bac94" stroke-width="2" stroke-linecap="round"/>
<text x="104" y="692" class="headline">Rust Bedrock 读取配置</text>
<text x="104" y="713" class="detail">通过 db::connect 选择 postgres。</text>
<text x="104" y="732" class="detail">配置由 BEDROCK_DB_CONFIG 指定。</text>
<rect x="84" y="821" width="452" height="75" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
<text x="104" y="847" class="headline">在已有 PostgreSQL 数据库内初始化</text>
<text x="104" y="869" class="detail">postgres.rs 提供 SQL,common.rs 在事务里执行。</text>
<text x="104" y="887" class="detail">创建 Bedrock 表并登记 production 部署。</text>
<text x="328" y="787" class="detail">进入 Store::initialize()</text>
<text x="118" y="909" class="result">成功</text>
<text x="614" y="909" class="result failed">失败</text>
<rect x="84" y="919" width="280" height="32" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
<path d="M93 931v8" stroke="#8bac94" stroke-width="2" stroke-linecap="round"/>
<text x="104" y="941.0" class="headline">保存版本并切换 current</text>
<rect x="401" y="919" width="348" height="32" rx="9" fill="#f7eee6" stroke="#d4b7a6"/>
<text x="421" y="941.0" class="headline">清理暂存目录,保留上一版 current</text>
<rect x="813" y="171" width="292" height="44" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="833" y="199.0" class="headline">手动运行</text>
<rect x="813" y="235" width="292" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="833" y="264" class="code">ci/check-sql.sh</text>
<text x="833" y="285" class="detail">脚本独立于部署工作流。</text>
<rect x="813" y="318" width="292" height="78" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="833" y="347" class="headline">准备隔离环境</text>
<text x="833" y="368" class="detail">启动临时 PostgreSQL 和 MySQL。</text>
<text x="833" y="387" class="detail">SQLite 使用临时本地文件。</text>
<rect x="813" y="416" width="292" height="78" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="833" y="445" class="headline">运行三库检查</text>
<text x="833" y="466" class="detail">执行格式检查、测试、构建,</text>
<text x="833" y="485" class="detail">验证 SQLite 默认启动。</text>
<rect x="813" y="522" width="292" height="63" rx="9" fill="#edf1e8" stroke="#c1ccbf"/>
<text x="833" y="551" class="headline">退出时清理</text>
<text x="833" y="572" class="detail">删除测试容器和临时网络。</text>
</svg>

After

Width:  |  Height:  |  Size: 7.4 KiB

+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
output="$PWD/target/bedrock-release"
mkdir -p "$output"
docker run --rm \
--mount "type=bind,source=$PWD,target=/work,readonly" \
--mount "type=bind,source=$output,target=/out" \
-w /work -e CARGO_TARGET_DIR=/tmp/bedrock-target \
rust:1.91.1-bookworm sh -ec '
cargo build --locked --release --bin bedrock
install -m 755 /tmp/bedrock-target/release/bedrock /out/bedrock
'
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
binary=${1:?Path to the built Bedrock executable is required}
revision=${2:?Git commit is required}
if [[ ! $revision =~ ^[0-9a-f]{40}$ || ! -x $binary ]]; then
printf 'Invalid release commit or executable\n' >&2
exit 1
fi
infra=/opt/endoleap-infra
root=$infra/bedrock-rust
network=endoleap-dev_default
test -d "$infra"
test ! -L "$root"
docker network inspect "$network" >/dev/null
install -d -m 700 "$root/releases"
stage=$(mktemp -d "$root/releases/.staging.XXXXXXXX")
cleanup() { rm -rf -- "$stage"; }
trap cleanup EXIT
install -m 755 "$binary" "$stage/bedrock"
python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.json" --deployment production
# The current binary is a one-shot storage initializer. It publishes no ports.
docker run --rm --network "$network" \
--user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \
--mount "type=bind,source=$stage,target=/release,readonly" \
-e BEDROCK_DB_CONFIG=/release/bedrock.json \
debian:bookworm-slim /release/bedrock
release="$revision.${stage##*.}"
# Keep the final release private; only switch current after initialization succeeds.
python3 - "$stage" "$root" "$release" <<'PY'
import os
from pathlib import Path
import sys
import tempfile
stage, root, release = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3]
destination = Path("releases") / release
stage.rename(root / destination)
with tempfile.TemporaryDirectory(prefix=".activate.", dir=root) as activation:
link = Path(activation) / "current"
link.symlink_to(destination)
os.replace(link, root / "current")
PY
printf 'Published Bedrock Rust release %s\n' "$release"
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Render the private Bedrock PostgreSQL config at deploy time."""
import argparse
import ipaddress
import json
import os
from pathlib import Path
import re
import tempfile
from urllib.parse import quote
def required(variable):
value = os.environ.get(variable)
if not value:
raise SystemExit(f"Missing {variable}")
return value
def database_url():
host = required("BEDROCK_PG_HOST").removeprefix("[").removesuffix("]")
if ":" in host:
try:
host = f"[{ipaddress.IPv6Address(host)}]"
except ValueError:
raise SystemExit("Invalid BEDROCK_PG_HOST") from None
elif not re.fullmatch(r"[A-Za-z0-9.-]+", host):
raise SystemExit("Invalid BEDROCK_PG_HOST")
try:
port = int(required("BEDROCK_PG_PORT"))
if not 1 <= port <= 65535:
raise ValueError
except ValueError:
raise SystemExit("Invalid BEDROCK_PG_PORT") from None
user = quote(required("BEDROCK_PG_USER"), safe="")
password = quote(required("BEDROCK_PG_PASSWORD"), safe="")
database = quote(required("BEDROCK_PG_DATABASE"), safe="")
return f"postgres://{user}:{password}@{host}:{port}/{database}"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path)
parser.add_argument("--deployment", default="default")
options = parser.parse_args()
if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment):
parser.error("invalid deployment name")
config = {
"deployment": options.deployment,
"cluster": "postgres",
"clusters": {
"postgres": {
"driver": "postgres",
"primary": database_url(),
}
},
}
# Write with owner-only permissions, then replace the destination atomically.
file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False)
try:
with file:
json.dump(config, file, indent=2)
file.write("\n")
os.replace(file.name, options.output)
finally:
Path(file.name).unlink(missing_ok=True)
if __name__ == "__main__":
main()
+4
View File
@@ -0,0 +1,4 @@
{
"deployment": "default",
"sqlite_path": "bedrock.sqlite3"
}
+18 -2
View File
@@ -1,3 +1,19 @@
fn main() { use std::{env, error::Error, fs};
println!("Hello, world!");
use db::{DeploymentConfig, connect};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?,
None => DeploymentConfig::default(),
};
let db = connect(&config).await?;
println!(
"Bedrock storage ready ({:?}, revision {}, read-only: {})",
db.driver(),
db.revision().await?,
db.is_read_only()
);
Ok(())
} }