datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Event-sourced behavior blueprints, effects, recovery, and runtime handles.

mod effect;
mod runtime;

use std::{marker::PhantomData, sync::Arc};

use datum::{
    RestartSettings, Topic,
    actor::{ActorRef, Message},
};

use crate::{
    EventAdapter, Journal, PersistenceError, PersistenceId, PersistenceResult, SequenceNr,
    SerializerCatalog, SnapshotCriteria, SnapshotMetadata, SnapshotStore, StateAdapter, Tag,
};

pub use effect::{Effect, ReplyEffect};

use runtime::{EventCodec, StateCodec};

type CommandHandler<C, E, S> = dyn Fn(&S, C) -> Effect<C, E, S> + Send + Sync + 'static;
type EventHandler<E, S> = dyn Fn(&S, &E) -> PersistenceResult<S> + Send + Sync + 'static;
type SnapshotPredicate<E, S> = dyn Fn(&S, &E, SequenceNr) -> bool + Send + Sync + 'static;
type Tagger<E, S> = dyn Fn(&S, &E) -> Vec<Tag> + Send + Sync + 'static;
type SignalHandler<S> = dyn Fn(&S, &EventSourcedSignal) + Send + Sync + 'static;

/// Converts an event-handler return value into a persistence result.
///
/// This permits the common `Fn(&S, &E) -> S` form while allowing validation
/// handlers to return `PersistenceResult<S>` and reject a staged transition
/// before journal I/O.
pub trait IntoEventHandlerResult<S> {
    /// Converts this handler output into the runtime result.
    fn into_event_handler_result(self) -> PersistenceResult<S>;
}

impl<S> IntoEventHandlerResult<S> for S {
    fn into_event_handler_result(self) -> PersistenceResult<S> {
        Ok(self)
    }
}

impl<S> IntoEventHandlerResult<S> for PersistenceResult<S> {
    fn into_event_handler_result(self) -> PersistenceResult<S> {
        self
    }
}

/// Snapshot selection used during recovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SnapshotSelection {
    /// Load the latest available snapshot.
    Latest,
    /// Do not load a snapshot; replay all retained events.
    None,
    /// Load the latest snapshot matching explicit bounds.
    Criteria(SnapshotCriteria),
}

impl SnapshotSelection {
    pub(crate) fn criteria(self) -> SnapshotCriteria {
        match self {
            Self::Latest => SnapshotCriteria::latest(),
            Self::None => SnapshotCriteria::none(),
            Self::Criteria(criteria) => criteria,
        }
    }
}

/// Recovery mode for an event-sourced behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Recovery {
    /// Restore a selected snapshot and replay later events.
    Enabled(SnapshotSelection),
    /// Skip state restoration but read the journal high watermark.
    Disabled,
}

impl Recovery {
    /// Uses explicit snapshot selection followed by event replay.
    #[must_use]
    pub const fn with_snapshot_selection(selection: SnapshotSelection) -> Self {
        Self::Enabled(selection)
    }
}

impl Default for Recovery {
    fn default() -> Self {
        Self::Enabled(SnapshotSelection::Latest)
    }
}

/// Count-based snapshot retention policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RetentionCriteria {
    /// No automatic count-based snapshots or cleanup.
    #[default]
    Disabled,
    /// Snapshot every `every` sequence numbers and keep `keep` snapshot windows.
    SnapshotEvery {
        /// Number of events per snapshot window.
        every: u64,
        /// Number of snapshot windows to retain.
        keep: u64,
        /// Whether journal events older than the retained window are deleted.
        delete_events: bool,
    },
}

impl RetentionCriteria {
    /// Creates count-based snapshot retention.
    pub fn snapshot_every(every: u64, keep: u64) -> PersistenceResult<Self> {
        if every == 0 {
            return Err(PersistenceError::Rejected(
                "snapshot frequency must be greater than zero".into(),
            ));
        }
        if keep == 0 {
            return Err(PersistenceError::Rejected(
                "snapshot retention count must be greater than zero".into(),
            ));
        }
        Ok(Self::SnapshotEvery {
            every,
            keep,
            delete_events: false,
        })
    }

