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
+1
View File
@@ -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
+88 -27
View File
@@ -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<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 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<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(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())
}
+72 -6
View File
@@ -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)
));
}