use happenstance_core::{
Authority, Checkpoint, CommitError, ProjectionId, ResetError, SendProjectionStore,
SequencePosition,
};
use sqlx::{PgPool, Postgres, Transaction};
use crate::error::PostgresProjectionStoreError;
use crate::projection_store::{
AUTHORITY_LIVE, AUTHORITY_REBUILDING, PgParam, authority_to_row, bind_all, mint_stamp,
position_from_row, position_to_row,
};
#[derive(Debug)]
pub struct LivePostgresBatch {
transaction: Transaction<'static, Postgres>,
stamp: u64,
}
impl LivePostgresBatch {
pub async fn execute(
&mut self,
sql: &'static str,
params: impl IntoIterator<Item = PgParam>,
) -> Result<(), PostgresProjectionStoreError> {
self.execute_raw_sql(sql, params.into_iter().collect())
.await
}
pub async fn execute_raw_sql(
&mut self,
sql: &str,
params: Vec<PgParam>,
) -> Result<(), PostgresProjectionStoreError> {
bind_all(sqlx::query(sql), ¶ms)
.execute(&mut *self.transaction)
.await?;
Ok(())
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LivePostgresProjectionStore {
pool: PgPool,
stamp: u64,
}
impl LivePostgresProjectionStore {
pub fn new(pool: PgPool) -> Self {
Self {
pool,
stamp: mint_stamp(),
}
}
pub fn pool(&self) -> &PgPool {
&self.pool
}
}
impl SendProjectionStore for LivePostgresProjectionStore {
type Error = PostgresProjectionStoreError;
type Batch = LivePostgresBatch;
async fn begin(&self) -> Result<Self::Batch, Self::Error> {
let transaction = self.pool.begin().await?;
Ok(LivePostgresBatch {
transaction,
stamp: 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 = batch.transaction;
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)?;
transaction
.rollback()
.await
.map_err(|error| CommitError::Store(PostgresProjectionStoreError::Driver(error)))?;
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 = batch.transaction;
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);
}
batch.transaction.rollback().await?;
Ok(())
}
}
#[cfg(feature = "conformance")]
impl happenstance_core::ProjectionProbe for LivePostgresProjectionStore {
const READS_THROUGH_BATCH: bool = true;
async fn probe_write(
&self,
batch: &mut Self::Batch,
key: &str,
value: u64,
) -> Result<(), Self::Error> {
batch
.execute(
"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())],
)
.await
}
async fn probe_delete_all(&self, batch: &mut Self::Batch) -> Result<(), Self::Error> {
batch.execute("DELETE FROM projection_probe", []).await
}
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()))
}
async fn probe_read_through(
&self,
batch: &mut Self::Batch,
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(&mut *batch.transaction)
.await?;
Ok(row.map(|(stored,)| stored.cast_unsigned()))
}
}