Skip to main content

behavior_actors/
machine.rs

1//! A finite-state behavior derived solely from receive and become.
2
3use std::collections::VecDeque;
4
5use behavior::{Actions, Address, Behavior, Creations, NoBirths, Protocol, SendsFor, User};
6use behavior::{Never, Step, Stopped};
7
8use crate::DeliveryRoute;
9use crate::inputs::HeldInputs;
10use crate::retention::{InputLimit, InputRetention};
11
12pub enum Move<P> {
13    Stay,
14    Goto(P),
15    Defer,
16    Stop,
17}
18
19/// Controlled machine rejection with the complete refused input.
20///
21/// A deferred-input refusal returns that original input and its sender, rather
22/// than the earlier mailbox communication that triggered replay. Earlier
23/// decisions and actual callback mutations remain in the machine.
24#[derive(Clone, PartialEq, Eq, thiserror::Error)]
25#[error("machine rejected its mailbox input: {cause}")]
26pub struct MachineError<A, M, E> {
27    /// Exact direct or deferred user event whose callback refused.
28    pub event: User<A, M>,
29    /// Domain error returned by the phase function.
30    #[source]
31    pub cause: E,
32}
33
34impl<A, M, E: core::fmt::Debug> core::fmt::Debug for MachineError<A, M, E> {
35    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        formatter
37            .debug_struct("MachineError")
38            .field("event", &"<retained>")
39            .field("cause", &self.cause)
40            .finish()
41    }
42}
43
44/// A phase machine with original-input deferral and ordered replay.
45///
46/// The callback borrows each message and mutates the actual state. Refusal
47/// returns the original input through [`MachineError`]; it does not roll back
48/// state mutations or earlier successful replay. State and messages need not
49/// implement Clone. [`Self::new`] retains without a bound; [`Self::bounded`]
50/// selects finite holding and complete refusal sends. An outer stash's limit
51/// does not bound this separate queue. The default unit policy performs actual
52/// unbounded holding; callers do not provide a marker or unused recipient.
53pub struct Machine<A: Address, S, M, P, E, R = ()> {
54    state: S,
55    phase: P,
56    on: fn(P, &mut S, &M) -> Result<Move<P>, E>,
57    held: VecDeque<User<A, M>>,
58    retention: R,
59}
60
61impl<A, S, M, P, E, R> Clone for Machine<A, S, M, P, E, R>
62where
63    A: Address,
64    S: Clone,
65    M: Clone,
66    P: Clone,
67    R: Clone,
68{
69    fn clone(&self) -> Self {
70        Self {
71            state: self.state.clone(),
72            phase: self.phase.clone(),
73            on: self.on,
74            held: self.held.clone(),
75            retention: self.retention.clone(),
76        }
77    }
78}
79
80impl<A, S, M, P, E, R> behavior::BehaviorBase for Machine<A, S, M, P, E, R>
81where
82    A: Address,
83{
84    type Base = Self;
85
86    fn base(&self) -> &Self {
87        self
88    }
89}
90
91impl<A: Address, S, M, P: Copy + PartialEq, E> Machine<A, S, M, P, E> {
92    /// Construct a phase machine without processing an input.
93    ///
94    /// A genuine phase change replays held inputs. Returning the current phase
95    /// does not replay them, but still stores the exact chosen phase value.
96    /// Stop ends the current drain. The callback must
97    /// perform no interpreter effects. Validate before mutation if a domain
98    /// refusal must leave a particular state value unchanged.
99    #[must_use]
100    pub fn new(state: S, phase: P, on: fn(P, &mut S, &M) -> Result<Move<P>, E>) -> Self {
101        Self {
102            state,
103            phase,
104            on,
105            held: VecDeque::new(),
106            retention: (),
107        }
108    }
109
110    /// Start finite holding with a real recipient for complete refused inputs.
111    ///
112    /// Only a newly Defer-selected input needs a slot. When full, its original
113    /// User is emitted and the actor continues; callback mutations remain.
114    /// Stay, Goto, Stop and callback errors need no slot. Replaying an admitted
115    /// input consumes no additional slot. Initialization emits no refusals.
116    ///
117    /// A recipient for a bare message cannot receive the original sender too:
118    ///
119    /// ```compile_fail,E0271
120    /// fn receive(_: (), _: &mut (), _: &u8) -> Result<behavior_actors::Move<()>, behavior::Never> {
121    ///     Ok(behavior_actors::Move::Defer)
122    /// }
123    /// let refused = behavior::Recipient::<behavior::MessageProtocol<behavior::MailAddr, u8>>::global(behavior::MailAddr(1));
124    /// let _ = behavior_actors::Machine::<behavior::MailAddr, _, _, _, _>::bounded((), (), receive, behavior_actors::InputLimit::new(1, refused));
125    /// ```
126    #[must_use]
127    pub fn bounded<R>(
128        state: S,
129        phase: P,
130        on: fn(P, &mut S, &M) -> Result<Move<P>, E>,
131        retention: InputLimit<R>,
132    ) -> Machine<A, S, M, P, E, InputLimit<R>>
133    where
134        R: DeliveryRoute + Clone,
135        R::Protocol: Protocol<Addr = A, Msg = User<A, M>>,
136        R::Sends: SendsFor<User<A, M>>,
137    {
138        Machine {
139            state,
140            phase,
141            on,
142            held: VecDeque::new(),
143            retention,
144        }
145    }
146}
147
148impl<A: Address, S, M, P: Copy + PartialEq, E, R> Machine<A, S, M, P, E, R> {
149    #[must_use]
150    pub fn state(&self) -> &S {
151        &self.state
152    }
153
154    #[must_use]
155    pub fn phase(&self) -> P {
156        self.phase
157    }
158
159    #[must_use]
160    pub fn held(&self) -> usize {
161        self.held.len()
162    }
163
164    /// Transfer the remaining original inputs without replay or cloning.
165    ///
166    /// Reheld inputs precede the unread suffix after Stop, refusal or unwinding
167    /// replay. Senders and payloads move together. State, phase and callback
168    /// remain unchanged; a second call returns an empty queue. An unwinding
169    /// callback retains the held input it only borrowed, but cannot restore
170    /// arbitrary state mutations or an incoming value consumed by unwinding.
171    #[must_use]
172    pub fn take(&mut self) -> VecDeque<User<A, M>> {
173        core::mem::take(&mut self.held)
174    }
175
176    fn drain(&mut self) -> Result<Step<Never, Stopped>, MachineError<A, M, E>> {
177        let mut inputs = HeldInputs {
178            unread: core::mem::take(&mut self.held),
179            held: &mut self.held,
180        };
181        while let Some(event) = inputs.unread.front() {
182            let decision = (self.on)(self.phase, &mut self.state, &event.message);
183            let Some(event) = inputs.unread.pop_front() else {
184                break;
185            };
186            match decision {
187                Err(cause) => return Err(MachineError { event, cause }),
188                Ok(Move::Stay) => {}
189                Ok(Move::Defer) => inputs.held.push_back(event),
190                Ok(Move::Stop) => return Ok(Step::Stop(Stopped)),
191                Ok(Move::Goto(next)) => {
192                    let previous = core::mem::replace(&mut self.phase, next);
193                    if next != previous {
194                        inputs.unread.append(inputs.held);
195                    }
196                }
197            }
198        }
199        Ok(Step::Continue)
200    }
201}
202
203impl<A: Address, S, M, P, E, R> behavior::Protocol for Machine<A, S, M, P, E, R> {
204    type Addr = A;
205    type Msg = M;
206}
207
208impl<A, S, M, P, E, R> Behavior for Machine<A, S, M, P, E, R>
209where
210    A: Address,
211    P: Copy + PartialEq,
212    R: InputRetention<A, M>,
213    R::Sends: SendsFor<User<A, M>>,
214{
215    type Protocol = Self;
216    type Event = User<A, M>;
217    type Sends = R::Sends;
218    type Ph = Never;
219    type Error = MachineError<A, M, E>;
220    type Birth = NoBirths;
221
222    fn init(
223        &mut self,
224        _: behavior::InitializationTurn,
225    ) -> Result<Actions<A, Never, Self::Sends, NoBirths>, Self::Error> {
226        Ok(Actions::cont())
227    }
228
229    fn transition(
230        &mut self,
231        _: behavior::ActiveTurn,
232        event: Self::Event,
233    ) -> Result<Actions<A, Never, Self::Sends, NoBirths>, Self::Error> {
234        match (self.on)(self.phase, &mut self.state, &event.message) {
235            Err(cause) => Err(MachineError { event, cause }),
236            Ok(Move::Stay) => Ok(Actions::cont()),
237            Ok(Move::Defer) => Ok(Actions::new(
238                self.retention.hold(&mut self.held, event),
239                Creations::empty(),
240                Step::Continue,
241            )),
242            Ok(Move::Stop) => Ok(Actions::stop()),
243            Ok(Move::Goto(next)) => {
244                let previous = core::mem::replace(&mut self.phase, next);
245                if next == previous {
246                    return Ok(Actions::cont());
247                }
248                self.drain().map(Actions::just)
249            }
250        }
251    }
252}