Skip to main content

kernable/
messages.rs

1//! Events, commands and queries as types: defined once, typed, used by reference.
2//!
3//! The attributes [`event`](crate::event), [`command`](crate::command) and
4//! [`query`](crate::query) turn a braced struct into a message of a domain:
5//!
6//! ```
7//! use kernable::{NewEvent, domain, event, command};
8//!
9//! #[event("shop")]
10//! pub struct OrderPlaced { pub customer_id: String, pub note: Option<String> }
11//!
12//! #[command("shop", aggregate = "order")]
13//! pub struct PlaceOrder { pub customer_id: String }
14//!
15//! #[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
16//! struct Order { placed: bool }
17//!
18//! let shop_domain = domain("shop");
19//! let order_aggregate = shop_domain.aggregate("order", Order::default());
20//! order_aggregate.apply(OrderPlaced, |s, _d, _evt, _ctx| s.placed = true);
21//! order_aggregate.command(PlaceOrder, |_s, d, _cmd, _ctx| {
22//!     Ok(vec![OrderPlaced { customer_id: d.customer_id, note: None }.into()])
23//! });
24//! ```
25//!
26//! Fields are snake_case in Rust and camelCase in the log (`customer_id` is `customerId`), so a
27//! Rust, a Python and a TypeScript process write and read the same events. An event writes an
28//! `Option` field that is `None` as `null` (it is part of the record); a command or query leaves
29//! it out; a missing field reads as `None`. A field with its own `#[serde(...)]` attribute is left
30//! as it says (an event's optional field: `#[serde(default, skip_serializing_if =
31//! "Option::is_none")]`). The struct's name is its type (`type = "..."` overrides it), and
32//! also a constant of type [`Of`] that stands for the type where the SDK takes one: in
33//! `apply`, `command`, `requires`, a listener's `on` and `query`; with [`crate::Submit::command`]
34//! and [`crate::Query::of`] the value itself goes.
35
36use std::marker::PhantomData;
37
38use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
39
40use crate::Domain;
41
42/// A message of a domain: implemented by the attributes, not by hand.
43pub trait Message: Serialize + DeserializeOwned + Send + Sync + 'static {
44    /// The domain it belongs to.
45    const DOMAIN: &'static str;
46    /// Its type within the domain.
47    const TYPE: &'static str;
48    /// Declares its schema on `domain` (an event's version, upcasts and vault fields; a
49    /// command's vault fields; a query's target). The SDK calls it once per domain.
50    fn declare(domain: &Domain);
51}
52
53/// An event: `#[event("domain")]`.
54pub trait EventType: Message {}
55
56/// A command of an aggregate: `#[command("domain", aggregate = "name")]`.
57pub trait CommandType: Message {
58    /// The aggregate type that runs it.
59    const AGGREGATE: &'static str;
60}
61
62/// A query and its answer: `#[query("domain", answer = Row)]`. A query about one aggregate
63/// names it, and the field with its ID: `#[query("shop", answer = OrderRow, target(aggregate =
64/// "order", field = order_id))]`. The SDK sends that aggregate with the query, and a middleware
65/// decides on it as on a command's aggregate ([`crate::Check::target`]): "only the order's
66/// owner may read it". The aggregate type is of the query's domain, or qualified:
67/// `shop.order`.
68pub trait QueryType: Message {
69    /// What the read model answers.
70    type Answer: Serialize + DeserializeOwned;
71}
72
73/// Stands for the message type `M` where the SDK takes a type: the attributes declare one
74/// named like the struct, so `apply(TenantCreated, ...)` reads like the type itself.
75pub struct Of<M>(PhantomData<fn() -> M>);
76
77impl<M> Of<M> {
78    #[doc(hidden)]
79    pub const fn new() -> Self {
80        Of(PhantomData)
81    }
82}
83
84impl<M> Clone for Of<M> {
85    fn clone(&self) -> Self {
86        *self
87    }
88}
89
90impl<M> Copy for Of<M> {}
91
92/// What a type parameter of `apply`, `command`, `requires`, `on` and `query` resolves to.
93#[doc(hidden)]
94pub struct Key {
95    /// The type's own domain, for a message type; a string says nothing.
96    pub(crate) domain: Option<&'static str>,
97    pub(crate) name: String,
98    pub(crate) declare: Option<fn(&Domain)>,
99}
100
101/// A type as `apply`, `command`, `requires`, `on` and `query` take it: a name (`"ItemAdded"`,
102/// `"orders.OrderPlaced"`) with the data as any `D`, or a message type's constant
103/// (`OrderPlaced`), whose data is then that type.
104pub trait TypeKey<D> {
105    #[doc(hidden)]
106    fn key(self) -> Key;
107}
108
109impl<D> TypeKey<D> for &str {
110    fn key(self) -> Key {
111        Key {
112            domain: None,
113            name: self.to_owned(),
114            declare: None,
115        }
116    }
117}
118
119impl<M: Message> TypeKey<M> for Of<M> {
120    fn key(self) -> Key {
121        Key {
122            domain: Some(M::DOMAIN),
123            name: M::TYPE.to_owned(),
124            declare: Some(M::declare),
125        }
126    }
127}
128
129impl Key {
130    /// The type within `domain`, declared there; a message type of another domain is an error.
131    pub(crate) fn within(self, domain: &Domain, what: &str) -> String {
132        if let Some(own) = self.domain {
133            assert!(
134                own == domain.name(),
135                "{own}.{} belongs to {own}; {what} of {} takes the types of its own domain",
136                self.name,
137                domain.name()
138            );
139            if let Some(declare) = self.declare {
140                domain.declare_once(&self.name, declare);
141            }
142        }
143        self.name
144    }
145
146    /// The type as a listener names it: qualified for another domain's message type.
147    pub(crate) fn qualified_for(&self, domain: &Domain) -> String {
148        match self.domain {
149            Some(own) if own != domain.name() => format!("{own}.{}", self.name),
150            _ => self.name.clone(),
151        }
152    }
153}
154
155/// The schema of a message type of `M::DOMAIN`, declared on a domain object of that name.
156pub(crate) fn domain_of<M: Message>() -> Domain {
157    let d = crate::domain(M::DOMAIN);
158    d.declare_once(M::TYPE, M::declare);
159    d
160}
161
162#[doc(hidden)]
163pub mod __private {
164    pub use serde;
165    pub use serde_json;
166
167    use super::{Deserialize, Deserializer};
168
169    /// A vault field: `null` once erased, read as the field's default.
170    pub fn null_as_default<'de, D: Deserializer<'de>, T: Deserialize<'de> + Default>(
171        d: D,
172    ) -> Result<T, D::Error> {
173        Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use serde::{Deserialize, Serialize};
180    use serde_json::{Value, json};
181
182    use crate::{
183        CommandContext, FoldEvent, NewEvent, Query, RequestContext, Submit, Timestamp, command,
184        domain, event, query,
185    };
186
187    fn own(_d: &Value, id: &str) -> String {
188        format!("account:{id}")
189    }
190
191    #[event("shopt", version = 2, upcasts = add_note, personal(fields = [email_address], subject = own))]
192    #[derive(Clone, Debug, PartialEq)]
193    pub struct Placed {
194        pub customer_id: String,
195        pub email_address: String,
196        pub note: Option<String>,
197        pub r#type: String,
198    }
199
200    fn add_note(schema: crate::EventSchema) -> crate::EventSchema {
201        schema.upcast(1, |mut d| {
202            d["type"] = json!("v1");
203            d
204        })
205    }
206
207    #[event("shopt")]
208    pub struct Cancelled {}
209
210    #[command("shopt", aggregate = "order", secret = [password])]
211    pub struct Place {
212        pub customer_id: String,
213        pub password: String,
214    }
215
216    #[query("shopt", answer = Vec<String>)]
217    pub struct ListOrders {
218        pub status: Option<String>,
219    }
220
221    #[query("shopt", answer = Vec<String>, target(aggregate = "order", field = order_id))]
222    pub struct GetOrder {
223        pub order_id: String,
224    }
225
226    #[derive(Clone, Default, Serialize, Deserialize)]
227    struct Order {
228        customer: String,
229        cancelled: bool,
230    }
231
232    #[test]
233    fn fields_are_camel_case_and_an_event_writes_none_as_null() {
234        let p = Placed {
235            customer_id: "c1".into(),
236            email_address: "a@b".into(),
237            note: None,
238            r#type: "x".into(),
239        };
240        assert_eq!(
241            serde_json::to_value(&p).unwrap(),
242            json!({ "customerId": "c1", "emailAddress": "a@b", "note": null, "type": "x" })
243        );
244        // A query (or command) leaves an unset option out.
245        assert_eq!(
246            serde_json::to_value(ListOrders { status: None }).unwrap(),
247            json!({})
248        );
249        // An erased vault value is null: read as the field's default.
250        let back: Placed = serde_json::from_value(
251            json!({ "customerId": "c1", "emailAddress": null, "type": "x" }),
252        )
253        .unwrap();
254        assert_eq!(back.email_address, "");
255        assert_eq!(back.note, None);
256    }
257
258    #[test]
259    fn apply_and_command_take_the_type_and_declare_its_schema() {
260        let shop = domain("shopt");
261        let order = shop.aggregate("order", Order::default());
262        order.apply(Placed, |s, d, _, _| s.customer = d.customer_id);
263        order.apply(Cancelled, |s, _d, _, _| s.cancelled = true);
264        order.command(Place, |_s, d, _, _| {
265            Ok(vec![
266                Placed {
267                    customer_id: d.customer_id,
268                    email_address: "a@b".into(),
269                    note: None,
270                    r#type: "t".into(),
271                }
272                .into(),
273            ])
274        });
275        // The event's version and upcast, from its declaration.
276        assert_eq!(shop.schema_of("Placed"), 2);
277        let v1 = FoldEvent {
278            schema: 1,
279            ..FoldEvent::new(
280                "Placed",
281                json!({ "customerId": "c1", "emailAddress": "a@b" }),
282            )
283        };
284        let state = order.fold([v1], None).unwrap();
285        assert_eq!(state.customer, "c1");
286        let mut ctx = CommandContext::new("cmd-1", RequestContext::default(), Timestamp(0));
287        let events = order
288            .handle(
289                &state,
290                "Place",
291                json!({ "customerId": "c2", "password": "p" }),
292                &mut ctx,
293            )
294            .unwrap();
295        assert_eq!(
296            events,
297            vec![NewEvent::new(
298                "Placed",
299                json!({ "customerId": "c2", "emailAddress": "a@b", "note": null, "type": "t" })
300            )]
301        );
302        // The command's vault fields and the event's personal ones, declared on the domain.
303        assert_eq!(
304            shop.command_vault("Place").unwrap().secret,
305            vec!["password"]
306        );
307        assert_eq!(
308            shop.event_def("Placed").unwrap().vault.personal[0].0,
309            vec!["emailAddress"]
310        );
311    }
312
313    #[test]
314    #[should_panic(expected = "belongs to shopt")]
315    fn another_domain_s_message_type_is_refused() {
316        domain("other")
317            .aggregate("order", Order::default())
318            .apply(Placed, |_, _, _, _| {});
319    }
320
321    #[test]
322    fn a_listener_learns_another_domain_s_event_schema() {
323        let billing = domain("billingt");
324        let listener = billing
325            .read_model("orders")
326            .on(Placed, |d, _evt, _ctx| async move {
327                assert!(!d.customer_id.is_empty());
328                Ok(())
329            });
330        assert_eq!(
331            listener.domain_of("shopt").map(|d| d.schema_of("Placed")),
332            Some(2)
333        );
334        listener.query(ListOrders, |_d, _q, _ctx| async move {
335            Ok(vec!["o1".to_owned()])
336        });
337    }
338
339    #[test]
340    fn submit_and_query_carry_the_type() {
341        let s = Submit::command(
342            Place {
343                customer_id: "c".into(),
344                password: "p".into(),
345            },
346            "o1",
347        );
348        let shown = format!("{s:?}");
349        assert!(
350            shown.contains("domain: \"shopt\"")
351                && shown.contains("aggregate_type: \"order\"")
352                && shown.contains("command_type: \"Place\""),
353            "{shown}"
354        );
355        assert!(shown.contains("secret: [\"password\"]"), "{shown}");
356        let q = format!("{:?}", Query::of(ListOrders { status: None }));
357        assert!(
358            q.contains("query_type: \"ListOrders\"") && q.contains("data: Object {}"),
359            "{q}"
360        );
361        assert!(q.contains("target: None"), "{q}");
362    }
363
364    #[test]
365    fn a_query_declares_its_target_and_sends_it_qualified_with_the_id_from_its_data() {
366        let target = crate::messages::domain_of::<GetOrder>()
367            .query_target("GetOrder")
368            .unwrap();
369        assert_eq!(
370            target,
371            crate::QueryTarget {
372                aggregate_type: "order".into(),
373                field: "orderId".into(),
374            }
375        );
376        let q = format!(
377            "{:?}",
378            Query::of(GetOrder {
379                order_id: "o1".into()
380            })
381        );
382        assert!(q.contains("field: \"orderId\""), "{q}");
383        let wire = target.wire("shopt", &json!({ "orderId": "o1" })).unwrap();
384        assert_eq!(
385            (wire.aggregate_type.as_str(), wire.aggregate_id.as_str()),
386            ("shopt.order", "o1")
387        );
388        // No ID, an empty one or one that is no string: no target.
389        for data in [json!({}), json!({ "orderId": "" }), json!({ "orderId": 7 })] {
390            assert!(target.wire("shopt", &data).is_none());
391        }
392        // Qualified, by name.
393        let shop = domain("shopt2");
394        shop.query("GetCustomer")
395            .target("crm.customer", "customerId");
396        let wire = shop
397            .query_target("GetCustomer")
398            .unwrap()
399            .wire("shopt2", &json!({ "customerId": "c1" }))
400            .unwrap();
401        assert_eq!(wire.aggregate_type, "crm.customer");
402        assert_eq!(shop.query_target("Other"), None);
403    }
404
405    #[test]
406    fn a_read_model_answering_a_query_type_declares_its_target_on_its_domain() {
407        // So a client that knows the domain (`with_domain`) sends it when it asks by name.
408        let shop = domain("shopt");
409        shop.read_model("orders")
410            .query(GetOrder, |_d, _q, _ctx| async move { Ok(()) });
411        assert_eq!(
412            shop.query_target("GetOrder").map(|t| t.field),
413            Some("orderId".to_owned())
414        );
415        // A declaration by name stays.
416        let other = domain("shopt");
417        other.query("GetOrder").target("customer", "customerId");
418        other
419            .read_model("orders")
420            .query(GetOrder, |_d, _q, _ctx| async move { Ok(()) });
421        assert_eq!(
422            other.query_target("GetOrder").map(|t| t.aggregate_type),
423            Some("customer".to_owned())
424        );
425    }
426}