Files
Bedrock/crates/db/tests/storage.rs

273 lines
7.9 KiB
Rust

use std::{collections::BTreeMap, env, time::Duration};
use db::{
Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, 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(),
cluster: Some("test".into()),
clusters: BTreeMap::from([(
"test".into(),
Cluster {
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 = DeploymentConfig {
sqlite_path: filename.to_str().unwrap().into(),
..DeploymentConfig::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 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");
config
.clusters
.get_mut("test")
.unwrap()
.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
);
}