Model pages and blocks as document nodes

This commit is contained in:
2026-11-30 18:36:16 +08:00
parent 365be3870e
commit 455a3580d6
11 changed files with 481 additions and 35 deletions
Generated
+2
View File
@@ -160,6 +160,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"clusters", "clusters",
"documents", "documents",
"serde",
"serde_json", "serde_json",
"sqlx", "sqlx",
"tempfile", "tempfile",
@@ -205,6 +206,7 @@ dependencies = [
name = "documents" name = "documents"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"serde",
"serde_json", "serde_json",
"thiserror", "thiserror",
] ]
+1
View File
@@ -7,6 +7,7 @@ rust-version.workspace = true
[dependencies] [dependencies]
clusters.workspace = true clusters.workspace = true
documents.workspace = true documents.workspace = true
serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] } sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] }
thiserror.workspace = true thiserror.workspace = true
+88 -27
View File
@@ -1,14 +1,15 @@
//! Maps workspace documents onto the versioned SQL store. //! Maps workspace documents onto the versioned SQL store.
//! //!
//! Within a deployment, the workspace selects a reserved collection prefix plus its ID. //! Within a deployment, the workspace selects a collection and the document ID selects
//! The document ID becomes the row key in that collection, and the body is JSON. //! 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}; use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError};
// This collection namespace belongs to the workspace-document adapter. const COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v2:";
const COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v1:"; const LEGACY_COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v1:";
/// A logical document and the deployment revision at which it was last written. /// A logical document and the deployment revision at which it was last written.
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@@ -17,27 +18,46 @@ pub struct StoredDocument {
pub revision: Revision, pub revision: Revision,
} }
#[derive(Deserialize, Serialize)]
struct DocumentPayload {
parent_id: Option<String>,
position: u64,
content: DocumentContent,
}
impl Connection { impl Connection {
/// Creates a document using the primary snapshot and its expected revision. /// Creates a document using the primary snapshot and its expected revision.
pub async fn create_document(&self, document: Document) -> Result<Revision> { pub async fn create_document(&self, document: Document) -> Result<Revision> {
if self.is_read_only() { if self.is_read_only() {
return Err(StorageError::ReadOnly); return Err(StorageError::ReadOnly);
} }
let collection = collection(&document.key); let (revision, existing) = self.lookup_document(&document.key, None).await?;
let id = document.key.document.as_str(); if existing.is_some() {
let snapshot = self
.get(&collection, id, None, ReadPreference::Primary)
.await?;
if snapshot.document.is_some() {
return Err(StorageError::DocumentAlreadyExists); 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( self.commit(
snapshot.revision, revision,
&[Mutation { &[Mutation {
collection, collection: collection(COLLECTION_PREFIX, &document.key),
id: id.to_owned(), id: document.key.document.as_str().to_owned(),
value: Some(document.body), value: Some(value),
}], }],
) )
.await .await
@@ -45,24 +65,65 @@ impl Connection {
/// Reads the latest state of a workspace document from the primary. /// Reads the latest state of a workspace document from the primary.
pub async fn get_document(&self, key: &DocumentKey) -> Result<Option<StoredDocument>> { 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 let snapshot = self
.get( .get(
&collection(key), &collection(COLLECTION_PREFIX, key),
key.document.as_str(), id,
None, at,
ReadPreference::Primary, ReadPreference::Primary,
) )
.await?; .await?;
Ok(snapshot.document.map(|stored| StoredDocument { let revision = snapshot.revision;
document: Document { if let Some(stored) = snapshot.document {
key: key.clone(), let payload: DocumentPayload = serde_json::from_value(stored.value)?;
body: stored.value, let parent_id = payload
}, .parent_id
revision: stored.revision, .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 { fn collection(prefix: &str, key: &DocumentKey) -> String {
format!("{COLLECTION_PREFIX}{}", key.workspace.as_str()) format!("{prefix}{}", key.workspace.as_str())
} }
+72 -6
View File
@@ -1,15 +1,17 @@
use db::{DeploymentConfig, StorageError, connect}; use db::{DeploymentConfig, Mutation, StorageError, connect};
use documents::{Document, DocumentId, DocumentKey, WorkspaceId}; use documents::{
Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, WorkspaceId,
};
use serde_json::json; use serde_json::json;
fn document(workspace: &str, body: serde_json::Value) -> Document { fn document(workspace: &str, body: serde_json::Value) -> Document {
Document { Document::new(
key: DocumentKey { DocumentKey {
workspace: WorkspaceId::new(workspace).unwrap(), workspace: WorkspaceId::new(workspace).unwrap(),
document: DocumentId::new("same-id").unwrap(), document: DocumentId::new("same-id").unwrap(),
}, },
body, DocumentContent::Json(body),
} )
} }
#[tokio::test] #[tokio::test]
@@ -54,3 +56,67 @@ async fn workspace_documents_keep_their_identity_and_contents_after_reopen() {
Err(StorageError::ReadOnly) 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)
));
}
+1
View File
@@ -5,5 +5,6 @@ edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
[dependencies] [dependencies]
serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
thiserror.workspace = true thiserror.workspace = true
+104
View File
@@ -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()
)
}
}
+37 -1
View File
@@ -1,7 +1,9 @@
use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use super::{ use super::{
id::{IdError, validate_id}, id::{IdError, validate_id},
rich_text::RichText,
workspace::WorkspaceId, workspace::WorkspaceId,
}; };
@@ -32,5 +34,39 @@ pub struct DocumentKey {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct Document { pub struct Document {
pub key: DocumentKey, pub key: DocumentKey,
pub body: Value, 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),
} }
+7 -1
View File
@@ -1,13 +1,19 @@
//! Logical models for documents, workspaces, users, and organizations. //! Logical models for documents, workspaces, users, and organizations.
mod context;
mod document; mod document;
mod id; mod id;
mod organization; mod organization;
mod rich_text;
mod tree;
mod user; mod user;
mod workspace; 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 id::IdError;
pub use organization::{Organization, OrganizationId, OrganizationMembership, OrganizationRole}; 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 user::{User, UserId};
pub use workspace::{Workspace, WorkspaceId}; pub use workspace::{Workspace, WorkspaceId};
+18
View File
@@ -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<Inline>);
impl From<&str> for RichText {
fn from(value: &str) -> Self {
Self(vec![Inline::Text(value.into())])
}
}
+81
View File
@@ -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<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)))
}
}
+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)
));
}