datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation
//! Single-envelope and grouped projection handlers.

use super::ProjectionResult;

#[cfg(feature = "postgres")]
use sqlx::{
    Executor, PgConnection, Postgres, Transaction,
    postgres::{PgArguments, PgQueryResult, PgRow},
    query::Query,
};

/// Processes one source envelope at a time.
///
/// A handler instance belongs to exactly one projection incarnation. The
/// projection blueprint stores a factory and constructs a fresh handler every
/// time the source is restarted. Returning an error enters the configured
/// per-invocation [`super::RecoveryStrategy`]; it is not classified by the
/// infrastructure fatal/restartable taxonomy until that recovery strategy has
/// been exhausted.
#[async_trait::async_trait]
pub trait Handler<Envelope>: Send + 'static {
    /// Processes one envelope.
    ///
    /// Retry strategies invoke this method again with the same envelope and
    /// preserve source order until the invocation succeeds, is skipped, or
    /// escalates to projection restart.
    async fn process(&mut self, envelope: &Envelope) -> ProjectionResult<()>;
}

#[async_trait::async_trait]
impl<Envelope, H> Handler<Envelope> for Box<H>
where
    Envelope: Sync + 'static,
    H: Handler<Envelope> + ?Sized,
{
    async fn process(&mut self, envelope: &Envelope) -> ProjectionResult<()> {
        (**self).process(envelope).await
    }
}

/// Processes one complete group of source envelopes at a time.
///
/// A grouped handler instance belongs to exactly one projection incarnation.
/// The projection blueprint stores a factory and constructs a fresh handler
/// every time the source is restarted. The slice is non-empty, remains in
/// source order, and is the complete recovery unit: retry strategies invoke
/// this trait again with the same group, while skip strategies advance past
/// the whole group.
#[async_trait::async_trait]
pub trait GroupedHandler<Envelope>: Send + 'static {
    /// Processes one non-empty, source-ordered group.
    ///
    /// A successful return causes grouped at-least-once delivery to save the
    /// cursor at the group's last envelope. Returning an error enters the
    /// configured per-invocation [`super::RecoveryStrategy`].
    async fn process(&mut self, envelopes: &[Envelope]) -> ProjectionResult<()>;
}

#[async_trait::async_trait]
impl<Envelope, H> GroupedHandler<Envelope> for Box<H>
where
    Envelope: Sync + 'static,
    H: GroupedHandler<Envelope> + ?Sized,
{
    async fn process(&mut self, envelopes: &[Envelope]) -> ProjectionResult<()> {
        (**self).process(envelopes).await
    }
}

/// Opaque PostgreSQL transaction supplied to an exactly-once handler.
///
/// The projection runtime begins this transaction, locks and validates the
/// offset row's owner generation and expected cursor position, and only then
/// invokes the handler. A successful invocation writes the replacement cursor
/// and commits this same transaction; a failed invocation rolls it back.
///
/// The execute/fetch helpers accept a value built with [`sqlx::query()`], so
/// callers can bind values without taking ownership of the transaction:
///
/// ```no_run
/// # use datum_persistence::projection::{PostgresProjectionTx, ProjectionResult};
/// # async fn write(tx: &mut PostgresProjectionTx) -> ProjectionResult<()> {
/// tx.execute(sqlx::query("INSERT INTO read_model (id) VALUES ($1)").bind(7_i64))
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// Fields and construction deliberately remain private. This keeps the
/// exactly-once protocol under runtime control while still exposing normal
/// SQL query operations.
#[cfg(feature = "postgres")]
pub struct PostgresProjectionTx {
    pub(crate) inner: Option<Transaction<'static, Postgres>>,
}

#[cfg(feature = "postgres")]
impl PostgresProjectionTx {
    pub(crate) fn new(transaction: Transaction<'static, Postgres>) -> Self {
        Self {
            inner: Some(transaction),
        }
    }

    fn connection(&mut self) -> ProjectionResult<&mut PgConnection> {
        self.inner.as_deref_mut().ok_or_else(|| {
            super::ProjectionError::Runtime(
                "PostgreSQL projection transaction is already complete".into(),
            )
        })
    }

