Use native drivers for Bedrock SQL storage
This commit is contained in:
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]
|
[workspace.dependencies]
|
||||||
clusters = { path = "crates/clusters" }
|
clusters = { path = "crates/clusters" }
|
||||||
db = { path = "crates/db" }
|
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 = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
sqlx = { version = "0.8.6", default-features = false, features = ["any", "runtime-tokio", "tls-rustls-ring-webpki"] }
|
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
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"
|
url = "2"
|
||||||
|
webpki-roots = "1"
|
||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "bedrock"
|
name = "bedrock"
|
||||||
|
|||||||
+11
-1
@@ -6,9 +6,19 @@ rust-version.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clusters.workspace = true
|
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
|
serde_json.workspace = true
|
||||||
sqlx = { workspace = true, features = ["mysql", "postgres", "sqlite"] }
|
|
||||||
thiserror.workspace = true
|
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]
|
[dev-dependencies]
|
||||||
tempfile.workspace = true
|
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 serde_json::Value;
|
||||||
use sqlx::{AnyConnection, AnyPool, Row, any::AnyPoolOptions};
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
pub type Revision = i64;
|
pub type Revision = i64;
|
||||||
pub type Result<T> = std::result::Result<T, Error>;
|
pub type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
#[error("invalid {0}")]
|
#[error("invalid {0}")]
|
||||||
Invalid(&'static str),
|
Invalid(&'static str),
|
||||||
#[error("the database connection failed")]
|
#[error("the database connection failed")]
|
||||||
Connection,
|
Connection,
|
||||||
#[error("SQL operation failed: {0}")]
|
#[error("SQLite operation failed: {0}")]
|
||||||
Sql(#[from] sqlx::Error),
|
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}")]
|
#[error("document encoding failed: {0}")]
|
||||||
Encoding(#[from] serde_json::Error),
|
Encoding(#[from] serde_json::Error),
|
||||||
#[error("the connection is read-only")]
|
#[error("the connection is read-only")]
|
||||||
@@ -38,18 +45,17 @@ impl Error {
|
|||||||
pub fn retry_on_primary(&self) -> bool {
|
pub fn retry_on_primary(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true,
|
Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true,
|
||||||
Self::Sql(error) => match error {
|
Self::Postgres(error) => {
|
||||||
sqlx::Error::Io(_)
|
error.is_closed()
|
||||||
| sqlx::Error::Tls(_)
|
|| error.code().is_some_and(|code| {
|
||||||
| sqlx::Error::PoolTimedOut
|
code.code().starts_with("08")
|
||||||
| sqlx::Error::PoolClosed
|
|| matches!(code.code(), "57P01" | "57P03" | "42P01")
|
||||||
| sqlx::Error::WorkerCrashed => true,
|
})
|
||||||
sqlx::Error::Database(db) => db.code().is_some_and(|code| {
|
}
|
||||||
code.starts_with("08")
|
Self::Mysql(mysql_async::Error::Server(error)) => {
|
||||||
|| matches!(code.as_ref(), "57P01" | "57P03" | "42P01" | "1146")
|
error.state.starts_with("08") || error.code == 1146
|
||||||
}),
|
}
|
||||||
_ => false,
|
Self::Mysql(error) => error.is_fatal(),
|
||||||
},
|
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,272 +81,75 @@ pub struct Mutation {
|
|||||||
pub value: Option<Value>,
|
pub value: Option<Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
pub(crate) type EncodedSnapshot = (Revision, Option<Revision>, Option<Vec<u8>>);
|
||||||
pub enum Dialect {
|
|
||||||
Sqlite,
|
pub(crate) struct EncodedMutation<'a> {
|
||||||
Postgres,
|
pub collection: &'a [u8],
|
||||||
Mysql,
|
pub id: &'a [u8],
|
||||||
|
pub payload: Option<Vec<u8>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opened SQL reader. Its pool is private so callers cannot bypass the read API.
|
pub(crate) fn validate_read(collection: &str, id: &str, at: Option<Revision>) -> Result<()> {
|
||||||
#[derive(Clone)]
|
validate_id(collection)?;
|
||||||
pub struct Reader {
|
validate_id(id)?;
|
||||||
pool: AnyPool,
|
if at.is_some_and(|revision| revision < 0) {
|
||||||
dialect: Dialect,
|
return Err(Error::Invalid("snapshot revision"));
|
||||||
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"));
|
|
||||||
}
|
}
|
||||||
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(())
|
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') {
|
if value.is_empty() || value.len() > 128 || value.contains('\0') {
|
||||||
return Err(Error::Invalid(
|
return Err(Error::Invalid(
|
||||||
"identifier (expected 1–128 bytes without NUL)",
|
"identifier (expected 1–128 bytes without NUL)",
|
||||||
@@ -349,38 +158,12 @@ fn validate_id(value: &str) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn initialize_schema(
|
// A single statement observes the revision and the document at the same point in time.
|
||||||
connection: &mut AnyConnection,
|
pub(crate) const GET_DOCUMENT: &str = "
|
||||||
schema: &[&str],
|
SELECT d.revision, v.revision, v.payload
|
||||||
insert_deployment: &str,
|
FROM bedrock_deployments d
|
||||||
deployment: &[u8],
|
LEFT JOIN bedrock_documents v
|
||||||
) -> Result<()> {
|
ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ?
|
||||||
for ddl in schema {
|
AND v.revision <= COALESCE(?, d.revision)
|
||||||
sqlx::query(ddl).execute(&mut *connection).await?;
|
WHERE d.deployment = ? AND d.retired = 0
|
||||||
}
|
ORDER BY v.revision DESC LIMIT 1";
|
||||||
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),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+74
-18
@@ -6,9 +6,10 @@ use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeploymen
|
|||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
common::{Error as StorageError, Mutation, Reader, Revision, Snapshot, Store},
|
common::{Error as StorageError, Mutation, Revision, Snapshot},
|
||||||
mysql::{self, MySql},
|
mysql::{self, MySql, MySqlReader},
|
||||||
postgres, sqlite,
|
postgres::{self, Postgres, PostgresReader},
|
||||||
|
sqlite::{self, Sqlite, SqliteReader},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
@@ -29,14 +30,69 @@ pub enum ReadPreference {
|
|||||||
PreferReplica,
|
PreferReplica,
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Writer {
|
/// A reader backed by the configured database. It exposes no raw SQL connection.
|
||||||
Sql(Store),
|
#[derive(Clone)]
|
||||||
MySql(MySql),
|
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 {
|
pub struct Connection {
|
||||||
driver: Driver,
|
driver: Driver,
|
||||||
writer: Option<Writer>,
|
writer: Option<Store>,
|
||||||
primary: Reader,
|
primary: Reader,
|
||||||
replicas: Vec<Reader>,
|
replicas: Vec<Reader>,
|
||||||
next_replica: AtomicUsize,
|
next_replica: AtomicUsize,
|
||||||
@@ -51,14 +107,13 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
|
|||||||
let name = &config.deployment;
|
let name = &config.deployment;
|
||||||
let max = config.max_connections;
|
let max = config.max_connections;
|
||||||
Some(match config.driver {
|
Some(match config.driver {
|
||||||
Driver::Sqlite => Writer::Sql(sqlite::connect(url, name).await?),
|
Driver::Sqlite => Store::Sqlite(sqlite::connect(url, name).await?),
|
||||||
Driver::Postgres => Writer::Sql(postgres::connect(url, name, max).await?),
|
Driver::Postgres => Store::Postgres(postgres::connect(url, name, max).await?),
|
||||||
Driver::Mysql => Writer::MySql(MySql::connect(url, name, max).await?),
|
Driver::Mysql => Store::Mysql(MySql::connect(url, name, max).await?),
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
let primary = match &writer {
|
let primary = match &writer {
|
||||||
Some(Writer::Sql(store)) => store.reader(),
|
Some(store) => store.reader(),
|
||||||
Some(Writer::MySql(store)) => store.reader(),
|
|
||||||
None => {
|
None => {
|
||||||
let reader = reader(&config, &config.primary)?;
|
let reader = reader(&config, &config.primary)?;
|
||||||
reader.revision().await?;
|
reader.revision().await?;
|
||||||
@@ -83,9 +138,11 @@ fn reader(config: &ResolvedDeployment, address: &Address) -> Result<Reader, Stor
|
|||||||
let url = address.connection_string();
|
let url = address.connection_string();
|
||||||
let name = &config.deployment;
|
let name = &config.deployment;
|
||||||
match config.driver {
|
match config.driver {
|
||||||
Driver::Sqlite => sqlite::reader(url, name),
|
Driver::Sqlite => sqlite::reader(url, name).map(Reader::Sqlite),
|
||||||
Driver::Postgres => postgres::reader(url, name, config.max_connections),
|
Driver::Postgres => {
|
||||||
Driver::Mysql => mysql::reader(url, name, config.max_connections),
|
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],
|
changes: &[Mutation],
|
||||||
) -> Result<Revision, StorageError> {
|
) -> Result<Revision, StorageError> {
|
||||||
match &self.writer {
|
match &self.writer {
|
||||||
Some(Writer::Sql(store)) => store.commit(expected, changes).await,
|
Some(store) => store.commit(expected, changes).await,
|
||||||
Some(Writer::MySql(store)) => store.commit(expected, changes).await,
|
|
||||||
None => Err(StorageError::ReadOnly),
|
None => Err(StorageError::ReadOnly),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mysql_writer(&self) -> Option<&MySql> {
|
pub fn mysql_writer(&self) -> Option<&MySql> {
|
||||||
match &self.writer {
|
match &self.writer {
|
||||||
Some(Writer::MySql(store)) => Some(store),
|
Some(Store::Mysql(store)) => Some(store),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,9 @@ pub mod mysql;
|
|||||||
pub mod postgres;
|
pub mod postgres;
|
||||||
pub mod sqlite;
|
pub mod sqlite;
|
||||||
|
|
||||||
|
pub use clusters::Driver as Dialect;
|
||||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
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::Error as StorageError;
|
||||||
pub use common::{
|
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot};
|
||||||
Dialect, Document, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Snapshot, Store,
|
pub use connection::{ConnectError, Connection, ReadPreference, Reader, Store, connect};
|
||||||
lock_mysql_deployment, pool,
|
pub use mysql::{Lease, MySql};
|
||||||
};
|
|
||||||
|
|||||||
+276
-75
@@ -1,12 +1,19 @@
|
|||||||
//! MySQL storage, writer leases and deployment cleanup.
|
//! 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::{
|
use crate::common::{
|
||||||
Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment,
|
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
|
||||||
pool,
|
snapshot, validate_id, validate_read,
|
||||||
};
|
};
|
||||||
use sqlx::AnyPool;
|
|
||||||
|
const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)";
|
||||||
|
|
||||||
const SCHEMA: &[&str] = &[
|
const SCHEMA: &[&str] = &[
|
||||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||||
@@ -29,12 +36,68 @@ const SCHEMA: &[&str] = &[
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct MySql {
|
pub struct MySql {
|
||||||
store: Store,
|
reader: MySqlReader,
|
||||||
pool: AnyPool,
|
|
||||||
deployment: Vec<u8>,
|
|
||||||
identity: Arc<()>,
|
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.
|
/// The monotonically increasing epoch fences off holders whose lease expired.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Lease {
|
pub struct Lease {
|
||||||
@@ -50,31 +113,34 @@ impl Lease {
|
|||||||
|
|
||||||
impl MySql {
|
impl MySql {
|
||||||
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Self> {
|
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Self> {
|
||||||
let pool = pool(Dialect::Mysql, url, max_connections, false)?;
|
let reader = MySqlReader::new(url, deployment, max_connections, false)?;
|
||||||
let store = Store::initialize(
|
{
|
||||||
pool.clone(),
|
let mut connection = reader.connection().await?;
|
||||||
Dialect::Mysql,
|
for ddl in SCHEMA {
|
||||||
deployment,
|
connection.query_drop(*ddl).await?;
|
||||||
SCHEMA,
|
}
|
||||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
connection
|
||||||
ON DUPLICATE KEY UPDATE revision = revision",
|
.exec_drop(
|
||||||
)
|
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
||||||
.await?;
|
ON DUPLICATE KEY UPDATE revision = revision",
|
||||||
|
(reader.deployment.as_ref(),),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
reader.revision().await?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
store,
|
reader,
|
||||||
pool,
|
|
||||||
deployment: deployment.as_bytes().to_vec(),
|
|
||||||
identity: Arc::new(()),
|
identity: Arc::new(()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reader(&self) -> Reader {
|
pub fn reader(&self) -> MySqlReader {
|
||||||
self.store.reader()
|
self.reader.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An ordinary write is allowed while no lease is active.
|
/// An ordinary write is allowed while no lease is active.
|
||||||
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
|
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(
|
pub async fn commit_with_lease(
|
||||||
@@ -83,12 +149,44 @@ impl MySql {
|
|||||||
expected: Revision,
|
expected: Revision,
|
||||||
mutations: &[Mutation],
|
mutations: &[Mutation],
|
||||||
) -> Result<Revision> {
|
) -> Result<Revision> {
|
||||||
let epoch = self.epoch(lease)?;
|
self.commit_with_fence(expected, mutations, Some(self.epoch(lease)?))
|
||||||
self.store
|
|
||||||
.commit_with_fence(expected, mutations, Some(epoch))
|
|
||||||
.await
|
.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.
|
/// Acquires an expired or unheld lease using the database clock.
|
||||||
pub async fn acquire_lease(&self, ttl: Duration) -> Result<Option<Lease>> {
|
pub async fn acquire_lease(&self, ttl: Duration) -> Result<Option<Lease>> {
|
||||||
let ttl = lease_millis(ttl)?;
|
let ttl = lease_millis(ttl)?;
|
||||||
@@ -98,21 +196,21 @@ impl MySql {
|
|||||||
SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ?
|
SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ?
|
||||||
WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}"
|
WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}"
|
||||||
);
|
);
|
||||||
let mut transaction = self.pool.begin().await?;
|
let deployment = self.reader.deployment.as_ref();
|
||||||
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
|
let mut connection = self.reader.connection().await?;
|
||||||
let changed = sqlx::query(&update)
|
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||||
.bind(ttl)
|
lock_deployment(&mut transaction, deployment).await?;
|
||||||
.bind(self.deployment.as_slice())
|
transaction.exec_drop(update, (ttl, deployment)).await?;
|
||||||
.execute(&mut *transaction)
|
if transaction.affected_rows() != 1 {
|
||||||
.await?;
|
|
||||||
if changed.rows_affected() != 1 {
|
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
let epoch =
|
let epoch: i64 = transaction
|
||||||
sqlx::query_scalar("SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?")
|
.exec_first(
|
||||||
.bind(self.deployment.as_slice())
|
"SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?",
|
||||||
.fetch_one(&mut *transaction)
|
(deployment,),
|
||||||
.await?;
|
)
|
||||||
|
.await?
|
||||||
|
.ok_or(Error::MissingDeployment)?;
|
||||||
transaction.commit().await?;
|
transaction.commit().await?;
|
||||||
Ok(Some(Lease {
|
Ok(Some(Lease {
|
||||||
epoch,
|
epoch,
|
||||||
@@ -130,15 +228,14 @@ impl MySql {
|
|||||||
SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?)
|
SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?)
|
||||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
||||||
);
|
);
|
||||||
let mut transaction = self.pool.begin().await?;
|
let deployment = self.reader.deployment.as_ref();
|
||||||
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
|
let mut connection = self.reader.connection().await?;
|
||||||
let changed = sqlx::query(&update)
|
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||||
.bind(ttl)
|
lock_deployment(&mut transaction, deployment).await?;
|
||||||
.bind(self.deployment.as_slice())
|
transaction
|
||||||
.bind(epoch)
|
.exec_drop(update, (ttl, deployment, epoch))
|
||||||
.execute(&mut *transaction)
|
|
||||||
.await?;
|
.await?;
|
||||||
if changed.rows_affected() != 1 {
|
if transaction.affected_rows() != 1 {
|
||||||
return Err(Error::LeaseLost);
|
return Err(Error::LeaseLost);
|
||||||
}
|
}
|
||||||
transaction.commit().await?;
|
transaction.commit().await?;
|
||||||
@@ -147,16 +244,15 @@ impl MySql {
|
|||||||
|
|
||||||
pub async fn release_lease(&self, lease: &Lease) -> Result<bool> {
|
pub async fn release_lease(&self, lease: &Lease) -> Result<bool> {
|
||||||
let epoch = self.epoch(lease)?;
|
let epoch = self.epoch(lease)?;
|
||||||
let changed = sqlx::query(
|
let mut connection = self.reader.connection().await?;
|
||||||
"
|
connection
|
||||||
UPDATE bedrock_deployments SET lease_until = 0
|
.exec_drop(
|
||||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
|
"UPDATE bedrock_deployments SET lease_until = 0
|
||||||
)
|
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
|
||||||
.bind(self.deployment.as_slice())
|
(self.reader.deployment.as_ref(), epoch),
|
||||||
.bind(epoch)
|
)
|
||||||
.execute(&self.pool)
|
.await?;
|
||||||
.await?;
|
Ok(connection.affected_rows() == 1)
|
||||||
Ok(changed.rows_affected() == 1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes only this deployment's documents and retires its identity in one transaction.
|
/// 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
|
UPDATE bedrock_deployments SET retired = 1, lease_until = 0
|
||||||
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
|
||||||
);
|
);
|
||||||
let mut transaction = self.pool.begin().await?;
|
let deployment = self.reader.deployment.as_ref();
|
||||||
lock_mysql_deployment(&mut transaction, &self.deployment).await?;
|
let mut connection = self.reader.connection().await?;
|
||||||
let changed = sqlx::query(&update)
|
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
|
||||||
.bind(self.deployment.as_slice())
|
lock_deployment(&mut transaction, deployment).await?;
|
||||||
.bind(epoch)
|
transaction.exec_drop(update, (deployment, epoch)).await?;
|
||||||
.execute(&mut *transaction)
|
if transaction.affected_rows() != 1 {
|
||||||
.await?;
|
|
||||||
if changed.rows_affected() != 1 {
|
|
||||||
return Err(Error::LeaseLost);
|
return Err(Error::LeaseLost);
|
||||||
}
|
}
|
||||||
let removed = sqlx::query("DELETE FROM bedrock_documents WHERE deployment = ?")
|
transaction
|
||||||
.bind(self.deployment.as_slice())
|
.exec_drop(
|
||||||
.execute(&mut *transaction)
|
"DELETE FROM bedrock_documents WHERE deployment = ?",
|
||||||
|
(deployment,),
|
||||||
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
let removed = transaction.affected_rows();
|
||||||
transaction.commit().await?;
|
transaction.commit().await?;
|
||||||
Ok(removed.rows_affected())
|
Ok(removed)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn epoch(&self, lease: &Lease) -> Result<i64> {
|
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> {
|
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<MySqlReader> {
|
||||||
Reader::new(
|
MySqlReader::new(url, deployment, max_connections, true)
|
||||||
pool(Dialect::Mysql, url, max_connections, true)?,
|
}
|
||||||
Dialect::Mysql,
|
|
||||||
deployment,
|
// 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> {
|
fn lease_millis(ttl: Duration) -> Result<i64> {
|
||||||
|
|||||||
+251
-18
@@ -1,6 +1,17 @@
|
|||||||
//! PostgreSQL connection pools and the Bedrock document layout.
|
//! 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] = &[
|
const SCHEMA: &[&str] = &[
|
||||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
"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> {
|
const GET_DOCUMENT: &str = "
|
||||||
let pool = pool(Dialect::Postgres, url, max_connections, false)?;
|
SELECT d.revision, v.revision, v.payload
|
||||||
Store::initialize(
|
FROM bedrock_deployments d
|
||||||
pool,
|
LEFT JOIN bedrock_documents v
|
||||||
Dialect::Postgres,
|
ON v.deployment = d.deployment AND v.collection = $1 AND v.document_id = $2
|
||||||
deployment,
|
AND v.revision <= COALESCE($3, d.revision)
|
||||||
SCHEMA,
|
WHERE d.deployment = $4 AND d.retired = 0
|
||||||
"INSERT INTO bedrock_deployments (deployment) VALUES ($1)
|
ORDER BY v.revision DESC LIMIT 1";
|
||||||
ON CONFLICT (deployment) DO NOTHING",
|
|
||||||
)
|
#[derive(Clone)]
|
||||||
.await
|
pub struct PostgresReader {
|
||||||
|
pool: Pool,
|
||||||
|
deployment: Arc<[u8]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<Reader> {
|
#[derive(Clone)]
|
||||||
Reader::new(
|
pub struct Postgres {
|
||||||
pool(Dialect::Postgres, url, max_connections, true)?,
|
reader: PostgresReader,
|
||||||
Dialect::Postgres,
|
}
|
||||||
deployment,
|
|
||||||
)
|
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.
|
//! 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] = &[
|
const SCHEMA: &[&str] = &[
|
||||||
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
|
||||||
@@ -19,23 +28,179 @@ const SCHEMA: &[&str] = &[
|
|||||||
)",
|
)",
|
||||||
];
|
];
|
||||||
|
|
||||||
pub async fn connect(url: &str, deployment: &str) -> Result<Store> {
|
#[derive(Clone)]
|
||||||
let pool = pool(Dialect::Sqlite, url, 1, false)?;
|
pub struct SqliteReader {
|
||||||
Store::initialize(
|
inner: Arc<Endpoint>,
|
||||||
pool,
|
|
||||||
Dialect::Sqlite,
|
|
||||||
deployment,
|
|
||||||
SCHEMA,
|
|
||||||
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
|
|
||||||
ON CONFLICT (deployment) DO NOTHING",
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reader(url: &str, deployment: &str) -> Result<Reader> {
|
struct Endpoint {
|
||||||
Reader::new(
|
uri: String,
|
||||||
pool(Dialect::Sqlite, url, 1, true)?,
|
flags: OpenFlags,
|
||||||
Dialect::Sqlite,
|
deployment: Vec<u8>,
|
||||||
deployment,
|
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]
|
#[tokio::test]
|
||||||
async fn postgres_reads_replicas_and_falls_back_when_behind() {
|
async fn postgres_reads_replicas_and_falls_back_when_behind() {
|
||||||
let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else {
|
let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else {
|
||||||
|
|||||||
Reference in New Issue
Block a user