use core::sync::atomic::{AtomicU64, Ordering};
use happenstance_core::{
Authority, Checkpoint, CommitError, ProjectionId, ResetError, SendProjectionStore,
SequencePosition,
};
use sqlx::{PgPool, Postgres, Transaction};
use crate::error::PostgresProjectionStoreError;
const AUTHORITY_LIVE: &str = "live";
const AUTHORITY_REBUILDING: &str = "rebuilding";
#[cfg(feature = "conformance")]
pub const PROBE_TABLE: &str = "\
CREATE TABLE IF NOT EXISTS projection_probe (
k text NOT NULL PRIMARY KEY,
v bigint NOT NULL
);";
fn mint_stamp() -> u64 {
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum PgParam {
Text(Option<String>),
Int8(Option<i64>),
Int4(Option<i32>),
Bool(Option<bool>),
Float8(Option<f64>),
Bytea(Option<Vec<u8>>),
}
impl PgParam {
pub fn text(value: impl Into<String>) -> Self {
Self::Text(Some(value.into()))
}
pub const fn int8(value: i64) -> Self {
Self::Int8(Some(value))
}
pub fn bytea(value: impl Into<Vec<u8>>) -> Self {
Self::Bytea(Some(value.into()))
}
}
#[derive(Debug, Clone)]
struct PendingStatement {
sql: Box<str>,
params: Box<[PgParam]>,
}
#[derive(Debug, Clone)]
pub struct PostgresProjectionBatch {
statements: Vec<PendingStatement>,
stamp: u64,
}
impl PostgresProjectionBatch {
const fn stamped(stamp: u64) -> Self {
Self {
statements: Vec::new(),
stamp,
}
}
pub fn push(&mut self, sql: &'static str, params: impl IntoIterator<Item = PgParam>) {
self.statements.push(PendingStatement {
sql: sql.into(),
params: params.into_iter().collect(),
});
}
pub fn push_raw_sql(&mut self, sql: impl Into<Box<str>>, params: Vec<PgParam>) {
self.statements.push(PendingStatement {
sql: sql.into(),
params: params.into_boxed_slice(),
});
}
pub fn len(&self) -> usize {
self.statements.len()
}
pub fn is_empty(&self) -> bool {
self.statements.is_empty()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PostgresProjectionStore {
pool: PgPool,
stamp: u64,
}
impl PostgresProjectionStore {
pub fn new(pool: PgPool) -> Self {
Self {
pool,
stamp: mint_stamp(),
}
}
pub fn pool(&self) -> &PgPool {
&self.pool
}
}
fn bind_all<'q>(
mut query: sqlx::query::Query<'q, Postgres, sqlx::postgres::PgArguments>,
params: &'q [PgParam],
) -> sqlx::query::Query<'q, Postgres, sqlx::postgres::PgArguments> {
for param in params {
query = match param {
PgParam::Text(value) => query.bind(value.as_deref()),
PgParam::Int8(value) => query.bind(*value),
PgParam::Int4(value) => query.bind(*value),
PgParam::Bool(value) => query.bind(*value),
PgParam::Float8(value) => query.bind(*value),
PgParam::Bytea(value) => query.bind(value.as_deref()),
};
}
query
}
async fn replay(
transaction: &mut Transaction<'static, Postgres>,
batch: &PostgresProjectionBatch,
) -> Result<(), sqlx::Error> {
for statement in &batch.statements {
bind_all(sqlx::query(&statement.sql), &statement.params)
.execute(&mut **transaction)
.await?;
}
Ok(())
}
fn position_from_row(stored: i64) -> Result<SequencePosition, PostgresProjectionStoreError> {
u64::try_from(stored)
.ok()
.and_then(SequencePosition::new)
.ok_or(PostgresProjectionStoreError::CheckpointOutOfRange { value: stored })
}
fn position_to_row(position: SequencePosition) -> Result<i64, PostgresProjectionStoreError> {
i64::try_from(position.get()).map_err(|_| {
PostgresProjectionStoreError::CheckpointOutOfRange {
value: position.get().cast_signed(),
}
})
}
const fn authority_to_row(authority: Authority) -> &'static str {
match authority {
Authority::Live => AUTHORITY_LIVE,
Authority::Rebuilding => AUTHORITY_REBUILDING,
_ => "unknown",
}
}
impl SendProjectionStore for PostgresProjectionStore {
type Error = PostgresProjectionStoreError;
type Batch = PostgresProjectionBatch;
fn begin(&self) -> Self::Batch {
PostgresProjectionBatch::stamped(self.stamp)
}
async fn checkpoint(&self, id: &ProjectionId) -> Result<Checkpoint, Self::Error> {
let row: Option<(i64, String)> = sqlx::query_as(
"SELECT position, authority FROM projection_checkpoint WHERE projection_id = $1",
)
.bind(id.as_str())
.fetch_optional(&self.pool)
.await?;
let Some((stored_position, stored_authority)) = row else {
return Ok(Checkpoint::NeverRun);
};
let through = position_from_row(stored_position)?;
match stored_authority.as_str() {
AUTHORITY_LIVE => Ok(Checkpoint::Live { through }),
AUTHORITY_REBUILDING => Ok(Checkpoint::Rebuilding { through }),
_ => Err(PostgresProjectionStoreError::InvalidAuthority(
stored_authority,
)),
}
}
async fn commit(
&self,
batch: Self::Batch,
id: &ProjectionId,
position: SequencePosition,
authority: Authority,
) -> Result<(), CommitError<Self::Error>> {
if batch.stamp != self.stamp {
return Err(CommitError::ForeignBatch);
}
let stored_position = position_to_row(position).map_err(CommitError::Store)?;
let mut transaction = self
.pool
.begin()
.await
.map_err(|error| CommitError::Store(PostgresProjectionStoreError::Driver(error)))?;
replay(&mut transaction, &batch)
.await
.map_err(|error| CommitError::Store(PostgresProjectionStoreError::Driver(error)))?;
let advanced: Option<(i64,)> = sqlx::query_as(
"INSERT INTO projection_checkpoint (projection_id, position, authority) \
VALUES ($1, $2, $3) \
ON CONFLICT (projection_id) DO UPDATE \
SET position = excluded.position, authority = excluded.authority \
WHERE projection_checkpoint.position <= excluded.position \
RETURNING position",
)
.bind(id.as_str())
.bind(stored_position)
.bind(authority_to_row(authority))
.fetch_optional(&mut *transaction)
.await
.map_err(|error| CommitError::Store(PostgresProjectionStoreError::Driver(error)))?;
if advanced.is_some() {
return transaction
.commit()
.await
.map_err(|error| CommitError::Store(PostgresProjectionStoreError::Driver(error)));
}
let current: (i64,) =
sqlx::query_as("SELECT position FROM projection_checkpoint WHERE projection_id = $1")
.bind(id.as_str())
.fetch_one(&mut *transaction)
.await
.map_err(|error| CommitError::Store(PostgresProjectionStoreError::Driver(error)))?;
let current = position_from_row(current.0).map_err(CommitError::Store)?;
drop(transaction);
Err(CommitError::CheckpointRegression {
current,
attempted: position,
})
}
async fn reset(
&self,
batch: Self::Batch,
id: &ProjectionId,
) -> Result<(), ResetError<Self::Error>> {
if batch.stamp != self.stamp {
return Err(ResetError::ForeignBatch);
}
let mut transaction = self
.pool
.begin()
.await
.map_err(|error| ResetError::Store(PostgresProjectionStoreError::Driver(error)))?;
replay(&mut transaction, &batch)
.await
.map_err(|error| ResetError::Store(PostgresProjectionStoreError::Driver(error)))?;
sqlx::query("DELETE FROM projection_checkpoint WHERE projection_id = $1")
.bind(id.as_str())
.execute(&mut *transaction)
.await
.map_err(|error| ResetError::Store(PostgresProjectionStoreError::Driver(error)))?;
transaction
.commit()
.await
.map_err(|error| ResetError::Store(PostgresProjectionStoreError::Driver(error)))
}
async fn rollback(&self, batch: Self::Batch) -> Result<(), Self::Error> {
if batch.stamp != self.stamp {
return Err(PostgresProjectionStoreError::ForeignBatch);
}
drop(batch);
Ok(())
}
}
#[cfg(feature = "conformance")]
impl happenstance_core::ProjectionProbe for PostgresProjectionStore {
const READS_THROUGH_BATCH: bool = false;
fn probe_write(&self, batch: &mut Self::Batch, key: &str, value: u64) {
batch.push(
"INSERT INTO projection_probe (k, v) VALUES ($1, $2) \
ON CONFLICT (k) DO UPDATE SET v = excluded.v",
[
PgParam::text(key),
PgParam::int8(value.cast_signed()),
],
);
}
fn probe_delete_all(&self, batch: &mut Self::Batch) {
batch.push("DELETE FROM projection_probe", core::iter::empty());
}
async fn probe_read(&self, key: &str) -> Result<Option<u64>, Self::Error> {
let row: Option<(i64,)> = sqlx::query_as("SELECT v FROM projection_probe WHERE k = $1")
.bind(key)
.fetch_optional(&self.pool)
.await?;
Ok(row.map(|(stored,)| stored.cast_unsigned()))
}
fn probe_read_through(&self, _batch: &Self::Batch, _key: &str) -> Option<u64> {
unimplemented!(
"PostgresProjectionBatch buffers its statements, so `READS_THROUGH_BATCH` \
is `false` and this is never called: there is no open transaction to \
read through, and answering from committed state is what PS-12 forbids"
)
}
}
#[cfg(test)]
mod tests {
use super::{PgParam, PostgresProjectionBatch, PostgresProjectionStore, mint_stamp};
use happenstance_core::ProjectionStore;
#[test]
fn send_flavour_satisfies_the_bare_bound() {
fn assert_projection_store<P: ProjectionStore>() {}
assert_projection_store::<PostgresProjectionStore>();
}
fn the_batch_does_not_borrow_the_store(
batch: <PostgresProjectionStore as ProjectionStore>::Batch,
) -> PostgresProjectionBatch {
batch
}
#[test]
fn the_batch_is_owned() {
fn assert_static<T: 'static>() {}
fn assert_send<T: Send>() {}
assert_static::<<PostgresProjectionStore as ProjectionStore>::Batch>();
assert_send::<<PostgresProjectionStore as ProjectionStore>::Batch>();
let _ = the_batch_does_not_borrow_the_store;
}
#[test]
fn each_store_mints_a_distinct_stamp() {
let first = mint_stamp();
let second = mint_stamp();
assert_ne!(first, second);
}
#[test]
fn a_batch_carries_the_stamp_of_the_store_that_began_it() {
let first = PostgresProjectionBatch::stamped(mint_stamp());
let second = PostgresProjectionBatch::stamped(mint_stamp());
assert_ne!(first.stamp, second.stamp);
}
#[test]
fn a_fresh_batch_is_empty_and_grows() {
let mut batch = PostgresProjectionBatch::stamped(1);
assert!(batch.is_empty());
assert_eq!(batch.len(), 0);
batch.push("SELECT $1", [PgParam::text("x")]);
assert!(!batch.is_empty());
assert_eq!(batch.len(), 1);
}
#[test]
fn a_null_parameter_carries_its_type() {
assert_eq!(PgParam::Int8(None), PgParam::Int8(None));
assert_ne!(PgParam::Int8(None), PgParam::Text(None));
}
}