Skip to main content

datum_persistence/projection/
error.rs

1use thiserror::Error;
2
3use super::ProjectionId;
4
5/// Result type used by projection infrastructure.
6pub type ProjectionResult<T> = Result<T, ProjectionError>;
7
8/// Restart disposition of a projection infrastructure error.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum ProjectionErrorKind {
11    /// Stop the projection with terminal status; restarting cannot repair it.
12    Fatal,
13    /// Restart the complete source/handler incarnation under configured backoff.
14    Restartable,
15}
16
17/// Projection infrastructure failures.
18///
19/// Fatal errors are deterministic configuration, durable-data, or ownership
20/// violations. They bypass restart backoff. Restartable errors are transient
21/// source and offset-store failures. [`ProjectionError::Handler`] records an
22/// error returned by a handler or handler factory, but handler-invocation
23/// errors first follow [`super::RecoveryStrategy`]; only an exhausted
24/// invocation escalates to projection restart. The D9 fatal/restartable split
25/// governs infrastructure errors directly.
26#[derive(Debug, Clone, PartialEq, Eq, Error)]
27#[non_exhaustive]
28pub enum ProjectionError {
29    /// A durable cursor could not be decoded or was not canonically encoded.
30    #[error("projection cursor codec failed: {0}")]
31    CursorCodec(String),
32
33    /// A cursor belongs to a different source-provider identity.
34    #[error("projection provider manifest mismatch: expected {expected:?}, found {actual:?}")]
35    ProviderManifestMismatch {
36        /// Manifest required by the configured source provider.
37        expected: String,
38        /// Manifest stored with the durable cursor.
39        actual: String,
40    },
41
42    /// Projection configuration is deterministically invalid.
43    #[error("invalid projection configuration for {setting}: {reason}")]
44    InvalidConfig {
45        /// Setting or identity component that failed validation.
46        setting: &'static str,
47        /// Human-readable validation failure.
48        reason: String,
49    },
50
51    /// A second in-process owner attempted to spawn the same projection id.
52    #[error("projection {projection_id} is already running in this process")]
53    AlreadyRunning {
54        /// Projection identity already reserved by a live actor.
55        projection_id: ProjectionId,
56    },
57
58    /// An offset-store write used an owner generation superseded by a claimant.
59    #[error(
60        "projection {projection_id} lost offset-store fencing: generation \
61         {attempted_generation} is not current generation {current_generation}"
62    )]
63    Fenced {
64        /// Projection whose store ownership was lost.
65        projection_id: ProjectionId,
66        /// Generation carried by the rejected operation.
67        attempted_generation: u64,
68        /// Generation currently recorded by the store.
69        current_generation: u64,
70    },
71
72    /// A compare-and-set save observed a different cursor position.
73    #[error(
74        "projection {projection_id} cursor position conflict: expected {expected:?}, \
75         found {actual:?}"
76    )]
77    UnexpectedPosition {
78        /// Projection whose cursor changed unexpectedly.
79        projection_id: ProjectionId,
80        /// Position the caller previously loaded, or `None` for no cursor.
81        expected: Option<String>,
82        /// Position present at the save linearization point.
83        actual: Option<String>,
84    },
85
86    /// A projection generation reached its durable numeric limit.
87    #[error("projection {projection_id} offset-store generation is exhausted")]
88    GenerationExhausted {
89        /// Projection whose generation cannot advance.
90        projection_id: ProjectionId,
91    },
92
93    /// A projection source failed while being created or consumed.
94    #[error("projection source failed: {0}")]
95    Source(String),
96
97    /// A handler invocation or handler factory failed.
98    ///
99    /// Runtime code routes this through `RecoveryStrategy` before considering
100    /// projection restart, regardless of this variant's infrastructure kind.
101    #[error("projection handler failed: {0}")]
102    Handler(String),
103
104    /// Offset-store I/O failed or its result is uncertain.
105    #[error("projection offset store failed: {0}")]
106    OffsetStore(String),
107
108    /// The Ractor shell or its bounded execution bridge failed.
109    #[error("projection runtime failed: {0}")]
110    Runtime(String),
111
112    /// A projection-testkit assertion did not pass within its bounded window.
113    #[error("projection testkit assertion timed out after {timeout_ms} ms")]
114    TestKitTimeout {
115        /// Configured assertion window in milliseconds.
116        timeout_ms: u64,
117    },
118}
119
120impl ProjectionError {
121    /// Returns the D9 fatal-versus-restartable classification.
122    #[must_use]
123    pub const fn kind(&self) -> ProjectionErrorKind {
124        match self {
125            Self::CursorCodec(_)
126            | Self::ProviderManifestMismatch { .. }
127            | Self::InvalidConfig { .. }
128            | Self::AlreadyRunning { .. }
129            | Self::Fenced { .. }
130            | Self::UnexpectedPosition { .. }
131            | Self::GenerationExhausted { .. }
132            | Self::Runtime(_)
133            | Self::TestKitTimeout { .. } => ProjectionErrorKind::Fatal,
134            Self::Source(_) | Self::Handler(_) | Self::OffsetStore(_) => {
135                ProjectionErrorKind::Restartable
136            }
137        }
138    }
139
140    /// Returns whether this error must stop without entering restart backoff.
141    #[must_use]
142    pub const fn is_fatal(&self) -> bool {
143        matches!(self.kind(), ProjectionErrorKind::Fatal)
144    }
145
146    /// Returns whether this error may restart the projection under backoff.
147    #[must_use]
148    pub const fn is_restartable(&self) -> bool {
149        matches!(self.kind(), ProjectionErrorKind::Restartable)
150    }
151
152    pub(super) fn invalid_config(setting: &'static str, reason: impl Into<String>) -> Self {
153        Self::InvalidConfig {
154            setting,
155            reason: reason.into(),
156        }
157    }
158}