Skip to main content

behavior/
user_event.rs

1//! The user-message lane and its composition contracts.
2
3use crate::actor::Address;
4
5/// The current layer of a structurally composed event algebra owns an input.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct Here;
8
9/// An inner event algebra owns an input at `Path`.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct Inside<Path>(core::marker::PhantomData<fn() -> Path>);
12
13/// Address-free destination for one interpreter-originated input.
14///
15/// Unlike an actor [`Recipient`](crate::Recipient), this capability targets one
16/// exact member of the current actor's composed ingress algebra. Service
17/// requests retain it so the eventual fact does not have to search the final
18/// behavior type for a matching payload. `Path` is compile-time evidence and
19/// occupies no runtime storage.
20pub struct Ingress<Input, Path> {
21    marker: core::marker::PhantomData<fn(Input, Path)>,
22}
23
24impl<Input, Path> Copy for Ingress<Input, Path> {}
25
26impl<Input, Path> Clone for Ingress<Input, Path> {
27    fn clone(&self) -> Self {
28        *self
29    }
30}
31
32impl<Input, Path> Ingress<Input, Path> {
33    /// Select a statically proven ingress member.
34    #[must_use]
35    pub const fn new() -> Self {
36        Self {
37            marker: core::marker::PhantomData,
38        }
39    }
40
41    /// Construct the exact concrete event without runtime route discovery.
42    #[must_use]
43    pub fn event<Event>(self, input: Input) -> Event
44    where
45        Event: InjectEvent<Input, Path>,
46    {
47        Event::inject_at(input)
48    }
49
50    /// Lift this destination through one outer structural event layer.
51    #[must_use]
52    pub const fn inside(self) -> Ingress<Input, Inside<Path>> {
53        Ingress {
54            marker: core::marker::PhantomData,
55        }
56    }
57}
58
59impl<Input, Path> Default for Ingress<Input, Path> {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl<Input, Path> core::fmt::Debug for Ingress<Input, Path> {
66    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
67        formatter.write_str("Ingress")
68    }
69}
70
71impl<Input, Path> PartialEq for Ingress<Input, Path> {
72    fn eq(&self, _: &Self) -> bool {
73        true
74    }
75}
76
77impl<Input, Path> Eq for Ingress<Input, Path> {}
78
79/// Owner-selected event ingress for one statically identified source.
80///
81/// `Source` distinguishes otherwise identical inputs without an absolute
82/// wrapper path. A child report uses its semantic [`ChildRole`](crate::ChildRole)
83/// as the source; a current-actor policy input uses [`Here`]. Outer
84/// [`EventLayer`] composition lifts the selected
85/// ingress automatically, so adding a [`BehaviorLayer`](crate::BehaviorLayer)
86/// never requires a caller to recount structural event depth.
87///
88/// This is a derived Bombay composition contract, not an actor-model
89/// primitive. It constructs a typed event only and performs no delivery,
90/// lookup, or interpreter effect.
91pub trait EventIngress<Source, Input>: Sized {
92    /// Construct the event selected for `Source` and `Input`.
93    fn ingress(input: Input) -> Self;
94}
95
96/// Construction of one private input sent by an established parent to its
97/// concrete direct child.
98///
99/// This is the event-side contract of [`ChildInput`](crate::ChildInput). It is
100/// deliberately distinct from [`EventIngress`], which selects a parent event
101/// for an incoming child report or a same-actor owner input. Keeping the two
102/// directions distinct lets a report-owning behavior transformation preserve
103/// every inner child-input capability without knowing its source or payload.
104///
105/// `Source` identifies the behavior law that owns `Input`; it is neither an
106/// actor address nor runtime lookup key. Constructing the event performs no
107/// delivery or other actor effect.
108pub trait ChildInputIngress<Source, Input>: Sized {
109    /// Construct the concrete child event selected by `Source` and `Input`.
110    fn child_input(input: Input) -> Self;
111}
112
113/// One statically owned input lane composed in front of an inner event algebra.
114///
115/// `EventLayer` is a concrete coproduct, not an erased envelope. `Owned` is the
116/// lane introduced by the current behavior template and `Inner` preserves the
117/// complete event algebra of the wrapped behavior.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub enum EventLayer<Owned, Inner> {
120    Owned(Owned),
121    Inner(Inner),
122}
123
124impl<Owned, Inner, Source, Input> EventIngress<Source, Input> for EventLayer<Owned, Inner>
125where
126    Inner: EventIngress<Source, Input>,
127{
128    fn ingress(input: Input) -> Self {
129        Self::Inner(Inner::ingress(input))
130    }
131}
132
133/// A complete event algebra formed by adding owned inputs around an inner
134/// behavior event algebra.
135///
136/// `from_inner` is the structure-preserving injection used by effect
137/// composition. A single owned lane uses [`EventLayer`]; a domain with several
138/// genuinely coexisting owned inputs may use a named exhaustive sum.
139pub trait ComposedEvent: UserEvent {
140    type Inner: UserEvent<Addr = Self::Addr, Message = Self::Message>;
141
142    fn from_inner(event: Self::Inner) -> Self;
143}
144
145impl<Owned, Inner> ComposedEvent for EventLayer<Owned, Inner>
146where
147    Inner: UserEvent,
148{
149    type Inner = Inner;
150
151    fn from_inner(event: Inner) -> Self {
152        Self::Inner(event)
153    }
154}
155
156/// Path-indexed injection into a structural event coproduct.
157///
158/// The path is compile-time routing evidence. It prevents the overlapping
159/// implementations that arise when an outer layer owns the same input type as
160/// an inner layer and makes that ownership choice explicit in the type system.
161/// Unsupported input has no construction capability:
162///
163/// ```compile_fail
164/// use behavior::{Here, InjectEvent, MailAddr, User};
165/// let _ = <User<MailAddr, ()> as InjectEvent<u8, Here>>::inject_at(7);
166/// ```
167///
168/// Repeated payload types require an explicit ownership path rather than an
169/// outermost-first runtime guess:
170///
171/// ```compile_fail
172/// use behavior::{EventLayer, InjectEvent, MailAddr, User};
173/// type Duplicate = EventLayer<u8, EventLayer<u8, User<MailAddr, ()>>>;
174/// let _ = <Duplicate as InjectEvent<u8, _>>::inject_at(7);
175/// ```
176pub trait InjectEvent<Input, Path>: Sized {
177    fn inject_at(input: Input) -> Self;
178}
179
180/// Exact recovery of one statically selected input from a returned event.
181///
182/// A failed runtime admission returns the complete root event. This ownership
183/// port recovers the original input without cloning, downcasting, or searching
184/// another lane. An event from a different lane is returned unchanged.
185/// Discarding the returned event cannot preserve an affine input:
186///
187/// ```compile_fail,E0382
188/// type Event = behavior::EventLayer<
189///     String,
190///     behavior::User<behavior::MailAddr, ()>,
191/// >;
192/// let input = String::from("worker");
193/// let event = <Event as behavior::InjectEvent<String, behavior::Here>>::inject_at(input);
194/// drop(event);
195/// drop(input);
196/// ```
197pub trait RecoverEvent<Input, Path>: Sized {
198    /// Recover `Input` when this event belongs to `Path`.
199    ///
200    /// # Errors
201    /// Returns the unchanged event when another lane owns it.
202    fn recover(event: Self) -> Result<Input, Self>;
203}
204
205impl<Owned, Inner> InjectEvent<Owned, Here> for EventLayer<Owned, Inner> {
206    fn inject_at(input: Owned) -> Self {
207        Self::Owned(input)
208    }
209}
210
211impl<Owned, Inner> RecoverEvent<Owned, Here> for EventLayer<Owned, Inner> {
212    fn recover(event: Self) -> Result<Owned, Self> {
213        match event {
214            Self::Owned(input) => Ok(input),
215            other @ Self::Inner(_) => Err(other),
216        }
217    }
218}
219
220impl<Owned, Inner, Input, Path> InjectEvent<Input, Inside<Path>> for EventLayer<Owned, Inner>
221where
222    Inner: InjectEvent<Input, Path>,
223{
224    fn inject_at(input: Input) -> Self {
225        Self::Inner(Inner::inject_at(input))
226    }
227}
228
229impl<Owned, Inner, Input, Path> RecoverEvent<Input, Inside<Path>> for EventLayer<Owned, Inner>
230where
231    Inner: RecoverEvent<Input, Path>,
232{
233    fn recover(event: Self) -> Result<Input, Self> {
234        match event {
235            Self::Inner(inner) => Inner::recover(inner).map_err(Self::Inner),
236            other @ Self::Owned(_) => Err(other),
237        }
238    }
239}
240
241/// The user-message event at the Agha floor.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct User<A, M> {
244    pub from: A,
245    pub message: M,
246}
247
248impl<A, M> User<A, M> {
249    #[must_use]
250    pub const fn new(from: A, message: M) -> Self {
251        Self { from, message }
252    }
253}
254
255impl<A, M> From<(A, M)> for User<A, M> {
256    fn from((from, message): (A, M)) -> Self {
257        Self::new(from, message)
258    }
259}
260
261/// Construction/extraction of the user lane through a composed event type.
262pub trait UserEvent: Sized {
263    type Addr: Address;
264    type Message;
265
266    fn user(from: Self::Addr, message: Self::Message) -> Self;
267
268    /// # Errors
269    /// Returns the unchanged event when it belongs to another composed lane.
270    fn into_user(self) -> Result<User<Self::Addr, Self::Message>, Self>;
271}
272
273impl<A: Address, M> UserEvent for User<A, M> {
274    type Addr = A;
275    type Message = M;
276
277    fn user(from: A, message: M) -> Self {
278        Self::new(from, message)
279    }
280    fn into_user(self) -> Result<Self, Self> {
281        Ok(self)
282    }
283}
284
285impl<Owned, Inner> UserEvent for EventLayer<Owned, Inner>
286where
287    Inner: UserEvent,
288{
289    type Addr = Inner::Addr;
290    type Message = Inner::Message;
291
292    fn user(from: Self::Addr, message: Self::Message) -> Self {
293        Self::Inner(Inner::user(from, message))
294    }
295
296    fn into_user(self) -> Result<User<Self::Addr, Self::Message>, Self> {
297        match self {
298            Self::Inner(inner) => inner.into_user().map_err(Self::Inner),
299            owned @ Self::Owned(_) => Err(owned),
300        }
301    }
302}
303
304#[cfg(test)]
305mod structural_tests {
306    use super::*;
307    use crate::MailAddr;
308
309    type Nested = EventLayer<u8, EventLayer<u16, User<MailAddr, ()>>>;
310
311    #[test]
312    fn paths_select_exactly_one_layer_without_runtime_search() {
313        let outer = <Nested as InjectEvent<u8, Here>>::inject_at(3);
314        assert_eq!(outer, EventLayer::Owned(3));
315
316        let inner = <Nested as InjectEvent<u16, Inside<Here>>>::inject_at(5);
317        assert_eq!(inner, EventLayer::Inner(EventLayer::Owned(5)));
318    }
319
320    #[test]
321    fn duplicate_payload_types_remain_distinct_ownership_capabilities() {
322        type Duplicate = EventLayer<u8, EventLayer<u8, User<MailAddr, ()>>>;
323
324        let outer = <Duplicate as InjectEvent<u8, Here>>::inject_at(7);
325        let inner = <Duplicate as InjectEvent<u8, Inside<Here>>>::inject_at(7);
326
327        assert_eq!(outer, EventLayer::Owned(7));
328        assert_eq!(inner, EventLayer::Inner(EventLayer::Owned(7)));
329    }
330
331    #[test]
332    fn a_unique_structural_path_is_inferred_at_a_concrete_composition() {
333        let event = <Nested as InjectEvent<u16, _>>::inject_at(9);
334        assert_eq!(event, EventLayer::Inner(EventLayer::Owned(9)));
335    }
336
337    #[test]
338    fn ingress_identity_lifts_without_payload_or_runtime_route_search() {
339        type Inner = EventLayer<u16, User<MailAddr, ()>>;
340        type Outer = EventLayer<u8, Inner>;
341
342        let inner = Ingress::<u16, Here>::new();
343        let outer: Ingress<u16, Inside<Here>> = inner.inside();
344
345        let event: Outer = outer.event(12);
346        assert_eq!(event, EventLayer::Inner(EventLayer::Owned(12)));
347    }
348
349    #[test]
350    #[allow(
351        clippy::clone_on_copy,
352        reason = "the contract test independently exercises both promised construction traits"
353    )]
354    fn ingress_is_a_copyable_equal_capability_with_stable_debug_identity() {
355        let ingress = Ingress::<u16, Here>::new();
356        let copied = ingress;
357        let cloned = ingress.clone();
358
359        assert_eq!(ingress, copied);
360        assert_eq!(ingress, cloned);
361        assert_eq!(format!("{ingress:?}"), "Ingress");
362    }
363}