//! MySQL storage, writer leases and deployment cleanup. use std::{sync::Arc, time::Duration}; use crate::{ Dialect, Error, MYSQL_NOW, Mutation, Reader, Result, Revision, Store, lock_mysql_deployment, pool, }; use sqlx::AnyPool; const SCHEMA: &[&str] = &[ "CREATE TABLE IF NOT EXISTS bedrock_deployments ( deployment VARBINARY(128) PRIMARY KEY, revision BIGINT NOT NULL DEFAULT 0, retired BIGINT NOT NULL DEFAULT 0, lease_epoch BIGINT NOT NULL DEFAULT 0, lease_until BIGINT NOT NULL DEFAULT 0 ) ENGINE=InnoDB", "CREATE TABLE IF NOT EXISTS bedrock_documents ( deployment VARBINARY(128) NOT NULL, collection VARBINARY(128) NOT NULL, document_id VARBINARY(128) NOT NULL, revision BIGINT NOT NULL, payload LONGBLOB, PRIMARY KEY (deployment, collection, document_id, revision), FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment) ) ENGINE=InnoDB", ]; #[derive(Clone)] pub struct MySql { store: Store, pool: AnyPool, deployment: Vec, identity: Arc<()>, } /// The monotonically increasing epoch fences off holders whose lease expired. #[derive(Debug)] pub struct Lease { epoch: i64, issuer: Arc<()>, } impl Lease { pub fn epoch(&self) -> i64 { self.epoch } } impl MySql { pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result { 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?; Ok(Self { store, pool, deployment: deployment.as_bytes().to_vec(), identity: Arc::new(()), }) } pub fn reader(&self) -> Reader { self.store.reader() } /// An ordinary write is allowed while no lease is active. pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result { self.store.commit(expected, mutations).await } pub async fn commit_with_lease( &self, lease: &Lease, expected: Revision, mutations: &[Mutation], ) -> Result { let epoch = self.epoch(lease)?; self.store .commit_with_fence(expected, mutations, Some(epoch)) .await } /// Acquires an expired or unheld lease using the database clock. pub async fn acquire_lease(&self, ttl: Duration) -> Result> { let ttl = lease_millis(ttl)?; let update = format!( " UPDATE bedrock_deployments 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 { 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?; transaction.commit().await?; Ok(Some(Lease { epoch, issuer: self.identity.clone(), })) } /// Extends an active lease from the current database time without shortening it. pub async fn renew_lease(&self, lease: &Lease, ttl: Duration) -> Result<()> { let epoch = self.epoch(lease)?; let ttl = lease_millis(ttl)?; let update = format!( " UPDATE bedrock_deployments 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) .await?; if changed.rows_affected() != 1 { return Err(Error::LeaseLost); } transaction.commit().await?; Ok(()) } pub async fn release_lease(&self, lease: &Lease) -> Result { 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) } /// Removes only this deployment's documents and retires its identity in one transaction. /// The retained deployment row prevents a restart from recreating the deleted deployment. pub async fn delete_deployment(&self, lease: &Lease) -> Result { let epoch = self.epoch(lease)?; let update = format!( " 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 { return Err(Error::LeaseLost); } let removed = sqlx::query("DELETE FROM bedrock_documents WHERE deployment = ?") .bind(self.deployment.as_slice()) .execute(&mut *transaction) .await?; transaction.commit().await?; Ok(removed.rows_affected()) } fn epoch(&self, lease: &Lease) -> Result { if !Arc::ptr_eq(&self.identity, &lease.issuer) { return Err(Error::LeaseLost); } Ok(lease.epoch) } } pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result { Reader::new( pool(Dialect::Mysql, url, max_connections, true)?, Dialect::Mysql, deployment, ) } fn lease_millis(ttl: Duration) -> Result { let millis = ttl.as_millis(); if millis == 0 || millis >= i64::MAX as u128 / 2 { return Err(Error::Invalid("lease duration")); } Ok(millis as i64) }