Skip to main content

plexus_client/
lift.rs

1//! RETURNS-46 · the aggregate up the tree: how a call made through a
2//! parent's client yields the parent's aggregate.
3//!
4//! An activation's aggregate (`{Ns}Event`) nests its children's: a static
5//! child is a variant carrying the child's aggregate, a dynamic child a
6//! variant carrying the instance's name and its aggregate. A generated client
7//! `XClient<T, L = Root>` carries a [`Lift`] `L` from its own aggregate into
8//! the aggregate of the client it was reached from:
9//!
10//! | client | `L` | its `.events()` yield |
11//! |---|---|---|
12//! | `TreeClient::new(t)` | [`Root`] | `TreeEvent` |
13//! | `tree.branch()` | `Static<Root, __TreeClientBranch>` | `TreeEvent::Branch(..)` |
14//! | `tree.item("a")` | `Named<Root, ItemEvent, TreeEvent>` | `TreeEvent::Item { name: "a", .. }` |
15//! | `tree.branch().leaf()` | `Static<Static<Root, ..>, __BranchClientLeaf>` | `TreeEvent::Branch(BranchEvent::Leaf(..))` |
16//!
17//! The lift is a type: [`Root`] is nothing at all (an event of a client
18//! reached through nothing is its own, at no cost); [`Static`] is the
19//! parent's lift and a zero-sized [`Wrap`] (the variant, inlined); [`Named`] adds the instance's name,
20//! an `Arc<str>` each event shares. No closure, no allocation but the
21//! variant's own box.
22//!
23//! [`Aggregated`] names a client's own aggregate — how a parent's expansion
24//! names a child's aggregate without guessing it from the child's type name
25//! (a child's aggregate is named by its namespace, its client by its stem).
26
27use std::fmt;
28use std::sync::Arc;
29
30/// The aggregate a generated client's calls are of: its activation's
31/// `{Ns}Event`. Implemented by every generated client, whatever its
32/// transport and whatever it lifts into; a parent's aggregate names a
33/// child's as `<InputsClient<()> as Aggregated>::Event`.
34pub trait Aggregated {
35    /// The activation's own aggregate.
36    type Event;
37}
38
39/// An activation that has a generated client (RETURNS-46). The activation
40/// macro implements it beside the server half of every activation it emits
41/// a client for; a parent's expansion holds each `#[child]` to it, so a child
42/// without a client is told what to do.
43#[diagnostic::on_unimplemented(
44    message = "`{Self}` has no client, so the parent's client cannot reach it as a `#[child]`",
45    label = "a `#[child]` of an activation with a client must have a client too",
46    note = "mark the child `#[plexus_macros::child(opaque)]`: no accessor, no variant in the parent's aggregate, routed as before — or give `{Self}` a client (name it `…Activation`, or add `client`)"
47)]
48pub trait HasClient {}
49
50/// A lift from an aggregate `E` into an enclosing one, [`Lift::Out`]: how
51/// many levels of variants to wrap an event in, and which instance names.
52pub trait Lift<E>: Clone + Send + Sync + 'static {
53    /// The aggregate an event ends in.
54    type Out;
55    /// Lift one event.
56    fn lift(&self, event: E) -> Self::Out;
57}
58
59/// No lift: an event is its own aggregate's. Zero-sized.
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
61pub struct Root;
62
63impl<E> Lift<E> for Root {
64    type Out = E;
65    #[inline(always)]
66    fn lift(&self, event: E) -> E {
67        event
68    }
69}
70
71/// How a static child's event `C` becomes its parent's: the parent's variant.
72/// The activation macro emits one zero-sized type per static child that
73/// implements it, so a static level's wrapping is a direct, inlined call, not
74/// a call through a pointer; a `fn(C) -> P` is one too, for a lift by hand.
75pub trait Wrap<C>: Clone + Send + Sync + 'static {
76    /// The parent's aggregate.
77    type Into;
78    /// `event` in the parent's variant.
79    fn wrap(&self, event: C) -> Self::Into;
80}
81
82impl<C: 'static, P: 'static> Wrap<C> for fn(C) -> P {
83    type Into = P;
84    #[inline]
85    fn wrap(&self, event: C) -> P {
86        self(event)
87    }
88}
89
90/// A static child's lift: wrap the child's event in the parent's variant
91/// (`W`), then lift as the parent does (`L`).
92pub struct Static<L, W> {
93    outer: L,
94    wrap: W,
95}
96
97impl<L, W> Static<L, W> {
98    /// `wrap`, then `outer`.
99    pub fn new(outer: L, wrap: W) -> Self {
100        Self { outer, wrap }
101    }
102}
103
104impl<C, L, W> Lift<C> for Static<L, W>
105where
106    W: Wrap<C>,
107    L: Lift<W::Into>,
108{
109    type Out = L::Out;
110    #[inline(always)]
111    fn lift(&self, event: C) -> L::Out {
112        self.outer.lift(self.wrap.wrap(event))
113    }
114}
115
116/// A dynamic child's lift: the instance's name and the child's event `C` in
117/// the parent's variant (`P`), then lifted as the parent does (`L`).
118pub struct Named<L, C, P> {
119    outer: L,
120    name: Arc<str>,
121    wrap: fn(Arc<str>, C) -> P,
122}
123
124impl<L, C, P> Named<L, C, P> {
125    /// The instance `name`: `wrap`, then `outer`.
126    pub fn new(outer: L, name: Arc<str>, wrap: fn(Arc<str>, C) -> P) -> Self {
127        Self { outer, name, wrap }
128    }
129
130    /// The instance's name.
131    pub fn name(&self) -> &Arc<str> {
132        &self.name
133    }
134}
135
136impl<L: Lift<P>, C: 'static, P: 'static> Lift<C> for Named<L, C, P> {
137    type Out = L::Out;
138    #[inline]
139    fn lift(&self, event: C) -> L::Out {
140        self.outer.lift((self.wrap)(Arc::clone(&self.name), event))
141    }
142}
143
144impl<L: Clone, W: Clone> Clone for Static<L, W> {
145    fn clone(&self) -> Self {
146        Self { outer: self.outer.clone(), wrap: self.wrap.clone() }
147    }
148}
149
150impl<L: Clone, C, P> Clone for Named<L, C, P> {
151    fn clone(&self) -> Self {
152        Self { outer: self.outer.clone(), name: Arc::clone(&self.name), wrap: self.wrap }
153    }
154}
155
156impl<L: fmt::Debug, W> fmt::Debug for Static<L, W> {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.debug_struct("Static").field("wrap", &std::any::type_name::<W>()).field("outer", &self.outer).finish()
159    }
160}
161
162impl<L: fmt::Debug, C, P> fmt::Debug for Named<L, C, P> {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.debug_struct("Named")
165            .field("name", &self.name)
166            .field("into", &std::any::type_name::<P>())
167            .field("outer", &self.outer)
168            .finish()
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[derive(Debug, PartialEq)]
177    enum Leaf {
178        Fall(u32),
179    }
180    #[derive(Debug, PartialEq)]
181    enum Branch {
182        Leaf(Box<Leaf>),
183    }
184    #[derive(Debug, PartialEq)]
185    enum Tree {
186        Branch(Box<Branch>),
187        Item { name: Arc<str>, event: Box<Leaf> },
188    }
189
190    #[test]
191    fn lifts_compose_one_level_at_a_time() {
192        let branch: Static<Root, fn(Branch) -> Tree> = Static::new(Root, |b| Tree::Branch(Box::new(b)));
193        let leaf: Static<_, fn(Leaf) -> Branch> = Static::new(branch, |l| Branch::Leaf(Box::new(l)));
194        assert_eq!(leaf.lift(Leaf::Fall(1)), Tree::Branch(Box::new(Branch::Leaf(Box::new(Leaf::Fall(1))))));
195        let item: Named<Root, Leaf, Tree> = Named::new(Root, Arc::from("a"), |name, l| Tree::Item { name, event: Box::new(l) });
196        assert_eq!(item.lift(Leaf::Fall(2)), Tree::Item { name: Arc::from("a"), event: Box::new(Leaf::Fall(2)) });
197    }
198
199    #[test]
200    fn the_root_lift_is_nothing() {
201        assert_eq!(std::mem::size_of::<Root>(), 0);
202        fn send_sync<T: Send + Sync + Clone>() {}
203        send_sync::<Static<Root, fn(Leaf) -> Tree>>();
204        send_sync::<Named<Root, Leaf, Tree>>();
205    }
206}