    /// Deletes old events after a retention snapshot saves successfully.
    #[must_use]
    pub fn with_delete_events_on_snapshot(self) -> Self {
        match self {
            Self::Disabled => Self::Disabled,
            Self::SnapshotEvery { every, keep, .. } => Self::SnapshotEvery {
                every,
                keep,
                delete_events: true,
            },
        }
    }
}

/// Persistence-specific lifecycle and maintenance signals.
#[derive(Debug)]
#[non_exhaustive]
pub enum EventSourcedSignal {
    /// A snapshot was decoded and installed during recovery.
    SnapshotRecovered(SnapshotMetadata),
    /// Recovery completed, including for a fresh persistence id.
    RecoveryCompleted,
    /// Snapshot load or journal replay failed.
    RecoveryFailed(PersistenceError),
    /// Journal storage failed or the commit result was uncertain.
    PersistFailed {
        /// First sequence number attempted by the failed write.
        sequence_nr: SequenceNr,
        /// Storage failure.
        error: PersistenceError,
    },
    /// A deterministic write was rejected before storage.
    PersistRejected {
        /// First sequence number attempted by the rejected write.
        sequence_nr: SequenceNr,
        /// Rejection explanation.
        reason: String,
    },
    /// Snapshot save completed.
    SnapshotCompleted(SnapshotMetadata),
    /// Snapshot save failed non-fatally.
    SnapshotFailed {
        /// Metadata of the attempted snapshot.
        metadata: SnapshotMetadata,
        /// Save or serialization failure.
        error: PersistenceError,
    },
    /// Inclusive event deletion completed.
    DeleteEventsCompleted(SequenceNr),
    /// Inclusive event deletion failed.
    DeleteEventsFailed {
        /// Inclusive deletion target.
        to: SequenceNr,
        /// Storage failure.
        error: PersistenceError,
    },
    /// Snapshot criteria deletion completed.
    DeleteSnapshotsCompleted(SnapshotCriteria),
    /// Snapshot criteria deletion failed.
    DeleteSnapshotsFailed {
        /// Attempted criteria.
        criteria: SnapshotCriteria,
        /// Storage failure.
        error: PersistenceError,
    },
}

/// A confirmed domain-typed event published by a running behavior.
///
/// This deliberately publishes `E`, rather than the erased journal payload:
/// Datum's typed [`Topic`] makes the domain event the useful subscription type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublishedEvent<E> {
    /// Persistent entity identity.
    pub persistence_id: PersistenceId,
    /// Confirmed event sequence number.
    pub sequence_nr: SequenceNr,
    /// Domain event supplied to the event handler.
    pub event: E,
    /// Journal timestamp in Unix-epoch milliseconds.
    pub timestamp_ms: i64,
    /// Query tags stored with the event.
    pub tags: Vec<Tag>,
}

/// Runtime resources supplied only when a behavior is spawned.
pub struct EventSourcedRuntime {
    pub(crate) journal: Arc<dyn Journal>,
    pub(crate) snapshot_store: Option<Arc<dyn SnapshotStore>>,
    pub(crate) writer_uuid: Option<String>,
    pub(crate) topic_capacity: usize,
}

impl EventSourcedRuntime {
    /// Creates runtime configuration using an event journal and no snapshot store.
    #[must_use]
    pub fn new(journal: Arc<dyn Journal>) -> Self {
        Self {
            journal,
            snapshot_store: None,
            writer_uuid: None,
            topic_capacity: 256,
        }
    }

    /// Adds a snapshot store used by recovery and snapshot saves.
    #[must_use]
    pub fn with_snapshot_store(mut self, snapshot_store: Arc<dyn SnapshotStore>) -> Self {
        self.snapshot_store = Some(snapshot_store);
        self
    }

