Move SQL connection routing into sql_storage
This commit is contained in:
@@ -5,6 +5,11 @@ edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
clusters.workspace = true
|
||||
serde_json.workspace = true
|
||||
sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] }
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Deployment bootstrap and read routing.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeployment};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
Error as StorageError, Mutation, Reader, Revision, Snapshot, Store,
|
||||
mysql::{self, MySql},
|
||||
postgres, sqlite,
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ConnectError {
|
||||
#[error(transparent)]
|
||||
Config(#[from] ConfigError),
|
||||
#[error(transparent)]
|
||||
Storage(#[from] StorageError),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ReadPreference {
|
||||
/// Read from the primary endpoint.
|
||||
#[default]
|
||||
Primary,
|
||||
/// Try configured replicas in round-robin order, then fall back to the primary.
|
||||
/// Without an explicit snapshot revision a replica may return stale data.
|
||||
PreferReplica,
|
||||
}
|
||||
|
||||
enum Writer {
|
||||
Sql(Store),
|
||||
MySql(MySql),
|
||||
}
|
||||
|
||||
pub struct Connection {
|
||||
driver: Driver,
|
||||
writer: Option<Writer>,
|
||||
primary: Reader,
|
||||
replicas: Vec<Reader>,
|
||||
next_replica: AtomicUsize,
|
||||
}
|
||||
|
||||
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
|
||||
let config = config.resolve()?;
|
||||
let writer = if config.read_only {
|
||||
None
|
||||
} else {
|
||||
let url = config.primary.connection_string();
|
||||
let name = &config.deployment;
|
||||
let max = config.max_connections;
|
||||
Some(match config.driver {
|
||||
Driver::Sqlite => Writer::Sql(sqlite::connect(url, name).await?),
|
||||
Driver::Postgres => Writer::Sql(postgres::connect(url, name, max).await?),
|
||||
Driver::Mysql => Writer::MySql(MySql::connect(url, name, max).await?),
|
||||
})
|
||||
};
|
||||
let primary = match &writer {
|
||||
Some(Writer::Sql(store)) => store.reader(),
|
||||
Some(Writer::MySql(store)) => store.reader(),
|
||||
None => {
|
||||
let reader = reader(&config, &config.primary)?;
|
||||
reader.revision().await?;
|
||||
reader
|
||||
}
|
||||
};
|
||||
let replicas = config
|
||||
.replicas
|
||||
.iter()
|
||||
.map(|address| reader(&config, address))
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Connection {
|
||||
driver: config.driver,
|
||||
writer,
|
||||
primary,
|
||||
replicas,
|
||||
next_replica: AtomicUsize::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
fn reader(config: &ResolvedDeployment, address: &Address) -> Result<Reader, StorageError> {
|
||||
let url = address.connection_string();
|
||||
let name = &config.deployment;
|
||||
match config.driver {
|
||||
Driver::Sqlite => sqlite::reader(url, name),
|
||||
Driver::Postgres => postgres::reader(url, name, config.max_connections),
|
||||
Driver::Mysql => mysql::reader(url, name, config.max_connections),
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
pub fn driver(&self) -> Driver {
|
||||
self.driver
|
||||
}
|
||||
|
||||
pub fn is_read_only(&self) -> bool {
|
||||
self.writer.is_none()
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision, StorageError> {
|
||||
self.primary.revision().await
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
&self,
|
||||
collection: &str,
|
||||
id: &str,
|
||||
at: Option<Revision>,
|
||||
preference: ReadPreference,
|
||||
) -> Result<Snapshot, StorageError> {
|
||||
if preference == ReadPreference::PreferReplica && !self.replicas.is_empty() {
|
||||
let count = self.replicas.len();
|
||||
let start = self.next_replica.fetch_add(1, Ordering::Relaxed) % count;
|
||||
for replica in self.replicas.iter().cycle().skip(start).take(count) {
|
||||
match replica.get(collection, id, at).await {
|
||||
Ok(snapshot) => return Ok(snapshot),
|
||||
Err(error) if error.retry_on_primary() => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.primary.get(collection, id, at).await
|
||||
}
|
||||
|
||||
pub async fn commit(
|
||||
&self,
|
||||
expected: Revision,
|
||||
changes: &[Mutation],
|
||||
) -> Result<Revision, StorageError> {
|
||||
match &self.writer {
|
||||
Some(Writer::Sql(store)) => store.commit(expected, changes).await,
|
||||
Some(Writer::MySql(store)) => store.commit(expected, changes).await,
|
||||
None => Err(StorageError::ReadOnly),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mysql_writer(&self) -> Option<&MySql> {
|
||||
match &self.writer {
|
||||
Some(Writer::MySql(store)) => Some(store),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
//! Bedrock's transactional document storage for SQL databases.
|
||||
|
||||
mod connection;
|
||||
pub mod mysql;
|
||||
pub mod postgres;
|
||||
pub mod sqlite;
|
||||
|
||||
pub use Error as StorageError;
|
||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||
pub use connection::{ConnectError, Connection, ReadPreference, connect};
|
||||
pub use mysql::{Lease, MySql};
|
||||
|
||||
use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
use std::{collections::BTreeMap, env, time::Duration};
|
||||
|
||||
use serde_json::json;
|
||||
use sql_storage::{
|
||||
Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, StorageError, Tls,
|
||||
connect,
|
||||
};
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user