From b64a88011f9dfc3c29ce0662fba1dd12b3907fb6 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:41:20 +0800 Subject: [PATCH 1/7] Add a workspace document model and SQL storage adapter --- Cargo.lock | 9 ++++ Cargo.toml | 1 + crates/db/Cargo.toml | 1 + crates/db/src/common.rs | 2 + crates/db/src/lib.rs | 2 + crates/db/src/workspace_documents.rs | 68 ++++++++++++++++++++++++++ crates/db/tests/workspace_documents.rs | 56 +++++++++++++++++++++ crates/documents/Cargo.toml | 9 ++++ crates/documents/src/lib.rs | 66 +++++++++++++++++++++++++ 9 files changed, 214 insertions(+) create mode 100644 crates/db/src/workspace_documents.rs create mode 100644 crates/db/tests/workspace_documents.rs create mode 100644 crates/documents/Cargo.toml create mode 100644 crates/documents/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index a2ca10a..1230dfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -159,6 +159,7 @@ name = "db" version = "0.1.0" dependencies = [ "clusters", + "documents", "serde_json", "sqlx", "tempfile", @@ -200,6 +201,14 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "documents" +version = "0.1.0" +dependencies = [ + "serde_json", + "thiserror", +] + [[package]] name = "dotenvy" version = "0.15.7" diff --git a/Cargo.toml b/Cargo.toml index 08da929..5f53285 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ rust-version = "1.91" [workspace.dependencies] clusters = { path = "crates/clusters" } db = { path = "crates/db" } +documents = { path = "crates/documents" } serde = { version = "1", features = ["derive"] } serde_json = "1" sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] } diff --git a/crates/db/Cargo.toml b/crates/db/Cargo.toml index 9717099..8eae459 100644 --- a/crates/db/Cargo.toml +++ b/crates/db/Cargo.toml @@ -6,6 +6,7 @@ rust-version.workspace = true [dependencies] clusters.workspace = true +documents.workspace = true serde_json.workspace = true sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } thiserror.workspace = true diff --git a/crates/db/src/common.rs b/crates/db/src/common.rs index ca2c37c..f80e13d 100644 --- a/crates/db/src/common.rs +++ b/crates/db/src/common.rs @@ -30,6 +30,8 @@ pub enum Error { }, #[error("the write conflicts with the current revision or lease")] WriteConflict, + #[error("the workspace document already exists")] + DocumentAlreadyExists, #[error("lease is missing, expired, or belongs to another store")] LeaseLost, } diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 4253f53..bd48c64 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -5,10 +5,12 @@ mod connection; pub mod mysql; pub mod postgres; pub mod sqlite; +mod workspace_documents; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; pub use connection::{ConnectError, Connection, ReadPreference, connect}; pub use mysql::{Lease, MySql}; +pub use workspace_documents::StoredDocument; pub use common::Error as StorageError; pub use common::{ diff --git a/crates/db/src/workspace_documents.rs b/crates/db/src/workspace_documents.rs new file mode 100644 index 0000000..81362b5 --- /dev/null +++ b/crates/db/src/workspace_documents.rs @@ -0,0 +1,68 @@ +//! Maps workspace documents onto the versioned SQL store. +//! +//! Within a deployment, the workspace selects a reserved collection prefix plus its ID. +//! The document ID becomes the row key in that collection, and the body is JSON. + +use documents::{Document, DocumentKey}; + +use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError}; + +// This collection namespace belongs to the workspace-document adapter. +const COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v1:"; + +/// A logical document and the deployment revision at which it was last written. +#[derive(Debug, PartialEq)] +pub struct StoredDocument { + pub document: Document, + pub revision: Revision, +} + +impl Connection { + /// Creates a document using the primary snapshot and its expected revision. + pub async fn create_document(&self, document: Document) -> Result { + if self.is_read_only() { + return Err(StorageError::ReadOnly); + } + let collection = collection(&document.key); + let id = document.key.document.as_str(); + let snapshot = self + .get(&collection, id, None, ReadPreference::Primary) + .await?; + if snapshot.document.is_some() { + return Err(StorageError::DocumentAlreadyExists); + } + + self.commit( + snapshot.revision, + &[Mutation { + collection, + id: id.to_owned(), + value: Some(document.body), + }], + ) + .await + } + + /// Reads the latest state of a workspace document from the primary. + pub async fn get_document(&self, key: &DocumentKey) -> Result> { + let snapshot = self + .get( + &collection(key), + key.document.as_str(), + None, + ReadPreference::Primary, + ) + .await?; + Ok(snapshot.document.map(|stored| StoredDocument { + document: Document { + key: key.clone(), + body: stored.value, + }, + revision: stored.revision, + })) + } +} + +fn collection(key: &DocumentKey) -> String { + format!("{COLLECTION_PREFIX}{}", key.workspace.as_str()) +} diff --git a/crates/db/tests/workspace_documents.rs b/crates/db/tests/workspace_documents.rs new file mode 100644 index 0000000..e603a03 --- /dev/null +++ b/crates/db/tests/workspace_documents.rs @@ -0,0 +1,56 @@ +use db::{DeploymentConfig, StorageError, connect}; +use documents::{Document, DocumentId, DocumentKey, WorkspaceId}; +use serde_json::json; + +fn document(workspace: &str, body: serde_json::Value) -> Document { + Document { + key: DocumentKey { + workspace: WorkspaceId::new(workspace).unwrap(), + document: DocumentId::new("same-id").unwrap(), + }, + body, + } +} + +#[tokio::test] +async fn workspace_documents_keep_their_identity_and_contents_after_reopen() { + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("documents.sqlite3"); + let mut config = DeploymentConfig { + sqlite_path: path.to_str().unwrap().into(), + ..DeploymentConfig::default() + }; + let connection = connect(&config).await.unwrap(); + let first = document( + &"w".repeat(WorkspaceId::MAX_BYTES), + json!({"title": "notes"}), + ); + let second = document("other-workspace", json!(null)); + + assert!(connection.get_document(&first.key).await.unwrap().is_none()); + let first_revision = connection.create_document(first.clone()).await.unwrap(); + let second_revision = connection.create_document(second.clone()).await.unwrap(); + assert!(second_revision > first_revision); + assert!(matches!( + connection + .create_document(document(first.key.workspace.as_str(), json!("overwrite"))) + .await, + Err(StorageError::DocumentAlreadyExists) + )); + drop(connection); + + config.read_only = true; + let connection = connect(&config).await.unwrap(); + let read = connection.get_document(&first.key).await.unwrap().unwrap(); + assert_eq!(read.document, first); + assert_eq!(read.revision, first_revision); + let read = connection.get_document(&second.key).await.unwrap().unwrap(); + assert_eq!(read.document, second); + assert_eq!(read.revision, second_revision); + assert!(matches!( + connection + .create_document(document("third-workspace", json!(null))) + .await, + Err(StorageError::ReadOnly) + )); +} diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.toml new file mode 100644 index 0000000..e8d48fd --- /dev/null +++ b/crates/documents/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "documents" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +serde_json.workspace = true +thiserror.workspace = true diff --git a/crates/documents/src/lib.rs b/crates/documents/src/lib.rs new file mode 100644 index 0000000..2b2329b --- /dev/null +++ b/crates/documents/src/lib.rs @@ -0,0 +1,66 @@ +//! Workspace document identities and contents. + +use serde_json::Value; +use thiserror::Error; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum IdError { + #[error("a workspace ID must contain 1–96 bytes and no NUL")] + Workspace, + #[error("a document ID must contain 1–128 bytes and no NUL")] + Document, +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct WorkspaceId(String); + +impl WorkspaceId { + pub const MAX_BYTES: usize = 96; + + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate_id(&value, Self::MAX_BYTES, IdError::Workspace)?; + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct DocumentId(String); + +impl DocumentId { + pub const MAX_BYTES: usize = 128; + + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate_id(&value, Self::MAX_BYTES, IdError::Document)?; + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A document ID identifies a document within its workspace. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct DocumentKey { + pub workspace: WorkspaceId, + pub document: DocumentId, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Document { + pub key: DocumentKey, + pub body: Value, +} + +fn validate_id(value: &str, max_bytes: usize, error: IdError) -> Result<(), IdError> { + if value.is_empty() || value.len() > max_bytes || value.contains('\0') { + return Err(error); + } + Ok(()) +} From deb535c2560bcb01a4eeff682ef6551212a91dd0 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:48:50 +0800 Subject: [PATCH 2/7] Shorten the SQL document adapter module name --- crates/db/src/{workspace_documents.rs => documents.rs} | 2 +- crates/db/src/lib.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) rename crates/db/src/{workspace_documents.rs => documents.rs} (98%) diff --git a/crates/db/src/workspace_documents.rs b/crates/db/src/documents.rs similarity index 98% rename from crates/db/src/workspace_documents.rs rename to crates/db/src/documents.rs index 81362b5..c8c607b 100644 --- a/crates/db/src/workspace_documents.rs +++ b/crates/db/src/documents.rs @@ -3,7 +3,7 @@ //! Within a deployment, the workspace selects a reserved collection prefix plus its ID. //! The document ID becomes the row key in that collection, and the body is JSON. -use documents::{Document, DocumentKey}; +use ::documents::{Document, DocumentKey}; use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError}; diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index bd48c64..4acbd5f 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -2,15 +2,15 @@ mod common; mod connection; +mod documents; pub mod mysql; pub mod postgres; pub mod sqlite; -mod workspace_documents; +pub use self::documents::StoredDocument; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; pub use connection::{ConnectError, Connection, ReadPreference, connect}; pub use mysql::{Lease, MySql}; -pub use workspace_documents::StoredDocument; pub use common::Error as StorageError; pub use common::{ From 296fb9b1b72800002d47880cb773a059d3de4aa9 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:02:10 +0800 Subject: [PATCH 3/7] Add initial Axum application and admin backends --- Cargo.lock | 222 +++++++++++++++++++++++++++++++ Cargo.toml | 2 + README.md | 22 +++ crates/admin_backend/Cargo.toml | 13 ++ crates/admin_backend/src/lib.rs | 87 ++++++++++++ crates/admin_backend/src/main.rs | 50 +++++++ crates/backend/Cargo.toml | 11 ++ crates/backend/src/lib.rs | 17 +++ crates/backend/src/main.rs | 41 ++++++ 9 files changed, 465 insertions(+) create mode 100644 crates/admin_backend/Cargo.toml create mode 100644 crates/admin_backend/src/lib.rs create mode 100644 crates/admin_backend/src/main.rs create mode 100644 crates/backend/Cargo.toml create mode 100644 crates/backend/src/lib.rs create mode 100644 crates/backend/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index a2ca10a..7f45856 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,18 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "admin_backend" +version = "0.1.0" +dependencies = [ + "axum", + "clusters", + "serde", + "serde_json", + "subtle", + "tokio", +] + [[package]] name = "allocator-api2" version = "0.2.22" @@ -17,12 +29,76 @@ dependencies = [ "num-traits", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "backend" +version = "0.1.0" +dependencies = [ + "axum", + "db", + "serde_json", + "tokio", +] + [[package]] name = "base64" version = "0.22.1" @@ -458,6 +534,85 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + [[package]] name = "icu_collections" version = "2.4.0" @@ -649,6 +804,12 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "md-5" version = "0.10.6" @@ -665,6 +826,12 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "mio" version = "1.2.5" @@ -1036,6 +1203,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1076,6 +1254,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "signature" version = "2.2.0" @@ -1365,6 +1553,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + [[package]] name = "synstructure" version = "0.14.0" @@ -1435,6 +1629,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", @@ -1462,6 +1657,33 @@ dependencies = [ "tokio", ] +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.44" diff --git a/Cargo.toml b/Cargo.toml index 08da929..f17d4a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,11 +7,13 @@ edition = "2024" 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" } serde = { version = "1", features = ["derive"] } serde_json = "1" sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] } +subtle = "2" tempfile = "3" thiserror = "2" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } diff --git a/README.md b/README.md index 37bbfcd..cdde64b 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,28 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i 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) +## Web backends + +The workspace has two independently started Axum services. Run the packages +with `cargo run --locked -p backend` and `cargo run --locked -p admin_backend` +in a development environment. + +| Package | Listen setting and default | Routes | +|---|---|---| +| `backend` | `BEDROCK_BACKEND_LISTEN`, default `127.0.0.1:8080` | `GET /healthz`, `GET /readyz` | +| `admin_backend` | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status` | + +Both services use the `BEDROCK_DB_CONFIG` setting described below. The business +service opens storage at startup and verifies access to the current deployment +revision in its readiness handler. The admin service resolves the deployment +configuration at startup. Its status endpoint reports the configured deployment, +storage driver, read-only mode, and optional `BEDROCK_CONFIG_VERSION`. + +Set `BEDROCK_ADMIN_TOKEN` from a private credential source before starting +`admin_backend`. Send it as `Authorization: Bearer ` for the status +endpoint. Keep the admin listener on loopback or behind an internal TLS endpoint. +The root `bedrock` binary remains the one-shot storage initializer. + ## Database configuration Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example: diff --git a/crates/admin_backend/Cargo.toml b/crates/admin_backend/Cargo.toml new file mode 100644 index 0000000..3dbe1b3 --- /dev/null +++ b/crates/admin_backend/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "admin_backend" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +axum.workspace = true +clusters.workspace = true +serde.workspace = true +serde_json.workspace = true +subtle.workspace = true +tokio = { workspace = true, features = ["net", "signal"] } diff --git a/crates/admin_backend/src/lib.rs b/crates/admin_backend/src/lib.rs new file mode 100644 index 0000000..70b9655 --- /dev/null +++ b/crates/admin_backend/src/lib.rs @@ -0,0 +1,87 @@ +use std::{io, sync::Arc}; + +use axum::{ + Json, Router, + extract::{Request, State}, + http::{HeaderMap, StatusCode, header}, + middleware::{self, Next}, + response::{IntoResponse, Response}, + routing::get, +}; +use clusters::{Driver, ResolvedDeployment}; +use serde::Serialize; +use subtle::ConstantTimeEq; + +#[derive(Clone, Serialize)] +pub struct DeploymentStatus { + deployment: String, + config_version: Option, + storage_driver: &'static str, + read_only: bool, +} + +impl DeploymentStatus { + pub fn new(config: ResolvedDeployment, config_version: Option) -> Self { + Self { + deployment: config.deployment, + config_version, + storage_driver: match config.driver { + Driver::Sqlite => "sqlite", + Driver::Postgres => "postgres", + Driver::Mysql => "mysql", + }, + read_only: config.read_only, + } + } +} + +pub fn router(status: DeploymentStatus, token: String) -> io::Result { + if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_graphic()) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "BEDROCK_ADMIN_TOKEN must contain visible ASCII characters without spaces", + )); + } + + let admin = Router::new() + .route("/status", get(deployment_status)) + .route_layer(middleware::from_fn_with_state( + Arc::::from(token), + require_admin, + )); + Ok(Router::new() + .route("/healthz", get(|| async { StatusCode::NO_CONTENT })) + .route("/readyz", get(|| async { StatusCode::NO_CONTENT })) + .nest("/admin/v1", admin) + .with_state(status)) +} + +async fn deployment_status(State(status): State) -> impl IntoResponse { + ([(header::CACHE_CONTROL, "no-store")], Json(status)) +} + +async fn require_admin(State(token): State>, request: Request, next: Next) -> Response { + if authorized(request.headers(), &token) { + next.run(request).await + } else { + ( + StatusCode::UNAUTHORIZED, + [(header::WWW_AUTHENTICATE, "Bearer")], + ) + .into_response() + } +} + +fn authorized(headers: &HeaderMap, token: &str) -> bool { + let mut values = headers.get_all(header::AUTHORIZATION).iter(); + let Some(value) = values.next().and_then(|value| value.to_str().ok()) else { + return false; + }; + if values.next().is_some() { + return false; + } + let Some((scheme, supplied)) = value.split_once(' ') else { + return false; + }; + scheme.eq_ignore_ascii_case("Bearer") && bool::from(supplied.as_bytes().ct_eq(token.as_bytes())) +} diff --git a/crates/admin_backend/src/main.rs b/crates/admin_backend/src/main.rs new file mode 100644 index 0000000..299fe4a --- /dev/null +++ b/crates/admin_backend/src/main.rs @@ -0,0 +1,50 @@ +use std::{env, error::Error, fs, net::SocketAddr}; + +use admin_backend::{DeploymentStatus, router}; +use clusters::DeploymentConfig; +use tokio::net::TcpListener; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let address: SocketAddr = env::var("BEDROCK_ADMIN_LISTEN") + .or_else(|error| match error { + env::VarError::NotPresent => Ok("127.0.0.1:8081".to_owned()), + error => Err(error), + })? + .parse()?; + let token = env::var("BEDROCK_ADMIN_TOKEN")?; + let config = match env::var_os("BEDROCK_DB_CONFIG") { + Some(path) => serde_json::from_slice::(&fs::read(path)?)?, + None => DeploymentConfig::default(), + }; + let version = match env::var("BEDROCK_CONFIG_VERSION") { + Ok(version) => Some(version), + Err(env::VarError::NotPresent) => None, + Err(error) => return Err(error.into()), + }; + let router = router(DeploymentStatus::new(config.resolve()?, version), token)?; + let listener = TcpListener::bind(address).await?; + println!( + "Bedrock admin backend listening on {}", + listener.local_addr()? + ); + axum::serve(listener, router) + .with_graceful_shutdown(shutdown()) + .await?; + Ok(()) +} + +async fn shutdown() { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + if let Ok(mut terminate) = signal(SignalKind::terminate()) { + tokio::select! { + _ = terminate.recv() => {}, + _ = tokio::signal::ctrl_c() => {}, + } + return; + } + } + let _ = tokio::signal::ctrl_c().await; +} diff --git a/crates/backend/Cargo.toml b/crates/backend/Cargo.toml new file mode 100644 index 0000000..b0a1ea8 --- /dev/null +++ b/crates/backend/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "backend" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +axum.workspace = true +db.workspace = true +serde_json.workspace = true +tokio = { workspace = true, features = ["net", "signal", "time"] } diff --git a/crates/backend/src/lib.rs b/crates/backend/src/lib.rs new file mode 100644 index 0000000..1adda8c --- /dev/null +++ b/crates/backend/src/lib.rs @@ -0,0 +1,17 @@ +use std::{sync::Arc, time::Duration}; + +use axum::{Router, extract::State, http::StatusCode, routing::get}; + +pub fn router(db: db::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 { + 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 new file mode 100644 index 0000000..5e912f9 --- /dev/null +++ b/crates/backend/src/main.rs @@ -0,0 +1,41 @@ +use std::{env, error::Error, fs, net::SocketAddr}; + +use db::{DeploymentConfig, connect}; +use tokio::net::TcpListener; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let address: SocketAddr = env::var("BEDROCK_BACKEND_LISTEN") + .or_else(|error| match error { + env::VarError::NotPresent => Ok("127.0.0.1:8080".to_owned()), + error => Err(error), + })? + .parse()?; + let config = match env::var_os("BEDROCK_DB_CONFIG") { + Some(path) => serde_json::from_slice::(&fs::read(path)?)?, + None => DeploymentConfig::default(), + }; + + let db = connect(&config).await?; + let listener = TcpListener::bind(address).await?; + println!("Bedrock backend listening on {}", listener.local_addr()?); + axum::serve(listener, backend::router(db)) + .with_graceful_shutdown(shutdown()) + .await?; + Ok(()) +} + +async fn shutdown() { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + if let Ok(mut terminate) = signal(SignalKind::terminate()) { + tokio::select! { + _ = terminate.recv() => {}, + _ = tokio::signal::ctrl_c() => {}, + } + return; + } + } + let _ = tokio::signal::ctrl_c().await; +} From 365be3870e999e137dc731d561477fad9e30ec2d Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:19:05 +0800 Subject: [PATCH 4/7] Model workspaces, users, and organizations --- crates/documents/src/document.rs | 36 +++++++++++++ crates/documents/src/id.rs | 20 ++++++++ crates/documents/src/lib.rs | 75 ++++------------------------ crates/documents/src/organization.rs | 42 ++++++++++++++++ crates/documents/src/user.rs | 24 +++++++++ crates/documents/src/workspace.rs | 29 +++++++++++ 6 files changed, 162 insertions(+), 64 deletions(-) create mode 100644 crates/documents/src/document.rs create mode 100644 crates/documents/src/id.rs create mode 100644 crates/documents/src/organization.rs create mode 100644 crates/documents/src/user.rs create mode 100644 crates/documents/src/workspace.rs diff --git a/crates/documents/src/document.rs b/crates/documents/src/document.rs new file mode 100644 index 0000000..0a143e6 --- /dev/null +++ b/crates/documents/src/document.rs @@ -0,0 +1,36 @@ +use serde_json::Value; + +use super::{ + id::{IdError, validate_id}, + workspace::WorkspaceId, +}; + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct DocumentId(String); + +impl DocumentId { + pub const MAX_BYTES: usize = 128; + + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate_id(&value, Self::MAX_BYTES, IdError::Document)?; + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A document ID identifies a document within its workspace. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct DocumentKey { + pub workspace: WorkspaceId, + pub document: DocumentId, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Document { + pub key: DocumentKey, + pub body: Value, +} diff --git a/crates/documents/src/id.rs b/crates/documents/src/id.rs new file mode 100644 index 0000000..6adb466 --- /dev/null +++ b/crates/documents/src/id.rs @@ -0,0 +1,20 @@ +use thiserror::Error; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum IdError { + #[error("a workspace ID must contain 1–96 bytes and no NUL")] + Workspace, + #[error("a document ID must contain 1–128 bytes and no NUL")] + Document, + #[error("a user ID must contain 1–128 bytes and no NUL")] + User, + #[error("an organization ID must contain 1–128 bytes and no NUL")] + Organization, +} + +pub(super) fn validate_id(value: &str, max_bytes: usize, error: IdError) -> Result<(), IdError> { + if value.is_empty() || value.len() > max_bytes || value.contains('\0') { + return Err(error); + } + Ok(()) +} diff --git a/crates/documents/src/lib.rs b/crates/documents/src/lib.rs index 2b2329b..6e161eb 100644 --- a/crates/documents/src/lib.rs +++ b/crates/documents/src/lib.rs @@ -1,66 +1,13 @@ -//! Workspace document identities and contents. +//! Logical models for documents, workspaces, users, and organizations. -use serde_json::Value; -use thiserror::Error; +mod document; +mod id; +mod organization; +mod user; +mod workspace; -#[derive(Debug, Error, PartialEq, Eq)] -pub enum IdError { - #[error("a workspace ID must contain 1–96 bytes and no NUL")] - Workspace, - #[error("a document ID must contain 1–128 bytes and no NUL")] - Document, -} - -#[derive(Clone, Debug, Eq, Hash, PartialEq)] -pub struct WorkspaceId(String); - -impl WorkspaceId { - pub const MAX_BYTES: usize = 96; - - pub fn new(value: impl Into) -> Result { - let value = value.into(); - validate_id(&value, Self::MAX_BYTES, IdError::Workspace)?; - Ok(Self(value)) - } - - pub fn as_str(&self) -> &str { - &self.0 - } -} - -#[derive(Clone, Debug, Eq, Hash, PartialEq)] -pub struct DocumentId(String); - -impl DocumentId { - pub const MAX_BYTES: usize = 128; - - pub fn new(value: impl Into) -> Result { - let value = value.into(); - validate_id(&value, Self::MAX_BYTES, IdError::Document)?; - Ok(Self(value)) - } - - pub fn as_str(&self) -> &str { - &self.0 - } -} - -/// A document ID identifies a document within its workspace. -#[derive(Clone, Debug, Eq, Hash, PartialEq)] -pub struct DocumentKey { - pub workspace: WorkspaceId, - pub document: DocumentId, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct Document { - pub key: DocumentKey, - pub body: Value, -} - -fn validate_id(value: &str, max_bytes: usize, error: IdError) -> Result<(), IdError> { - if value.is_empty() || value.len() > max_bytes || value.contains('\0') { - return Err(error); - } - Ok(()) -} +pub use document::{Document, DocumentId, DocumentKey}; +pub use id::IdError; +pub use organization::{Organization, OrganizationId, OrganizationMembership, OrganizationRole}; +pub use user::{User, UserId}; +pub use workspace::{Workspace, WorkspaceId}; diff --git a/crates/documents/src/organization.rs b/crates/documents/src/organization.rs new file mode 100644 index 0000000..0407d15 --- /dev/null +++ b/crates/documents/src/organization.rs @@ -0,0 +1,42 @@ +use super::{ + id::{IdError, validate_id}, + user::UserId, +}; + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct OrganizationId(String); + +impl OrganizationId { + pub const MAX_BYTES: usize = 128; + + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate_id(&value, Self::MAX_BYTES, IdError::Organization)?; + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Organization { + pub id: OrganizationId, + pub name: String, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum OrganizationRole { + Owner, + Admin, + Member, +} + +/// Links a user to an organization with a role in that organization. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct OrganizationMembership { + pub organization_id: OrganizationId, + pub user_id: UserId, + pub role: OrganizationRole, +} diff --git a/crates/documents/src/user.rs b/crates/documents/src/user.rs new file mode 100644 index 0000000..9e1be6e --- /dev/null +++ b/crates/documents/src/user.rs @@ -0,0 +1,24 @@ +use super::id::{IdError, validate_id}; + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct UserId(String); + +impl UserId { + pub const MAX_BYTES: usize = 128; + + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate_id(&value, Self::MAX_BYTES, IdError::User)?; + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct User { + pub id: UserId, + pub display_name: String, +} diff --git a/crates/documents/src/workspace.rs b/crates/documents/src/workspace.rs new file mode 100644 index 0000000..dc701fa --- /dev/null +++ b/crates/documents/src/workspace.rs @@ -0,0 +1,29 @@ +use super::{ + id::{IdError, validate_id}, + organization::OrganizationId, +}; + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct WorkspaceId(String); + +impl WorkspaceId { + pub const MAX_BYTES: usize = 96; + + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate_id(&value, Self::MAX_BYTES, IdError::Workspace)?; + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A workspace belongs to one organization and contains documents. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Workspace { + pub id: WorkspaceId, + pub organization_id: OrganizationId, + pub name: String, +} From 6469d3aad6d524258a567c5c8fc951e79c9c2f3c Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:24:21 +0800 Subject: [PATCH 5/7] Serve business and admin routes from one backend process --- Cargo.lock | 3 +- README.md | 33 ++++++------- crates/admin_backend/Cargo.toml | 2 - crates/admin_backend/src/lib.rs | 38 ++++++++++----- crates/admin_backend/src/main.rs | 50 -------------------- crates/backend/Cargo.toml | 3 +- crates/backend/src/main.rs | 81 +++++++++++++++++++++++++++----- crates/db/src/connection.rs | 8 +++- crates/db/src/lib.rs | 2 +- 9 files changed, 122 insertions(+), 98 deletions(-) delete mode 100644 crates/admin_backend/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 7f45856..194c4df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9,9 +9,7 @@ dependencies = [ "axum", "clusters", "serde", - "serde_json", "subtle", - "tokio", ] [[package]] @@ -93,6 +91,7 @@ dependencies = [ name = "backend" version = "0.1.0" dependencies = [ + "admin_backend", "axum", "db", "serde_json", diff --git a/README.md b/README.md index cdde64b..44dde53 100644 --- a/README.md +++ b/README.md @@ -8,27 +8,28 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i 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) -## Web backends +## Web backend -The workspace has two independently started Axum services. Run the packages -with `cargo run --locked -p backend` and `cargo run --locked -p admin_backend` -in a development environment. +Run the Axum service with `cargo run --locked -p backend`. One process owns +the database connection, loads one deployment configuration, and serves +separate routers on the business and optional admin listeners. -| Package | Listen setting and default | Routes | +| Listener | Setting and default | Routes | |---|---|---| -| `backend` | `BEDROCK_BACKEND_LISTEN`, default `127.0.0.1:8080` | `GET /healthz`, `GET /readyz` | -| `admin_backend` | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status` | +| Business | `BEDROCK_BACKEND_LISTEN`, default `127.0.0.1:8080` | `GET /healthz`, `GET /readyz` | +| Admin | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` when enabled | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status` | -Both services use the `BEDROCK_DB_CONFIG` setting described below. The business -service opens storage at startup and verifies access to the current deployment -revision in its readiness handler. The admin service resolves the deployment -configuration at startup. Its status endpoint reports the configured deployment, -storage driver, read-only mode, and optional `BEDROCK_CONFIG_VERSION`. +The business readiness probe checks access to the current deployment revision. +Set `BEDROCK_ADMIN_TOKEN` from a private credential source to enable the admin +listener. Send it as `Authorization: Bearer ` for the status endpoint. +Keep the admin listener on loopback or behind an internal TLS endpoint. -Set `BEDROCK_ADMIN_TOKEN` from a private credential source before starting -`admin_backend`. Send it as `Authorization: Bearer ` for the status -endpoint. Keep the admin listener on loopback or behind an internal TLS endpoint. -The root `bedrock` binary remains the one-shot storage initializer. +The `admin_backend` library reports the deployment, storage driver, read-only +mode, and optional `BEDROCK_CONFIG_VERSION` for the instance that served the +request. It reads the same resolved configuration that 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. ## Database configuration diff --git a/crates/admin_backend/Cargo.toml b/crates/admin_backend/Cargo.toml index 3dbe1b3..3c48bab 100644 --- a/crates/admin_backend/Cargo.toml +++ b/crates/admin_backend/Cargo.toml @@ -8,6 +8,4 @@ rust-version.workspace = true axum.workspace = true clusters.workspace = true serde.workspace = true -serde_json.workspace = true subtle.workspace = true -tokio = { workspace = true, features = ["net", "signal"] } diff --git a/crates/admin_backend/src/lib.rs b/crates/admin_backend/src/lib.rs index 70b9655..45dbcff 100644 --- a/crates/admin_backend/src/lib.rs +++ b/crates/admin_backend/src/lib.rs @@ -12,19 +12,26 @@ use clusters::{Driver, ResolvedDeployment}; use serde::Serialize; use subtle::ConstantTimeEq; -#[derive(Clone, Serialize)] -pub struct DeploymentStatus { - deployment: String, +#[derive(Clone)] +struct AdminState { + config: Arc, config_version: Option, +} + +#[derive(Serialize)] +struct DeploymentStatus<'a> { + deployment: &'a str, + config_version: Option<&'a str>, storage_driver: &'static str, read_only: bool, } -impl DeploymentStatus { - pub fn new(config: ResolvedDeployment, config_version: Option) -> Self { - Self { - deployment: config.deployment, - config_version, +impl AdminState { + fn status(&self) -> DeploymentStatus<'_> { + let config = &self.config; + DeploymentStatus { + deployment: &config.deployment, + config_version: self.config_version.as_deref(), storage_driver: match config.driver { Driver::Sqlite => "sqlite", Driver::Postgres => "postgres", @@ -35,7 +42,11 @@ impl DeploymentStatus { } } -pub fn router(status: DeploymentStatus, token: String) -> io::Result { +pub fn router( + config: Arc, + config_version: Option, + token: String, +) -> io::Result { if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_graphic()) { return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -53,11 +64,14 @@ pub fn router(status: DeploymentStatus, token: String) -> io::Result { .route("/healthz", get(|| async { StatusCode::NO_CONTENT })) .route("/readyz", get(|| async { StatusCode::NO_CONTENT })) .nest("/admin/v1", admin) - .with_state(status)) + .with_state(AdminState { + config, + config_version, + })) } -async fn deployment_status(State(status): State) -> impl IntoResponse { - ([(header::CACHE_CONTROL, "no-store")], Json(status)) +async fn deployment_status(State(state): State) -> Response { + ([(header::CACHE_CONTROL, "no-store")], Json(state.status())).into_response() } async fn require_admin(State(token): State>, request: Request, next: Next) -> Response { diff --git a/crates/admin_backend/src/main.rs b/crates/admin_backend/src/main.rs deleted file mode 100644 index 299fe4a..0000000 --- a/crates/admin_backend/src/main.rs +++ /dev/null @@ -1,50 +0,0 @@ -use std::{env, error::Error, fs, net::SocketAddr}; - -use admin_backend::{DeploymentStatus, router}; -use clusters::DeploymentConfig; -use tokio::net::TcpListener; - -#[tokio::main] -async fn main() -> Result<(), Box> { - let address: SocketAddr = env::var("BEDROCK_ADMIN_LISTEN") - .or_else(|error| match error { - env::VarError::NotPresent => Ok("127.0.0.1:8081".to_owned()), - error => Err(error), - })? - .parse()?; - let token = env::var("BEDROCK_ADMIN_TOKEN")?; - let config = match env::var_os("BEDROCK_DB_CONFIG") { - Some(path) => serde_json::from_slice::(&fs::read(path)?)?, - None => DeploymentConfig::default(), - }; - let version = match env::var("BEDROCK_CONFIG_VERSION") { - Ok(version) => Some(version), - Err(env::VarError::NotPresent) => None, - Err(error) => return Err(error.into()), - }; - let router = router(DeploymentStatus::new(config.resolve()?, version), token)?; - let listener = TcpListener::bind(address).await?; - println!( - "Bedrock admin backend listening on {}", - listener.local_addr()? - ); - axum::serve(listener, router) - .with_graceful_shutdown(shutdown()) - .await?; - Ok(()) -} - -async fn shutdown() { - #[cfg(unix)] - { - use tokio::signal::unix::{SignalKind, signal}; - if let Ok(mut terminate) = signal(SignalKind::terminate()) { - tokio::select! { - _ = terminate.recv() => {}, - _ = tokio::signal::ctrl_c() => {}, - } - return; - } - } - let _ = tokio::signal::ctrl_c().await; -} diff --git a/crates/backend/Cargo.toml b/crates/backend/Cargo.toml index b0a1ea8..076bf49 100644 --- a/crates/backend/Cargo.toml +++ b/crates/backend/Cargo.toml @@ -5,7 +5,8 @@ edition.workspace = true rust-version.workspace = true [dependencies] +admin_backend = { path = "../admin_backend" } axum.workspace = true db.workspace = true serde_json.workspace = true -tokio = { workspace = true, features = ["net", "signal", "time"] } +tokio = { workspace = true, features = ["net", "signal", "sync", "time"] } diff --git a/crates/backend/src/main.rs b/crates/backend/src/main.rs index 5e912f9..1a63d61 100644 --- a/crates/backend/src/main.rs +++ b/crates/backend/src/main.rs @@ -1,30 +1,87 @@ -use std::{env, error::Error, fs, net::SocketAddr}; +use std::{env, error::Error, fs, io, net::SocketAddr, sync::Arc}; -use db::{DeploymentConfig, connect}; -use tokio::net::TcpListener; +use axum::Router; +use db::{DeploymentConfig, connect_resolved}; +use tokio::{net::TcpListener, sync::watch}; #[tokio::main] async fn main() -> Result<(), Box> { - let address: SocketAddr = env::var("BEDROCK_BACKEND_LISTEN") - .or_else(|error| match error { - env::VarError::NotPresent => Ok("127.0.0.1:8080".to_owned()), - error => Err(error), - })? + 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) => serde_json::from_slice::(&fs::read(path)?)?, None => DeploymentConfig::default(), }; + let config = Arc::new(config.resolve()?); + + let admin_address = optional_env("BEDROCK_ADMIN_LISTEN")?; + let admin = match optional_env("BEDROCK_ADMIN_TOKEN")? { + Some(token) => { + let address: SocketAddr = admin_address + .as_deref() + .unwrap_or("127.0.0.1:8081") + .parse()?; + let router = admin_backend::router( + Arc::clone(&config), + optional_env("BEDROCK_CONFIG_VERSION")?, + token, + )?; + Some((TcpListener::bind(address).await?, router)) + } + None if admin_address.is_some() => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "BEDROCK_ADMIN_LISTEN requires BEDROCK_ADMIN_TOKEN", + ) + .into()); + } + None => None, + }; - let db = connect(&config).await?; let listener = TcpListener::bind(address).await?; + let db = connect_resolved(&config).await?; println!("Bedrock backend listening on {}", listener.local_addr()?); - axum::serve(listener, backend::router(db)) - .with_graceful_shutdown(shutdown()) - .await?; + + let (stop, shutdown_signal) = watch::channel(false); + tokio::spawn(async move { + shutdown().await; + stop.send_replace(true); + }); + + if let Some((admin_listener, admin_router)) = admin { + println!("Bedrock admin listener on {}", admin_listener.local_addr()?); + tokio::try_join!( + serve(listener, backend::router(db), shutdown_signal.clone()), + serve(admin_listener, admin_router, shutdown_signal), + )?; + } else { + serve(listener, backend::router(db), shutdown_signal).await?; + } Ok(()) } +fn optional_env(name: &str) -> Result, env::VarError> { + match env::var(name) { + Ok(value) => Ok(Some(value)), + Err(env::VarError::NotPresent) => Ok(None), + Err(error) => Err(error), + } +} + +async fn serve( + listener: TcpListener, + router: Router, + mut shutdown_signal: watch::Receiver, +) -> io::Result<()> { + axum::serve(listener, router) + .with_graceful_shutdown(async move { + let _ = shutdown_signal.wait_for(|stop| *stop).await; + }) + .await +} + async fn shutdown() { #[cfg(unix)] { diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index 708094f..d1d4c6c 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -44,6 +44,10 @@ pub struct Connection { pub async fn connect(config: &DeploymentConfig) -> Result { let config = config.resolve()?; + Ok(connect_resolved(&config).await?) +} + +pub async fn connect_resolved(config: &ResolvedDeployment) -> Result { let writer = if config.read_only { None } else { @@ -60,7 +64,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result store.reader(), Some(Writer::MySql(store)) => store.reader(), None => { - let reader = reader(&config, &config.primary)?; + let reader = reader(config, &config.primary)?; reader.revision().await?; reader } @@ -68,7 +72,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result>()?; Ok(Connection { driver: config.driver, diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 4253f53..7cc14b6 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -7,7 +7,7 @@ pub mod postgres; pub mod sqlite; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; -pub use connection::{ConnectError, Connection, ReadPreference, connect}; +pub use connection::{ConnectError, Connection, ReadPreference, connect, connect_resolved}; pub use mysql::{Lease, MySql}; pub use common::Error as StorageError; From 455a3580d61e93e2e32c0b8dc7065539b3a27e83 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:36:16 +0800 Subject: [PATCH 6/7] Model pages and blocks as document nodes --- Cargo.lock | 2 + crates/db/Cargo.toml | 1 + crates/db/src/documents.rs | 115 ++++++++++++++++++------ crates/db/tests/workspace_documents.rs | 78 ++++++++++++++-- crates/documents/Cargo.toml | 1 + crates/documents/src/context.rs | 104 +++++++++++++++++++++ crates/documents/src/document.rs | 38 +++++++- crates/documents/src/lib.rs | 8 +- crates/documents/src/rich_text.rs | 18 ++++ crates/documents/src/tree.rs | 81 +++++++++++++++++ crates/documents/tests/document_tree.rs | 70 +++++++++++++++ 11 files changed, 481 insertions(+), 35 deletions(-) create mode 100644 crates/documents/src/context.rs create mode 100644 crates/documents/src/rich_text.rs create mode 100644 crates/documents/src/tree.rs create mode 100644 crates/documents/tests/document_tree.rs diff --git a/Cargo.lock b/Cargo.lock index 1230dfa..af5d81c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -160,6 +160,7 @@ version = "0.1.0" dependencies = [ "clusters", "documents", + "serde", "serde_json", "sqlx", "tempfile", @@ -205,6 +206,7 @@ dependencies = [ name = "documents" version = "0.1.0" dependencies = [ + "serde", "serde_json", "thiserror", ] diff --git a/crates/db/Cargo.toml b/crates/db/Cargo.toml index 8eae459..a936406 100644 --- a/crates/db/Cargo.toml +++ b/crates/db/Cargo.toml @@ -7,6 +7,7 @@ rust-version.workspace = true [dependencies] clusters.workspace = true documents.workspace = true +serde.workspace = true serde_json.workspace = true sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } thiserror.workspace = true diff --git a/crates/db/src/documents.rs b/crates/db/src/documents.rs index c8c607b..9ac2b2b 100644 --- a/crates/db/src/documents.rs +++ b/crates/db/src/documents.rs @@ -1,14 +1,15 @@ //! Maps workspace documents onto the versioned SQL store. //! -//! Within a deployment, the workspace selects a reserved collection prefix plus its ID. -//! The document ID becomes the row key in that collection, and the body is JSON. +//! Within a deployment, the workspace selects a collection and the document ID selects +//! a row. The v2 JSON payload stores the parent, position, and typed content. -use ::documents::{Document, DocumentKey}; +use ::documents::{Document, DocumentContent, DocumentId, DocumentKey}; +use serde::{Deserialize, Serialize}; use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError}; -// This collection namespace belongs to the workspace-document adapter. -const COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v1:"; +const COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v2:"; +const LEGACY_COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v1:"; /// A logical document and the deployment revision at which it was last written. #[derive(Debug, PartialEq)] @@ -17,27 +18,46 @@ pub struct StoredDocument { pub revision: Revision, } +#[derive(Deserialize, Serialize)] +struct DocumentPayload { + parent_id: Option, + position: u64, + content: DocumentContent, +} + impl Connection { /// Creates a document using the primary snapshot and its expected revision. pub async fn create_document(&self, document: Document) -> Result { if self.is_read_only() { return Err(StorageError::ReadOnly); } - let collection = collection(&document.key); - let id = document.key.document.as_str(); - let snapshot = self - .get(&collection, id, None, ReadPreference::Primary) - .await?; - if snapshot.document.is_some() { + let (revision, existing) = self.lookup_document(&document.key, None).await?; + if existing.is_some() { return Err(StorageError::DocumentAlreadyExists); } + if let Some(parent) = &document.parent_id { + let parent_key = DocumentKey { + workspace: document.key.workspace.clone(), + document: parent.clone(), + }; + let (_, stored) = self.lookup_document(&parent_key, Some(revision)).await?; + if stored.is_none() { + return Err(StorageError::Invalid("document parent")); + } + } + + let value = serde_json::to_value(DocumentPayload { + parent_id: document.parent_id.map(|id| id.as_str().to_owned()), + position: document.position, + content: document.content, + })?; self.commit( - snapshot.revision, + revision, &[Mutation { - collection, - id: id.to_owned(), - value: Some(document.body), + collection: collection(COLLECTION_PREFIX, &document.key), + id: document.key.document.as_str().to_owned(), + value: Some(value), }], ) .await @@ -45,24 +65,65 @@ impl Connection { /// Reads the latest state of a workspace document from the primary. pub async fn get_document(&self, key: &DocumentKey) -> Result> { + let (_, document) = self.lookup_document(key, None).await?; + Ok(document) + } + + async fn lookup_document( + &self, + key: &DocumentKey, + at: Option, + ) -> Result<(Revision, Option)> { + let id = key.document.as_str(); let snapshot = self .get( - &collection(key), - key.document.as_str(), - None, + &collection(COLLECTION_PREFIX, key), + id, + at, ReadPreference::Primary, ) .await?; - Ok(snapshot.document.map(|stored| StoredDocument { - document: Document { - key: key.clone(), - body: stored.value, - }, - revision: stored.revision, - })) + let revision = snapshot.revision; + if let Some(stored) = snapshot.document { + let payload: DocumentPayload = serde_json::from_value(stored.value)?; + let parent_id = payload + .parent_id + .map(DocumentId::new) + .transpose() + .map_err(|_| StorageError::Invalid("stored document parent ID"))?; + return Ok(( + revision, + Some(StoredDocument { + document: Document { + key: key.clone(), + parent_id, + position: payload.position, + content: payload.content, + }, + revision: stored.revision, + }), + )); + } + + // Use the same snapshot when looking up a document saved with the original encoding. + let legacy = self + .get( + &collection(LEGACY_COLLECTION_PREFIX, key), + id, + Some(revision), + ReadPreference::Primary, + ) + .await?; + Ok(( + revision, + legacy.document.map(|stored| StoredDocument { + document: Document::new(key.clone(), DocumentContent::Json(stored.value)), + revision: stored.revision, + }), + )) } } -fn collection(key: &DocumentKey) -> String { - format!("{COLLECTION_PREFIX}{}", key.workspace.as_str()) +fn collection(prefix: &str, key: &DocumentKey) -> String { + format!("{prefix}{}", key.workspace.as_str()) } diff --git a/crates/db/tests/workspace_documents.rs b/crates/db/tests/workspace_documents.rs index e603a03..c957ee6 100644 --- a/crates/db/tests/workspace_documents.rs +++ b/crates/db/tests/workspace_documents.rs @@ -1,15 +1,17 @@ -use db::{DeploymentConfig, StorageError, connect}; -use documents::{Document, DocumentId, DocumentKey, WorkspaceId}; +use db::{DeploymentConfig, Mutation, StorageError, connect}; +use documents::{ + Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, WorkspaceId, +}; use serde_json::json; fn document(workspace: &str, body: serde_json::Value) -> Document { - Document { - key: DocumentKey { + Document::new( + DocumentKey { workspace: WorkspaceId::new(workspace).unwrap(), document: DocumentId::new("same-id").unwrap(), }, - body, - } + DocumentContent::Json(body), + ) } #[tokio::test] @@ -54,3 +56,67 @@ async fn workspace_documents_keep_their_identity_and_contents_after_reopen() { Err(StorageError::ReadOnly) )); } + +#[tokio::test] +async fn persists_typed_nodes_and_reads_the_original_json_encoding() { + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("documents.sqlite3"); + let connection = connect(&DeploymentConfig { + sqlite_path: path.to_str().unwrap().into(), + ..DeploymentConfig::default() + }) + .await + .unwrap(); + + let page = Document::new( + document("team", json!(null)).key, + DocumentContent::Page { + title: "Planning".into(), + }, + ); + let mut todo = page.clone(); + todo.key.document = DocumentId::new("todo").unwrap(); + todo.parent_id = Some(page.key.document.clone()); + todo.position = 2; + todo.content = DocumentContent::Todo { + text: "Review".into(), + checked: true, + }; + + assert!(matches!( + connection.create_document(todo.clone()).await, + Err(StorageError::Invalid("document parent")) + )); + connection.create_document(page.clone()).await.unwrap(); + connection.create_document(todo.clone()).await.unwrap(); + let read = connection.get_document(&todo.key).await.unwrap().unwrap(); + assert_eq!(read.document, todo); + let tree = DocumentTree::new(page, [read.document]).unwrap(); + assert_eq!(tree.render_context(), "# Planning\n- [x] Review"); + + let legacy = document("legacy", json!({"previous": "body"})); + connection + .commit( + connection.revision().await.unwrap(), + &[Mutation { + collection: "bedrock:workspace-documents:v1:legacy".into(), + id: legacy.key.document.as_str().into(), + value: Some(json!({"previous": "body"})), + }], + ) + .await + .unwrap(); + assert_eq!( + connection + .get_document(&legacy.key) + .await + .unwrap() + .unwrap() + .document, + legacy + ); + assert!(matches!( + connection.create_document(legacy).await, + Err(StorageError::DocumentAlreadyExists) + )); +} diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.toml index e8d48fd..91e477a 100644 --- a/crates/documents/Cargo.toml +++ b/crates/documents/Cargo.toml @@ -5,5 +5,6 @@ edition.workspace = true rust-version.workspace = true [dependencies] +serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/crates/documents/src/context.rs b/crates/documents/src/context.rs new file mode 100644 index 0000000..99d2edb --- /dev/null +++ b/crates/documents/src/context.rs @@ -0,0 +1,104 @@ +use crate::{ + Document, DocumentContent, DocumentTree, Inline, Organization, OrganizationMembership, + OrganizationRole, RichText, User, Workspace, +}; + +/// Produces a textual description from already available data. +pub trait Contextualize { + fn render_context(&self) -> String; +} + +impl Contextualize for RichText { + fn render_context(&self) -> String { + let mut text = String::new(); + for item in &self.0 { + match item { + Inline::Text(value) => text.push_str(value), + Inline::Link { label, url } => { + text.push_str(label); + text.push_str(" ("); + text.push_str(url); + text.push(')'); + } + } + } + text + } +} + +impl Contextualize for DocumentContent { + fn render_context(&self) -> String { + match self { + Self::Page { title } => format!("# {title}"), + Self::Heading(text) => format!("## {}", text.render_context()), + Self::Paragraph(text) => text.render_context(), + Self::ListItem(text) => format!("- {}", text.render_context()), + Self::Todo { text, checked } => { + let mark = if *checked { 'x' } else { ' ' }; + format!("- [{mark}] {}", text.render_context()) + } + Self::Code { language, source } => format!("Code ({language}):\n{source}"), + Self::Json(value) => value.to_string(), + } + } +} + +impl Contextualize for Document { + fn render_context(&self) -> String { + self.content.render_context() + } +} + +impl Contextualize for DocumentTree { + fn render_context(&self) -> String { + let mut text = String::new(); + let mut first_line = true; + for (depth, node) in self.nodes() { + let rendered = node.render_context(); + for line in rendered.split('\n') { + if !first_line { + text.push('\n'); + } + first_line = false; + for _ in 1..depth { + text.push_str(" "); + } + text.push_str(line); + } + } + text + } +} + +impl Contextualize for User { + fn render_context(&self) -> String { + format!("User: {}", self.display_name) + } +} + +impl Contextualize for Workspace { + fn render_context(&self) -> String { + format!("Workspace: {}", self.name) + } +} + +impl Contextualize for Organization { + fn render_context(&self) -> String { + format!("Organization: {}", self.name) + } +} + +impl Contextualize for OrganizationMembership { + fn render_context(&self) -> String { + let role = match self.role { + OrganizationRole::Owner => "owner", + OrganizationRole::Admin => "admin", + OrganizationRole::Member => "member", + }; + format!( + "User {} is a {role} of organization {}", + self.user_id.as_str(), + self.organization_id.as_str() + ) + } +} diff --git a/crates/documents/src/document.rs b/crates/documents/src/document.rs index 0a143e6..35903f5 100644 --- a/crates/documents/src/document.rs +++ b/crates/documents/src/document.rs @@ -1,7 +1,9 @@ +use serde::{Deserialize, Serialize}; use serde_json::Value; use super::{ id::{IdError, validate_id}, + rich_text::RichText, workspace::WorkspaceId, }; @@ -32,5 +34,39 @@ pub struct DocumentKey { #[derive(Clone, Debug, PartialEq)] pub struct Document { pub key: DocumentKey, - pub body: Value, + pub parent_id: Option, + pub position: u64, + pub content: DocumentContent, +} + +impl Document { + pub fn new(key: DocumentKey, content: DocumentContent) -> Self { + Self { + key, + parent_id: None, + position: 0, + content, + } + } +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(tag = "kind", content = "data", rename_all = "snake_case")] +pub enum DocumentContent { + Page { + title: String, + }, + Heading(RichText), + Paragraph(RichText), + ListItem(RichText), + Todo { + text: RichText, + checked: bool, + }, + Code { + language: String, + source: String, + }, + /// Preserves documents written with the original arbitrary JSON model. + Json(Value), } diff --git a/crates/documents/src/lib.rs b/crates/documents/src/lib.rs index 6e161eb..0ce51f4 100644 --- a/crates/documents/src/lib.rs +++ b/crates/documents/src/lib.rs @@ -1,13 +1,19 @@ //! Logical models for documents, workspaces, users, and organizations. +mod context; mod document; mod id; mod organization; +mod rich_text; +mod tree; mod user; mod workspace; -pub use document::{Document, DocumentId, DocumentKey}; +pub use context::Contextualize; +pub use document::{Document, DocumentContent, DocumentId, DocumentKey}; pub use id::IdError; pub use organization::{Organization, OrganizationId, OrganizationMembership, OrganizationRole}; +pub use rich_text::{Inline, RichText}; +pub use tree::{DocumentTree, TreeError}; pub use user::{User, UserId}; pub use workspace::{Workspace, WorkspaceId}; diff --git a/crates/documents/src/rich_text.rs b/crates/documents/src/rich_text.rs new file mode 100644 index 0000000..b49312b --- /dev/null +++ b/crates/documents/src/rich_text.rs @@ -0,0 +1,18 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(tag = "kind", content = "data", rename_all = "snake_case")] +pub enum Inline { + Text(String), + Link { label: String, url: String }, +} + +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] +#[serde(transparent)] +pub struct RichText(pub Vec); + +impl From<&str> for RichText { + fn from(value: &str) -> Self { + Self(vec![Inline::Text(value.into())]) + } +} diff --git a/crates/documents/src/tree.rs b/crates/documents/src/tree.rs new file mode 100644 index 0000000..7a6b4d8 --- /dev/null +++ b/crates/documents/src/tree.rs @@ -0,0 +1,81 @@ +use std::collections::{HashMap, HashSet}; + +use thiserror::Error; + +use crate::{Document, DocumentId}; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum TreeError { + #[error("all documents in the tree must belong to the same workspace")] + WorkspaceMismatch, + #[error("a document ID occurs more than once")] + DuplicateDocument, + #[error("the document tree has a missing parent or a cycle")] + InvalidParent, +} + +/// An ordered view assembled from one page or content node and its descendants. +#[derive(Debug)] +pub struct DocumentTree { + root: Document, + descendants: Vec<(usize, Document)>, +} + +impl DocumentTree { + pub fn new( + root: Document, + descendants: impl IntoIterator, + ) -> Result { + let mut ids = HashSet::from([root.key.document.clone()]); + let mut by_parent: HashMap> = HashMap::new(); + + for document in descendants { + if document.key.workspace != root.key.workspace { + return Err(TreeError::WorkspaceMismatch); + } + if !ids.insert(document.key.document.clone()) { + return Err(TreeError::DuplicateDocument); + } + let parent = document.parent_id.clone().ok_or(TreeError::InvalidParent)?; + by_parent.entry(parent).or_default().push(document); + } + if root.parent_id.as_ref().is_some_and(|id| ids.contains(id)) { + return Err(TreeError::InvalidParent); + } + for siblings in by_parent.values_mut() { + // The ID breaks ties consistently when nodes have the same position. + siblings.sort_by(|a, b| { + a.position + .cmp(&b.position) + .then_with(|| a.key.document.as_str().cmp(b.key.document.as_str())) + }); + } + let mut pending: Vec<_> = by_parent + .remove(&root.key.document) + .unwrap_or_default() + .into_iter() + .rev() + .map(|node| (1, node)) + .collect(); + let mut ordered = Vec::with_capacity(ids.len() - 1); + while let Some((depth, node)) = pending.pop() { + if let Some(children) = by_parent.remove(&node.key.document) { + pending.extend(children.into_iter().rev().map(|child| (depth + 1, child))); + } + ordered.push((depth, node)); + } + if !by_parent.is_empty() { + return Err(TreeError::InvalidParent); + } + Ok(Self { + root, + descendants: ordered, + }) + } + + /// Traverses the root and descendants in display order, with their depth. + pub fn nodes(&self) -> impl Iterator { + std::iter::once((0, &self.root)) + .chain(self.descendants.iter().map(|(depth, node)| (*depth, node))) + } +} diff --git a/crates/documents/tests/document_tree.rs b/crates/documents/tests/document_tree.rs new file mode 100644 index 0000000..29fc23e --- /dev/null +++ b/crates/documents/tests/document_tree.rs @@ -0,0 +1,70 @@ +use documents::{ + Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, TreeError, + WorkspaceId, +}; + +fn node(id: &str, parent: Option<&str>, position: u64, content: DocumentContent) -> Document { + Document { + key: DocumentKey { + workspace: WorkspaceId::new("workspace").unwrap(), + document: DocumentId::new(id).unwrap(), + }, + parent_id: parent.map(|id| DocumentId::new(id).unwrap()), + position, + content, + } +} + +#[test] +fn nested_pages_and_blocks_share_an_ordered_tree() { + let root = node( + "root", + None, + 0, + DocumentContent::Page { + title: "Root".into(), + }, + ); + let page = node( + "page", + Some("root"), + 2, + DocumentContent::Page { + title: "Nested".into(), + }, + ); + let paragraph = node( + "paragraph", + Some("page"), + 0, + DocumentContent::Paragraph("Details".into()), + ); + let heading = node( + "heading", + Some("root"), + 1, + DocumentContent::Heading("Overview".into()), + ); + let tree = DocumentTree::new(root, [paragraph, page, heading]).unwrap(); + assert_eq!( + tree.nodes() + .map(|(depth, node)| (depth, node.key.document.as_str())) + .collect::>(), + [(0, "root"), (1, "heading"), (1, "page"), (2, "paragraph")], + ); + assert_eq!( + tree.render_context(), + "# Root\n## Overview\n# Nested\n Details" + ); +} + +#[test] +fn unreachable_cycle_is_rejected() { + let root = node("root", None, 0, DocumentContent::Paragraph("root".into())); + let a = node("a", Some("b"), 0, DocumentContent::Paragraph("a".into())); + let b = node("b", Some("a"), 0, DocumentContent::Paragraph("b".into())); + assert!(matches!( + DocumentTree::new(root, [a, b]), + Err(TreeError::InvalidParent) + )); +} From 66b6910eb141262e72dfa1cdb4c33c78368b5b1b Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 18:56:28 +0800 Subject: [PATCH 7/7] Keep context implementations with their document models --- crates/documents/src/context.rs | 104 -------------------------- crates/documents/src/contextualize.rs | 4 + crates/documents/src/document.rs | 25 +++++++ crates/documents/src/lib.rs | 4 +- crates/documents/src/organization.rs | 22 ++++++ crates/documents/src/rich_text.rs | 20 +++++ crates/documents/src/tree.rs | 23 ++++++ crates/documents/src/user.rs | 7 ++ crates/documents/src/workspace.rs | 7 ++ 9 files changed, 110 insertions(+), 106 deletions(-) delete mode 100644 crates/documents/src/context.rs create mode 100644 crates/documents/src/contextualize.rs diff --git a/crates/documents/src/context.rs b/crates/documents/src/context.rs deleted file mode 100644 index 99d2edb..0000000 --- a/crates/documents/src/context.rs +++ /dev/null @@ -1,104 +0,0 @@ -use crate::{ - Document, DocumentContent, DocumentTree, Inline, Organization, OrganizationMembership, - OrganizationRole, RichText, User, Workspace, -}; - -/// Produces a textual description from already available data. -pub trait Contextualize { - fn render_context(&self) -> String; -} - -impl Contextualize for RichText { - fn render_context(&self) -> String { - let mut text = String::new(); - for item in &self.0 { - match item { - Inline::Text(value) => text.push_str(value), - Inline::Link { label, url } => { - text.push_str(label); - text.push_str(" ("); - text.push_str(url); - text.push(')'); - } - } - } - text - } -} - -impl Contextualize for DocumentContent { - fn render_context(&self) -> String { - match self { - Self::Page { title } => format!("# {title}"), - Self::Heading(text) => format!("## {}", text.render_context()), - Self::Paragraph(text) => text.render_context(), - Self::ListItem(text) => format!("- {}", text.render_context()), - Self::Todo { text, checked } => { - let mark = if *checked { 'x' } else { ' ' }; - format!("- [{mark}] {}", text.render_context()) - } - Self::Code { language, source } => format!("Code ({language}):\n{source}"), - Self::Json(value) => value.to_string(), - } - } -} - -impl Contextualize for Document { - fn render_context(&self) -> String { - self.content.render_context() - } -} - -impl Contextualize for DocumentTree { - fn render_context(&self) -> String { - let mut text = String::new(); - let mut first_line = true; - for (depth, node) in self.nodes() { - let rendered = node.render_context(); - for line in rendered.split('\n') { - if !first_line { - text.push('\n'); - } - first_line = false; - for _ in 1..depth { - text.push_str(" "); - } - text.push_str(line); - } - } - text - } -} - -impl Contextualize for User { - fn render_context(&self) -> String { - format!("User: {}", self.display_name) - } -} - -impl Contextualize for Workspace { - fn render_context(&self) -> String { - format!("Workspace: {}", self.name) - } -} - -impl Contextualize for Organization { - fn render_context(&self) -> String { - format!("Organization: {}", self.name) - } -} - -impl Contextualize for OrganizationMembership { - fn render_context(&self) -> String { - let role = match self.role { - OrganizationRole::Owner => "owner", - OrganizationRole::Admin => "admin", - OrganizationRole::Member => "member", - }; - format!( - "User {} is a {role} of organization {}", - self.user_id.as_str(), - self.organization_id.as_str() - ) - } -} diff --git a/crates/documents/src/contextualize.rs b/crates/documents/src/contextualize.rs new file mode 100644 index 0000000..1c16864 --- /dev/null +++ b/crates/documents/src/contextualize.rs @@ -0,0 +1,4 @@ +/// Produces a textual description from already available data. +pub trait Contextualize { + fn render_context(&self) -> String; +} diff --git a/crates/documents/src/document.rs b/crates/documents/src/document.rs index 35903f5..530f316 100644 --- a/crates/documents/src/document.rs +++ b/crates/documents/src/document.rs @@ -1,6 +1,8 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; +use super::contextualize::Contextualize; + use super::{ id::{IdError, validate_id}, rich_text::RichText, @@ -70,3 +72,26 @@ pub enum DocumentContent { /// Preserves documents written with the original arbitrary JSON model. Json(Value), } + +impl Contextualize for DocumentContent { + fn render_context(&self) -> String { + match self { + Self::Page { title } => format!("# {title}"), + Self::Heading(text) => format!("## {}", text.render_context()), + Self::Paragraph(text) => text.render_context(), + Self::ListItem(text) => format!("- {}", text.render_context()), + Self::Todo { text, checked } => { + let mark = if *checked { 'x' } else { ' ' }; + format!("- [{mark}] {}", text.render_context()) + } + Self::Code { language, source } => format!("Code ({language}):\n{source}"), + Self::Json(value) => value.to_string(), + } + } +} + +impl Contextualize for Document { + fn render_context(&self) -> String { + self.content.render_context() + } +} diff --git a/crates/documents/src/lib.rs b/crates/documents/src/lib.rs index 0ce51f4..d5d258c 100644 --- a/crates/documents/src/lib.rs +++ b/crates/documents/src/lib.rs @@ -1,6 +1,6 @@ //! Logical models for documents, workspaces, users, and organizations. -mod context; +mod contextualize; mod document; mod id; mod organization; @@ -9,7 +9,7 @@ mod tree; mod user; mod workspace; -pub use context::Contextualize; +pub use contextualize::Contextualize; pub use document::{Document, DocumentContent, DocumentId, DocumentKey}; pub use id::IdError; pub use organization::{Organization, OrganizationId, OrganizationMembership, OrganizationRole}; diff --git a/crates/documents/src/organization.rs b/crates/documents/src/organization.rs index 0407d15..848db9e 100644 --- a/crates/documents/src/organization.rs +++ b/crates/documents/src/organization.rs @@ -1,3 +1,4 @@ +use super::contextualize::Contextualize; use super::{ id::{IdError, validate_id}, user::UserId, @@ -40,3 +41,24 @@ pub struct OrganizationMembership { pub user_id: UserId, pub role: OrganizationRole, } + +impl Contextualize for Organization { + fn render_context(&self) -> String { + format!("Organization: {}", self.name) + } +} + +impl Contextualize for OrganizationMembership { + fn render_context(&self) -> String { + let role = match self.role { + OrganizationRole::Owner => "owner", + OrganizationRole::Admin => "admin", + OrganizationRole::Member => "member", + }; + format!( + "User {} is a {role} of organization {}", + self.user_id.as_str(), + self.organization_id.as_str() + ) + } +} diff --git a/crates/documents/src/rich_text.rs b/crates/documents/src/rich_text.rs index b49312b..5117bf8 100644 --- a/crates/documents/src/rich_text.rs +++ b/crates/documents/src/rich_text.rs @@ -1,5 +1,7 @@ use serde::{Deserialize, Serialize}; +use super::contextualize::Contextualize; + #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(tag = "kind", content = "data", rename_all = "snake_case")] pub enum Inline { @@ -16,3 +18,21 @@ impl From<&str> for RichText { Self(vec![Inline::Text(value.into())]) } } + +impl Contextualize for RichText { + fn render_context(&self) -> String { + let mut text = String::new(); + for item in &self.0 { + match item { + Inline::Text(value) => text.push_str(value), + Inline::Link { label, url } => { + text.push_str(label); + text.push_str(" ("); + text.push_str(url); + text.push(')'); + } + } + } + text + } +} diff --git a/crates/documents/src/tree.rs b/crates/documents/src/tree.rs index 7a6b4d8..1c3d665 100644 --- a/crates/documents/src/tree.rs +++ b/crates/documents/src/tree.rs @@ -1,5 +1,7 @@ use std::collections::{HashMap, HashSet}; +use super::contextualize::Contextualize; + use thiserror::Error; use crate::{Document, DocumentId}; @@ -79,3 +81,24 @@ impl DocumentTree { .chain(self.descendants.iter().map(|(depth, node)| (*depth, node))) } } + +impl Contextualize for DocumentTree { + fn render_context(&self) -> String { + let mut text = String::new(); + let mut first_line = true; + for (depth, node) in self.nodes() { + let rendered = node.render_context(); + for line in rendered.split('\n') { + if !first_line { + text.push('\n'); + } + first_line = false; + for _ in 1..depth { + text.push_str(" "); + } + text.push_str(line); + } + } + text + } +} diff --git a/crates/documents/src/user.rs b/crates/documents/src/user.rs index 9e1be6e..47ef685 100644 --- a/crates/documents/src/user.rs +++ b/crates/documents/src/user.rs @@ -1,3 +1,4 @@ +use super::contextualize::Contextualize; use super::id::{IdError, validate_id}; #[derive(Clone, Debug, Eq, Hash, PartialEq)] @@ -22,3 +23,9 @@ pub struct User { pub id: UserId, pub display_name: String, } + +impl Contextualize for User { + fn render_context(&self) -> String { + format!("User: {}", self.display_name) + } +} diff --git a/crates/documents/src/workspace.rs b/crates/documents/src/workspace.rs index dc701fa..437553e 100644 --- a/crates/documents/src/workspace.rs +++ b/crates/documents/src/workspace.rs @@ -1,3 +1,4 @@ +use super::contextualize::Contextualize; use super::{ id::{IdError, validate_id}, organization::OrganizationId, @@ -27,3 +28,9 @@ pub struct Workspace { pub organization_id: OrganizationId, pub name: String, } + +impl Contextualize for Workspace { + fn render_context(&self) -> String { + format!("Workspace: {}", self.name) + } +}