    /// Overrides the stable identifier written by this spawned writer instance.
    #[must_use]
    pub fn with_writer_uuid(mut self, writer_uuid: impl Into<String>) -> Self {
        self.writer_uuid = Some(writer_uuid.into());
        self
    }

    /// Sets the per-subscriber published-event topic capacity.
    #[must_use]
    pub fn with_topic_capacity(mut self, capacity: usize) -> Self {
        assert!(
            capacity > 0,
            "published-event topic capacity must be greater than zero"
        );
        self.topic_capacity = capacity;
        self
    }
}

/// Immutable, side-effect-free event-sourced behavior blueprint.
pub struct EventSourcedBehavior<C, E, S, J = E> {
    pub(crate) persistence_id: PersistenceId,
    pub(crate) empty_state: S,
    pub(crate) command_handler: Arc<CommandHandler<C, E, S>>,
    pub(crate) event_handler: Arc<EventHandler<E, S>>,
    pub(crate) event_codec: Option<EventCodec<E, J>>,
    pub(crate) state_codec: Option<Arc<dyn StateCodec<S>>>,
    pub(crate) snapshot_when: Arc<SnapshotPredicate<E, S>>,
    pub(crate) retention: RetentionCriteria,
    pub(crate) tagger: Arc<Tagger<E, S>>,
    pub(crate) persist_failure_backoff: Option<RestartSettings>,
    pub(crate) recovery: Recovery,
    pub(crate) publish_events: bool,
    pub(crate) stash_capacity: usize,
    pub(crate) signal_handler: Arc<SignalHandler<S>>,
    pub(crate) _journal: PhantomData<fn() -> J>,
}

impl<C, E, S> EventSourcedBehavior<C, E, S, E> {
    /// Creates a side-effect-free behavior blueprint.
    ///
    /// A serializer/adapter is selected separately with
    /// [`Self::with_event_adapter`]; no journal, snapshot, topic, actor, or task
    /// is touched until [`Self::spawn`].
    pub fn new<CH, EH, O>(
        persistence_id: PersistenceId,
        empty_state: S,
        command_handler: CH,
        event_handler: EH,
    ) -> Self
    where
        CH: Fn(&S, C) -> Effect<C, E, S> + Send + Sync + 'static,
        EH: Fn(&S, &E) -> O + Send + Sync + 'static,
        O: IntoEventHandlerResult<S>,
    {
        Self::from_handlers(
            persistence_id,
            empty_state,
            Arc::new(command_handler),
            Arc::new(move |state, event| event_handler(state, event).into_event_handler_result()),
        )
    }

    /// Creates a blueprint whose command handler must return a [`ReplyEffect`].
    pub fn with_enforced_replies<CH, EH, O>(
        persistence_id: PersistenceId,
        empty_state: S,
        command_handler: CH,
        event_handler: EH,
    ) -> Self
    where
        CH: Fn(&S, C) -> ReplyEffect<C, E, S> + Send + Sync + 'static,
        EH: Fn(&S, &E) -> O + Send + Sync + 'static,
        O: IntoEventHandlerResult<S>,
    {
        Self::from_handlers(
            persistence_id,
            empty_state,
            Arc::new(move |state, command| command_handler(state, command).into_effect()),
            Arc::new(move |state, event| event_handler(state, event).into_event_handler_result()),
        )
    }

    fn from_handlers(
        persistence_id: PersistenceId,
        empty_state: S,
        command_handler: Arc<CommandHandler<C, E, S>>,
        event_handler: Arc<EventHandler<E, S>>,
    ) -> Self {
        Self {
            persistence_id,
            empty_state,
            command_handler,
            event_handler,
            event_codec: None,
            state_codec: None,
            snapshot_when: Arc::new(|_, _, _| false),
            retention: RetentionCriteria::Disabled,
            tagger: Arc::new(|_, _| Vec::new()),
            persist_failure_backoff: None,
            recovery: Recovery::default(),
            publish_events: true,
            stash_capacity: 1_024,
            signal_handler: Arc::new(|_, _| {}),
            _journal: PhantomData,
        }
    }
}

