From af9f25baa56a08f6cfd9eeb9bd154779cf4a9a74 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 20:23:23 +0800 Subject: [PATCH 1/2] Move storage initialization into the backend executable --- Cargo.lock | 10 +------ Cargo.toml | 11 ------- README.md | 4 +-- ci/README.md | 4 +-- ci/check-sql.sh | 2 +- crates/backend/Cargo.toml | 1 + crates/backend/src/main.rs | 54 +++++++++++++++++++++++++++++++---- deploy/README.md | 10 +++---- deploy/gitea/build-release.sh | 4 +-- deploy/gitea/release.sh | 4 +-- src/main.rs | 34 ---------------------- 11 files changed, 64 insertions(+), 74 deletions(-) delete mode 100644 src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 7cc76ca..8d11f44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -146,6 +146,7 @@ version = "0.1.0" dependencies = [ "admin_backend", "axum", + "clusters", "db", "tokio", ] @@ -162,15 +163,6 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" -[[package]] -name = "bedrock" -version = "0.1.0" -dependencies = [ - "clusters", - "db", - "tokio", -] - [[package]] name = "bitflags" version = "2.13.2" diff --git a/Cargo.toml b/Cargo.toml index 909afb6..d9dc6c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,14 +29,3 @@ tokio-postgres-rustls = { version = "0.13", default-features = false } tokio-rusqlite = "0.6" url = "2" webpki-roots = "1" - -[package] -name = "bedrock" -version = "0.1.0" -edition.workspace = true -rust-version.workspace = true - -[dependencies] -clusters.workspace = true -db.workspace = true -tokio.workspace = true diff --git a/README.md b/README.md index 4b9a7f9..3ac5b1d 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ mode, and the loaded configuration version for the instance that served the request. `BEDROCK_CONFIG_VERSION` can override the reported version label. The admin router reads the same resolved configuration the process used to open the database. Give every replica the same config file and version label through your -deployment process. The root `bedrock` binary remains the one-shot storage -initializer. +deployment process. Run `cargo run --locked -p backend -- --init-storage` for one-shot storage +initialization. The release process uses the same mode. ## Database configuration diff --git a/ci/README.md b/ci/README.md index ed0eac5..f752d0c 100644 --- a/ci/README.md +++ b/ci/README.md @@ -7,13 +7,13 @@ ```mermaid flowchart TD M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] - W --> B["build-release.sh 编译发布版"] + W --> B["build-release.sh 编译 backend 发布版"] B -->|Bedrock 二进制和 Git SHA| R E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P subgraph release["release.sh"] R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"] - P -->|配置就绪| I["启动临时容器,由 Bedrock 初始化 PostgreSQL"] + P -->|配置就绪| I["临时容器运行 backend 的 --init-storage,初始化 PostgreSQL"] I -->|成功| S["保存版本并原子切换 current"] P -->|失败| F["清理暂存目录,保留现有 current"] I -->|失败| F diff --git a/ci/check-sql.sh b/ci/check-sql.sh index 192fe6d..5aab154 100644 --- a/ci/check-sql.sh +++ b/ci/check-sql.sh @@ -44,6 +44,6 @@ docker run --rm --name "$prefix-rust" --network "$prefix" \ cargo test --locked --workspace cargo build --locked --workspace cd "$(mktemp -d)" - /tmp/bedrock-target/debug/bedrock + BEDROCK_BACKEND_LISTEN=invalid /tmp/bedrock-target/debug/backend --init-storage test -f bedrock.sqlite3 ' diff --git a/crates/backend/Cargo.toml b/crates/backend/Cargo.toml index d8c5411..71e0e89 100644 --- a/crates/backend/Cargo.toml +++ b/crates/backend/Cargo.toml @@ -7,5 +7,6 @@ rust-version.workspace = true [dependencies] admin_backend = { path = "../admin_backend" } axum.workspace = true +clusters.workspace = true db.workspace = true tokio = { workspace = true, features = ["net", "signal", "sync", "time"] } diff --git a/crates/backend/src/main.rs b/crates/backend/src/main.rs index 6dfc998..0e18b80 100644 --- a/crates/backend/src/main.rs +++ b/crates/backend/src/main.rs @@ -1,20 +1,38 @@ use std::{env, error::Error, io, net::SocketAddr, sync::Arc}; use axum::Router; -use db::{DeploymentConfig, connect_resolved}; +use clusters::{DOCUMENTS, DeploymentConfig, ResolvedDeployment}; +use db::{ConnectError, connect_resolved, connect_sql}; use tokio::{net::TcpListener, sync::watch}; #[tokio::main] async fn main() -> Result<(), Box> { + let mut args = env::args_os().skip(1); + let init_storage = match (args.next(), args.next()) { + (None, None) => false, + (Some(arg), None) if arg == "--init-storage" => true, + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "expected no arguments or --init-storage", + ) + .into()); + } + }; + let config = match env::var_os("BEDROCK_DB_CONFIG") { + Some(path) => DeploymentConfig::load(path)?, + None => DeploymentConfig::default(), + } + .resolve()?; + if init_storage { + return initialize_storage(&config).await; + } + let address: SocketAddr = optional_env("BEDROCK_BACKEND_LISTEN")? .as_deref() .unwrap_or("127.0.0.1:8080") .parse()?; - let config = match env::var_os("BEDROCK_DB_CONFIG") { - Some(path) => DeploymentConfig::load(path)?, - None => DeploymentConfig::default(), - }; - let config = Arc::new(config.resolve()?); + let config = Arc::new(config); let admin_address = optional_env("BEDROCK_ADMIN_LISTEN")?; let admin = match optional_env("BEDROCK_ADMIN_TOKEN")? { @@ -62,6 +80,30 @@ async fn main() -> Result<(), Box> { Ok(()) } +async fn initialize_storage(resolved: &ResolvedDeployment) -> Result<(), Box> { + if resolved + .binding(DOCUMENTS) + .is_some_and(|resource| resource.as_sql().is_none()) + { + return Err(ConnectError::InvalidDocuments.into()); + } + for (role, resource) in resolved.bound_resources() { + let Some(settings) = resource.as_sql() else { + continue; + }; + let connection = connect_sql(settings).await?; + println!( + "Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})", + resolved.config_version, + role, + connection.driver(), + connection.revision().await?, + connection.is_read_only(), + ); + } + Ok(()) +} + fn optional_env(name: &str) -> Result, env::VarError> { match env::var(name) { Ok(value) => Ok(Some(value)), diff --git a/deploy/README.md b/deploy/README.md index b2ca387..32567f5 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -10,11 +10,11 @@ Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. The loader also a ## Local SQLite -Bedrock defaults to `bedrock.sqlite3` in the working directory. To choose another path, set `BEDROCK_DB_CONFIG` to a [SQLite configuration](local/sqlite.yaml) and set the resource's `primary` to a persistent, writable path. +Run `backend --init-storage` to initialize storage once. Bedrock defaults to `bedrock.sqlite3` in the working directory. To choose another path, set `BEDROCK_DB_CONFIG` to a [SQLite configuration](local/sqlite.yaml) and set the resource's `primary` to a persistent, writable path. ```mermaid flowchart TD - A["在本机启动 Bedrock"] --> B{"是否设置 BEDROCK_DB_CONFIG"} + A["在本机运行 backend --init-storage"] --> B{"是否设置 BEDROCK_DB_CONFIG"} B -->|是| C["读取指定的 SQLite 配置,取得文件路径"] B -->|否| D["使用工作目录下的 bedrock.sqlite3"] C --> E["打开或创建 SQLite 文件"] @@ -26,18 +26,18 @@ flowchart TD PostgreSQL on the existing host uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/gitea/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. -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. +Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs `backend --init-storage` through the published `bedrock` executable 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. ```mermaid flowchart TD M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] - W --> B["build-release.sh 编译发布版"] + W --> B["build-release.sh 编译 backend 发布版"] B -->|Bedrock 二进制和 Git SHA| R E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P subgraph release["release.sh"] R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"] - P -->|配置就绪| I["启动临时容器,由 Bedrock 初始化 PostgreSQL"] + P -->|配置就绪| I["临时容器运行 backend 的 --init-storage,初始化 PostgreSQL"] I -->|成功| S["保存版本并原子切换 current"] P -->|失败| F["清理暂存目录,保留现有 current"] I -->|失败| F diff --git a/deploy/gitea/build-release.sh b/deploy/gitea/build-release.sh index 546f0eb..c1621ab 100644 --- a/deploy/gitea/build-release.sh +++ b/deploy/gitea/build-release.sh @@ -8,6 +8,6 @@ docker run --rm \ --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 + cargo build --locked --release -p backend + install -m 755 /tmp/bedrock-target/release/backend /out/bedrock ' diff --git a/deploy/gitea/release.sh b/deploy/gitea/release.sh index e88606a..2df87a4 100644 --- a/deploy/gitea/release.sh +++ b/deploy/gitea/release.sh @@ -25,12 +25,12 @@ release="$revision.${stage##*.}" python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.yaml" \ --deployment production --config-version "$release" -# The current binary is a one-shot storage initializer. It publishes no ports. +# Run storage initialization as a one-shot command in the release container. 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.yaml \ - debian:bookworm-slim /release/bedrock + debian:bookworm-slim /release/bedrock --init-storage # Keep the final release private; only switch current after initialization succeeds. python3 - "$stage" "$root" "$release" <<'PY' diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index d8f4cce..0000000 --- a/src/main.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::{env, error::Error}; - -use clusters::{DOCUMENTS, DeploymentConfig}; -use db::connect_sql; - -#[tokio::main] -async fn main() -> Result<(), Box> { - let config = match env::var_os("BEDROCK_DB_CONFIG") { - Some(path) => DeploymentConfig::load(path)?, - None => DeploymentConfig::default(), - }; - let resolved = config.resolve()?; - if resolved - .binding(DOCUMENTS) - .is_some_and(|resource| resource.as_sql().is_none()) - { - return Err(db::ConnectError::InvalidDocuments.into()); - } - for (role, resource) in resolved.bound_resources() { - let Some(settings) = resource.as_sql() else { - continue; - }; - let connection = connect_sql(settings).await?; - println!( - "Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})", - resolved.config_version, - role, - connection.driver(), - connection.revision().await?, - connection.is_read_only(), - ); - } - Ok(()) -} From f0470c406b801a1f824a0b9a343a3ea5f8123097 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 20:23:47 +0800 Subject: [PATCH 2/2] Rename the db crate to database --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- README.md | 6 +++--- crates/backend/Cargo.toml | 2 +- crates/backend/src/lib.rs | 4 ++-- crates/backend/src/main.rs | 2 +- crates/{db => database}/Cargo.toml | 2 +- crates/{db => database}/src/common.rs | 0 crates/{db => database}/src/connection.rs | 0 crates/{db => database}/src/documents.rs | 0 crates/{db => database}/src/lib.rs | 0 crates/{db => database}/src/mysql.rs | 0 crates/{db => database}/src/postgres.rs | 0 crates/{db => database}/src/sqlite.rs | 0 crates/{db => database}/tests/storage.rs | 2 +- crates/{db => database}/tests/workspace_documents.rs | 4 +++- 16 files changed, 15 insertions(+), 13 deletions(-) rename crates/{db => database}/Cargo.toml (97%) rename crates/{db => database}/src/common.rs (100%) rename crates/{db => database}/src/connection.rs (100%) rename crates/{db => database}/src/documents.rs (100%) rename crates/{db => database}/src/lib.rs (100%) rename crates/{db => database}/src/mysql.rs (100%) rename crates/{db => database}/src/postgres.rs (100%) rename crates/{db => database}/src/sqlite.rs (100%) rename crates/{db => database}/tests/storage.rs (99%) rename crates/{db => database}/tests/workspace_documents.rs (97%) diff --git a/Cargo.lock b/Cargo.lock index 8d11f44..e63f0ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -147,7 +147,7 @@ dependencies = [ "admin_backend", "axum", "clusters", - "db", + "database", "tokio", ] @@ -357,7 +357,7 @@ dependencies = [ ] [[package]] -name = "db" +name = "database" version = "0.1.0" dependencies = [ "clusters", diff --git a/Cargo.toml b/Cargo.toml index d9dc6c7..f1b2a97 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ rust-version = "1.91" [workspace.dependencies] axum = { version = "0.8", default-features = false, features = ["http1", "json", "tokio"] } clusters = { path = "crates/clusters" } -db = { path = "crates/db" } +database = { path = "crates/database" } documents = { path = "crates/documents" } deadpool-postgres = "0.14.1" mysql_async = { version = "0.36.1", default-features = false, features = ["minimal-rust", "ring", "rustls-tls", "tls12"] } diff --git a/README.md b/README.md index 3ac5b1d..e63744f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # 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. +Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `database` 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 document types, validation, and encoding in `common.rs`. +`database` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `database` connection module selects the SQL driver and read endpoints. The backend modules share document types, validation, and encoding in `common.rs`. Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock supports named SQL roles and read replicas. The catalog can describe S3 buckets. Object I/O, workspace routing, 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) @@ -40,7 +40,7 @@ Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [mul 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 SQL resource's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. For SQLite, set the resource's `primary` to the file path. -Applications use `db::connect` for the documents role or `db::connect_sql` for an explicitly resolved SQL role. 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. +Applications use `database::connect` for the documents role or `database::connect_sql` for an explicitly resolved SQL role. 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. diff --git a/crates/backend/Cargo.toml b/crates/backend/Cargo.toml index 71e0e89..fd768ab 100644 --- a/crates/backend/Cargo.toml +++ b/crates/backend/Cargo.toml @@ -8,5 +8,5 @@ rust-version.workspace = true admin_backend = { path = "../admin_backend" } axum.workspace = true clusters.workspace = true -db.workspace = true +database.workspace = true tokio = { workspace = true, features = ["net", "signal", "sync", "time"] } diff --git a/crates/backend/src/lib.rs b/crates/backend/src/lib.rs index 1adda8c..c624316 100644 --- a/crates/backend/src/lib.rs +++ b/crates/backend/src/lib.rs @@ -2,14 +2,14 @@ use std::{sync::Arc, time::Duration}; use axum::{Router, extract::State, http::StatusCode, routing::get}; -pub fn router(db: db::Connection) -> Router { +pub fn router(db: database::Connection) -> Router { Router::new() .route("/healthz", get(|| async { StatusCode::NO_CONTENT })) .route("/readyz", get(readiness)) .with_state(Arc::new(db)) } -async fn readiness(State(db): State>) -> StatusCode { +async fn readiness(State(db): State>) -> StatusCode { match tokio::time::timeout(Duration::from_secs(2), db.revision()).await { Ok(Ok(_)) => StatusCode::NO_CONTENT, _ => StatusCode::SERVICE_UNAVAILABLE, diff --git a/crates/backend/src/main.rs b/crates/backend/src/main.rs index 0e18b80..86a6869 100644 --- a/crates/backend/src/main.rs +++ b/crates/backend/src/main.rs @@ -2,7 +2,7 @@ use std::{env, error::Error, io, net::SocketAddr, sync::Arc}; use axum::Router; use clusters::{DOCUMENTS, DeploymentConfig, ResolvedDeployment}; -use db::{ConnectError, connect_resolved, connect_sql}; +use database::{ConnectError, connect_resolved, connect_sql}; use tokio::{net::TcpListener, sync::watch}; #[tokio::main] diff --git a/crates/db/Cargo.toml b/crates/database/Cargo.toml similarity index 97% rename from crates/db/Cargo.toml rename to crates/database/Cargo.toml index 2422574..92e1a4d 100644 --- a/crates/db/Cargo.toml +++ b/crates/database/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "db" +name = "database" version = "0.1.0" edition.workspace = true rust-version.workspace = true diff --git a/crates/db/src/common.rs b/crates/database/src/common.rs similarity index 100% rename from crates/db/src/common.rs rename to crates/database/src/common.rs diff --git a/crates/db/src/connection.rs b/crates/database/src/connection.rs similarity index 100% rename from crates/db/src/connection.rs rename to crates/database/src/connection.rs diff --git a/crates/db/src/documents.rs b/crates/database/src/documents.rs similarity index 100% rename from crates/db/src/documents.rs rename to crates/database/src/documents.rs diff --git a/crates/db/src/lib.rs b/crates/database/src/lib.rs similarity index 100% rename from crates/db/src/lib.rs rename to crates/database/src/lib.rs diff --git a/crates/db/src/mysql.rs b/crates/database/src/mysql.rs similarity index 100% rename from crates/db/src/mysql.rs rename to crates/database/src/mysql.rs diff --git a/crates/db/src/postgres.rs b/crates/database/src/postgres.rs similarity index 100% rename from crates/db/src/postgres.rs rename to crates/database/src/postgres.rs diff --git a/crates/db/src/sqlite.rs b/crates/database/src/sqlite.rs similarity index 100% rename from crates/db/src/sqlite.rs rename to crates/database/src/sqlite.rs diff --git a/crates/db/tests/storage.rs b/crates/database/tests/storage.rs similarity index 99% rename from crates/db/tests/storage.rs rename to crates/database/tests/storage.rs index 8c138ae..e4a40cd 100644 --- a/crates/db/tests/storage.rs +++ b/crates/database/tests/storage.rs @@ -1,6 +1,6 @@ use std::{collections::BTreeMap, env, time::Duration}; -use db::{ +use database::{ Connection, DeploymentConfig, Driver, Mutation, ReadPreference, Resource, SqlCluster, StorageError, Tls, connect, }; diff --git a/crates/db/tests/workspace_documents.rs b/crates/database/tests/workspace_documents.rs similarity index 97% rename from crates/db/tests/workspace_documents.rs rename to crates/database/tests/workspace_documents.rs index d0e873f..02f19ac 100644 --- a/crates/db/tests/workspace_documents.rs +++ b/crates/database/tests/workspace_documents.rs @@ -1,6 +1,8 @@ use std::{collections::BTreeMap, path::Path}; -use db::{DeploymentConfig, Driver, Mutation, Resource, SqlCluster, StorageError, Tls, connect}; +use database::{ + DeploymentConfig, Driver, Mutation, Resource, SqlCluster, StorageError, Tls, connect, +}; use documents::{ Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, WorkspaceId, };