Add a workspace document model and SQL storage adapter
This commit is contained in:
Generated
+9
@@ -159,6 +159,7 @@ name = "db"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clusters",
|
"clusters",
|
||||||
|
"documents",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
@@ -200,6 +201,14 @@ dependencies = [
|
|||||||
"syn 3.0.10",
|
"syn 3.0.10",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "documents"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"serde_json",
|
||||||
|
"thiserror",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dotenvy"
|
name = "dotenvy"
|
||||||
version = "0.15.7"
|
version = "0.15.7"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ rust-version = "1.91"
|
|||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
clusters = { path = "crates/clusters" }
|
clusters = { path = "crates/clusters" }
|
||||||
db = { path = "crates/db" }
|
db = { path = "crates/db" }
|
||||||
|
documents = { path = "crates/documents" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] }
|
sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] }
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ rust-version.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clusters.workspace = true
|
clusters.workspace = true
|
||||||
|
documents.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
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ pub enum Error {
|
|||||||
},
|
},
|
||||||
#[error("the write conflicts with the current revision or lease")]
|
#[error("the write conflicts with the current revision or lease")]
|
||||||
WriteConflict,
|
WriteConflict,
|
||||||
|
#[error("the workspace document already exists")]
|
||||||
|
DocumentAlreadyExists,
|
||||||
#[error("lease is missing, expired, or belongs to another store")]
|
#[error("lease is missing, expired, or belongs to another store")]
|
||||||
LeaseLost,
|
LeaseLost,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ mod connection;
|
|||||||
pub mod mysql;
|
pub mod mysql;
|
||||||
pub mod postgres;
|
pub mod postgres;
|
||||||
pub mod sqlite;
|
pub mod sqlite;
|
||||||
|
mod workspace_documents;
|
||||||
|
|
||||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||||
pub use connection::{ConnectError, Connection, ReadPreference, connect};
|
pub use connection::{ConnectError, Connection, ReadPreference, connect};
|
||||||
pub use mysql::{Lease, MySql};
|
pub use mysql::{Lease, MySql};
|
||||||
|
pub use workspace_documents::StoredDocument;
|
||||||
|
|
||||||
pub use common::Error as StorageError;
|
pub use common::Error as StorageError;
|
||||||
pub use common::{
|
pub use common::{
|
||||||
|
|||||||
@@ -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<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() {
|
||||||
|
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<Option<StoredDocument>> {
|
||||||
|
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())
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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<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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 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(())
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user