//! Deployment bootstrap and read routing. use std::sync::atomic::{AtomicUsize, Ordering}; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; pub use mysql::{Lease, MySql}; pub use persistence::{Document, Error as StorageError, Mutation, Revision, Snapshot}; use clusters::ResolvedDeployment; use persistence::{Reader, Store}; use thiserror::Error; #[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, primary: Reader, replicas: Vec, next_replica: AtomicUsize, } pub async fn connect(config: &DeploymentConfig) -> Result { 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::>()?; Ok(Connection { driver: config.driver, writer, primary, replicas, next_replica: AtomicUsize::new(0), }) } fn reader(config: &ResolvedDeployment, address: &Address) -> Result { 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 { self.primary.revision().await } pub async fn get( &self, collection: &str, id: &str, at: Option, preference: ReadPreference, ) -> Result { 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 { 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, } } }