Skip to main content

behavior_actors/stash/
queue.rs

1//! The authoritative original-input FIFO and replay policy.
2
3use std::collections::VecDeque;
4
5use behavior::{Actions, Address, Behavior, BirthMode, SendEffects, User, UserEvent};
6use behavior::{Never, Step};
7
8use crate::inputs::HeldInputs;
9
10mod sealed {
11    pub trait StaticallyInfallible {}
12}
13
14/// Statically proven uninhabited transition error accepted by both stash policies.
15///
16/// The trait is sealed: replay safety depends on the error being genuinely
17/// impossible, so downstream code cannot assert the capability for an
18/// inhabited type.
19#[diagnostic::on_unimplemented(
20    message = "stash replay requires an infallible inner behavior",
21    label = "this error type is not supported for infallible replay",
22    note = "use Never or MachineError<A, M, Never> for the inner transition error; replay cannot undo actions from earlier messages"
23)]
24pub trait StaticallyInfallible: sealed::StaticallyInfallible {}
25
26impl sealed::StaticallyInfallible for Never {}
27impl StaticallyInfallible for Never {}
28
29impl<A, M> sealed::StaticallyInfallible for crate::MachineError<A, M, Never> {}
30impl<A, M> StaticallyInfallible for crate::MachineError<A, M, Never> {}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum StashRoute {
34    Stash,
35    Deliver,
36    Release,
37}
38
39/// Semantic observation of the outermost composed stash, independent of its
40/// structural nesting depth.
41pub trait StashStatus {
42    fn stashed_messages(&self) -> usize;
43}
44
45/// Deliberately unbounded FIFO holding for an infallible inner fold.
46///
47/// Prefer [`super::Stash`] when original-input retention must be finite. This
48/// explicit policy needs no refusal recipient, including for Never protocols
49/// and compositions whose selector never holds an input.
50///
51/// Releasing one command may replay several retained mailbox inputs in one
52/// transition. Because [`behavior::Actions`] has no rollback effect, a
53/// fallible inner fold could reject after earlier replayed inputs had already
54/// produced unreturnable actions. Such an inner behavior is therefore not a
55/// valid `UnlimitedStash` composition:
56///
57/// ```compile_fail,E0277
58/// struct Fallible;
59/// impl behavior::Protocol for Fallible { type Addr = behavior::MailAddr; type Msg = (); }
60/// impl behavior::Behavior for Fallible {
61///     type Protocol = Self;
62///     type Event = behavior::User<behavior::MailAddr, ()>;
63///     type Sends = Vec<behavior::Never>;
64///     type Ph = behavior::Never;
65///     type Error = u8;
66///     type Birth = behavior::NoBirths;
67///     fn transition(&mut self, _: behavior::ActiveTurn, _: Self::Event) -> behavior::BehaviorActed<Self> {
68///         Err(1)
69///     }
70/// }
71/// fn route(_: &()) -> behavior_actors::StashRoute { behavior_actors::StashRoute::Release }
72/// let _ = behavior_actors::UnlimitedStash::new(Fallible, |_, message| route(message));
73/// ```
74pub struct UnlimitedStash<B: Behavior> {
75    inner: B,
76    route: fn(&B, &behavior::BehaviorMessage<B>) -> StashRoute,
77    pub(super) held: VecDeque<User<behavior::BehaviorAddr<B>, behavior::BehaviorMessage<B>>>,
78}
79
80impl<B: Behavior> UnlimitedStash<B> {
81    /// Take all held messages in arrival order, leaving this stash empty.
82    ///
83    /// Original senders and messages move to the caller without cloning.
84    /// The inner behavior and routing policy stay unchanged. This operation
85    /// does not replay messages or produce actor effects.
86    ///
87    /// Messages still in a runtime mailbox belong to that mailbox, not this
88    /// stash. A second call returns an empty queue.
89    ///
90    /// With unwinding panics, a replay selector retains its borrowed original;
91    /// inner execution retains only originals not yet delegated to it. Neither
92    /// case rolls back inner mutations or recovers consumed inputs or Actions
93    /// that the panicking transition never returned. Aborts are not recoverable.
94    #[must_use]
95    pub fn take(
96        &mut self,
97    ) -> VecDeque<User<behavior::BehaviorAddr<B>, behavior::BehaviorMessage<B>>> {
98        core::mem::take(&mut self.held)
99    }
100}
101
102impl<B: Behavior<Ph = Never>> UnlimitedStash<B> {
103    /// Wrap `inner` with `route`, a pure decision over the actual inner state and message.
104    ///
105    /// Stashed messages retain FIFO order and ownership until a later
106    /// [`StashRoute::Release`]. Each replay borrows the state returned by the
107    /// preceding inner transition; the route must perform no effect.
108    /// Construction performs no transition or runtime
109    /// operation.
110    #[must_use]
111    pub fn new(inner: B, route: fn(&B, &behavior::BehaviorMessage<B>) -> StashRoute) -> Self
112    where
113        B::Error: StaticallyInfallible,
114    {
115        Self {
116            inner,
117            route,
118            held: VecDeque::new(),
119        }
120    }
121
122    #[must_use]
123    pub fn held(&self) -> usize {
124        self.held.len()
125    }
126
127    pub(super) fn route(&self, message: &behavior::BehaviorMessage<B>) -> StashRoute {
128        (self.route)(&self.inner, message)
129    }
130}
131
132impl<B: Behavior<Ph = Never>> StashStatus for UnlimitedStash<B> {
133    fn stashed_messages(&self) -> usize {
134        self.held()
135    }
136}
137
138impl<B> behavior::BehaviorBase for UnlimitedStash<B>
139where
140    B: Behavior<Ph = Never> + behavior::BehaviorBase,
141{
142    type Base = B::Base;
143
144    fn base(&self) -> &Self::Base {
145        self.inner.base()
146    }
147}
148
149impl<B, A, Sends, Br> UnlimitedStash<B>
150where
151    A: Address,
152    Sends: SendEffects + behavior::SendsFor<B::Event>,
153    Br: BirthMode,
154    B: Behavior<Ph = Never, Sends = Sends, Birth = Br>,
155    B::Error: StaticallyInfallible,
156    B::Protocol: behavior::Protocol<Addr = A>,
157{
158    pub(super) fn receive(
159        &mut self,
160        user: User<behavior::BehaviorAddr<B>, behavior::BehaviorMessage<B>>,
161        route: StashRoute,
162    ) -> Result<Actions<behavior::BehaviorAddr<B>, Never, B::Sends, B::Birth>, B::Error> {
163        match route {
164            StashRoute::Stash => {
165                self.held.push_back(user);
166                Ok(Actions::cont())
167            }
168            StashRoute::Deliver => behavior::delegate_transition(
169                &mut self.inner,
170                B::Event::user(user.from, user.message),
171            ),
172            StashRoute::Release => {
173                let mut actions = behavior::delegate_transition(
174                    &mut self.inner,
175                    B::Event::user(user.from, user.message),
176                )?;
177                if !matches!(actions.become_, Step::Stop(_)) {
178                    self.drain_into(&mut actions)?;
179                }
180                Ok(actions)
181            }
182        }
183    }
184
185    fn drain_into(
186        &mut self,
187        acc: &mut Actions<behavior::BehaviorAddr<B>, Never, B::Sends, B::Birth>,
188    ) -> Result<(), B::Error> {
189        let mut inputs = HeldInputs {
190            unread: core::mem::take(&mut self.held),
191            held: &mut self.held,
192        };
193        while let Some(user) = inputs.unread.front() {
194            let route = (self.route)(&self.inner, &user.message);
195            let Some(user) = inputs.unread.pop_front() else {
196                break;
197            };
198            match route {
199                StashRoute::Stash => inputs.held.push_back(user),
200                StashRoute::Deliver | StashRoute::Release => {
201                    let actions = behavior::delegate_transition(
202                        &mut self.inner,
203                        B::Event::user(user.from, user.message),
204                    )?;
205                    acc.sends.append(actions.sends);
206                    acc.creates.extend(actions.creates);
207                    if let Step::Stop(exit) = actions.become_ {
208                        acc.become_ = Step::Stop(exit);
209                        return Ok(());
210                    }
211                }
212            }
213        }
214        Ok(())
215    }
216}
217
218impl<B, A, Sends, Br> Behavior for UnlimitedStash<B>
219where
220    A: Address,
221    Sends: SendEffects + behavior::SendsFor<B::Event>,
222    Br: BirthMode,
223    B: Behavior<Ph = Never, Sends = Sends, Birth = Br>,
224    B::Error: StaticallyInfallible,
225    B::Protocol: behavior::Protocol<Addr = A>,
226{
227    type Protocol = B::Protocol;
228    type Event = B::Event;
229    type Sends = Sends;
230    type Ph = Never;
231    type Error = B::Error;
232    type Birth = Br;
233
234    fn init(
235        &mut self,
236        _: behavior::InitializationTurn,
237    ) -> Result<Actions<A, Never, Sends, Br>, Self::Error> {
238        behavior::initialize(&mut self.inner)
239    }
240
241    fn transition(
242        &mut self,
243        _: behavior::ActiveTurn,
244        event: B::Event,
245    ) -> Result<Actions<A, Never, Sends, Br>, Self::Error> {
246        let user = match event.into_user() {
247            Ok(user) => user,
248            Err(other) => return behavior::delegate_transition(&mut self.inner, other),
249        };
250        let route = self.route(&user.message);
251        self.receive(user, route)
252    }
253}