Rename the db crate to database

This commit is contained in:
2026-11-30 20:23:47 +08:00
parent af9f25baa5
commit f0470c406b
16 changed files with 15 additions and 13 deletions
+277
View File
@@ -0,0 +1,277 @@
use std::{collections::BTreeMap, env, time::Duration};
use database::{
Connection, DeploymentConfig, Driver, Mutation, ReadPreference, Resource, SqlCluster,
StorageError, Tls, connect,
};
use serde_json::json;
fn change(id: &str, text: &str) -> Mutation {
Mutation {
collection: "notes".into(),
id: id.into(),
value: Some(json!({ "text": text })),
}
}
fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig {
DeploymentConfig {
deployment: deployment.into(),
bindings: BTreeMap::from([("documents".into(), "test".into())]),
resources: BTreeMap::from([(
"test".into(),
Resource::Sql(SqlCluster {
driver,
primary: url.into(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 4,
}),
)]),
..DeploymentConfig::default()
}
}
fn test_url(variable: &str) -> Option<String> {
match env::var(variable) {
Ok(url) => Some(url),
Err(_) if env::var_os("BEDROCK_REQUIRE_SQL_TESTS").is_some() => {
panic!("{variable} is required for the remote storage checks")
}
Err(_) => None,
}
}
async fn check_document_contract(db: &Connection) {
assert_eq!(db.revision().await.unwrap(), 0);
let original = change("doc", "first");
assert_eq!(db.commit(0, &[original]).await.unwrap(), 1);
let duplicate = [
change("other", "never written"),
change("other", "duplicate"),
];
assert!(matches!(
db.commit(1, &duplicate).await,
Err(StorageError::Invalid(_))
));
assert!(matches!(
db.commit(0, &[change("other", "stale")]).await,
Err(StorageError::WriteConflict)
));
let second = [change("doc", "second")];
let alternative = [change("doc", "alternative")];
let (one, two) = tokio::join!(db.commit(1, &second), db.commit(1, &alternative));
assert!(matches!(
(&one, &two),
(Ok(2), Err(StorageError::WriteConflict)) | (Err(StorageError::WriteConflict), Ok(2))
));
let old = db
.get("notes", "doc", Some(1), ReadPreference::Primary)
.await
.unwrap();
assert_eq!(old.document.unwrap().value, json!({ "text": "first" }));
assert!(matches!(
db.get("notes", "doc", Some(3), ReadPreference::Primary)
.await,
Err(StorageError::Behind {
requested: 3,
available: 2
})
));
assert!(
db.get("notes", "other", None, ReadPreference::Primary)
.await
.unwrap()
.document
.is_none()
);
let tombstone = Mutation {
collection: "notes".into(),
id: "doc".into(),
value: None,
};
let null_document = Mutation {
collection: "notes".into(),
id: "null".into(),
value: Some(json!(null)),
};
assert_eq!(db.commit(2, &[tombstone, null_document]).await.unwrap(), 3);
assert!(
db.get("notes", "doc", None, ReadPreference::Primary)
.await
.unwrap()
.document
.is_none()
);
let null_document = db
.get("notes", "null", None, ReadPreference::Primary)
.await
.unwrap();
assert_eq!(null_document.document.unwrap().value, json!(null));
}
#[tokio::test]
async fn sqlite_persists_across_reopening_and_enforces_read_only() {
let folder = tempfile::tempdir().unwrap();
let filename = folder.path().join("bedrock +?#%.sqlite");
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
let db = connect(&config).await.unwrap();
assert_eq!(db.driver(), Driver::Sqlite);
check_document_contract(&db).await;
drop(db);
config.read_only = true;
let db = connect(&config).await.unwrap();
assert_eq!(db.revision().await.unwrap(), 3);
assert!(db.is_read_only());
assert!(matches!(
db.commit(3, &[change("doc", "invalid")]).await,
Err(StorageError::ReadOnly)
));
}
#[tokio::test]
async fn sqlite_read_only_startup_does_not_create_a_database() {
let folder = tempfile::tempdir().unwrap();
let filename = folder.path().join("missing.sqlite");
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
config.read_only = true;
assert!(connect(&config).await.is_err());
assert!(!filename.exists());
}
#[tokio::test]
async fn postgres_reads_replicas_and_falls_back_when_behind() {
let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else {
return;
};
let replica_url = test_url("BEDROCK_TEST_POSTGRES_REPLICA").unwrap();
let mut config = sql_config(Driver::Postgres, &url, "pg_contract");
let Some(Resource::Sql(cluster)) = config.resources.get_mut("test") else {
panic!("expected a SQL resource");
};
cluster.replicas.push(replica_url.clone().into());
let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract"))
.await
.unwrap();
let (db, concurrent) = tokio::join!(connect(&config), connect(&config));
let db = db.unwrap();
assert_eq!(concurrent.unwrap().revision().await.unwrap(), 0);
check_document_contract(&db).await;
replica
.commit(0, &[change("doc", "replica")])
.await
.unwrap();
let stale = db
.get("notes", "doc", None, ReadPreference::PreferReplica)
.await
.unwrap();
assert_eq!(stale.revision, 1);
assert_eq!(stale.document.unwrap().value, json!({ "text": "replica" }));
let fresh = db
.get("notes", "null", Some(3), ReadPreference::PreferReplica)
.await
.unwrap();
assert_eq!(fresh.revision, 3);
assert_eq!(fresh.document.unwrap().value, json!(null));
config.read_only = true;
let db = connect(&config).await.unwrap();
assert!(db.is_read_only());
assert_eq!(db.revision().await.unwrap(), 3);
}
#[tokio::test]
async fn mysql_fences_writers_and_cleans_only_one_deployment() {
let Some(url) = test_url("BEDROCK_TEST_MYSQL") else {
return;
};
let config = sql_config(Driver::Mysql, &url, "mysql_contract");
let db = connect(&config).await.unwrap();
check_document_contract(&db).await;
let other = connect(&sql_config(Driver::Mysql, &url, "mysql_other"))
.await
.unwrap();
other.commit(0, &[change("doc", "keep")]).await.unwrap();
let mysql = db.mysql_writer().unwrap();
let lease = mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(
mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.is_none()
);
assert!(matches!(
db.commit(3, &[change("doc", "blocked")]).await,
Err(StorageError::WriteConflict)
));
assert!(matches!(
other
.mysql_writer()
.unwrap()
.delete_deployment(&lease)
.await,
Err(StorageError::LeaseLost)
));
mysql
.renew_lease(&lease, Duration::from_secs(30))
.await
.unwrap();
assert_eq!(
mysql
.commit_with_lease(&lease, 3, &[change("doc", "leased")])
.await
.unwrap(),
4
);
assert!(mysql.release_lease(&lease).await.unwrap());
let next = mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(next.epoch() > lease.epoch());
assert!(matches!(
mysql
.commit_with_lease(&lease, 4, &[change("doc", "stale")])
.await,
Err(StorageError::WriteConflict)
));
assert!(mysql.delete_deployment(&next).await.unwrap() > 0);
assert!(matches!(
db.revision().await,
Err(StorageError::MissingDeployment)
));
assert!(connect(&config).await.is_err());
assert_eq!(
other
.get("notes", "doc", None, ReadPreference::Primary)
.await
.unwrap()
.document
.unwrap()
.value,
json!({ "text": "keep" })
);
let mut other_config = sql_config(Driver::Mysql, &url, "mysql_other");
other_config.read_only = true;
assert_eq!(
connect(&other_config)
.await
.unwrap()
.revision()
.await
.unwrap(),
1
);
}
@@ -0,0 +1,135 @@
use std::{collections::BTreeMap, path::Path};
use database::{
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)
));
}