1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use core::fmt;
use crate::{
batch::BatchShapeError,
position::{
BlockRef,
Position,
},
};
/// Classified fold failure; the variant fixes the engine's recovery obligation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FoldError<E> {
/// Event is not mine; engine counts it and advances the cursor.
Skip(E),
/// State is clean up to the previous position; recovery is rollback or resync.
Halt(E),
/// Apply mutated state partially; state is untrusted until a restore.
Poison(E),
}
impl<E: fmt::Display> fmt::Display for FoldError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Skip(error) => write!(f, "skip: {error}"),
Self::Halt(error) => write!(f, "halt: {error}"),
Self::Poison(error) => write!(f, "poison: {error}"),
}
}
}
impl<E: fmt::Debug + fmt::Display> core::error::Error for FoldError<E> {}
/// Coarse-grained state of the fold engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EngineStatus {
/// Applying batches and advancing the cursor.
Active,
/// Fold refused an event with clean state below it.
Halted {
/// Position the fold halted at.
at: Position,
},
/// Fold refused an event after mutating state.
Poisoned {
/// Position the fold poisoned at.
at: Position,
},
/// Automated recovery is exhausted; only a reset leaves this state.
Unrecoverable {
/// Divergence that ended automated recovery.
cause: DivergenceCause,
},
}
impl EngineStatus {
/// True while the engine still accepts batches.
pub const fn is_active(&self) -> bool {
matches!(self, Self::Active)
}
}
impl fmt::Display for EngineStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Active => write!(f, "active"),
Self::Halted { at } => {
write!(f, "halted at block {} log index {}", at.block, at.log_index)
}
Self::Poisoned { at } => {
write!(
f,
"poisoned at block {} log index {}",
at.block, at.log_index
)
}
Self::Unrecoverable { cause } => write!(f, "unrecoverable: {cause}"),
}
}
}
impl core::error::Error for EngineStatus {}
/// Terminal divergence reason the engine cannot recover from automatically.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DivergenceCause {
/// Fork deeper than the oldest observed block in the ring.
ForkBeyondWindow,
/// A canonical ancestor exists but no retained checkpoint sits at or below it.
NoCheckpointBelowAncestor {
/// Deepest still-canonical observed block.
ancestor: u64,
},
/// Replay is required but the source's horizon no longer covers the start block.
HorizonExceeded {
/// Block replay must start from.
needed: u64,
/// Oldest block the source still serves.
horizon: u64,
},
/// Fold view disagreed with the anchor after retries.
AnchorDivergence {
/// Block whose anchor comparison failed.
at: u64,
},
}
impl fmt::Display for DivergenceCause {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ForkBeyondWindow => write!(f, "fork deeper than the observed window"),
Self::NoCheckpointBelowAncestor { ancestor } => {
write!(f, "no checkpoint at or below ancestor block {ancestor}")
}
Self::HorizonExceeded { needed, horizon } => {
write!(
f,
"replay needs block {needed}, source horizon is {horizon}"
)
}
Self::AnchorDivergence { at } => write!(f, "anchor divergence at block {at}"),
}
}
}
impl core::error::Error for DivergenceCause {}
/// Durability sink refused a snapshot offer; persistence has stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DurabilityLost;
impl fmt::Display for DurabilityLost {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"durability sink refused a snapshot; snapshots are no longer persisted"
)
}
}
impl core::error::Error for DurabilityLost {}
/// Rejected engine construction configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigError {
/// Ring capacity is not a power of two.
RingCapacityNotPowerOfTwo {
/// Capacity the caller asked for.
got: usize,
},
/// Ring capacity is outside the allowed range.
RingCapacityOutOfRange {
/// Capacity the caller asked for.
got: usize,
},
/// Source cannot replay from the configured start block.
HorizonExceedsStart {
/// Block the driver folds from.
start: u64,
/// Oldest block the source still serves.
horizon: u64,
},
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RingCapacityNotPowerOfTwo { got } => {
write!(f, "ring capacity {got} is not a power of two")
}
Self::RingCapacityOutOfRange { got } => {
write!(f, "ring capacity {got} is out of the allowed range")
}
Self::HorizonExceedsStart { start, horizon } => {
write!(f, "replay horizon {horizon} exceeds start block {start}")
}
}
}
}
impl core::error::Error for ConfigError {}
/// Rejected or failed batch application.
#[derive(Debug, PartialEq, Eq)]
pub enum ApplyError<E> {
/// Engine is halted, poisoned, or unrecoverable.
NotActive {
/// Status that refused the batch.
status: EngineStatus,
},
/// Batch violates the flat layout rules.
Shape(BatchShapeError),
/// Cursor is set but the batch carries no boundary header.
MissingBoundary,
/// Boundary header names a block other than the cursor block.
BoundaryNumberMismatch {
/// Cursor block the boundary must name.
expected: u64,
/// Block the boundary named.
got: u64,
},
/// Refetched header disagrees with the observed block of that number.
ForkSuspected {
/// Block as the engine observed it.
observed: BlockRef,
/// Block as the source refetched it.
refetched: BlockRef,
},
/// Observed ring holds no entry for the cursor block, so no boundary is verifiable.
CursorBlockUnobserved {
/// Cursor block absent from the ring.
block: u64,
},
/// Fold halted; state is clean up to the position before `at`.
Halted {
/// Position the fold refused.
at: Position,
/// Error the fold reported.
error: E,
},
/// Fold poisoned; state is untrusted until a restore.
Poisoned {
/// Position the fold refused after mutating.
at: Position,
/// Error the fold reported.
error: E,
},
}
impl<E: fmt::Display> fmt::Display for ApplyError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotActive { status } => write!(f, "engine not active: {status}"),
Self::Shape(error) => write!(f, "batch shape invalid: {error}"),
Self::MissingBoundary => {
write!(f, "cursor is set but the batch carries no boundary")
}
Self::BoundaryNumberMismatch { expected, got } => {
write!(
f,
"boundary block {got} does not match cursor block {expected}"
)
}
Self::ForkSuspected {
observed,
refetched,
} => {
write!(
f,
"fork suspected at block {}: observed hash {}, refetched hash {}",
observed.number,
HexHash(&observed.hash),
HexHash(&refetched.hash)
)
}
Self::CursorBlockUnobserved { block } => {
write!(f, "observed ring holds no entry for cursor block {block}")
}
Self::Halted { at, error } => {
write!(
f,
"halted at block {} log index {}: {error}",
at.block, at.log_index
)
}
Self::Poisoned { at, error } => {
write!(
f,
"poisoned at block {} log index {}: {error}",
at.block, at.log_index
)
}
}
}
}
impl<E: fmt::Debug + fmt::Display> core::error::Error for ApplyError<E> {}
/// Rejected rollback request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RollbackError {
/// No retained checkpoint sits at or below the requested block.
NoCheckpointAtOrBelow {
/// Block the rollback targeted.
block: u64,
},
/// Engine is unrecoverable; only a reset leaves this state.
Unrecoverable {
/// Divergence that ended automated recovery.
cause: DivergenceCause,
},
}
impl fmt::Display for RollbackError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoCheckpointAtOrBelow { block } => {
write!(f, "no retained checkpoint at or below block {block}")
}
Self::Unrecoverable { cause } => write!(f, "unrecoverable: {cause}"),
}
}
}
impl core::error::Error for RollbackError {}
/// Renders a 32-byte hash as lowercase hex.
struct HexHash<'a>(&'a [u8; 32]);
impl fmt::Display for HexHash<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in self.0 {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}