218 lines
6.4 KiB
Rust
218 lines
6.4 KiB
Rust
//! 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<Revision, StorageError> {
|
|
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<Revision>,
|
|
) -> Result<Snapshot, StorageError> {
|
|
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<Revision, StorageError> {
|
|
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<Store>,
|
|
primary: Reader,
|
|
replicas: Vec<Reader>,
|
|
next_replica: AtomicUsize,
|
|
}
|
|
|
|
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
|
|
connect_resolved(&config.resolve()?).await
|
|
}
|
|
|
|
pub async fn connect_resolved(config: &ResolvedDeployment) -> Result<Connection, ConnectError> {
|
|
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<Connection, ConnectError> {
|
|
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::<Result<_, _>>()?;
|
|
Ok(Connection {
|
|
driver: config.driver,
|
|
writer,
|
|
primary,
|
|
replicas,
|
|
next_replica: AtomicUsize::new(0),
|
|
})
|
|
}
|
|
|
|
fn reader(config: &ResolvedSql, address: &Address) -> Result<Reader, StorageError> {
|
|
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<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(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,
|
|
}
|
|
}
|
|
}
|