    /// Executes a bound PostgreSQL query inside the projection transaction.
    pub async fn execute<'query>(
        &mut self,
        query: Query<'query, Postgres, PgArguments>,
    ) -> ProjectionResult<PgQueryResult> {
        self.connection()?
            .execute(query)
            .await
            .map_err(handler_query_error)
    }

    /// Fetches exactly one row inside the projection transaction.
    pub async fn fetch_one<'query>(
        &mut self,
        query: Query<'query, Postgres, PgArguments>,
    ) -> ProjectionResult<PgRow> {
        self.connection()?
            .fetch_one(query)
            .await
            .map_err(handler_query_error)
    }

    /// Fetches at most one row inside the projection transaction.
    pub async fn fetch_optional<'query>(
        &mut self,
        query: Query<'query, Postgres, PgArguments>,
    ) -> ProjectionResult<Option<PgRow>> {
        self.connection()?
            .fetch_optional(query)
            .await
            .map_err(handler_query_error)
    }

    /// Fetches all rows inside the projection transaction.
    pub async fn fetch_all<'query>(
        &mut self,
        query: Query<'query, Postgres, PgArguments>,
    ) -> ProjectionResult<Vec<PgRow>> {
        self.connection()?
            .fetch_all(query)
            .await
            .map_err(handler_query_error)
    }

    /// Returns the sqlx connection borrowed by the projection transaction.
    ///
    /// This is a **version-unstable escape hatch** for sqlx operations not
    /// covered by the helpers above, including typed `query_as` queries and
    /// row streams. Its exact return type and lifetime may change when Datum
    /// updates sqlx; code using only the wrapper helpers is insulated from
    /// that churn.
    ///
    /// The returned value is deliberately the transaction's `DerefMut`
    /// target, not the [`Transaction`] itself. Safe handler code therefore
    /// cannot move, replace, commit, or roll back the runtime-owned
    /// transaction. Commit and rollback remain exclusively under projection
    /// runtime control.
    pub fn sqlx_connection(&mut self) -> ProjectionResult<&mut PgConnection> {
        self.connection()
    }

    pub(crate) fn connection_for_cursor(&mut self) -> ProjectionResult<&mut PgConnection> {
        self.connection()
    }

    pub(crate) async fn commit(mut self) -> ProjectionResult<()> {
        self.inner
            .take()
            .ok_or_else(|| {
                super::ProjectionError::Runtime(
                    "PostgreSQL projection transaction is already complete".into(),
                )
            })?
            .commit()
            .await
            .map_err(|error| {
                super::ProjectionError::OffsetStore(format!(
                    "commit PostgreSQL exactly-once transaction: {error}"
                ))
            })
    }

    pub(crate) async fn rollback(mut self) -> ProjectionResult<()> {
        self.inner
            .take()
            .ok_or_else(|| {
                super::ProjectionError::Runtime(
                    "PostgreSQL projection transaction is already complete".into(),
                )
            })?
            .rollback()
            .await
            .map_err(|error| {
                super::ProjectionError::OffsetStore(format!(
                    "rollback PostgreSQL exactly-once transaction: {error}"
                ))
            })
    }
}

#[cfg(feature = "postgres")]
fn handler_query_error(error: sqlx::Error) -> super::ProjectionError {
    super::ProjectionError::Handler(format!(
        "PostgreSQL exactly-once handler query failed: {error}"
    ))
}

/// Processes one envelope in the transaction that also commits its cursor.
///
/// Each retry receives a fresh transaction. User writes from a failed or
/// panicking invocation are rolled back before retry, skip, or restart.
/// [`super::RecoveryStrategy::Skip`] and retry-then-skip are the documented
/// exactly-once exception: after rollback, the runtime advances the cursor in
/// a separate cursor-only transaction, so read-model state and cursor
/// intentionally do not agree for that skipped invocation.
#[cfg(feature = "postgres")]
#[async_trait::async_trait]
pub trait ExactlyOncePostgresHandler<Envelope>: Send + 'static {
    /// Processes one envelope inside the cursor transaction.
    async fn process(
        &mut self,
        transaction: &mut PostgresProjectionTx,
        envelope: &Envelope,
    ) -> ProjectionResult<()>;
}

#[cfg(feature = "postgres")]
#[async_trait::async_trait]
impl<Envelope, H> ExactlyOncePostgresHandler<Envelope> for Box<H>
where
    Envelope: Sync + 'static,
    H: ExactlyOncePostgresHandler<Envelope> + ?Sized,
{
    async fn process(
        &mut self,
        transaction: &mut PostgresProjectionTx,
        envelope: &Envelope,
    ) -> ProjectionResult<()> {
        (**self).process(transaction, envelope).await
    }
}

/// Processes one complete envelope group in the transaction committing its cursor.
///
/// Retry and skip apply to the whole non-empty group. Failed attempts roll
/// back every user write. A skipped group advances only the cursor in a
/// separate transaction, the same documented exception as the single-envelope
/// exactly-once handler.
#[cfg(feature = "postgres")]
#[async_trait::async_trait]
pub trait GroupedExactlyOncePostgresHandler<Envelope>: Send + 'static {
    /// Processes one source-ordered group inside the cursor transaction.
    async fn process(
        &mut self,
        transaction: &mut PostgresProjectionTx,
        envelopes: &[Envelope],
    ) -> ProjectionResult<()>;
}

#[cfg(feature = "postgres")]
#[async_trait::async_trait]
impl<Envelope, H> GroupedExactlyOncePostgresHandler<Envelope> for Box<H>
where
    Envelope: Sync + 'static,
    H: GroupedExactlyOncePostgresHandler<Envelope> + ?Sized,
{
    async fn process(
        &mut self,
        transaction: &mut PostgresProjectionTx,
        envelopes: &[Envelope],
    ) -> ProjectionResult<()> {
        (**self).process(transaction, envelopes).await
    }
}