//! Deployment bootstrap and read routing. use std::sync::atomic::{AtomicUsize, Ordering}; use clusters::{ Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedDeployment, ResolvedSql, SqlDriver as Driver, }; use thiserror::Error; use crate::{ common::{Error as StorageError, Mutation, Revision, Snapshot}, mysql::{self, MySql, MySqlReader}, postgres::{self, Postgres, PostgresReader}, sqlite::{self, Sqlite, SqliteReader}, }; #[derive(Debug, Error)] pub enum ConnectError { #[error(transparent)] Config(#[from] ConfigError), #[error("the documents SQL role is not configured")] MissingDocuments, #[error("the documents role must reference a SQL resource")] InvalidDocuments, #[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, } /// A reader backed by the configured database. It exposes no raw SQL connection. #[derive(Clone)] pub enum Reader { Sqlite(SqliteReader), Postgres(PostgresReader), Mysql(MySqlReader), } impl Reader { pub async fn revision(&self) -> Result { match self { Self::Sqlite(reader) => reader.revision().await, Self::Postgres(reader) => reader.revision().await, Self::Mysql(reader) => reader.revision().await, } } pub async fn get( &self, collection: &str, id: &str, at: Option, ) -> Result { match self { Self::Sqlite(reader) => reader.get(collection, id, at).await, Self::Postgres(reader) => reader.get(collection, id, at).await, Self::Mysql(reader) => reader.get(collection, id, at).await, } } } #[derive(Clone)] pub enum Store { Sqlite(Sqlite), Postgres(Postgres), Mysql(MySql), } impl Store { pub fn reader(&self) -> Reader { match self { Self::Sqlite(store) => Reader::Sqlite(store.reader()), Self::Postgres(store) => Reader::Postgres(store.reader()), Self::Mysql(store) => Reader::Mysql(store.reader()), } } pub async fn commit( &self, expected: Revision, changes: &[Mutation], ) -> Result { match self { Self::Sqlite(store) => store.commit(expected, changes).await, Self::Postgres(store) => store.commit(expected, changes).await, Self::Mysql(store) => store.commit(expected, changes).await, } } } pub struct Connection { driver: Driver, writer: Option, primary: Reader, replicas: Vec, next_replica: AtomicUsize, } pub async fn connect(config: &DeploymentConfig) -> Result { connect_resolved(&config.resolve()?).await } pub async fn connect_resolved(config: &ResolvedDeployment) -> Result { let resource = config .binding(DOCUMENTS) .ok_or(ConnectError::MissingDocuments)?; connect_sql(resource.as_sql().ok_or(ConnectError::InvalidDocuments)?).await } pub async fn connect_sql(config: &ResolvedSql) -> Result { 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 => Store::Sqlite(sqlite::connect(url, name).await?), Driver::Postgres => Store::Postgres(postgres::connect(url, name, max).await?), Driver::Mysql => Store::Mysql(MySql::connect(url, name, max).await?), }) }; let primary = match &writer { Some(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: &ResolvedSql, address: &Address) -> Result { let url = address.connection_string(); let name = &config.deployment; match config.driver { Driver::Sqlite => sqlite::reader(url, name).map(Reader::Sqlite), Driver::Postgres => { postgres::reader(url, name, config.max_connections).map(Reader::Postgres) } Driver::Mysql => mysql::reader(url, name, config.max_connections).map(Reader::Mysql), } } 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(store) => store.commit(expected, changes).await, None => Err(StorageError::ReadOnly), } } pub fn mysql_writer(&self) -> Option<&MySql> { match &self.writer { Some(Store::Mysql(store)) => Some(store), _ => None, } } }