impl<C, E, S, J> EventSourcedBehavior<C, E, S, J> {
    /// Selects an event adapter and serializer catalog, possibly changing `J`.
    #[must_use]
    pub fn with_event_adapter<J2, A>(
        self,
        adapter: A,
        catalog: SerializerCatalog<J2>,
    ) -> EventSourcedBehavior<C, E, S, J2>
    where
        A: EventAdapter<E, J2>,
        J2: 'static,
    {
        EventSourcedBehavior {
            persistence_id: self.persistence_id,
            empty_state: self.empty_state,
            command_handler: self.command_handler,
            event_handler: self.event_handler,
            event_codec: Some(EventCodec::new(adapter, catalog)),
            state_codec: self.state_codec,
            snapshot_when: self.snapshot_when,
            retention: self.retention,
            tagger: self.tagger,
            persist_failure_backoff: self.persist_failure_backoff,
            recovery: self.recovery,
            publish_events: self.publish_events,
            stash_capacity: self.stash_capacity,
            signal_handler: self.signal_handler,
            _journal: PhantomData,
        }
    }

    /// Selects the state adapter and serializer catalog used for snapshots.
    #[must_use]
    pub fn with_state_adapter<SJ, A>(mut self, adapter: A, catalog: SerializerCatalog<SJ>) -> Self
    where
        A: StateAdapter<S, SJ>,
        SJ: 'static,
        S: 'static,
    {
        self.state_codec = Some(Arc::new(runtime::AdaptedStateCodec::new(adapter, catalog)));
        self
    }

    /// Saves a snapshot after a batch when any post-event predicate invocation matches.
    #[must_use]
    pub fn snapshot_when<F>(mut self, predicate: F) -> Self
    where
        F: Fn(&S, &E, SequenceNr) -> bool + Send + Sync + 'static,
    {
        self.snapshot_when = Arc::new(predicate);
        self
    }

    /// Configures count-based snapshots and asynchronous cleanup.
    #[must_use]
    pub fn with_retention(mut self, retention: RetentionCriteria) -> Self {
        self.retention = retention;
        self
    }

    /// Tags stored events using the domain event.
    #[must_use]
    pub fn with_tagger<F>(mut self, tagger: F) -> Self
    where
        F: Fn(&E) -> Vec<Tag> + Send + Sync + 'static,
    {
        self.tagger = Arc::new(move |_, event| tagger(event));
        self
    }

    /// Tags stored events using post-event state and the domain event.
    #[must_use]
    pub fn with_state_tagger<F>(mut self, tagger: F) -> Self
    where
        F: Fn(&S, &E) -> Vec<Tag> + Send + Sync + 'static,
    {
        self.tagger = Arc::new(tagger);
        self
    }

    /// Restarts this persistent behavior with recovery after journal failures.
    ///
    /// Exponential delay, jitter, restart limits, and reset windows come from
    /// Datum's shared [`RestartSettings`]. The actor remains responsive during
    /// the delayed backoff and automatically stashes domain commands.
    #[must_use]
    pub fn on_persist_failure(mut self, settings: RestartSettings) -> Self {
        self.persist_failure_backoff = Some(settings);
        self
    }

    /// Changes recovery mode and snapshot selection.
    #[must_use]
    pub fn with_recovery(mut self, recovery: Recovery) -> Self {
        self.recovery = recovery;
        self
    }

    /// Enables or disables confirmed domain-event publishing (enabled by default).
    #[must_use]
    pub fn with_event_publishing(mut self, enabled: bool) -> Self {
        self.publish_events = enabled;
        self
    }

    /// Sets the manual stash capacity.
    ///
    /// Overflow follows Akka's default drop strategy: the newest command is
    /// dropped and chained effects registered on that stash decision do not
    /// run. If it owns a `ReplyPort`, dropping that command closes the port.
    #[must_use]
    pub fn with_stash_capacity(mut self, capacity: usize) -> Self {
        self.stash_capacity = capacity;
        self
    }

