Skip to main content

datum_persistence/behavior/
effect.rs

1use std::{future::Future, pin::Pin};
2
3use datum::ReplyPort;
4
5use crate::SerializedPayload;
6
7pub(crate) type BoxEffectFuture<C, E, S> =
8    Pin<Box<dyn Future<Output = Effect<C, E, S>> + Send + 'static>>;
9
10pub(crate) struct EventWithMetadata<E> {
11    pub(crate) event: E,
12    pub(crate) metadata: Option<SerializedPayload>,
13}
14
15pub(crate) enum MainEffect<C, E, S> {
16    Persist(Vec<EventWithMetadata<E>>),
17    None,
18    Unhandled,
19    Stash(C),
20    Async(BoxEffectFuture<C, E, S>),
21}
22
23pub(crate) enum ChainedEffect<S> {
24    Run(Box<dyn FnOnce(&S) + Send + 'static>),
25    Stop,
26    UnstashAll,
27}
28
29/// A command decision for an [`EventSourcedBehavior`](super::EventSourcedBehavior).
30///
31/// One main effect is followed by zero or more side effects. Side effects retain
32/// registration order and run only after the main effect completes successfully.
33#[must_use]
34pub struct Effect<C, E, S> {
35    pub(crate) main: MainEffect<C, E, S>,
36    pub(crate) chained: Vec<ChainedEffect<S>>,
37}
38
39impl<C, E, S> Effect<C, E, S> {
40    /// Persists one event.
41    pub fn persist(event: E) -> Self {
42        Self::persist_with_metadata(event, None)
43    }
44
45    /// Persists one event with an optional already-serialized metadata frame.
46    pub fn persist_with_metadata(event: E, metadata: Option<SerializedPayload>) -> Self {
47        Self {
48            main: MainEffect::Persist(vec![EventWithMetadata { event, metadata }]),
49            chained: Vec::new(),
50        }
51    }
52
53    /// Persists all events as one all-or-nothing atomic journal write.
54    pub fn persist_all(events: impl IntoIterator<Item = E>) -> Self {
55        Self::persist_all_with_metadata(events.into_iter().map(|event| (event, None)))
56    }
57
58    /// Persists all events and metadata as one all-or-nothing atomic journal write.
59    pub fn persist_all_with_metadata(
60        events: impl IntoIterator<Item = (E, Option<SerializedPayload>)>,
61    ) -> Self {
62        Self {
63            main: MainEffect::Persist(
64                events
65                    .into_iter()
66                    .map(|(event, metadata)| EventWithMetadata { event, metadata })
67                    .collect(),
68            ),
69            chained: Vec::new(),
70        }
71    }
72
73    /// Handles the command without changing persistent state.
74    pub fn none() -> Self {
75        Self {
76            main: MainEffect::None,
77            chained: Vec::new(),
78        }
79    }
80
81    /// Marks the command unhandled without changing persistent state.
82    pub fn unhandled() -> Self {
83        Self {
84            main: MainEffect::Unhandled,
85            chained: Vec::new(),
86        }
87    }
88
89    /// Stops the behavior after processing the command.
90    pub fn stop() -> Self {
91        Self::none().then_stop()
92    }
93
94    /// Places an owned command in the bounded in-memory manual stash.
95    ///
96    /// Datum handlers consume commands so commands may own one-shot
97    /// [`ReplyPort`] values. Passing the command explicitly preserves that
98    /// ownership without imposing a `Clone` bound on the command type. If the
99    /// stash is full, the command is dropped and chained side effects are not
100    /// run because the main effect did not succeed.
101    pub fn stash(command: C) -> Self {
102        Self {
103            main: MainEffect::Stash(command),
104            chained: Vec::new(),
105        }
106    }
107
108    /// Starts draining the commands that were manually stashed at this point.
109    pub fn unstash_all() -> Self {
110        Self::none().then_unstash_all()
111    }
112
113    /// Replies immediately after a successful no-persist effect.
114    pub fn reply<R>(reply_to: ReplyPort<R>, reply: R) -> ReplyEffect<C, E, S>
115    where
116        R: Send + 'static,
117    {
118        Self::none().then_reply(reply_to, move |_| reply)
119    }
120
121    /// Explicitly chooses not to reply in an enforced-replies handler.
122    pub fn no_reply() -> ReplyEffect<C, E, S> {
123        Self::none().then_no_reply()
124    }
125
126    /// Defers the command decision to an asynchronous computation.
127    ///
128    /// This is the Rust-native spelling of Akka's `Effect.async`; Akka readers
129    /// can treat `async_effect` as its direct behavioral alias.
130    pub fn async_effect<F>(future: F) -> Self
131    where
132        F: Future<Output = Self> + Send + 'static,
133    {
134        Self {
135            main: MainEffect::Async(Box::pin(future)),
136            chained: Vec::new(),
137        }
138    }
139
140    /// Defers an enforced-replies decision to an asynchronous computation.
141    pub fn async_reply<F>(future: F) -> ReplyEffect<C, E, S>
142    where
143        C: Send + 'static,
144        E: Send + 'static,
145        S: Send + 'static,
146        F: Future<Output = ReplyEffect<C, E, S>> + Send + 'static,
147    {
148        ReplyEffect(Self::async_effect(
149            async move { future.await.into_effect() },
150        ))
151    }
152
153    /// Runs a callback with the resulting state.
154    pub fn then_run<F>(mut self, callback: F) -> Self
155    where
156        F: FnOnce(&S) + Send + 'static,
157    {
158        self.chained.push(ChainedEffect::Run(Box::new(callback)));
159        self
160    }
161
162    /// Stops the behavior after all earlier side effects have run.
163    pub fn then_stop(mut self) -> Self {
164        self.chained.push(ChainedEffect::Stop);
165        self
166    }
167
168    /// Starts a bounded drain of the current manual stash after earlier side effects.
169    pub fn then_unstash_all(mut self) -> Self {
170        self.chained.push(ChainedEffect::UnstashAll);
171        self
172    }
173
174    /// Sends a reply computed from the resulting state.
175    pub fn then_reply<R, F>(mut self, reply_to: ReplyPort<R>, reply: F) -> ReplyEffect<C, E, S>
176    where
177        R: Send + 'static,
178        F: FnOnce(&S) -> R + Send + 'static,
179    {
180        self.chained.push(ChainedEffect::Run(Box::new(move |state| {
181            let _ = reply_to.send(reply(state));
182        })));
183        ReplyEffect(self)
184    }
185
186    /// Explicitly records that this command will not reply.
187    pub fn then_no_reply(self) -> ReplyEffect<C, E, S> {
188        ReplyEffect(self)
189    }
190}
191
192/// An effect that statically records either a reply or an explicit no-reply decision.
193#[must_use]
194pub struct ReplyEffect<C, E, S>(Effect<C, E, S>);
195
196impl<C, E, S> ReplyEffect<C, E, S> {
197    /// Runs a callback with the resulting state while preserving reply enforcement.
198    pub fn then_run<F>(self, callback: F) -> Self
199    where
200        F: FnOnce(&S) + Send + 'static,
201    {
202        Self(self.0.then_run(callback))
203    }
204
205    /// Stops the behavior after all earlier side effects have run.
206    pub fn then_stop(self) -> Self {
207        Self(self.0.then_stop())
208    }
209
210    /// Starts a bounded drain of the current manual stash.
211    pub fn then_unstash_all(self) -> Self {
212        Self(self.0.then_unstash_all())
213    }
214
215    pub(crate) fn into_effect(self) -> Effect<C, E, S> {
216        self.0
217    }
218}