Skip to main content

datum_persistence/behavior/
mod.rs

1//! Event-sourced behavior blueprints, effects, recovery, and runtime handles.
2
3mod effect;
4mod runtime;
5
6use std::{marker::PhantomData, sync::Arc};
7
8use datum::{
9    RestartSettings, Topic,
10    actor::{ActorRef, Message},
11};
12
13use crate::{
14    EventAdapter, Journal, PersistenceError, PersistenceId, PersistenceResult, SequenceNr,
15    SerializerCatalog, SnapshotCriteria, SnapshotMetadata, SnapshotStore, StateAdapter, Tag,
16};
17
18pub use effect::{Effect, ReplyEffect};
19
20use runtime::{EventCodec, StateCodec};
21
22type CommandHandler<C, E, S> = dyn Fn(&S, C) -> Effect<C, E, S> + Send + Sync + 'static;
23type EventHandler<E, S> = dyn Fn(&S, &E) -> PersistenceResult<S> + Send + Sync + 'static;
24type SnapshotPredicate<E, S> = dyn Fn(&S, &E, SequenceNr) -> bool + Send + Sync + 'static;
25type Tagger<E, S> = dyn Fn(&S, &E) -> Vec<Tag> + Send + Sync + 'static;
26type SignalHandler<S> = dyn Fn(&S, &EventSourcedSignal) + Send + Sync + 'static;
27
28/// Converts an event-handler return value into a persistence result.
29///
30/// This permits the common `Fn(&S, &E) -> S` form while allowing validation
31/// handlers to return `PersistenceResult<S>` and reject a staged transition
32/// before journal I/O.
33pub trait IntoEventHandlerResult<S> {
34    /// Converts this handler output into the runtime result.
35    fn into_event_handler_result(self) -> PersistenceResult<S>;
36}
37
38impl<S> IntoEventHandlerResult<S> for S {
39    fn into_event_handler_result(self) -> PersistenceResult<S> {
40        Ok(self)
41    }
42}
43
44impl<S> IntoEventHandlerResult<S> for PersistenceResult<S> {
45    fn into_event_handler_result(self) -> PersistenceResult<S> {
46        self
47    }
48}
49
50/// Snapshot selection used during recovery.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum SnapshotSelection {
53    /// Load the latest available snapshot.
54    Latest,
55    /// Do not load a snapshot; replay all retained events.
56    None,
57    /// Load the latest snapshot matching explicit bounds.
58    Criteria(SnapshotCriteria),
59}
60
61impl SnapshotSelection {
62    pub(crate) fn criteria(self) -> SnapshotCriteria {
63        match self {
64            Self::Latest => SnapshotCriteria::latest(),
65            Self::None => SnapshotCriteria::none(),
66            Self::Criteria(criteria) => criteria,
67        }
68    }
69}
70
71/// Recovery mode for an event-sourced behavior.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Recovery {
74    /// Restore a selected snapshot and replay later events.
75    Enabled(SnapshotSelection),
76    /// Skip state restoration but read the journal high watermark.
77    Disabled,
78}
79
80impl Recovery {
81    /// Uses explicit snapshot selection followed by event replay.
82    #[must_use]
83    pub const fn with_snapshot_selection(selection: SnapshotSelection) -> Self {
84        Self::Enabled(selection)
85    }
86}
87
88impl Default for Recovery {
89    fn default() -> Self {
90        Self::Enabled(SnapshotSelection::Latest)
91    }
92}
93
94/// Count-based snapshot retention policy.
95#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
96pub enum RetentionCriteria {
97    /// No automatic count-based snapshots or cleanup.
98    #[default]
99    Disabled,
100    /// Snapshot every `every` sequence numbers and keep `keep` snapshot windows.
101    SnapshotEvery {
102        /// Number of events per snapshot window.
103        every: u64,
104        /// Number of snapshot windows to retain.
105        keep: u64,
106        /// Whether journal events older than the retained window are deleted.
107        delete_events: bool,
108    },
109}
110
111impl RetentionCriteria {
112    /// Creates count-based snapshot retention.
113    pub fn snapshot_every(every: u64, keep: u64) -> PersistenceResult<Self> {
114        if every == 0 {
115            return Err(PersistenceError::Rejected(
116                "snapshot frequency must be greater than zero".into(),
117            ));
118        }
119        if keep == 0 {
120            return Err(PersistenceError::Rejected(
121                "snapshot retention count must be greater than zero".into(),
122            ));
123        }
124        Ok(Self::SnapshotEvery {
125            every,
126            keep,
127            delete_events: false,
128        })
129    }
130
131    /// Deletes old events after a retention snapshot saves successfully.
132    #[must_use]
133    pub fn with_delete_events_on_snapshot(self) -> Self {
134        match self {
135            Self::Disabled => Self::Disabled,
136            Self::SnapshotEvery { every, keep, .. } => Self::SnapshotEvery {
137                every,
138                keep,
139                delete_events: true,
140            },
141        }
142    }
143}
144
145/// Persistence-specific lifecycle and maintenance signals.
146#[derive(Debug)]
147#[non_exhaustive]
148pub enum EventSourcedSignal {
149    /// A snapshot was decoded and installed during recovery.
150    SnapshotRecovered(SnapshotMetadata),
151    /// Recovery completed, including for a fresh persistence id.
152    RecoveryCompleted,
153    /// Snapshot load or journal replay failed.
154    RecoveryFailed(PersistenceError),
155    /// Journal storage failed or the commit result was uncertain.
156    PersistFailed {
157        /// First sequence number attempted by the failed write.
158        sequence_nr: SequenceNr,
159        /// Storage failure.
160        error: PersistenceError,
161    },
162    /// A deterministic write was rejected before storage.
163    PersistRejected {
164        /// First sequence number attempted by the rejected write.
165        sequence_nr: SequenceNr,
166        /// Rejection explanation.
167        reason: String,
168    },
169    /// Snapshot save completed.
170    SnapshotCompleted(SnapshotMetadata),
171    /// Snapshot save failed non-fatally.
172    SnapshotFailed {
173        /// Metadata of the attempted snapshot.
174        metadata: SnapshotMetadata,
175        /// Save or serialization failure.
176        error: PersistenceError,
177    },
178    /// Inclusive event deletion completed.
179    DeleteEventsCompleted(SequenceNr),
180    /// Inclusive event deletion failed.
181    DeleteEventsFailed {
182        /// Inclusive deletion target.
183        to: SequenceNr,
184        /// Storage failure.
185        error: PersistenceError,
186    },
187    /// Snapshot criteria deletion completed.
188    DeleteSnapshotsCompleted(SnapshotCriteria),
189    /// Snapshot criteria deletion failed.
190    DeleteSnapshotsFailed {
191        /// Attempted criteria.
192        criteria: SnapshotCriteria,
193        /// Storage failure.
194        error: PersistenceError,
195    },
196}
197
198/// A confirmed domain-typed event published by a running behavior.
199///
200/// This deliberately publishes `E`, rather than the erased journal payload:
201/// Datum's typed [`Topic`] makes the domain event the useful subscription type.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct PublishedEvent<E> {
204    /// Persistent entity identity.
205    pub persistence_id: PersistenceId,
206    /// Confirmed event sequence number.
207    pub sequence_nr: SequenceNr,
208    /// Domain event supplied to the event handler.
209    pub event: E,
210    /// Journal timestamp in Unix-epoch milliseconds.
211    pub timestamp_ms: i64,
212    /// Query tags stored with the event.
213    pub tags: Vec<Tag>,
214}
215
216/// Runtime resources supplied only when a behavior is spawned.
217pub struct EventSourcedRuntime {
218    pub(crate) journal: Arc<dyn Journal>,
219    pub(crate) snapshot_store: Option<Arc<dyn SnapshotStore>>,
220    pub(crate) writer_uuid: Option<String>,
221    pub(crate) topic_capacity: usize,
222}
223
224impl EventSourcedRuntime {
225    /// Creates runtime configuration using an event journal and no snapshot store.
226    #[must_use]
227    pub fn new(journal: Arc<dyn Journal>) -> Self {
228        Self {
229            journal,
230            snapshot_store: None,
231            writer_uuid: None,
232            topic_capacity: 256,
233        }
234    }
235
236    /// Adds a snapshot store used by recovery and snapshot saves.
237    #[must_use]
238    pub fn with_snapshot_store(mut self, snapshot_store: Arc<dyn SnapshotStore>) -> Self {
239        self.snapshot_store = Some(snapshot_store);
240        self
241    }
242
243    /// Overrides the stable identifier written by this spawned writer instance.
244    #[must_use]
245    pub fn with_writer_uuid(mut self, writer_uuid: impl Into<String>) -> Self {
246        self.writer_uuid = Some(writer_uuid.into());
247        self
248    }
249
250    /// Sets the per-subscriber published-event topic capacity.
251    #[must_use]
252    pub fn with_topic_capacity(mut self, capacity: usize) -> Self {
253        assert!(
254            capacity > 0,
255            "published-event topic capacity must be greater than zero"
256        );
257        self.topic_capacity = capacity;
258        self
259    }
260}
261
262/// Immutable, side-effect-free event-sourced behavior blueprint.
263pub struct EventSourcedBehavior<C, E, S, J = E> {
264    pub(crate) persistence_id: PersistenceId,
265    pub(crate) empty_state: S,
266    pub(crate) command_handler: Arc<CommandHandler<C, E, S>>,
267    pub(crate) event_handler: Arc<EventHandler<E, S>>,
268    pub(crate) event_codec: Option<EventCodec<E, J>>,
269    pub(crate) state_codec: Option<Arc<dyn StateCodec<S>>>,
270    pub(crate) snapshot_when: Arc<SnapshotPredicate<E, S>>,
271    pub(crate) retention: RetentionCriteria,
272    pub(crate) tagger: Arc<Tagger<E, S>>,
273    pub(crate) persist_failure_backoff: Option<RestartSettings>,
274    pub(crate) recovery: Recovery,
275    pub(crate) publish_events: bool,
276    pub(crate) stash_capacity: usize,
277    pub(crate) signal_handler: Arc<SignalHandler<S>>,
278    pub(crate) _journal: PhantomData<fn() -> J>,
279}
280
281impl<C, E, S> EventSourcedBehavior<C, E, S, E> {
282    /// Creates a side-effect-free behavior blueprint.
283    ///
284    /// A serializer/adapter is selected separately with
285    /// [`Self::with_event_adapter`]; no journal, snapshot, topic, actor, or task
286    /// is touched until [`Self::spawn`].
287    pub fn new<CH, EH, O>(
288        persistence_id: PersistenceId,
289        empty_state: S,
290        command_handler: CH,
291        event_handler: EH,
292    ) -> Self
293    where
294        CH: Fn(&S, C) -> Effect<C, E, S> + Send + Sync + 'static,
295        EH: Fn(&S, &E) -> O + Send + Sync + 'static,
296        O: IntoEventHandlerResult<S>,
297    {
298        Self::from_handlers(
299            persistence_id,
300            empty_state,
301            Arc::new(command_handler),
302            Arc::new(move |state, event| event_handler(state, event).into_event_handler_result()),
303        )
304    }
305
306    /// Creates a blueprint whose command handler must return a [`ReplyEffect`].
307    pub fn with_enforced_replies<CH, EH, O>(
308        persistence_id: PersistenceId,
309        empty_state: S,
310        command_handler: CH,
311        event_handler: EH,
312    ) -> Self
313    where
314        CH: Fn(&S, C) -> ReplyEffect<C, E, S> + Send + Sync + 'static,
315        EH: Fn(&S, &E) -> O + Send + Sync + 'static,
316        O: IntoEventHandlerResult<S>,
317    {
318        Self::from_handlers(
319            persistence_id,
320            empty_state,
321            Arc::new(move |state, command| command_handler(state, command).into_effect()),
322            Arc::new(move |state, event| event_handler(state, event).into_event_handler_result()),
323        )
324    }
325
326    fn from_handlers(
327        persistence_id: PersistenceId,
328        empty_state: S,
329        command_handler: Arc<CommandHandler<C, E, S>>,
330        event_handler: Arc<EventHandler<E, S>>,
331    ) -> Self {
332        Self {
333            persistence_id,
334            empty_state,
335            command_handler,
336            event_handler,
337            event_codec: None,
338            state_codec: None,
339            snapshot_when: Arc::new(|_, _, _| false),
340            retention: RetentionCriteria::Disabled,
341            tagger: Arc::new(|_, _| Vec::new()),
342            persist_failure_backoff: None,
343            recovery: Recovery::default(),
344            publish_events: true,
345            stash_capacity: 1_024,
346            signal_handler: Arc::new(|_, _| {}),
347            _journal: PhantomData,
348        }
349    }
350}
351
352impl<C, E, S, J> EventSourcedBehavior<C, E, S, J> {
353    /// Selects an event adapter and serializer catalog, possibly changing `J`.
354    #[must_use]
355    pub fn with_event_adapter<J2, A>(
356        self,
357        adapter: A,
358        catalog: SerializerCatalog<J2>,
359    ) -> EventSourcedBehavior<C, E, S, J2>
360    where
361        A: EventAdapter<E, J2>,
362        J2: 'static,
363    {
364        EventSourcedBehavior {
365            persistence_id: self.persistence_id,
366            empty_state: self.empty_state,
367            command_handler: self.command_handler,
368            event_handler: self.event_handler,
369            event_codec: Some(EventCodec::new(adapter, catalog)),
370            state_codec: self.state_codec,
371            snapshot_when: self.snapshot_when,
372            retention: self.retention,
373            tagger: self.tagger,
374            persist_failure_backoff: self.persist_failure_backoff,
375            recovery: self.recovery,
376            publish_events: self.publish_events,
377            stash_capacity: self.stash_capacity,
378            signal_handler: self.signal_handler,
379            _journal: PhantomData,
380        }
381    }
382
383    /// Selects the state adapter and serializer catalog used for snapshots.
384    #[must_use]
385    pub fn with_state_adapter<SJ, A>(mut self, adapter: A, catalog: SerializerCatalog<SJ>) -> Self
386    where
387        A: StateAdapter<S, SJ>,
388        SJ: 'static,
389        S: 'static,
390    {
391        self.state_codec = Some(Arc::new(runtime::AdaptedStateCodec::new(adapter, catalog)));
392        self
393    }
394
395    /// Saves a snapshot after a batch when any post-event predicate invocation matches.
396    #[must_use]
397    pub fn snapshot_when<F>(mut self, predicate: F) -> Self
398    where
399        F: Fn(&S, &E, SequenceNr) -> bool + Send + Sync + 'static,
400    {
401        self.snapshot_when = Arc::new(predicate);
402        self
403    }
404
405    /// Configures count-based snapshots and asynchronous cleanup.
406    #[must_use]
407    pub fn with_retention(mut self, retention: RetentionCriteria) -> Self {
408        self.retention = retention;
409        self
410    }
411
412    /// Tags stored events using the domain event.
413    #[must_use]
414    pub fn with_tagger<F>(mut self, tagger: F) -> Self
415    where
416        F: Fn(&E) -> Vec<Tag> + Send + Sync + 'static,
417    {
418        self.tagger = Arc::new(move |_, event| tagger(event));
419        self
420    }
421
422    /// Tags stored events using post-event state and the domain event.
423    #[must_use]
424    pub fn with_state_tagger<F>(mut self, tagger: F) -> Self
425    where
426        F: Fn(&S, &E) -> Vec<Tag> + Send + Sync + 'static,
427    {
428        self.tagger = Arc::new(tagger);
429        self
430    }
431
432    /// Restarts this persistent behavior with recovery after journal failures.
433    ///
434    /// Exponential delay, jitter, restart limits, and reset windows come from
435    /// Datum's shared [`RestartSettings`]. The actor remains responsive during
436    /// the delayed backoff and automatically stashes domain commands.
437    #[must_use]
438    pub fn on_persist_failure(mut self, settings: RestartSettings) -> Self {
439        self.persist_failure_backoff = Some(settings);
440        self
441    }
442
443    /// Changes recovery mode and snapshot selection.
444    #[must_use]
445    pub fn with_recovery(mut self, recovery: Recovery) -> Self {
446        self.recovery = recovery;
447        self
448    }
449
450    /// Enables or disables confirmed domain-event publishing (enabled by default).
451    #[must_use]
452    pub fn with_event_publishing(mut self, enabled: bool) -> Self {
453        self.publish_events = enabled;
454        self
455    }
456
457    /// Sets the manual stash capacity.
458    ///
459    /// Overflow follows Akka's default drop strategy: the newest command is
460    /// dropped and chained effects registered on that stash decision do not
461    /// run. If it owns a `ReplyPort`, dropping that command closes the port.
462    #[must_use]
463    pub fn with_stash_capacity(mut self, capacity: usize) -> Self {
464        self.stash_capacity = capacity;
465        self
466    }
467
468    /// Installs a persistence signal callback.
469    #[must_use]
470    pub fn on_signal<F>(mut self, handler: F) -> Self
471    where
472        F: Fn(&S, &EventSourcedSignal) + Send + Sync + 'static,
473    {
474        self.signal_handler = Arc::new(handler);
475        self
476    }
477}
478
479impl<C, E, S, J> EventSourcedBehavior<C, E, S, J>
480where
481    C: Message,
482    E: Send + Sync + 'static,
483    S: Clone + Send + Sync + 'static,
484    J: Send + 'static,
485{
486    /// Spawns the Ractor runtime and begins recovery.
487    pub async fn spawn(
488        self,
489        runtime: EventSourcedRuntime,
490    ) -> PersistenceResult<EventSourcedHandle<C, E, S>> {
491        runtime::spawn(self, runtime).await
492    }
493
494    /// Alias for [`Self::spawn`] emphasizing execution on the active Tokio runtime.
495    pub async fn run_on(
496        self,
497        runtime: EventSourcedRuntime,
498    ) -> PersistenceResult<EventSourcedHandle<C, E, S>> {
499        self.spawn(runtime).await
500    }
501}
502
503/// A point-in-time state and sequence-number observation.
504#[derive(Debug, Clone, PartialEq, Eq)]
505pub struct EventSourcedState<S> {
506    /// Current confirmed state.
507    pub state: S,
508    /// Current confirmed or recovered high watermark.
509    pub sequence_nr: SequenceNr,
510}
511
512/// Spawned event-sourced behavior handle.
513pub struct EventSourcedHandle<C: Message, E: Send + Sync + 'static, S: Send + 'static> {
514    pub(crate) control: ActorRef<runtime::EventSourcedMessage<C, S>>,
515    pub(crate) published_events: Option<Topic<PublishedEvent<E>>>,
516}
517
518impl<C, E, S> EventSourcedHandle<C, E, S>
519where
520    C: Message,
521    E: Send + Sync + 'static,
522    S: Clone + Send + 'static,
523{
524    /// Returns the behavior's single ordered ingress actor ref.
525    ///
526    /// `ActorFlow::ask` request builders should wrap domain commands with
527    /// [`EventSourcedMessage::command`]. Commands and state queries share this
528    /// mailbox, so same-sender enqueue order is FIFO.
529    #[must_use]
530    pub fn actor_ref(&self) -> &ActorRef<EventSourcedMessage<C, S>> {
531        &self.control
532    }
533
534    /// Sends one command without waiting for persistence.
535    pub fn tell(&self, command: C) -> PersistenceResult<()> {
536        self.control
537            .cast(runtime::EventSourcedMessage::command(command))
538            .map_err(|error| {
539                PersistenceError::Failure(format!("behavior command send failed: {error}"))
540            })
541    }
542
543    /// Observes current confirmed state through the behavior's ordered mailbox.
544    ///
545    /// Earlier messages have been handled before the reply. During persistence
546    /// backoff, this remains responsive and does not wait for domain commands
547    /// that were handled by moving them into the automatic backoff stash.
548    pub async fn state(&self) -> PersistenceResult<EventSourcedState<S>> {
549        let (sender, receiver) = tokio::sync::oneshot::channel();
550        self.control
551            .cast(runtime::EventSourcedMessage::get_state(sender))
552            .map_err(|error| {
553                PersistenceError::Failure(format!("behavior state query failed: {error}"))
554            })?;
555        receiver.await.map_err(|_| {
556            PersistenceError::Failure("behavior stopped before answering state query".into())
557        })
558    }
559
560    /// Returns the typed confirmed-event topic when publishing is enabled.
561    #[must_use]
562    pub fn published_events(&self) -> Option<&Topic<PublishedEvent<E>>> {
563        self.published_events.as_ref()
564    }
565
566    /// Requests behavior shutdown.
567    ///
568    /// Event publishing closes from the behavior's terminal path after any
569    /// in-flight command has quiesced.
570    pub fn stop(&self) {
571        self.control.stop(None);
572    }
573}
574
575impl<C, E, S> Clone for EventSourcedHandle<C, E, S>
576where
577    C: Message,
578    E: Send + Sync + 'static,
579    S: Send + 'static,
580{
581    fn clone(&self) -> Self {
582        Self {
583            control: self.control.clone(),
584            published_events: self.published_events.clone(),
585        }
586    }
587}
588
589pub use runtime::EventSourcedMessage;