reliar-store-postgres 0.8.0

PostgreSQL provider for the Reliar transactional outbox and inbox: migrations, migrate(), enqueue and the SKIP LOCKED claim.
Documentation
//! Hand-rolled error enum for the inbox side of the PostgreSQL provider (ADR 0008, inbox contract
//! §3).

use core::fmt;

use reliar_core::{Classify, FailureKind, MessageId};

use crate::error::{classify_sqlstate, is_undefined_table};

/// A failure of a [`crate::PostgresInboxStore`] call (inbox contract §3). Deliberately smaller
/// than [`crate::PostgresOutboxError`]: the inbox has no `enqueue`/`acquire` analog, so it needs
/// no `Decode`/`UnknownMetadataVersion`/`DuplicateMessage` variant.
#[derive(Debug)]
#[non_exhaustive]
pub enum PostgresInboxError {
    /// The relation does not resolve on this connection's `search_path` (SQLSTATE `42P01`).
    /// Either `migrate()` has not run, or the connection's `search_path` does not resolve the
    /// unqualified name `inbox` to the migrated schema. **Permanent** — the table does not
    /// appear on its own. Reliar does not check this at construction (ADR 0047); this is the
    /// first statement reporting it, with PostgreSQL's own message attached as the `source`.
    /// Mapped from SQLSTATE `42P01` on **every** call.
    NotMigrated {
        /// The underlying `42P01` error, returned from [`std::error::Error::source`].
        source: sqlx::Error,
    },

    /// [`crate::PostgresInboxStore`]'s `InboxStore::complete` matched zero rows — reachable only
    /// by misuse (completing without a preceding `Claimed` claim, after the claiming
    /// transaction aborted, or completing a row that has since gone dead — `complete`'s own
    /// guard is `completed_at IS NULL AND dead_at IS NULL`, ADR 0042 A.2.4). **Permanent** —
    /// retrying the same call changes nothing.
    NotClaimed {
        /// The scope the caller completed under.
        scope: String,
        /// The message id the caller tried to complete.
        message_id: MessageId,
    },

    /// `PostgresInboxSettings::validate` rejected the settings — currently only
    /// `max_attempts == 0` (ADR 0042 A.2.4). Checked at
    /// [`crate::PostgresInboxStore::with_settings`], before any query runs. **Permanent.**
    InvalidSettings {
        /// A payload-free description of what was rejected.
        message: String,
    },

    /// Any other `sqlx` failure, classified by SQLSTATE exactly as
    /// [`crate::PostgresOutboxError::Database`].
    Database {
        /// The underlying `sqlx` error.
        source: sqlx::Error,
    },
}

impl fmt::Display for PostgresInboxError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotMigrated { source } => write!(
                f,
                "the inbox table does not resolve on this connection's search_path: {source}; \
                 run reliar_store_postgres::migrate(&pool, ..) and put the migrated schema first \
                 on search_path — in the connection URL \
                 (options=-c search_path=reliar,public) or with ALTER ROLE <role> SET \
                 search_path = reliar, public"
            ),
            Self::NotClaimed { scope, message_id } => write!(
                f,
                "no claimed inbox row for scope {scope:?}, message {message_id}; complete() may \
                 only follow a Claimed claim() in the same transaction, and never a dead one"
            ),
            Self::InvalidSettings { message } => {
                write!(f, "invalid PostgresInboxSettings: {message}")
            }
            Self::Database { source } => write!(f, "database error: {source}"),
        }
    }
}

impl std::error::Error for PostgresInboxError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NotMigrated { source } | Self::Database { source } => Some(source),
            Self::NotClaimed { .. } | Self::InvalidSettings { .. } => None,
        }
    }
}

/// Per-variant classification table, exactly as [`crate::PostgresOutboxError`]'s: no blanket
/// "everything else is transient".
impl Classify for PostgresInboxError {
    fn kind(&self) -> FailureKind {
        match self {
            Self::NotMigrated { .. } | Self::NotClaimed { .. } | Self::InvalidSettings { .. } => {
                FailureKind::Permanent
            }
            Self::Database { source } => classify_sqlstate(source),
        }
    }
}

impl From<sqlx::Error> for PostgresInboxError {
    fn from(source: sqlx::Error) -> Self {
        map_operational_error(source)
    }
}

/// Maps a `sqlx::Error` to a typed error, keying on SQLSTATE — never on message text — so
/// `42P01` maps to `NotMigrated` **on every path**, and everything else falls through to
/// `Database` for [`classify_sqlstate`] to classify. Mirrors the outbox's own operational-error
/// mapping (ADR 0047 §4 — the inbox gains this mapping on every path, not only at a construction
/// check that no longer exists).
pub(crate) fn map_operational_error(err: sqlx::Error) -> PostgresInboxError {
    if is_undefined_table(&err) {
        return PostgresInboxError::NotMigrated { source: err };
    }

    PostgresInboxError::Database { source: err }
}

impl crate::error::FromDatabaseError for PostgresInboxError {
    fn from_database_error(err: sqlx::Error) -> Self {
        map_operational_error(err)
    }
}