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/// let _ = <behavior::User<behavior::MailAddr, ()> as behavior::InjectEvent<u8, behavior::Here>>::inject_at(7);
165/// ```
166///
167/// Repeated payload types require an explicit ownership path rather than an
168/// outermost-first runtime guess:
169///
170/// ```compile_fail
171/// type Duplicate = behavior::EventLayer<u8, behavior::EventLayer<u8, behavior::User<behavior::MailAddr, ()>>>;
172/// let _ = <Duplicate as behavior::InjectEvent<u8, _>>::inject_at(7);
173/// ```
174pub trait InjectEvent<Input, Path>: Sized {
175    fn inject_at(input: Input) -> Self;
176}
177
178/// Exact recovery of one statically selected input from a returned event.
179///
180/// A failed runtime admission returns the complete root event. This ownership
181/// port recovers the original input without cloning, downcasting, or searching
182/// another lane. An event from a different lane is returned unchanged.
183/// Discarding the returned event cannot preserve an affine input:
184///
185/// ```compile_fail,E0382
186/// type Event = behavior::EventLayer<
187///     String,
188///     behavior::User<behavior::MailAddr, ()>,
189/// >;
190/// let input = String::from("worker");
191/// let event = <Event as behavior::InjectEvent<String, behavior::Here>>::inject_at(input);
192/// drop(event);
193/// drop(input);
194/// ```
195pub trait RecoverEvent<Input, Path>: Sized {
196    /// Recover `Input` when this event belongs to `Path`.
197    ///
198    /// # Errors
199    /// Returns the unchanged event when another lane owns it.
200    fn recover(event: Self) -> Result<Input, Self>;
201}
202
203impl<Owned, Inner> InjectEvent<Owned, Here> for EventLayer<Owned, Inner> {
204    fn inject_at(input: Owned) -> Self {
205        Self::Owned(input)
206    }
207}
208
209impl<Owned, Inner> RecoverEvent<Owned, Here> for EventLayer<Owned, Inner> {
210    fn recover(event: Self) -> Result<Owned, Self> {
211        match event {
212            Self::Owned(input) => Ok(input),
213            other @ Self::Inner(_) => Err(other),
214        }
215    }
216}
217
218impl<Owned, Inner, Input, Path> InjectEvent<Input, Inside<Path>> for EventLayer<Owned, Inner>
219where
220    Inner: InjectEvent<Input, Path>,
221{
222    fn inject_at(input: Input) -> Self {
223        Self::Inner(Inner::inject_at(input))
224    }
225}
226
227impl<Owned, Inner, Input, Path> RecoverEvent<Input, Inside<Path>> for EventLayer<Owned, Inner>
228where
229    Inner: RecoverEvent<Input, Path>,
230{
231    fn recover(event: Self) -> Result<Input, Self> {
232        match event {
233            Self::Inner(inner) => Inner::recover(inner).map_err(Self::Inner),
234            other @ Self::Owned(_) => Err(other),
235        }
236    }
237}
238
239/// The user-message event at the Agha floor.
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub struct User<A, M> {
242    pub from: A,
243    pub message: M,
244}
245
246impl<A, M> User<A, M> {
247    #[must_use]
248    pub const fn new(from: A, message: M) -> Self {
249        Self { from, message }
250    }
251}
252
253impl<A, M> From<(A, M)> for User<A, M> {
254    fn from((from, message): (A, M)) -> Self {
255        Self::new(from, message)
256    }
257}
258
259/// Construction/extraction of the user lane through a composed event type.
260pub trait UserEvent: Sized {
261    type Addr: Address;
262    type Message;
263
264    fn user(from: Self::Addr, message: Self::Message) -> Self;
265
266    /// # Errors
267    /// Returns the unchanged event when it belongs to another composed lane.
268    fn into_user(self) -> Result<User<Self::Addr, Self::Message>, Self>;
269}
270
271impl<A: Address, M> UserEvent for User<A, M> {
272    type Addr = A;
273    type Message = M;
274
275    fn user(from: A, message: M) -> Self {
276        Self::new(from, message)
277    }
278    fn into_user(self) -> Result<Self, Self> {
279        Ok(self)
280    }
281}
282
283impl<Owned, Inner> UserEvent for EventLayer<Owned, Inner>
284where
285    Inner: UserEvent,
286{
287    type Addr = Inner::Addr;
288    type Message = Inner::Message;
289
290    fn user(from: Self::Addr, message: Self::Message) -> Self {
291        Self::Inner(Inner::user(from, message))
292    }
293
294    fn into_user(self) -> Result<User<Self::Addr, Self::Message>, Self> {
295        match self {
296            Self::Inner(inner) => inner.into_user().map_err(Self::Inner),
297            owned @ Self::Owned(_) => Err(owned),
298        }
299    }
300}
301
302#[cfg(test)]
303mod structural_tests {
304    use super::*;
305    use crate::MailAddr;
306
307    type Nested = EventLayer<u8, EventLayer<u16, User<MailAddr, ()>>>;
308
309    #[test]
310    fn paths_select_exactly_one_layer_without_runtime_search() {
311        let outer = <Nested as InjectEvent<u8, Here>>::inject_at(3);
312        assert_eq!(outer, EventLayer::Owned(3));
313
314        let inner = <Nested as InjectEvent<u16, Inside<Here>>>::inject_at(5);
315        assert_eq!(inner, EventLayer::Inner(EventLayer::Owned(5)));
316    }
317
318    #[test]
319    fn duplicate_payload_types_remain_distinct_ownership_capabilities() {
320        type Duplicate = EventLayer<u8, EventLayer<u8, User<MailAddr, ()>>>;
321
322        let outer = <Duplicate as InjectEvent<u8, Here>>::inject_at(7);
323        let inner = <Duplicate as InjectEvent<u8, Inside<Here>>>::inject_at(7);
324
325        assert_eq!(outer, EventLayer::Owned(7));
326        assert_eq!(inner, EventLayer::Inner(EventLayer::Owned(7)));
327    }
328
329    #[test]
330    fn a_unique_structural_path_is_inferred_at_a_concrete_composition() {
331        let event = <Nested as InjectEvent<u16, _>>::inject_at(9);
332        assert_eq!(event, EventLayer::Inner(EventLayer::Owned(9)));
333    }
334
335    #[test]
336    fn ingress_identity_lifts_without_payload_or_runtime_route_search() {
337        type Inner = EventLayer<u16, User<MailAddr, ()>>;
338        type Outer = EventLayer<u8, Inner>;
339
340        let inner = Ingress::<u16, Here>::new();
341        let outer: Ingress<u16, Inside<Here>> = inner.inside();
342
343        let event: Outer = outer.event(12);
344        assert_eq!(event, EventLayer::Inner(EventLayer::Owned(12)));
345    }
346
347    #[test]
348    #[allow(
349        clippy::clone_on_copy,
350        reason = "the contract test independently exercises both promised construction traits"
351    )]
352    fn ingress_is_a_copyable_equal_capability_with_stable_debug_identity() {
353        let ingress = Ingress::<u16, Here>::new();
354        let copied = ingress;
355        let cloned = ingress.clone();
356
357        assert_eq!(ingress, copied);
358        assert_eq!(ingress, cloned);
359        assert_eq!(format!("{ingress:?}"), "Ingress");
360    }
361}