1mod 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
28pub trait IntoEventHandlerResult<S> {
34 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum SnapshotSelection {
53 Latest,
55 None,
57 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Recovery {
74 Enabled(SnapshotSelection),
76 Disabled,
78}
79
80impl Recovery {
81 #[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
96pub enum RetentionCriteria {
97 #[default]
99 Disabled,
100 SnapshotEvery {
102 every: u64,
104 keep: u64,
106 delete_events: bool,
108 },
109}
110
111impl RetentionCriteria {
112 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 #[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#[derive(Debug)]
147#[non_exhaustive]
148pub enum EventSourcedSignal {
149 SnapshotRecovered(SnapshotMetadata),
151 RecoveryCompleted,
153 RecoveryFailed(PersistenceError),
155 PersistFailed {
157 sequence_nr: SequenceNr,
159 error: PersistenceError,
161 },
162 PersistRejected {
164 sequence_nr: SequenceNr,
166 reason: String,
168 },
169 SnapshotCompleted(SnapshotMetadata),
171 SnapshotFailed {
173 metadata: SnapshotMetadata,
175 error: PersistenceError,
177 },
178 DeleteEventsCompleted(SequenceNr),
180 DeleteEventsFailed {
182 to: SequenceNr,
184 error: PersistenceError,
186 },
187 DeleteSnapshotsCompleted(SnapshotCriteria),
189 DeleteSnapshotsFailed {
191 criteria: SnapshotCriteria,
193 error: PersistenceError,
195 },
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct PublishedEvent<E> {
204 pub persistence_id: PersistenceId,
206 pub sequence_nr: SequenceNr,
208 pub event: E,
210 pub timestamp_ms: i64,
212 pub tags: Vec<Tag>,
214}
215
216pub 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 #[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 #[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 #[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 #[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
262pub 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 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 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 #[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 #[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 #[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 #[must_use]
407 pub fn with_retention(mut self, retention: RetentionCriteria) -> Self {
408 self.retention = retention;
409 self
410 }
411
412 #[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 #[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 #[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 #[must_use]
445 pub fn with_recovery(mut self, recovery: Recovery) -> Self {
446 self.recovery = recovery;
447 self
448 }
449
450 #[must_use]
452 pub fn with_event_publishing(mut self, enabled: bool) -> Self {
453 self.publish_events = enabled;
454 self
455 }
456
457 #[must_use]
463 pub fn with_stash_capacity(mut self, capacity: usize) -> Self {
464 self.stash_capacity = capacity;
465 self
466 }
467
468 #[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 pub async fn spawn(
488 self,
489 runtime: EventSourcedRuntime,
490 ) -> PersistenceResult<EventSourcedHandle<C, E, S>> {
491 runtime::spawn(self, runtime).await
492 }
493
494 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#[derive(Debug, Clone, PartialEq, Eq)]
505pub struct EventSourcedState<S> {
506 pub state: S,
508 pub sequence_nr: SequenceNr,
510}
511
512pub 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 #[must_use]
530 pub fn actor_ref(&self) -> &ActorRef<EventSourcedMessage<C, S>> {
531 &self.control
532 }
533
534 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 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 #[must_use]
562 pub fn published_events(&self) -> Option<&Topic<PublishedEvent<E>>> {
563 self.published_events.as_ref()
564 }
565
566 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;