Use native drivers for Bedrock SQL storage
This commit is contained in:
+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> {
|
||||
|
||||
Reference in New Issue
Block a user