Merge main into SQL persistence and integrate backend configuration

This commit is contained in:
2026-11-30 19:19:27 +08:00
25 changed files with 1284 additions and 4 deletions
+11
View File
@@ -0,0 +1,11 @@
[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
subtle.workspace = true
+120
View File
@@ -0,0 +1,120 @@
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::{DOCUMENTS, ResolvedDeployment, SqlDriver};
use serde::Serialize;
use subtle::ConstantTimeEq;
#[derive(Clone)]
struct AdminState {
config: Arc<ResolvedDeployment>,
config_version: Option<String>,
storage_driver: &'static str,
read_only: bool,
}
#[derive(Serialize)]
struct DeploymentStatus<'a> {
deployment: &'a str,
config_version: Option<&'a str>,
storage_driver: &'static str,
read_only: bool,
}
impl AdminState {
fn status(&self) -> DeploymentStatus<'_> {
let config = &self.config;
DeploymentStatus {
deployment: &config.deployment,
config_version: self
.config_version
.as_deref()
.or(Some(&config.config_version)),
storage_driver: self.storage_driver,
read_only: self.read_only,
}
}
}
pub fn router(
config: Arc<ResolvedDeployment>,
config_version: Option<String>,
token: String,
) -> io::Result<Router> {
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 settings = config
.binding(DOCUMENTS)
.and_then(|resource| resource.as_sql())
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"documents must reference a SQL resource",
)
})?;
let storage_driver = match settings.driver {
SqlDriver::Sqlite => "sqlite",
SqlDriver::Postgres => "postgres",
SqlDriver::Mysql => "mysql",
};
let read_only = settings.read_only;
let admin = Router::new()
.route("/status", get(deployment_status))
.route_layer(middleware::from_fn_with_state(
Arc::<str>::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(AdminState {
config,
config_version,
storage_driver,
read_only,
}))
}
async fn deployment_status(State(state): State<AdminState>) -> Response {
([(header::CACHE_CONTROL, "no-store")], Json(state.status())).into_response()
}
async fn require_admin(State(token): State<Arc<str>>, 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()))
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "backend"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
admin_backend = { path = "../admin_backend" }
axum.workspace = true
db.workspace = true
tokio = { workspace = true, features = ["net", "signal", "sync", "time"] }
+17
View File
@@ -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<Arc<db::Connection>>) -> StatusCode {
match tokio::time::timeout(Duration::from_secs(2), db.revision()).await {
Ok(Ok(_)) => StatusCode::NO_CONTENT,
_ => StatusCode::SERVICE_UNAVAILABLE,
}
}
+98
View File
@@ -0,0 +1,98 @@
use std::{env, error::Error, io, net::SocketAddr, sync::Arc};
use axum::Router;
use db::{DeploymentConfig, connect_resolved};
use tokio::{net::TcpListener, sync::watch};
#[tokio::main]
async fn main() -> Result<(), Box<dyn 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) => DeploymentConfig::load(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 listener = TcpListener::bind(address).await?;
let db = connect_resolved(&config).await?;
println!("Bedrock backend listening on {}", listener.local_addr()?);
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<Option<String>, 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<bool>,
) -> 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)]
{
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;
}
+2
View File
@@ -7,10 +7,12 @@ rust-version.workspace = true
[dependencies]
clusters.workspace = true
deadpool-postgres.workspace = true
documents.workspace = true
mysql_async.workspace = true
rusqlite.workspace = true
rustls.workspace = true
rustls-pemfile.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["sync", "time"] }
+2
View File
@@ -37,6 +37,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,
}
+6 -2
View File
@@ -3,7 +3,8 @@
use std::sync::atomic::{AtomicUsize, Ordering};
use clusters::{
Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedSql, SqlDriver as Driver,
Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedDeployment, ResolvedSql,
SqlDriver as Driver,
};
use thiserror::Error;
@@ -105,7 +106,10 @@ pub struct Connection {
}
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
let config = config.resolve()?;
connect_resolved(&config.resolve()?).await
}
pub async fn connect_resolved(config: &ResolvedDeployment) -> Result<Connection, ConnectError> {
let resource = config
.binding(DOCUMENTS)
.ok_or(ConnectError::MissingDocuments)?;
+129
View File
@@ -0,0 +1,129 @@
//! Maps workspace documents onto the versioned SQL store.
//!
//! 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, DocumentContent, DocumentId, DocumentKey};
use serde::{Deserialize, Serialize};
use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError};
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)]
pub struct StoredDocument {
pub document: Document,
pub revision: Revision,
}
#[derive(Deserialize, Serialize)]
struct DocumentPayload {
parent_id: Option<String>,
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<Revision> {
if self.is_read_only() {
return Err(StorageError::ReadOnly);
}
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(
revision,
&[Mutation {
collection: collection(COLLECTION_PREFIX, &document.key),
id: document.key.document.as_str().to_owned(),
value: Some(value),
}],
)
.await
}
/// Reads the latest state of a workspace document from the primary.
pub async fn get_document(&self, key: &DocumentKey) -> Result<Option<StoredDocument>> {
let (_, document) = self.lookup_document(key, None).await?;
Ok(document)
}
async fn lookup_document(
&self,
key: &DocumentKey,
at: Option<Revision>,
) -> Result<(Revision, Option<StoredDocument>)> {
let id = key.document.as_str();
let snapshot = self
.get(
&collection(COLLECTION_PREFIX, key),
id,
at,
ReadPreference::Primary,
)
.await?;
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(prefix: &str, key: &DocumentKey) -> String {
format!("{prefix}{}", key.workspace.as_str())
}
+3 -1
View File
@@ -2,10 +2,12 @@
mod common;
mod connection;
mod documents;
pub mod mysql;
pub mod postgres;
pub mod sqlite;
pub use self::documents::StoredDocument;
pub use clusters::SqlDriver as Dialect;
pub use clusters::{
Address, Cluster, ConfigError, DeploymentConfig, Resource, SqlCluster, SqlDriver as Driver, Tls,
@@ -13,6 +15,6 @@ pub use clusters::{
pub use common::Error as StorageError;
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot};
pub use connection::{
ConnectError, Connection, ReadPreference, Reader, Store, connect, connect_sql,
ConnectError, Connection, ReadPreference, Reader, Store, connect, connect_resolved, connect_sql,
};
pub use mysql::{Lease, MySql};
+133
View File
@@ -0,0 +1,133 @@
use std::{collections::BTreeMap, path::Path};
use db::{DeploymentConfig, Driver, Mutation, Resource, SqlCluster, StorageError, Tls, connect};
use documents::{
Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, WorkspaceId,
};
use serde_json::json;
fn document(workspace: &str, body: serde_json::Value) -> Document {
Document::new(
DocumentKey {
workspace: WorkspaceId::new(workspace).unwrap(),
document: DocumentId::new("same-id").unwrap(),
},
DocumentContent::Json(body),
)
}
fn sqlite_config(path: &Path) -> DeploymentConfig {
DeploymentConfig {
resources: BTreeMap::from([(
"local".into(),
Resource::Sql(SqlCluster {
driver: Driver::Sqlite,
primary: path.to_str().unwrap().into(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 1,
}),
)]),
bindings: BTreeMap::from([("documents".into(), "local".into())]),
..DeploymentConfig::default()
}
}
#[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 = sqlite_config(&path);
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)
));
}
#[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(&sqlite_config(&path)).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)
));
}
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "documents"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
+4
View File
@@ -0,0 +1,4 @@
/// Produces a textual description from already available data.
pub trait Contextualize {
fn render_context(&self) -> String;
}
+97
View File
@@ -0,0 +1,97 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::contextualize::Contextualize;
use super::{
id::{IdError, validate_id},
rich_text::RichText,
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<String>) -> Result<Self, IdError> {
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 parent_id: Option<DocumentId>,
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),
}
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()
}
}
+20
View File
@@ -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(())
}
+19
View File
@@ -0,0 +1,19 @@
//! Logical models for documents, workspaces, users, and organizations.
mod contextualize;
mod document;
mod id;
mod organization;
mod rich_text;
mod tree;
mod user;
mod workspace;
pub use contextualize::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};
+64
View File
@@ -0,0 +1,64 @@
use super::contextualize::Contextualize;
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<String>) -> Result<Self, IdError> {
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,
}
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()
)
}
}
+38
View File
@@ -0,0 +1,38 @@
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 {
Text(String),
Link { label: String, url: String },
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(transparent)]
pub struct RichText(pub Vec<Inline>);
impl From<&str> for RichText {
fn from(value: &str) -> Self {
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
}
}
+104
View File
@@ -0,0 +1,104 @@
use std::collections::{HashMap, HashSet};
use super::contextualize::Contextualize;
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<Item = Document>,
) -> Result<Self, TreeError> {
let mut ids = HashSet::from([root.key.document.clone()]);
let mut by_parent: HashMap<DocumentId, Vec<Document>> = 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<Item = (usize, &Document)> {
std::iter::once((0, &self.root))
.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
}
}
+31
View File
@@ -0,0 +1,31 @@
use super::contextualize::Contextualize;
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<String>) -> Result<Self, IdError> {
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,
}
impl Contextualize for User {
fn render_context(&self) -> String {
format!("User: {}", self.display_name)
}
}
+36
View File
@@ -0,0 +1,36 @@
use super::contextualize::Contextualize;
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<String>) -> Result<Self, IdError> {
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,
}
impl Contextualize for Workspace {
fn render_context(&self) -> String {
format!("Workspace: {}", self.name)
}
}
+70
View File
@@ -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::<Vec<_>>(),
[(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)
));
}