Merge main into SQL persistence and integrate backend configuration
This commit is contained in:
@@ -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"] }
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
@@ -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)
|
||||
));
|
||||
}
|
||||
Reference in New Issue
Block a user