Skip to main content

behavior/
behavior.rs

1//! The pure actor algebra: receive one event, then send, create, and become.
2
3use core::future::Future;
4use core::marker::PhantomData;
5
6use communication::{Consumer, Received};
7
8use crate::Exit;
9use crate::deadlined::{TimeEvent, TimeReached};
10use crate::shutdown::{ShutdownEvent, ShutdownRequested};
11use crate::supervising::{ChildEvent, ChildStopped, WorkerEvent, WorkerStopped};
12use crate::verdict::{Never, Step};
13use crate::watching::{PeerEvent, PeerStopped};
14
15/// A pure actor-address namespace.
16pub trait Address: Copy + Eq {
17    type Nonce: Copy + Eq;
18
19    #[must_use]
20    fn birth(self, nonce: Self::Nonce) -> Self;
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub struct MailAddr(pub u64);
25
26impl Address for MailAddr {
27    type Nonce = u64;
28
29    fn birth(self, nonce: u64) -> Self {
30        Self(self.0 ^ nonce.wrapping_mul(0x9E37_79B9_7F4A_7C15))
31    }
32}
33
34/// An address expression for ordinary actor delivery.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Route<A: Address> {
37    Global(A),
38    Child(A::Nonce),
39}
40
41/// A recipient statically coupled to the message it accepts.
42pub struct Recipient<A: Address, M> {
43    route: Route<A>,
44    message: PhantomData<fn(M)>,
45}
46
47impl<A: Address, M> Copy for Recipient<A, M> {}
48
49impl<A: Address, M> Clone for Recipient<A, M> {
50    fn clone(&self) -> Self {
51        *self
52    }
53}
54
55impl<A: Address, M> Recipient<A, M> {
56    #[must_use]
57    pub fn global(address: A) -> Self {
58        Self::from_route(Route::Global(address))
59    }
60
61    #[must_use]
62    pub fn child(nonce: A::Nonce) -> Self {
63        Self::from_route(Route::Child(nonce))
64    }
65
66    #[must_use]
67    pub fn route(self) -> Route<A> {
68        self.route
69    }
70
71    const fn from_route(route: Route<A>) -> Self {
72        Self {
73            route,
74            message: PhantomData,
75        }
76    }
77}
78
79/// One statically typed send operation.
80#[derive(Clone, PartialEq, Eq)]
81pub struct Delivery<A: Address, M> {
82    pub to: Recipient<A, M>,
83    pub message: M,
84}
85
86impl<A: Address, M> Delivery<A, M> {
87    #[must_use]
88    pub fn new(to: Recipient<A, M>, message: M) -> Self {
89        Self { to, message }
90    }
91}
92
93impl<A: Address, M> PartialEq for Recipient<A, M> {
94    fn eq(&self, other: &Self) -> bool {
95        self.route == other.route
96    }
97}
98
99impl<A: Address, M> Eq for Recipient<A, M> {}
100
101impl<A: Address + core::fmt::Debug, M> core::fmt::Debug for Recipient<A, M>
102where
103    A::Nonce: core::fmt::Debug,
104{
105    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
106        self.route.fmt(f)
107    }
108}
109
110/// A product of independently typed send protocols.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct SendProduct<L, R> {
113    pub inner: L,
114    pub own: R,
115}
116
117/// The monoid required to accumulate sends across transitions.
118pub trait SendAlgebra: Sized {
119    fn empty() -> Self;
120    fn append(&mut self, other: Self);
121}
122
123impl<T> SendAlgebra for Vec<T> {
124    fn empty() -> Self {
125        Vec::new()
126    }
127
128    fn append(&mut self, mut other: Self) {
129        Vec::append(self, &mut other);
130    }
131}
132
133impl<L: SendAlgebra, R: SendAlgebra> SendAlgebra for SendProduct<L, R> {
134    fn empty() -> Self {
135        Self {
136            inner: L::empty(),
137            own: R::empty(),
138        }
139    }
140
141    fn append(&mut self, other: Self) {
142        self.inner.append(other.inner);
143        self.own.append(other.own);
144    }
145}
146
147/// Requests interpreted by the runtime local to the emitting actor.
148///
149/// Unlike [`Delivery`], a service request has no actor address. Its recipient
150/// is definitionally the interpreter of the actor whose transition emitted
151/// it. This distinct algebra lets interpreters route ordinary deliveries and
152/// local services with disjoint static implementations.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct ServiceSends<M> {
155    requests: Vec<M>,
156}
157
158impl<M> ServiceSends<M> {
159    #[must_use]
160    pub fn new(requests: Vec<M>) -> Self {
161        Self { requests }
162    }
163
164    #[must_use]
165    pub fn one(request: M) -> Self {
166        Self::new(vec![request])
167    }
168
169    #[must_use]
170    pub fn as_slice(&self) -> &[M] {
171        &self.requests
172    }
173
174    pub fn iter(&self) -> core::slice::Iter<'_, M> {
175        self.requests.iter()
176    }
177
178    #[must_use]
179    pub fn len(&self) -> usize {
180        self.requests.len()
181    }
182
183    #[must_use]
184    pub fn is_empty(&self) -> bool {
185        self.requests.is_empty()
186    }
187
188    pub fn extend(&mut self, requests: impl IntoIterator<Item = M>) {
189        self.requests.extend(requests);
190    }
191
192    #[must_use]
193    pub fn into_requests(self) -> Vec<M> {
194        self.requests
195    }
196}
197
198impl<M> core::ops::Index<usize> for ServiceSends<M> {
199    type Output = M;
200
201    fn index(&self, index: usize) -> &Self::Output {
202        &self.requests[index]
203    }
204}
205
206impl<M> IntoIterator for ServiceSends<M> {
207    type Item = M;
208    type IntoIter = std::vec::IntoIter<M>;
209
210    fn into_iter(self) -> Self::IntoIter {
211        self.requests.into_iter()
212    }
213}
214
215impl<M> SendAlgebra for ServiceSends<M> {
216    fn empty() -> Self {
217        Self::new(Vec::new())
218    }
219
220    fn append(&mut self, mut other: Self) {
221        self.requests.append(&mut other.requests);
222    }
223}
224
225/// Fresh actor creation. Replacement at an existing address is deliberately
226/// absent; stable restart is derived with a proxy actor.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct Create<A: Address, New> {
229    pub nonce: A::Nonce,
230    pub child: New,
231}
232
233/// A type-level description of the creation leg of the actor algebra.
234pub trait BirthMode {
235    type Child;
236}
237
238/// This behavior cannot emit child births.
239#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
240pub struct NoBirths;
241
242impl BirthMode for NoBirths {
243    type Child = Never;
244}
245
246/// This behavior may emit births of `C`.
247#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
248pub struct Births<C>(PhantomData<fn() -> C>);
249
250impl<C> BirthMode for Births<C> {
251    type Child = C;
252}
253
254pub type Become<A, Ph = Never> = Step<Ph, Exit<A>>;
255
256/// Exactly Agha's effect triple, with a Bombay interpretation-order policy.
257///
258/// An interpreter installs every fresh actor in `creates` before interpreting
259/// any ordinary delivery or [`ServiceSends`] request in `sends` from this
260/// value. This makes actors created by a transition available to that
261/// transition's deliveries and local observation requests. Creation order is
262/// vector order, and each concrete send lane retains its own order; this
263/// contract does not impose an order between independent lanes of a
264/// [`SendProduct`].
265///
266/// The ordering rule belongs to the interpreter boundary. Constructing an
267/// `Actions` value remains pure and performs none of its effects.
268pub struct Actions<A: Address, Ph, Sends, Birth: BirthMode> {
269    pub sends: Sends,
270    pub creates: Vec<Create<A, Birth::Child>>,
271    pub become_: Become<A, Ph>,
272}
273
274impl<A: Address, Ph, Sends: SendAlgebra, Birth: BirthMode> Actions<A, Ph, Sends, Birth> {
275    #[must_use]
276    pub fn just(become_: Become<A, Ph>) -> Self {
277        Self {
278            sends: Sends::empty(),
279            creates: Vec::new(),
280            become_,
281        }
282    }
283
284    #[must_use]
285    pub fn cont() -> Self {
286        Self::just(Step::Continue)
287    }
288
289    #[must_use]
290    pub fn stop(exit: Exit<A>) -> Self {
291        Self::just(Step::Stop(exit))
292    }
293
294    #[must_use]
295    pub fn goto(phase: Ph) -> Self {
296        Self::just(Step::Goto(phase))
297    }
298}
299
300pub type Acted<A, Ph, Sends, Birth, E> = Result<Actions<A, Ph, Sends, Birth>, E>;
301
302/// The user-message event at the Agha floor.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct User<A, M> {
305    pub from: A,
306    pub message: M,
307}
308
309/// Construction/extraction of the user lane through a composed event type.
310pub trait UserEvent: Sized {
311    type Addr: Address;
312    type Message;
313
314    fn user(from: Self::Addr, message: Self::Message) -> Self;
315    /// Extract the user lane.
316    ///
317    /// # Errors
318    /// Returns the unchanged event when it belongs to another composed lane.
319    fn into_user(self) -> Result<User<Self::Addr, Self::Message>, Self>;
320}
321
322pub type StateActed<A, Out, Birth, Err> = Acted<A, Never, Vec<Delivery<A, Out>>, Birth, Err>;
323
324pub trait State<Out = Never, Birth = NoBirths, Err = Never>
325where
326    Birth: BirthMode,
327{
328    type Addr: Address;
329    type Msg;
330
331    /// Fold a user message into the Agha triple.
332    ///
333    /// # Errors
334    /// Returns the state's declared controlled failure.
335    #[allow(
336        clippy::type_complexity,
337        reason = "the alias exposes all state protocol seats"
338    )]
339    fn handle(
340        &mut self,
341        from: Self::Addr,
342        message: Self::Msg,
343    ) -> StateActed<Self::Addr, Out, Birth, Err>;
344}
345
346/// A composed pure behavior. `Event` is the complete accepted protocol;
347/// successful transitions always return the same Agha effect algebra.
348pub trait Behavior {
349    type Addr: Address;
350    type Msg;
351    type Event: UserEvent<Addr = Self::Addr, Message = Self::Msg>;
352    type Sends: SendAlgebra;
353    type Ph;
354    type Error;
355    type Birth: BirthMode;
356    type Effect;
357    type Done;
358
359    fn init(&mut self) -> impl Future<Output = Result<Self::Effect, Self::Error>> + Send;
360
361    fn step(
362        &mut self,
363        event: Self::Event,
364    ) -> impl Future<Output = Result<Self::Effect, Self::Error>> + Send;
365}
366
367pub struct Base<S: State<O, Br, E>, O = Never, Br: BirthMode = NoBirths, E = Never> {
368    state: S,
369    marker: PhantomData<fn(O, Br, E)>,
370}
371
372impl<S: State<O, Br, E>, O, Br: BirthMode, E> Base<S, O, Br, E> {
373    #[must_use]
374    pub fn new(state: S) -> Self {
375        Self {
376            state,
377            marker: PhantomData,
378        }
379    }
380
381    #[must_use]
382    pub fn state(&self) -> &S {
383        &self.state
384    }
385}
386
387pub type Transition<S, A, M, O, Br, E> =
388    fn(&mut S, A, M) -> Acted<A, Never, Vec<Delivery<A, O>>, Br, E>;
389
390pub struct FnState<S, A: Address, M, O = Never, Br: BirthMode = NoBirths, E = Never> {
391    pub state: S,
392    pub handle: Transition<S, A, M, O, Br, E>,
393}
394
395impl<S, A: Address, M, O, Br: BirthMode, E> State<O, Br, E> for FnState<S, A, M, O, Br, E> {
396    type Addr = A;
397    type Msg = M;
398
399    fn handle(&mut self, from: A, message: M) -> Acted<A, Never, Vec<Delivery<A, O>>, Br, E> {
400        (self.handle)(&mut self.state, from, message)
401    }
402}
403
404impl<S, A: Address, M, O, Br: BirthMode, E> Base<FnState<S, A, M, O, Br, E>, O, Br, E> {
405    #[must_use]
406    pub fn from_fn(state: S, handle: Transition<S, A, M, O, Br, E>) -> Self {
407        Self::new(FnState { state, handle })
408    }
409}
410
411impl<A: Address, M> UserEvent for User<A, M> {
412    type Addr = A;
413    type Message = M;
414
415    fn user(from: A, message: M) -> Self {
416        Self { from, message }
417    }
418
419    fn into_user(self) -> Result<Self, Self> {
420        Ok(self)
421    }
422}
423
424impl<A: Address, M> TimeEvent for User<A, M> {
425    fn time_reached(_: TimeReached) -> Option<Self> {
426        None
427    }
428}
429
430impl<A: Address, M> PeerEvent<A> for User<A, M> {
431    fn peer_stopped(_: PeerStopped<A>) -> Option<Self> {
432        None
433    }
434}
435
436impl<A: Address, M> ChildEvent<A> for User<A, M> {
437    fn child_stopped(_: ChildStopped<A>) -> Option<Self> {
438        None
439    }
440}
441
442impl<A: Address, M> WorkerEvent<A> for User<A, M> {
443    fn worker_stopped(_: WorkerStopped<A>) -> Option<Self> {
444        None
445    }
446}
447
448impl<A: Address, M> ShutdownEvent for User<A, M> {
449    fn shutdown_requested(_: ShutdownRequested) -> Option<Self> {
450        None
451    }
452}
453
454impl<S, O, Br, E> Behavior for Base<S, O, Br, E>
455where
456    S: State<O, Br, E> + Send,
457    S::Addr: Send,
458    S::Msg: Send,
459    Br: BirthMode,
460    Br::Child: Send,
461    E: Send,
462{
463    type Addr = S::Addr;
464    type Msg = S::Msg;
465    type Event = User<S::Addr, S::Msg>;
466    type Sends = Vec<Delivery<S::Addr, O>>;
467    type Ph = Never;
468    type Error = E;
469    type Birth = Br;
470    type Effect = Actions<S::Addr, Never, Self::Sends, Br>;
471    type Done = Exit<S::Addr>;
472
473    async fn init(&mut self) -> Result<Self::Effect, E> {
474        Ok(Actions::cont())
475    }
476
477    async fn step(&mut self, event: Self::Event) -> Result<Self::Effect, E> {
478        self.state.handle(event.from, event.message)
479    }
480}
481
482pub struct Transcript<A: Address, Sends, New> {
483    pub sends: Sends,
484    pub creates: Vec<Create<A, New>>,
485    pub exit: Exit<A>,
486}
487
488/// Drive user-lane messages through a complete behavior protocol.
489///
490/// # Errors
491/// Returns the first controlled behavior failure.
492pub async fn run<B, C, A, Sends, Br>(
493    mut behavior: B,
494    mut mailbox: Consumer<C, B::Msg>,
495    from: A,
496) -> Result<Transcript<A, Sends, Br::Child>, B::Error>
497where
498    A: Address,
499    Sends: SendAlgebra,
500    Br: BirthMode,
501    B: Behavior<
502            Addr = A,
503            Ph = Never,
504            Sends = Sends,
505            Birth = Br,
506            Effect = Actions<A, Never, Sends, Br>,
507            Done = Exit<A>,
508        >,
509{
510    let mut sends = Sends::empty();
511    let mut creates = Vec::new();
512    let initial = behavior.init().await?;
513    sends.append(initial.sends);
514    creates.extend(initial.creates);
515    match initial.become_ {
516        Step::Continue => {}
517        Step::Goto(never) => match never {},
518        Step::Stop(exit) => {
519            return Ok(Transcript {
520                sends,
521                creates,
522                exit,
523            });
524        }
525    }
526    while let Some(received) = mailbox.recv().await {
527        let Received::User(message) = received else {
528            continue;
529        };
530        let actions = behavior.step(B::Event::user(from, message)).await?;
531        sends.append(actions.sends);
532        creates.extend(actions.creates);
533        match actions.become_ {
534            Step::Continue => {}
535            Step::Goto(never) => match never {},
536            Step::Stop(exit) => {
537                return Ok(Transcript {
538                    sends,
539                    creates,
540                    exit,
541                });
542            }
543        }
544    }
545    Ok(Transcript {
546        sends,
547        creates,
548        exit: Exit::Collected,
549    })
550}