将 Bedrock 存储切换为数据库原生驱动 #25
Generated
+771
-530
File diff suppressed because it is too large
Load Diff
+9
-1
@@ -9,13 +9,21 @@ rust-version = "1.91"
|
||||
[workspace.dependencies]
|
||||
clusters = { path = "crates/clusters" }
|
||||
db = { path = "crates/db" }
|
||||
deadpool-postgres = "0.14.1"
|
||||
mysql_async = { version = "0.36.1", default-features = false, features = ["minimal-rust", "ring", "rustls-tls", "tls12"] }
|
||||
rusqlite = { version = "0.32.1", features = ["bundled"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-pemfile = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] }
|
||||
tempfile = "3"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
tokio-postgres = "0.7.18"
|
||||
tokio-postgres-rustls = { version = "0.13", default-features = false }
|
||||
tokio-rusqlite = "0.6"
|
||||
url = "2"
|
||||
webpki-roots = "1"
|
||||
|
||||
[package]
|
||||
name = "bedrock"
|
||||
|
||||
@@ -21,7 +21,7 @@ pub enum Tls {
|
||||
Disabled,
|
||||
}
|
||||
|
||||
/// A database address may contain credentials.
|
||||
/// A database address. Debug output includes the full value, which may contain credentials.
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Address(String);
|
||||
@@ -40,7 +40,7 @@ impl From<String> for Address {
|
||||
|
||||
impl fmt::Debug for Address {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("Address([redacted])")
|
||||
fmt::Debug::fmt(&self.0, formatter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use clusters::{Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||
use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||
|
||||
#[test]
|
||||
fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
|
||||
fn address_debug_formats_the_inner_string() {
|
||||
let value = "bedrock.sqlite3";
|
||||
assert_eq!(format!("{:?}", Address::from(value)), format!("{value:?}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_cluster_requires_matching_addresses() {
|
||||
let mut config = DeploymentConfig {
|
||||
cluster: Some("regional".into()),
|
||||
clusters: BTreeMap::from([(
|
||||
@@ -30,8 +36,6 @@ fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
|
||||
.connection_string()
|
||||
.ends_with("sslmode=verify-full")
|
||||
);
|
||||
assert!(!format!("{resolved:?}").contains("secret"));
|
||||
|
||||
config.clusters.get_mut("regional").unwrap().replicas[0] =
|
||||
"mysql://user:secret@replica/bedrock".into();
|
||||
assert!(matches!(
|
||||
|
||||
+11
-1
@@ -6,9 +6,19 @@ rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
clusters.workspace = true
|
||||
deadpool-postgres.workspace = true
|
||||
mysql_async.workspace = true
|
||||
rusqlite.workspace = true
|
||||
rustls.workspace = true
|
||||
rustls-pemfile.workspace = true
|
||||
serde_json.workspace = true
|
||||
sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] }
|
||||
thiserror.workspace = true
|
||||
tokio = { workspace = true, features = ["sync", "time"] }
|
||||
tokio-postgres.workspace = true
|
||||
tokio-postgres-rustls.workspace = true
|
||||
tokio-rusqlite.workspace = true
|
||||
url.workspace = true
|
||||
webpki-roots.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
+95
-312
@@ -1,22 +1,29 @@
|
||||
//! Shared SQL connection pools, documents, snapshots and write transactions.
|
||||
//! Driver-independent documents, revisions, validation and encoding.
|
||||
|
||||
use std::{borrow::Cow, collections::HashSet, fmt::Write, time::Duration};
|
||||
use std::{collections::HashSet, time::Duration};
|
||||
|
||||
use serde_json::Value;
|
||||
use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions};
|
||||
use thiserror::Error;
|
||||
|
||||
pub type Revision = i64;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("invalid {0}")]
|
||||
Invalid(&'static str),
|
||||
#[error("the database connection failed")]
|
||||
Connection,
|
||||
#[error("SQL operation failed: {0}")]
|
||||
Sql(#[from] sqlx::Error),
|
||||
#[error("SQLite operation failed: {0}")]
|
||||
Sqlite(#[from] rusqlite::Error),
|
||||
#[error("PostgreSQL operation failed: {0}")]
|
||||
Postgres(#[from] tokio_postgres::Error),
|
||||
#[error("MySQL operation failed: {0}")]
|
||||
Mysql(#[from] mysql_async::Error),
|
||||
#[error("invalid database row")]
|
||||
InvalidRow,
|
||||
#[error("document encoding failed: {0}")]
|
||||
Encoding(#[from] serde_json::Error),
|
||||
#[error("the connection is read-only")]
|
||||
@@ -38,18 +45,17 @@ impl Error {
|
||||
pub fn retry_on_primary(&self) -> bool {
|
||||
match self {
|
||||
Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true,
|
||||
Self::Sql(error) => match error {
|
||||
sqlx::Error::Io(_)
|
||||
| sqlx::Error::Tls(_)
|
||||
| sqlx::Error::PoolTimedOut
|
||||
| sqlx::Error::PoolClosed
|
||||
| sqlx::Error::WorkerCrashed => true,
|
||||
sqlx::Error::Database(db) => db.code().is_some_and(|code| {
|
||||
code.starts_with("08")
|
||||
|| matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146")
|
||||
}),
|
||||
_ => false,
|
||||
},
|
||||
Self::Postgres(error) => {
|
||||
error.is_closed()
|
||||
|| error.code().is_some_and(|code| {
|
||||
code.code().starts_with("08")
|
||||
|| matches!(code.code(), "57P01" | "57P03" | "42P01")
|
||||
})
|
||||
}
|
||||
Self::Mysql(mysql_async::Error::Server(error)) => {
|
||||
error.state.starts_with("08") || error.code == 1146
|
||||
}
|
||||
Self::Mysql(error) => error.is_fatal(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -75,272 +81,75 @@ pub struct Mutation {
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Dialect {
|
||||
Sqlite,
|
||||
Postgres,
|
||||
Mysql,
|
||||
pub(crate) type EncodedSnapshot = (Revision, Option<Revision>, Option<Vec<u8>>);
|
||||
|
||||
pub(crate) struct EncodedMutation<'a> {
|
||||
pub collection: &'a [u8],
|
||||
pub id: &'a [u8],
|
||||
pub payload: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Opened SQL reader. Its pool is private so callers cannot bypass the read API.
|
||||
#[derive(Clone)]
|
||||
pub struct Reader {
|
||||
pool: AnyPool,
|
||||
dialect: Dialect,
|
||||
deployment: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
reader: Reader,
|
||||
}
|
||||
|
||||
/// Returns a lazily connected pool. The writer initializes schema before use.
|
||||
#[doc(hidden)]
|
||||
pub fn pool(dialect: Dialect, url: &str, connections: u32, read_only: bool) -> Result<AnyPool> {
|
||||
if connections == 0 {
|
||||
return Err(Error::Invalid("database pool size"));
|
||||
pub(crate) fn validate_read(collection: &str, id: &str, at: Option<Revision>) -> Result<()> {
|
||||
validate_id(collection)?;
|
||||
validate_id(id)?;
|
||||
if at.is_some_and(|revision| revision < 0) {
|
||||
return Err(Error::Invalid("snapshot revision"));
|
||||
}
|
||||
sqlx::any::install_default_drivers();
|
||||
let mut options = AnyPoolOptions::new()
|
||||
.max_connections(connections)
|
||||
.acquire_timeout(Duration::from_secs(5));
|
||||
let read_only_statement = match dialect {
|
||||
Dialect::Sqlite => "PRAGMA query_only = ON",
|
||||
Dialect::Postgres => "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY",
|
||||
Dialect::Mysql => "SET SESSION TRANSACTION READ ONLY",
|
||||
};
|
||||
if read_only {
|
||||
options = options.after_connect(move |connection, _| {
|
||||
Box::pin(async move {
|
||||
sqlx::query(read_only_statement).execute(connection).await?;
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
}
|
||||
options.connect_lazy(url).map_err(|_| Error::Connection)
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
#[doc(hidden)]
|
||||
pub fn new(pool: AnyPool, dialect: Dialect, deployment: &str) -> Result<Self> {
|
||||
validate_id(deployment)?;
|
||||
Ok(Self {
|
||||
pool,
|
||||
dialect,
|
||||
deployment: deployment.as_bytes().to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision> {
|
||||
let statement = statement(
|
||||
self.dialect,
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
|
||||
);
|
||||
sqlx::query_scalar(&statement)
|
||||
.bind(self.deployment.as_slice())
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(connection_error)?
|
||||
.ok_or(Error::MissingDeployment)
|
||||
}
|
||||
|
||||
/// Fetch at the latest revision or at an exact, previously committed snapshot.
|
||||
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
|
||||
validate_id(collection)?;
|
||||
validate_id(id)?;
|
||||
if at.is_some_and(|at| at < 0) {
|
||||
return Err(Error::Invalid("snapshot revision"));
|
||||
}
|
||||
// A single statement keeps the revision and document on the same database snapshot.
|
||||
let statement = statement(
|
||||
self.dialect,
|
||||
"
|
||||
SELECT d.revision AS available, v.revision AS document_revision, v.payload
|
||||
FROM bedrock_deployments d
|
||||
LEFT JOIN bedrock_documents v
|
||||
ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ?
|
||||
AND v.revision <= COALESCE(?, d.revision)
|
||||
WHERE d.deployment = ? AND d.retired = 0
|
||||
ORDER BY v.revision DESC LIMIT 1",
|
||||
);
|
||||
let row = sqlx::query(&statement)
|
||||
.bind(collection.as_bytes())
|
||||
.bind(id.as_bytes())
|
||||
.bind(at)
|
||||
.bind(self.deployment.as_slice())
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(connection_error)?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
let available = row.try_get("available")?;
|
||||
let revision = at.unwrap_or(available);
|
||||
if revision > available {
|
||||
return Err(Error::Behind {
|
||||
requested: revision,
|
||||
available,
|
||||
});
|
||||
}
|
||||
let document_revision: Option<Revision> = row.try_get("document_revision")?;
|
||||
let payload: Option<Vec<u8>> = row.try_get("payload")?;
|
||||
let document = match (document_revision, payload) {
|
||||
(Some(revision), Some(payload)) => Some(Document {
|
||||
revision,
|
||||
value: serde_json::from_slice(&payload)?,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
Ok(Snapshot { revision, document })
|
||||
}
|
||||
}
|
||||
|
||||
impl Store {
|
||||
#[doc(hidden)]
|
||||
pub async fn initialize(
|
||||
pool: AnyPool,
|
||||
dialect: Dialect,
|
||||
deployment: &str,
|
||||
schema: &[&str],
|
||||
insert_deployment: &str,
|
||||
) -> Result<Self> {
|
||||
let reader = Reader::new(pool, dialect, deployment)?;
|
||||
if dialect == Dialect::Postgres {
|
||||
// PostgreSQL catalog inserts can race even with IF NOT EXISTS.
|
||||
let mut transaction = reader.pool.begin().await.map_err(connection_error)?;
|
||||
sqlx::query("SELECT pg_advisory_xact_lock(1694199371)")
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
initialize_schema(
|
||||
&mut transaction,
|
||||
schema,
|
||||
insert_deployment,
|
||||
&reader.deployment,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
} else {
|
||||
let mut connection = reader.pool.acquire().await.map_err(connection_error)?;
|
||||
initialize_schema(
|
||||
&mut connection,
|
||||
schema,
|
||||
insert_deployment,
|
||||
&reader.deployment,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
reader.revision().await?;
|
||||
Ok(Self { reader })
|
||||
}
|
||||
|
||||
pub fn reader(&self) -> Reader {
|
||||
self.reader.clone()
|
||||
}
|
||||
|
||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
||||
self.commit_with_fence(expected, mutations, None).await
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub async fn commit_with_fence(
|
||||
&self,
|
||||
expected: Revision,
|
||||
mutations: &[Mutation],
|
||||
fence: Option<i64>,
|
||||
) -> Result<Revision> {
|
||||
let revision = expected
|
||||
.checked_add(1)
|
||||
.filter(|_| expected >= 0)
|
||||
.ok_or(Error::Invalid("expected revision"))?;
|
||||
if mutations.is_empty() {
|
||||
return Err(Error::Invalid("empty write batch"));
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let mut rows = Vec::with_capacity(mutations.len());
|
||||
for mutation in mutations {
|
||||
validate_id(&mutation.collection)?;
|
||||
validate_id(&mutation.id)?;
|
||||
if !seen.insert((&mutation.collection, &mutation.id)) {
|
||||
return Err(Error::Invalid("duplicate document in write batch"));
|
||||
}
|
||||
let payload = mutation
|
||||
.value
|
||||
.as_ref()
|
||||
.map(serde_json::to_vec)
|
||||
.transpose()?;
|
||||
rows.push((
|
||||
mutation.collection.as_bytes(),
|
||||
mutation.id.as_bytes(),
|
||||
payload,
|
||||
));
|
||||
}
|
||||
|
||||
let store = &self.reader;
|
||||
let mut transaction = store.pool.begin().await.map_err(connection_error)?;
|
||||
let mut advance = "UPDATE bedrock_deployments SET revision = ? WHERE deployment = ? AND revision = ? AND retired = 0".to_owned();
|
||||
if store.dialect == Dialect::Mysql {
|
||||
lock_mysql_deployment(&mut transaction, &store.deployment).await?;
|
||||
if fence.is_some() {
|
||||
advance.push_str(" AND lease_epoch = ? AND lease_until > ");
|
||||
} else {
|
||||
advance.push_str(" AND lease_until <= ");
|
||||
}
|
||||
advance.push_str(MYSQL_NOW);
|
||||
} else if fence.is_some() {
|
||||
return Err(Error::Invalid("lease on a database without lease support"));
|
||||
}
|
||||
let advance = statement(store.dialect, &advance);
|
||||
let mut query = sqlx::query(&advance)
|
||||
.bind(revision)
|
||||
.bind(store.deployment.as_slice())
|
||||
.bind(expected);
|
||||
if let Some(fence) = fence {
|
||||
query = query.bind(fence);
|
||||
}
|
||||
if query.execute(&mut *transaction).await?.rows_affected() != 1 {
|
||||
return Err(Error::WriteConflict);
|
||||
}
|
||||
let insert = statement(
|
||||
store.dialect,
|
||||
"
|
||||
INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
|
||||
VALUES (?, ?, ?, ?, ?)",
|
||||
);
|
||||
for (collection, id, payload) in rows {
|
||||
sqlx::query(&insert)
|
||||
.bind(store.deployment.as_slice())
|
||||
.bind(collection)
|
||||
.bind(id)
|
||||
.bind(revision)
|
||||
.bind(payload)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(revision)
|
||||
}
|
||||
}
|
||||
|
||||
/// MySQL server time in milliseconds, shared by lease management and fenced writes.
|
||||
#[doc(hidden)]
|
||||
pub const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)";
|
||||
|
||||
/// Lock before reading the database clock. MySQL timestamps are fixed at statement start.
|
||||
#[doc(hidden)]
|
||||
pub async fn lock_mysql_deployment(
|
||||
connection: &mut AnyConnection,
|
||||
deployment: &[u8],
|
||||
) -> Result<()> {
|
||||
sqlx::query_scalar::<_, Revision>(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE",
|
||||
)
|
||||
.bind(deployment)
|
||||
.fetch_optional(connection)
|
||||
.await?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_id(value: &str) -> Result<()> {
|
||||
pub(crate) fn snapshot(row: Option<EncodedSnapshot>, at: Option<Revision>) -> Result<Snapshot> {
|
||||
let (available, document_revision, payload) = row.ok_or(Error::MissingDeployment)?;
|
||||
let revision = at.unwrap_or(available);
|
||||
if revision > available {
|
||||
return Err(Error::Behind {
|
||||
requested: revision,
|
||||
available,
|
||||
});
|
||||
}
|
||||
let document = match (document_revision, payload) {
|
||||
(Some(revision), Some(payload)) => Some(Document {
|
||||
revision,
|
||||
value: serde_json::from_slice(&payload)?,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
Ok(Snapshot { revision, document })
|
||||
}
|
||||
|
||||
pub(crate) fn encode_batch(
|
||||
expected: Revision,
|
||||
mutations: &[Mutation],
|
||||
) -> Result<(Revision, Vec<EncodedMutation<'_>>)> {
|
||||
let revision = expected
|
||||
.checked_add(1)
|
||||
.filter(|_| expected >= 0)
|
||||
.ok_or(Error::Invalid("expected revision"))?;
|
||||
if mutations.is_empty() {
|
||||
return Err(Error::Invalid("empty write batch"));
|
||||
}
|
||||
let mut seen = HashSet::with_capacity(mutations.len());
|
||||
let mut rows = Vec::with_capacity(mutations.len());
|
||||
for mutation in mutations {
|
||||
validate_id(&mutation.collection)?;
|
||||
validate_id(&mutation.id)?;
|
||||
if !seen.insert((&mutation.collection, &mutation.id)) {
|
||||
return Err(Error::Invalid("duplicate document in write batch"));
|
||||
}
|
||||
rows.push(EncodedMutation {
|
||||
collection: mutation.collection.as_bytes(),
|
||||
id: mutation.id.as_bytes(),
|
||||
payload: mutation
|
||||
.value
|
||||
.as_ref()
|
||||
.map(serde_json::to_vec)
|
||||
.transpose()?,
|
||||
});
|
||||
}
|
||||
Ok((revision, rows))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_id(value: &str) -> Result<()> {
|
||||
if value.is_empty() || value.len() > 128 || value.contains('\0') {
|
||||
return Err(Error::Invalid(
|
||||
"identifier (expected 1–128 bytes without NUL)",
|
||||
@@ -349,38 +158,12 @@ fn validate_id(value: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn initialize_schema(
|
||||
connection: &mut AnyConnection,
|
||||
schema: &[&str],
|
||||
insert_deployment: &str,
|
||||
deployment: &[u8],
|
||||
) -> Result<()> {
|
||||
for ddl in schema {
|
||||
sqlx::query(ddl).execute(&mut *connection).await?;
|
||||
}
|
||||
sqlx::query(insert_deployment)
|
||||
.bind(deployment)
|
||||
.execute(connection)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn statement(dialect: Dialect, sql: &str) -> Cow<'_, str> {
|
||||
if dialect != Dialect::Postgres {
|
||||
return Cow::Borrowed(sql);
|
||||
}
|
||||
let mut parts = sql.split('?');
|
||||
let mut translated = parts.next().unwrap_or_default().to_owned();
|
||||
for (index, part) in parts.enumerate() {
|
||||
let _ = write!(translated, "${}", index + 1);
|
||||
translated.push_str(part);
|
||||
}
|
||||
Cow::Owned(translated)
|
||||
}
|
||||
|
||||
fn connection_error(error: sqlx::Error) -> Error {
|
||||
match error {
|
||||
sqlx::Error::Configuration(_) => Error::Connection,
|
||||
other => Error::Sql(other),
|
||||
}
|
||||
}
|
||||
// A single statement observes the revision and the document at the same point in time.
|
||||
pub(crate) const GET_DOCUMENT: &str = "
|
||||
SELECT d.revision, v.revision, v.payload
|
||||
FROM bedrock_deployments d
|
||||
LEFT JOIN bedrock_documents v
|
||||
ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ?
|
||||
AND v.revision <= COALESCE(?, d.revision)
|
||||
WHERE d.deployment = ? AND d.retired = 0
|
||||
ORDER BY v.revision DESC LIMIT 1";
|
||||
|
||||
+74
-18
@@ -6,9 +6,10 @@ use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeploymen
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
common::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store},
|
||||
mysql::{self, MySql},
|
||||
postgres, sqlite,
|
||||
common::{Error as StorageError, Mutation, Revision, Snapshot},
|
||||
mysql::{self, MySql, MySqlReader},
|
||||
postgres::{self, Postgres, PostgresReader},
|
||||
sqlite::{self, Sqlite, SqliteReader},
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -29,14 +30,69 @@ pub enum ReadPreference {
|
||||
PreferReplica,
|
||||
}
|
||||
|
||||
enum Writer {
|
||||
Sql(Store),
|
||||
MySql(MySql),
|
||||
/// 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<Writer>,
|
||||
writer: Option<Store>,
|
||||
primary: Reader,
|
||||
replicas: Vec<Reader>,
|
||||
next_replica: AtomicUsize,
|
||||
@@ -51,14 +107,13 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
|
||||
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?),
|
||||
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(Writer::Sql(store)) => store.reader(),
|
||||
Some(Writer::MySql(store)) => store.reader(),
|
||||
Some(store) => store.reader(),
|
||||
None => {
|
||||
let reader = reader(&config, &config.primary)?;
|
||||
reader.revision().await?;
|
||||
@@ -83,9 +138,11 @@ fn reader(config: &ResolvedDeployment, address: &Address) -> Result<Reader, Stor
|
||||
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),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,15 +186,14 @@ impl Connection {
|
||||
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,
|
||||
Some(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),
|
||||
Some(Store::Mysql(store)) => Some(store),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,9 @@ pub mod mysql;
|
||||
pub mod postgres;
|
||||
pub mod sqlite;
|
||||
|
||||
pub use clusters::Driver as Dialect;
|
||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||
pub use connection::{ConnectError, Connection, ReadPreference, connect};
|
||||
pub use mysql::{Lease, MySql};
|
||||
|
||||
pub use common::Error as StorageError;
|
||||
pub use common::{
|
||||
Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store,
|
||||
lock_mysql_deployment, pool,
|
||||
};
|
||||
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot};
|
||||
pub use connection::{ConnectError, Connection, ReadPreference, Reader, Store, connect};
|
||||
pub use mysql::{Lease, MySql};
|
||||
|
||||
+276
-75
@@ -1,12 +1,19 @@
|
||||
//! MySQL storage, writer leases and deployment cleanup.
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use std::{fmt::Write, path::PathBuf, sync::Arc, time::Duration};
|
||||
|
||||
use mysql_async::{
|
||||
ClientIdentity, Conn, Opts, OptsBuilder, Pool, PoolConstraints, PoolOpts, Row, SslOpts, TxOpts,
|
||||
from_row_opt, prelude::Queryable,
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
use crate::common::{
|
||||
Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment,
|
||||
pool,
|
||||
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
|
||||
snapshot, validate_id, validate_read,
|
||||
};
|
||||
use sqlx::AnyPool;
|
||||
|
||||
const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)";
|
||||
|
||||
const SCHEMA: &[&str] = &[
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||
@@ -29,12 +36,68 @@ const SCHEMA: &[&str] = &[
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MySql {
|
||||
store: Store,
|
||||
pool: AnyPool,
|
||||
deployment: Vec<u8>,
|
||||
reader: MySqlReader,
|
||||
identity: Arc<()>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MySqlReader {
|
||||
pool: Pool,
|
||||
deployment: Arc<[u8]>,
|
||||
}
|
||||
|
||||
impl MySqlReader {
|
||||
fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result<Self> {
|
||||
validate_id(deployment)?;
|
||||
Ok(Self {
|
||||
pool: Pool::new(connection_options(url, max_connections, read_only)?),
|
||||
deployment: Arc::from(deployment.as_bytes()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn connection(&self) -> Result<Conn> {
|
||||
tokio::time::timeout(CONNECT_TIMEOUT, self.pool.get_conn())
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?
|
||||
.map_err(|_| Error::Connection)
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision> {
|
||||
let row: Row = self
|
||||
.connection()
|
||||
.await?
|
||||
.exec_first(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
|
||||
(self.deployment.as_ref(),),
|
||||
)
|
||||
.await?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
from_row_opt(row).map_err(|_| Error::InvalidRow)
|
||||
}
|
||||
|
||||
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
|
||||
validate_read(collection, id, at)?;
|
||||
let row: Option<Row> = self
|
||||
.connection()
|
||||
.await?
|
||||
.exec_first(
|
||||
GET_DOCUMENT,
|
||||
(
|
||||
collection.as_bytes(),
|
||||
id.as_bytes(),
|
||||
at,
|
||||
self.deployment.as_ref(),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
let row = row
|
||||
.map(from_row_opt)
|
||||
.transpose()
|
||||
.map_err(|_| Error::InvalidRow)?;
|
||||
snapshot(row, at)
|
||||
}
|
||||
}
|
||||
|
||||
/// The monotonically increasing epoch fences off holders whose lease expired.
|
||||
#[derive(Debug)]
|
||||
pub struct Lease {
|
||||
@@ -50,31 +113,34 @@ impl Lease {
|
||||
|
||||
impl MySql {
|
||||
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Self> {
|
||||
let pool = pool(Dialect::Mysql, url, max_connections, false)?;
|
||||
let store = Store::initialize(
|
||||
pool.clone(),
|
||||
Dialect::Mysql,
|
||||
deployment,
|
||||
SCHEMA,
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
||||
ON DUPLICATE KEY UPDATE revision = revision",
|
||||
)
|
||||
.await?;
|
||||
let reader = MySqlReader::new(url, deployment, max_connections, false)?;
|
||||
{
|
||||
let mut connection = reader.connection().await?;
|
||||
for ddl in SCHEMA {
|
||||
connection.query_drop(*ddl).await?;
|
||||
}
|
||||
connection
|
||||
.exec_drop(
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
||||
ON DUPLICATE KEY UPDATE revision = revision",
|
||||
(reader.deployment.as_ref(),),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
reader.revision().await?;
|
||||
Ok(Self {
|
||||
store,
|
||||
pool,
|
||||
deployment: deployment.as_bytes().to_vec(),
|
||||
reader,
|
||||
identity: Arc::new(()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn reader(&self) -> Reader {
|
||||
self.store.reader()
|
||||
pub fn reader(&self) -> MySqlReader {
|
||||
self.reader.clone()
|
||||
}
|
||||
|
||||
/// An ordinary write is allowed while no lease is active.
|
||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
||||
self.store.commit(expected, mutations).await
|
||||
self.commit_with_fence(expected, mutations, None).await
|
||||
}
|
||||
|
||||
pub async fn commit_with_lease(
|
||||
@@ -83,12 +149,44 @@ impl MySql {
|
||||
expected: Revision,
|
||||
mutations: &[Mutation],
|
||||
) -> Result<Revision> {
|
||||
let epoch = self.epoch(lease)?;
|
||||
self.store
|
||||
.commit_with_fence(expected, mutations, Some(epoch))
|
||||
self.commit_with_fence(expected, mutations, Some(self.epoch(lease)?))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn commit_with_fence(
|
||||
&self,
|
||||
expected: Revision,
|
||||
mutations: &[Mutation],
|
||||
fence: Option<i64>,
|
||||
) -> Result<Revision> {
|
||||
let (revision, rows) = encode_batch(expected, mutations)?;
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction
|
||||
.exec_drop(
|
||||
format!(
|
||||
"UPDATE bedrock_deployments SET revision = ?
|
||||
WHERE deployment = ? AND revision = ? AND retired = 0
|
||||
AND ((? IS NULL AND lease_until <= {MYSQL_NOW})
|
||||
OR (lease_epoch = ? AND lease_until > {MYSQL_NOW}))"
|
||||
),
|
||||
(revision, deployment, expected, fence, fence),
|
||||
)
|
||||
.await?;
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Err(Error::WriteConflict);
|
||||
}
|
||||
transaction.exec_batch(
|
||||
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
|
||||
VALUES (?, ?, ?, ?, ?)",
|
||||
rows.into_iter().map(|row| (deployment, row.collection, row.id, revision, row.payload)),
|
||||
).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
/// Acquires an expired or unheld lease using the database clock.
|
||||
pub async fn acquire_lease(&self, ttl: Duration) -> Result<Option<Lease>> {
|
||||
let ttl = lease_millis(ttl)?;
|
||||
@@ -98,21 +196,21 @@ impl MySql {
|
||||
SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ?
|
||||
WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}"
|
||||
);
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
|
||||
let changed = sqlx::query(&update)
|
||||
.bind(ttl)
|
||||
.bind(self.deployment.as_slice())
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
if changed.rows_affected() != 1 {
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction.exec_drop(update, (ttl, deployment)).await?;
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
let epoch =
|
||||
sqlx::query_scalar("SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?")
|
||||
.bind(self.deployment.as_slice())
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
let epoch: i64 = transaction
|
||||
.exec_first(
|
||||
"SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?",
|
||||
(deployment,),
|
||||
)
|
||||
.await?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
transaction.commit().await?;
|
||||
Ok(Some(Lease {
|
||||
epoch,
|
||||
@@ -130,15 +228,14 @@ impl MySql {
|
||||
SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?)
|
||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
||||
);
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
|
||||
let changed = sqlx::query(&update)
|
||||
.bind(ttl)
|
||||
.bind(self.deployment.as_slice())
|
||||
.bind(epoch)
|
||||
.execute(&mut *transaction)
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction
|
||||
.exec_drop(update, (ttl, deployment, epoch))
|
||||
.await?;
|
||||
if changed.rows_affected() != 1 {
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Err(Error::LeaseLost);
|
||||
}
|
||||
transaction.commit().await?;
|
||||
@@ -147,16 +244,15 @@ impl MySql {
|
||||
|
||||
pub async fn release_lease(&self, lease: &Lease) -> Result<bool> {
|
||||
let epoch = self.epoch(lease)?;
|
||||
let changed = sqlx::query(
|
||||
"
|
||||
UPDATE bedrock_deployments SET lease_until = 0
|
||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
|
||||
)
|
||||
.bind(self.deployment.as_slice())
|
||||
.bind(epoch)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(changed.rows_affected() == 1)
|
||||
let mut connection = self.reader.connection().await?;
|
||||
connection
|
||||
.exec_drop(
|
||||
"UPDATE bedrock_deployments SET lease_until = 0
|
||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
|
||||
(self.reader.deployment.as_ref(), epoch),
|
||||
)
|
||||
.await?;
|
||||
Ok(connection.affected_rows() == 1)
|
||||
}
|
||||
|
||||
/// Removes only this deployment's documents and retires its identity in one transaction.
|
||||
@@ -168,22 +264,23 @@ impl MySql {
|
||||
UPDATE bedrock_deployments SET retired = 1, lease_until = 0
|
||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
||||
);
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
|
||||
let changed = sqlx::query(&update)
|
||||
.bind(self.deployment.as_slice())
|
||||
.bind(epoch)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
if changed.rows_affected() != 1 {
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut connection = self.reader.connection().await?;
|
||||
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||
lock_deployment(&mut transaction, deployment).await?;
|
||||
transaction.exec_drop(update, (deployment, epoch)).await?;
|
||||
if transaction.affected_rows() != 1 {
|
||||
return Err(Error::LeaseLost);
|
||||
}
|
||||
let removed = sqlx::query("DELETE FROM bedrock_documents WHERE deployment = ?")
|
||||
.bind(self.deployment.as_slice())
|
||||
.execute(&mut *transaction)
|
||||
transaction
|
||||
.exec_drop(
|
||||
"DELETE FROM bedrock_documents WHERE deployment = ?",
|
||||
(deployment,),
|
||||
)
|
||||
.await?;
|
||||
let removed = transaction.affected_rows();
|
||||
transaction.commit().await?;
|
||||
Ok(removed.rows_affected())
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
fn epoch(&self, lease: &Lease) -> Result<i64> {
|
||||
@@ -194,12 +291,116 @@ impl MySql {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<Reader> {
|
||||
Reader::new(
|
||||
pool(Dialect::Mysql, url, max_connections, true)?,
|
||||
Dialect::Mysql,
|
||||
deployment,
|
||||
)
|
||||
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<MySqlReader> {
|
||||
MySqlReader::new(url, deployment, max_connections, true)
|
||||
}
|
||||
|
||||
// MySQL evaluates the clock at statement start. Take the lock before checking the lease.
|
||||
async fn lock_deployment(
|
||||
transaction: &mut mysql_async::Transaction<'_>,
|
||||
deployment: &[u8],
|
||||
) -> Result<()> {
|
||||
let revision: Option<Revision> = transaction.exec_first(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE",
|
||||
(deployment,),
|
||||
).await?;
|
||||
revision.ok_or(Error::MissingDeployment)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn connection_options(address: &str, max_connections: u32, read_only: bool) -> Result<Opts> {
|
||||
if max_connections == 0 {
|
||||
return Err(Error::Invalid("database pool size"));
|
||||
}
|
||||
let mut url = Url::parse(address).map_err(|_| Error::Connection)?;
|
||||
let mut tls = true;
|
||||
let (mut ca, mut cert, mut key) = (None, None, None);
|
||||
let (mut charset, mut collation, mut timezone, mut cache_size) = (None, None, None, None);
|
||||
for (name, value) in url.query_pairs() {
|
||||
match name.as_ref() {
|
||||
"sslmode" | "ssl-mode" => {
|
||||
tls = match value.as_ref() {
|
||||
"DISABLED" => false,
|
||||
"VERIFY_IDENTITY" => true,
|
||||
_ => return Err(Error::Connection),
|
||||
}
|
||||
}
|
||||
"sslca" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())),
|
||||
"sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())),
|
||||
"sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())),
|
||||
"charset" => charset = Some(mysql_identifier(&value)?),
|
||||
"collation" => collation = Some(mysql_identifier(&value)?),
|
||||
"timezone" | "time-zone" => timezone = Some(value.into_owned()),
|
||||
"statement-cache-capacity" => {
|
||||
cache_size = Some(value.parse::<usize>().map_err(|_| Error::Connection)?)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
url.set_query(None);
|
||||
let mut setup = Vec::new();
|
||||
if charset.is_some() || collation.is_some() {
|
||||
let charset = charset.as_deref().unwrap_or("utf8mb4");
|
||||
let names = match collation {
|
||||
Some(collation) => format!("SET NAMES {charset} COLLATE {collation}"),
|
||||
None => format!("SET NAMES {charset}"),
|
||||
};
|
||||
setup.push(names);
|
||||
}
|
||||
if let Some(timezone) = timezone {
|
||||
// A hex literal preserves the configured value without interpolating SQL syntax.
|
||||
let mut encoded = String::new();
|
||||
for byte in timezone.as_bytes() {
|
||||
write!(encoded, "{byte:02x}").expect("writing to a string cannot fail");
|
||||
}
|
||||
setup.push(format!("SET time_zone = X'{encoded}'"));
|
||||
}
|
||||
if read_only {
|
||||
setup.push("SET SESSION TRANSACTION READ ONLY".into());
|
||||
}
|
||||
let constraints =
|
||||
PoolConstraints::new(max_connections.min(8) as usize, max_connections as usize)
|
||||
.ok_or(Error::Invalid("database pool size"))?;
|
||||
let opts = Opts::from_url(url.as_str()).map_err(|_| Error::Connection)?;
|
||||
let mut builder = OptsBuilder::from_opts(opts)
|
||||
.prefer_socket(false)
|
||||
.pool_opts(
|
||||
PoolOpts::new()
|
||||
.with_constraints(constraints)
|
||||
.with_reset_connection(false),
|
||||
)
|
||||
.setup(setup);
|
||||
if let Some(cache_size) = cache_size {
|
||||
builder = builder.stmt_cache_size(cache_size);
|
||||
}
|
||||
if tls {
|
||||
let mut ssl = SslOpts::default();
|
||||
if let Some(ca) = ca {
|
||||
ssl = ssl
|
||||
.with_disable_built_in_roots(true)
|
||||
.with_root_certs(vec![ca.into()]);
|
||||
}
|
||||
match (cert, key) {
|
||||
(Some(cert), Some(key)) => {
|
||||
ssl = ssl.with_client_identity(Some(ClientIdentity::new(cert.into(), key.into())))
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => return Err(Error::Connection),
|
||||
}
|
||||
builder = builder.ssl_opts(Some(ssl));
|
||||
}
|
||||
Ok(builder.into())
|
||||
}
|
||||
|
||||
fn mysql_identifier(value: &str) -> Result<String> {
|
||||
if value.is_empty()
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
|
||||
{
|
||||
return Err(Error::Connection);
|
||||
}
|
||||
Ok(format!("`{value}`"))
|
||||
}
|
||||
|
||||
fn lease_millis(ttl: Duration) -> Result<i64> {
|
||||
|
||||
+251
-18
@@ -1,6 +1,17 @@
|
||||
//! PostgreSQL connection pools and the Bedrock document layout.
|
||||
|
||||
use crate::common::{Dialect, Reader, Result, Store, pool};
|
||||
use std::{fs::File, io::BufReader, path::PathBuf, sync::Arc};
|
||||
|
||||
use deadpool_postgres::{Manager, Pool, Runtime};
|
||||
use rustls::{ClientConfig, RootCertStore};
|
||||
use tokio_postgres::{Config, config::SslMode};
|
||||
use tokio_postgres_rustls::MakeRustlsConnect;
|
||||
use url::Url;
|
||||
|
||||
use crate::common::{
|
||||
CONNECT_TIMEOUT, Error, Mutation, Result, Revision, Snapshot, encode_batch, snapshot,
|
||||
validate_id, validate_read,
|
||||
};
|
||||
|
||||
const SCHEMA: &[&str] = &[
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||
@@ -18,23 +29,245 @@ const SCHEMA: &[&str] = &[
|
||||
)",
|
||||
];
|
||||
|
||||
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Store> {
|
||||
let pool = pool(Dialect::Postgres, url, max_connections, false)?;
|
||||
Store::initialize(
|
||||
pool,
|
||||
Dialect::Postgres,
|
||||
deployment,
|
||||
SCHEMA,
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES ($1)
|
||||
ON CONFLICT (deployment) DO NOTHING",
|
||||
)
|
||||
.await
|
||||
const GET_DOCUMENT: &str = "
|
||||
SELECT d.revision, v.revision, v.payload
|
||||
FROM bedrock_deployments d
|
||||
LEFT JOIN bedrock_documents v
|
||||
ON v.deployment = d.deployment AND v.collection = $1 AND v.document_id = $2
|
||||
AND v.revision <= COALESCE($3, d.revision)
|
||||
WHERE d.deployment = $4 AND d.retired = 0
|
||||
ORDER BY v.revision DESC LIMIT 1";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PostgresReader {
|
||||
pool: Pool,
|
||||
deployment: Arc<[u8]>,
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<Reader> {
|
||||
Reader::new(
|
||||
pool(Dialect::Postgres, url, max_connections, true)?,
|
||||
Dialect::Postgres,
|
||||
deployment,
|
||||
)
|
||||
#[derive(Clone)]
|
||||
pub struct Postgres {
|
||||
reader: PostgresReader,
|
||||
}
|
||||
|
||||
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Postgres> {
|
||||
let reader = PostgresReader::new(url, deployment, max_connections, false)?;
|
||||
{
|
||||
let mut client = reader.client().await?;
|
||||
let transaction = client.transaction().await?;
|
||||
// PostgreSQL catalog inserts can race even with IF NOT EXISTS.
|
||||
transaction
|
||||
.batch_execute("SELECT pg_advisory_xact_lock(1694199371)")
|
||||
.await?;
|
||||
for ddl in SCHEMA {
|
||||
transaction.batch_execute(ddl).await?;
|
||||
}
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES ($1)
|
||||
ON CONFLICT (deployment) DO NOTHING",
|
||||
&[&reader.deployment.as_ref()],
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
}
|
||||
reader.revision().await?;
|
||||
Ok(Postgres { reader })
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<PostgresReader> {
|
||||
PostgresReader::new(url, deployment, max_connections, true)
|
||||
}
|
||||
|
||||
impl PostgresReader {
|
||||
fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result<Self> {
|
||||
validate_id(deployment)?;
|
||||
if max_connections == 0 {
|
||||
return Err(Error::Invalid("database pool size"));
|
||||
}
|
||||
let (config, tls) = connection_options(url, read_only)?;
|
||||
let manager = Manager::new(config, tls);
|
||||
let pool = Pool::builder(manager)
|
||||
.max_size(max_connections as usize)
|
||||
.runtime(Runtime::Tokio1)
|
||||
.wait_timeout(Some(CONNECT_TIMEOUT))
|
||||
.create_timeout(Some(CONNECT_TIMEOUT))
|
||||
.build()
|
||||
.map_err(|_| Error::Connection)?;
|
||||
Ok(Self {
|
||||
pool,
|
||||
deployment: Arc::from(deployment.as_bytes()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn client(&self) -> Result<deadpool_postgres::Client> {
|
||||
self.pool.get().await.map_err(|_| Error::Connection)
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision> {
|
||||
let client = self.client().await?;
|
||||
let query = client
|
||||
.prepare_cached(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = $1 AND retired = 0",
|
||||
)
|
||||
.await?;
|
||||
let row = client
|
||||
.query_opt(&query, &[&self.deployment.as_ref()])
|
||||
.await?
|
||||
.ok_or(Error::MissingDeployment)?;
|
||||
Ok(row.try_get(0)?)
|
||||
}
|
||||
|
||||
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
|
||||
validate_read(collection, id, at)?;
|
||||
let client = self.client().await?;
|
||||
let query = client.prepare_cached(GET_DOCUMENT).await?;
|
||||
let row = client
|
||||
.query_opt(
|
||||
&query,
|
||||
&[
|
||||
&collection.as_bytes(),
|
||||
&id.as_bytes(),
|
||||
&at,
|
||||
&self.deployment.as_ref(),
|
||||
],
|
||||
)
|
||||
.await?
|
||||
.map(|row| -> Result<_> { Ok((row.try_get(0)?, row.try_get(1)?, row.try_get(2)?)) })
|
||||
.transpose()?;
|
||||
snapshot(row, at)
|
||||
}
|
||||
}
|
||||
|
||||
impl Postgres {
|
||||
pub fn reader(&self) -> PostgresReader {
|
||||
self.reader.clone()
|
||||
}
|
||||
|
||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
||||
let (revision, rows) = encode_batch(expected, mutations)?;
|
||||
let deployment = self.reader.deployment.as_ref();
|
||||
let mut client = self.reader.client().await?;
|
||||
let transaction = client.transaction().await?;
|
||||
let advance = transaction
|
||||
.prepare_cached(
|
||||
"UPDATE bedrock_deployments SET revision = $1
|
||||
WHERE deployment = $2 AND revision = $3 AND retired = 0",
|
||||
)
|
||||
.await?;
|
||||
if transaction
|
||||
.execute(&advance, &[&revision, &deployment, &expected])
|
||||
.await?
|
||||
!= 1
|
||||
{
|
||||
return Err(Error::WriteConflict);
|
||||
}
|
||||
let insert = transaction.prepare_cached(
|
||||
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
|
||||
VALUES ($1, $2, $3, $4, $5)",
|
||||
).await?;
|
||||
for row in rows {
|
||||
transaction
|
||||
.execute(
|
||||
&insert,
|
||||
&[
|
||||
&deployment,
|
||||
&row.collection,
|
||||
&row.id,
|
||||
&revision,
|
||||
&row.payload,
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(revision)
|
||||
}
|
||||
}
|
||||
|
||||
fn connection_options(address: &str, read_only: bool) -> Result<(Config, MakeRustlsConnect)> {
|
||||
let mut url = Url::parse(address).map_err(|_| Error::Connection)?;
|
||||
let mut mode = SslMode::Require;
|
||||
let (mut ca, mut cert, mut key) = (None, None, None);
|
||||
let mut parameters = Vec::new();
|
||||
for (name, value) in url.query_pairs() {
|
||||
match name.as_ref() {
|
||||
"sslmode" | "ssl-mode" => {
|
||||
mode = match value.as_ref() {
|
||||
"disable" => SslMode::Disable,
|
||||
// The rustls connector verifies both the certificate chain and hostname.
|
||||
"verify-full" | "require" => SslMode::Require,
|
||||
_ => return Err(Error::Connection),
|
||||
};
|
||||
}
|
||||
"sslrootcert" | "ssl-root-cert" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())),
|
||||
"sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())),
|
||||
"sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())),
|
||||
"application_name" | "user" | "password" => {
|
||||
parameters.push((name.into_owned(), value.into_owned()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
url.set_query(None);
|
||||
if !parameters.is_empty() {
|
||||
url.query_pairs_mut().extend_pairs(parameters);
|
||||
}
|
||||
let mut config: Config = url.as_str().parse().map_err(|_| Error::Connection)?;
|
||||
config.ssl_mode(mode).connect_timeout(CONNECT_TIMEOUT);
|
||||
if read_only {
|
||||
config.options("-c default_transaction_read_only=on");
|
||||
}
|
||||
let tls = tls_config(mode, ca, cert, key)?;
|
||||
Ok((config, MakeRustlsConnect::new(tls)))
|
||||
}
|
||||
|
||||
fn tls_config(
|
||||
mode: SslMode,
|
||||
ca: Option<PathBuf>,
|
||||
cert: Option<PathBuf>,
|
||||
key: Option<PathBuf>,
|
||||
) -> Result<ClientConfig> {
|
||||
let open = |path| {
|
||||
File::open(path)
|
||||
.map(BufReader::new)
|
||||
.map_err(|_| Error::Connection)
|
||||
};
|
||||
let mut roots = RootCertStore::empty();
|
||||
if mode != SslMode::Disable {
|
||||
if let Some(path) = ca {
|
||||
let mut file = open(path)?;
|
||||
let mut count = 0;
|
||||
for cert in rustls_pemfile::certs(&mut file) {
|
||||
roots
|
||||
.add(cert.map_err(|_| Error::Connection)?)
|
||||
.map_err(|_| Error::Connection)?;
|
||||
count += 1;
|
||||
}
|
||||
if count == 0 {
|
||||
return Err(Error::Connection);
|
||||
}
|
||||
} else {
|
||||
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
}
|
||||
}
|
||||
let builder =
|
||||
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|_| Error::Connection)?
|
||||
.with_root_certificates(roots);
|
||||
match (mode, cert, key) {
|
||||
(SslMode::Disable, _, _) | (_, None, None) => Ok(builder.with_no_client_auth()),
|
||||
(_, Some(cert), Some(key)) => {
|
||||
let chain = rustls_pemfile::certs(&mut open(cert)?)
|
||||
.collect::<std::io::Result<Vec<_>>>()
|
||||
.map_err(|_| Error::Connection)?;
|
||||
let key = rustls_pemfile::private_key(&mut open(key)?)
|
||||
.map_err(|_| Error::Connection)?
|
||||
.ok_or(Error::Connection)?;
|
||||
builder
|
||||
.with_client_auth_cert(chain, key)
|
||||
.map_err(|_| Error::Connection)
|
||||
}
|
||||
_ => Err(Error::Connection),
|
||||
}
|
||||
}
|
||||
|
||||
+183
-18
@@ -1,6 +1,15 @@
|
||||
//! File-backed Bedrock storage for self-hosted deployments.
|
||||
|
||||
use crate::common::{Dialect, Reader, Result, Store, pool};
|
||||
use std::sync::Arc;
|
||||
|
||||
use rusqlite::{OpenFlags, OptionalExtension, TransactionBehavior, params};
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio_rusqlite::Connection;
|
||||
|
||||
use crate::common::{
|
||||
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
|
||||
snapshot, validate_id, validate_read,
|
||||
};
|
||||
|
||||
const SCHEMA: &[&str] = &[
|
||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||
@@ -19,23 +28,179 @@ const SCHEMA: &[&str] = &[
|
||||
)",
|
||||
];
|
||||
|
||||
pub async fn connect(url: &str, deployment: &str) -> Result<Store> {
|
||||
let pool = pool(Dialect::Sqlite, url, 1, false)?;
|
||||
Store::initialize(
|
||||
pool,
|
||||
Dialect::Sqlite,
|
||||
deployment,
|
||||
SCHEMA,
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
||||
ON CONFLICT (deployment) DO NOTHING",
|
||||
)
|
||||
.await
|
||||
#[derive(Clone)]
|
||||
pub struct SqliteReader {
|
||||
inner: Arc<Endpoint>,
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str) -> Result<Reader> {
|
||||
Reader::new(
|
||||
pool(Dialect::Sqlite, url, 1, true)?,
|
||||
Dialect::Sqlite,
|
||||
deployment,
|
||||
)
|
||||
struct Endpoint {
|
||||
uri: String,
|
||||
flags: OpenFlags,
|
||||
deployment: Vec<u8>,
|
||||
connection: OnceCell<Connection>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Sqlite {
|
||||
reader: SqliteReader,
|
||||
}
|
||||
|
||||
pub async fn connect(url: &str, deployment: &str) -> Result<Sqlite> {
|
||||
let reader = SqliteReader::new(url, deployment, false)?;
|
||||
let deployment = reader.inner.deployment.clone();
|
||||
reader
|
||||
.call(move |connection| {
|
||||
let transaction =
|
||||
connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
for ddl in SCHEMA {
|
||||
transaction.execute_batch(ddl)?;
|
||||
}
|
||||
transaction.execute(
|
||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
||||
ON CONFLICT (deployment) DO NOTHING",
|
||||
[deployment],
|
||||
)?;
|
||||
transaction.commit()?;
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
reader.revision().await?;
|
||||
Ok(Sqlite { reader })
|
||||
}
|
||||
|
||||
pub fn reader(url: &str, deployment: &str) -> Result<SqliteReader> {
|
||||
SqliteReader::new(url, deployment, true)
|
||||
}
|
||||
|
||||
impl SqliteReader {
|
||||
fn new(url: &str, deployment: &str, read_only: bool) -> Result<Self> {
|
||||
validate_id(deployment)?;
|
||||
let address = url.strip_prefix("sqlite:").ok_or(Error::Connection)?;
|
||||
let address = address.strip_prefix("//").unwrap_or(address);
|
||||
let mut flags = OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX;
|
||||
let uri = if read_only {
|
||||
flags |= OpenFlags::SQLITE_OPEN_READ_ONLY;
|
||||
let (path, query) = address.split_once('?').unwrap_or((address, ""));
|
||||
let options =
|
||||
url::form_urlencoded::parse(query.as_bytes()).filter(|(key, _)| key != "mode");
|
||||
let query = url::form_urlencoded::Serializer::new(String::new())
|
||||
.extend_pairs(options)
|
||||
.append_pair("mode", "ro")
|
||||
.finish();
|
||||
format!("file:{path}?{query}")
|
||||
} else {
|
||||
flags |= OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE;
|
||||
if address == ":memory:" {
|
||||
address.to_owned()
|
||||
} else {
|
||||
format!("file:{address}")
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
inner: Arc::new(Endpoint {
|
||||
uri,
|
||||
flags,
|
||||
deployment: deployment.as_bytes().to_vec(),
|
||||
connection: OnceCell::new(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
async fn call<T: Send + 'static>(
|
||||
&self,
|
||||
operation: impl FnOnce(&mut rusqlite::Connection) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
let connection = self
|
||||
.inner
|
||||
.connection
|
||||
.get_or_try_init(|| async {
|
||||
let connection = Connection::open_with_flags(&self.inner.uri, self.inner.flags)
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?;
|
||||
connection
|
||||
.call(|connection| {
|
||||
connection.busy_timeout(CONNECT_TIMEOUT)?;
|
||||
connection.pragma_update(None, "foreign_keys", "ON")?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?;
|
||||
Ok::<_, Error>(connection)
|
||||
})
|
||||
.await?;
|
||||
connection
|
||||
.call(move |connection| Ok(operation(connection)))
|
||||
.await
|
||||
.map_err(|_| Error::Connection)?
|
||||
}
|
||||
|
||||
pub async fn revision(&self) -> Result<Revision> {
|
||||
let deployment = self.inner.deployment.clone();
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.prepare_cached(
|
||||
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
|
||||
)?
|
||||
.query_row([deployment], |row| row.get(0))
|
||||
.optional()?
|
||||
.ok_or(Error::MissingDeployment)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
|
||||
validate_read(collection, id, at)?;
|
||||
let collection = collection.as_bytes().to_vec();
|
||||
let id = id.as_bytes().to_vec();
|
||||
let deployment = self.inner.deployment.clone();
|
||||
let row = self
|
||||
.call(move |connection| {
|
||||
Ok(connection
|
||||
.prepare_cached(GET_DOCUMENT)?
|
||||
.query_row(params![collection, id, at, deployment], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||
})
|
||||
.optional()?)
|
||||
})
|
||||
.await?;
|
||||
snapshot(row, at)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sqlite {
|
||||
pub fn reader(&self) -> SqliteReader {
|
||||
self.reader.clone()
|
||||
}
|
||||
|
||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
||||
let (revision, rows) = encode_batch(expected, mutations)?;
|
||||
let rows: Vec<_> = rows
|
||||
.into_iter()
|
||||
.map(|row| (row.collection.to_vec(), row.id.to_vec(), row.payload))
|
||||
.collect();
|
||||
let deployment = self.reader.inner.deployment.clone();
|
||||
self.reader
|
||||
.call(move |connection| {
|
||||
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let advanced = transaction.prepare_cached(
|
||||
"UPDATE bedrock_deployments SET revision = ?
|
||||
WHERE deployment = ? AND revision = ? AND retired = 0",
|
||||
)?.execute(params![revision, deployment, expected])?;
|
||||
if advanced != 1 {
|
||||
return Err(Error::WriteConflict);
|
||||
}
|
||||
{
|
||||
let mut insert = transaction.prepare_cached(
|
||||
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
|
||||
VALUES (?, ?, ?, ?, ?)",
|
||||
)?;
|
||||
for (collection, id, payload) in rows {
|
||||
insert.execute(params![deployment, collection, id, revision, payload])?;
|
||||
}
|
||||
}
|
||||
transaction.commit()?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +136,19 @@ async fn sqlite_persists_across_reopening_and_enforces_read_only() {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlite_read_only_startup_does_not_create_a_database() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let filename = folder.path().join("missing.sqlite");
|
||||
let config = DeploymentConfig {
|
||||
read_only: true,
|
||||
sqlite_path: filename.to_str().unwrap().into(),
|
||||
..DeploymentConfig::default()
|
||||
};
|
||||
assert!(connect(&config).await.is_err());
|
||||
assert!(!filename.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn postgres_reads_replicas_and_falls_back_when_behind() {
|
||||
let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else {
|
||||
|
||||
Reference in New Issue
Block a user