datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation
use thiserror::Error;

use super::ProjectionId;

/// Result type used by projection infrastructure.
pub type ProjectionResult<T> = Result<T, ProjectionError>;

/// Restart disposition of a projection infrastructure error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProjectionErrorKind {
    /// Stop the projection with terminal status; restarting cannot repair it.
    Fatal,
    /// Restart the complete source/handler incarnation under configured backoff.
    Restartable,
}

/// Projection infrastructure failures.
///
/// Fatal errors are deterministic configuration, durable-data, or ownership
/// violations. They bypass restart backoff. Restartable errors are transient
/// source and offset-store failures. [`ProjectionError::Handler`] records an
/// error returned by a handler or handler factory, but handler-invocation
/// errors first follow [`super::RecoveryStrategy`]; only an exhausted
/// invocation escalates to projection restart. The D9 fatal/restartable split
/// governs infrastructure errors directly.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ProjectionError {
    /// A durable cursor could not be decoded or was not canonically encoded.
    #[error("projection cursor codec failed: {0}")]
    CursorCodec(String),

    /// A cursor belongs to a different source-provider identity.
    #[error("projection provider manifest mismatch: expected {expected:?}, found {actual:?}")]
    ProviderManifestMismatch {
        /// Manifest required by the configured source provider.
        expected: String,
        /// Manifest stored with the durable cursor.
        actual: String,
    },

    /// Projection configuration is deterministically invalid.
    #[error("invalid projection configuration for {setting}: {reason}")]
    InvalidConfig {
        /// Setting or identity component that failed validation.
        setting: &'static str,
        /// Human-readable validation failure.
        reason: String,
    },

    /// A second in-process owner attempted to spawn the same projection id.
    #[error("projection {projection_id} is already running in this process")]
    AlreadyRunning {
        /// Projection identity already reserved by a live actor.
        projection_id: ProjectionId,
    },

    /// An offset-store write used an owner generation superseded by a claimant.
    #[error(
        "projection {projection_id} lost offset-store fencing: generation \
         {attempted_generation} is not current generation {current_generation}"
    )]
    Fenced {
        /// Projection whose store ownership was lost.
        projection_id: ProjectionId,
        /// Generation carried by the rejected operation.
        attempted_generation: u64,
        /// Generation currently recorded by the store.
        current_generation: u64,
    },

    /// A compare-and-set save observed a different cursor position.
    #[error(
        "projection {projection_id} cursor position conflict: expected {expected:?}, \
         found {actual:?}"
    )]
    UnexpectedPosition {
        /// Projection whose cursor changed unexpectedly.
        projection_id: ProjectionId,
        /// Position the caller previously loaded, or `None` for no cursor.
        expected: Option<String>,
        /// Position present at the save linearization point.
        actual: Option<String>,
    },

    /// A projection generation reached its durable numeric limit.
    #[error("projection {projection_id} offset-store generation is exhausted")]
    GenerationExhausted {
        /// Projection whose generation cannot advance.
        projection_id: ProjectionId,
    },

    /// A projection source failed while being created or consumed.
    #[error("projection source failed: {0}")]
    Source(String),

    /// A handler invocation or handler factory failed.
    ///
    /// Runtime code routes this through `RecoveryStrategy` before considering
    /// projection restart, regardless of this variant's infrastructure kind.
    #[error("projection handler failed: {0}")]
    Handler(String),

    /// Offset-store I/O failed or its result is uncertain.
    #[error("projection offset store failed: {0}")]
    OffsetStore(String),

    /// The Ractor shell or its bounded execution bridge failed.
    #[error("projection runtime failed: {0}")]
    Runtime(String),

    /// A projection-testkit assertion did not pass within its bounded window.
    #[error("projection testkit assertion timed out after {timeout_ms} ms")]
    TestKitTimeout {
        /// Configured assertion window in milliseconds.
        timeout_ms: u64,
    },
}

impl ProjectionError {
    /// Returns the D9 fatal-versus-restartable classification.
    #[must_use]
    pub const fn kind(&self) -> ProjectionErrorKind {
        match self {
            Self::CursorCodec(_)
            | Self::ProviderManifestMismatch { .. }
            | Self::InvalidConfig { .. }
            | Self::AlreadyRunning { .. }
            | Self::Fenced { .. }
            | Self::UnexpectedPosition { .. }
            | Self::GenerationExhausted { .. }
            | Self::Runtime(_)
            | Self::TestKitTimeout { .. } => ProjectionErrorKind::Fatal,
            Self::Source(_) | Self::Handler(_) | Self::OffsetStore(_) => {
                ProjectionErrorKind::Restartable
            }
        }
    }

    /// Returns whether this error must stop without entering restart backoff.
    #[must_use]
    pub const fn is_fatal(&self) -> bool {
        matches!(self.kind(), ProjectionErrorKind::Fatal)
    }

    /// Returns whether this error may restart the projection under backoff.
    #[must_use]
    pub const fn is_restartable(&self) -> bool {
        matches!(self.kind(), ProjectionErrorKind::Restartable)
    }

    pub(super) fn invalid_config(setting: &'static str, reason: impl Into<String>) -> Self {
        Self::InvalidConfig {
            setting,
            reason: reason.into(),
        }
    }
}