    /// Installs a persistence signal callback.
    #[must_use]
    pub fn on_signal<F>(mut self, handler: F) -> Self
    where
        F: Fn(&S, &EventSourcedSignal) + Send + Sync + 'static,
    {
        self.signal_handler = Arc::new(handler);
        self
    }
}

impl<C, E, S, J> EventSourcedBehavior<C, E, S, J>
where
    C: Message,
    E: Send + Sync + 'static,
    S: Clone + Send + Sync + 'static,
    J: Send + 'static,
{
    /// Spawns the Ractor runtime and begins recovery.
    pub async fn spawn(
        self,
        runtime: EventSourcedRuntime,
    ) -> PersistenceResult<EventSourcedHandle<C, E, S>> {
        runtime::spawn(self, runtime).await
    }

    /// Alias for [`Self::spawn`] emphasizing execution on the active Tokio runtime.
    pub async fn run_on(
        self,
        runtime: EventSourcedRuntime,
    ) -> PersistenceResult<EventSourcedHandle<C, E, S>> {
        self.spawn(runtime).await
    }
}

/// A point-in-time state and sequence-number observation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventSourcedState<S> {
    /// Current confirmed state.
    pub state: S,
    /// Current confirmed or recovered high watermark.
    pub sequence_nr: SequenceNr,
}

/// Spawned event-sourced behavior handle.
pub struct EventSourcedHandle<C: Message, E: Send + Sync + 'static, S: Send + 'static> {
    pub(crate) control: ActorRef<runtime::EventSourcedMessage<C, S>>,
    pub(crate) published_events: Option<Topic<PublishedEvent<E>>>,
}

impl<C, E, S> EventSourcedHandle<C, E, S>
where
    C: Message,
    E: Send + Sync + 'static,
    S: Clone + Send + 'static,
{
    /// Returns the behavior's single ordered ingress actor ref.
    ///
    /// `ActorFlow::ask` request builders should wrap domain commands with
    /// [`EventSourcedMessage::command`]. Commands and state queries share this
    /// mailbox, so same-sender enqueue order is FIFO.
    #[must_use]
    pub fn actor_ref(&self) -> &ActorRef<EventSourcedMessage<C, S>> {
        &self.control
    }

    /// Sends one command without waiting for persistence.
    pub fn tell(&self, command: C) -> PersistenceResult<()> {
        self.control
            .cast(runtime::EventSourcedMessage::command(command))
            .map_err(|error| {
                PersistenceError::Failure(format!("behavior command send failed: {error}"))
            })
    }

    /// Observes current confirmed state through the behavior's ordered mailbox.
    ///
    /// Earlier messages have been handled before the reply. During persistence
    /// backoff, this remains responsive and does not wait for domain commands
    /// that were handled by moving them into the automatic backoff stash.
    pub async fn state(&self) -> PersistenceResult<EventSourcedState<S>> {
        let (sender, receiver) = tokio::sync::oneshot::channel();
        self.control
            .cast(runtime::EventSourcedMessage::get_state(sender))
            .map_err(|error| {
                PersistenceError::Failure(format!("behavior state query failed: {error}"))
            })?;
        receiver.await.map_err(|_| {
            PersistenceError::Failure("behavior stopped before answering state query".into())
        })
    }

    /// Returns the typed confirmed-event topic when publishing is enabled.
    #[must_use]
    pub fn published_events(&self) -> Option<&Topic<PublishedEvent<E>>> {
        self.published_events.as_ref()
    }

    /// Requests behavior shutdown.
    ///
    /// Event publishing closes from the behavior's terminal path after any
    /// in-flight command has quiesced.
    pub fn stop(&self) {
        self.control.stop(None);
    }
}

impl<C, E, S> Clone for EventSourcedHandle<C, E, S>
where
    C: Message,
    E: Send + Sync + 'static,
    S: Send + 'static,
{
    fn clone(&self) -> Self {
        Self {
            control: self.control.clone(),
            published_events: self.published_events.clone(),
        }
    }
}

pub use runtime::EventSourcedMessage;