Skip to main content

kernable/
domain.rs

1//! Domains, their event and command schemas, and aggregates.
2
3use std::{
4    collections::{HashMap, HashSet},
5    panic::{AssertUnwindSafe, catch_unwind},
6    sync::{Arc, Mutex, RwLock},
7};
8
9use kernable_core::{proto, signing};
10use serde::{Serialize, de::DeserializeOwned};
11use serde_json::{Map, Value};
12
13use crate::{
14    BoxError, Error, Listener, Rejected, RequestContext,
15    context::Timestamp,
16    index::{Index, KeySubject, Requirement, Unique, UniqueKey, reindex_type},
17    messages::{EventType, TypeKey},
18    vault::{self, VaultFields},
19};
20
21type Upcast = Arc<dyn Fn(Value) -> Value + Send + Sync>;
22/// Whose personal data a payload holds: from the payload and the aggregate's ID.
23pub(crate) type Subject = Arc<dyn Fn(&Value, &str) -> String + Send + Sync>;
24
25#[derive(Clone, Default)]
26pub(crate) struct EventDef {
27    pub schema: u32,
28    pub steps: HashMap<u32, Upcast>,
29    pub vault: VaultFields,
30    pub eraser: Option<Subject>,
31}
32
33struct DomainInner {
34    name: String,
35    events: RwLock<HashMap<String, EventDef>>,
36    commands: RwLock<HashMap<String, VaultFields>>,
37    /// What query types given by name are about: [`Domain::query`].
38    queries: RwLock<HashMap<String, Option<QueryTarget>>>,
39    /// The aggregates created through it, in order, whatever their state type.
40    aggregates: RwLock<Vec<Arc<dyn Runnable>>>,
41    /// The read models and reactors created through it, in order.
42    listeners: RwLock<Vec<Listener>>,
43    /// The business processes defined on it, in order.
44    processes: RwLock<Vec<crate::process::Process>>,
45    /// The message types whose schemas are declared from their type (see [`crate::Message`]).
46    declared: RwLock<HashSet<String>>,
47}
48
49/// A domain: a name that scopes its aggregates, commands and events, lowercase by convention
50/// (`orders`) like aggregates, while message types are capitalized (`orders.PlaceOrder`). Both
51/// cases are valid; names are case-sensitive. Types are unique within a domain; elsewhere they
52/// are named `domain.Type`. Cloning gives another handle to the same domain.
53///
54/// Make it with [`domain`]: `let shop_domain = domain("shop");`. A domain remembers the
55/// aggregates, read models and reactors created through it, so that an app runs all of them
56/// (see [`crate::Kernable::app`]); they live as long as the domain does.
57#[derive(Clone)]
58pub struct Domain {
59    inner: Arc<DomainInner>,
60}
61
62/// A domain named `name`, on which you define its aggregates, read models, reactors and event
63/// and command schemas: `let shop_domain = domain("shop");`.
64///
65/// # Panics
66///
67/// If `name` does not start with a letter or holds characters other than letters, digits,
68/// `-` and `_`.
69pub fn domain(name: &str) -> Domain {
70    let valid = name.starts_with(|c: char| c.is_ascii_alphabetic())
71        && name
72            .chars()
73            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
74    assert!(valid, "invalid domain name {name:?}");
75    Domain {
76        inner: Arc::new(DomainInner {
77            name: name.to_owned(),
78            events: RwLock::default(),
79            commands: RwLock::default(),
80            queries: RwLock::default(),
81            aggregates: RwLock::default(),
82            listeners: RwLock::default(),
83            processes: RwLock::default(),
84            declared: RwLock::default(),
85        }),
86    }
87}
88
89impl Domain {
90    /// The domain's name, e.g. `shop`.
91    pub fn name(&self) -> &str {
92        &self.inner.name
93    }
94
95    /// Declares that this domain writes `event_type` events at version `schema`, with an
96    /// `upcast` per older version, and which of their fields the vault keeps; see
97    /// [`EventSchema`]. The domain's aggregates and listeners use it; other domains' listeners
98    /// get it with [`Listener::with_domain`]. Types not declared are at version 1.
99    ///
100    /// # Panics
101    ///
102    /// If `event_type` is qualified or `schema` is 0.
103    pub fn event(&self, event_type: &str, schema: u32) -> EventSchema {
104        assert!(
105            unqualified(event_type),
106            "event types are unqualified within their domain, not {event_type:?}"
107        );
108        assert!(schema >= 1, "a schema is a version from 1, not {schema}");
109        self.inner.events.write().unwrap().insert(
110            event_type.to_owned(),
111            EventDef {
112                schema,
113                ..EventDef::default()
114            },
115        );
116        EventSchema {
117            domain: self.clone(),
118            event_type: event_type.to_owned(),
119        }
120    }
121
122    /// Declares which fields of `command_type` commands the vault keeps (`personal`,
123    /// `secret`); see [`CommandSchema`]. Clients that submit them need the domain:
124    /// `kernable.with_domain(&domain)`.
125    ///
126    /// # Panics
127    ///
128    /// If `command_type` is qualified.
129    pub fn command(&self, command_type: &str) -> CommandSchema {
130        assert!(
131            unqualified(command_type),
132            "command types are unqualified within their domain, not {command_type:?}"
133        );
134        self.inner
135            .commands
136            .write()
137            .unwrap()
138            .insert(command_type.to_owned(), VaultFields::default());
139        CommandSchema {
140            domain: self.clone(),
141            command_type: command_type.to_owned(),
142        }
143    }
144
145    /// Declares what `query_type` queries are about (see [`QuerySchema::target`]): returns the
146    /// [`QuerySchema`] to chain `target` on. A query type (see [`crate::query`]) declares it
147    /// with `target(...)` instead. Clients that ask such queries by name need the domain:
148    /// `kernable.with_domain(&domain)`.
149    ///
150    /// # Panics
151    ///
152    /// If `query_type` is qualified.
153    pub fn query(&self, query_type: &str) -> QuerySchema {
154        assert!(
155            unqualified(query_type),
156            "query types are unqualified within their domain, not {query_type:?}"
157        );
158        self.inner
159            .queries
160            .write()
161            .unwrap()
162            .insert(query_type.to_owned(), None);
163        QuerySchema {
164            domain: self.clone(),
165            query_type: query_type.to_owned(),
166        }
167    }
168
169    /// A business process of this domain named `name` (`fulfilment`; qualified
170    /// `shop.fulfilment`): add its start and steps to the [`crate::process::Process`] it
171    /// returns. An app of the domain registers it with the kernel ([`crate::Kernable::app`]).
172    /// Example: `shop_domain.process("fulfilment").start::<OrderSubmitted>(Start::key("aggregate_id"))...`.
173    ///
174    /// # Panics
175    ///
176    /// If `name` is not letters, digits, `-` and `_`, or the domain has a process named `name`
177    /// already.
178    pub fn process(&self, name: &str) -> crate::process::Process {
179        let valid = !name.is_empty()
180            && name
181                .chars()
182                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
183        assert!(valid, "invalid process name {name:?}");
184        let process = crate::process::Process::new(self.name(), name);
185        let mut processes = self.inner.processes.write().unwrap();
186        let qualified = process.name();
187        assert!(
188            !processes.iter().any(|p| p.name() == qualified),
189            "{} has a process {name} already",
190            self.inner.name
191        );
192        processes.push(process.clone());
193        process
194    }
195
196    /// The business processes defined on this domain, in order.
197    pub(crate) fn processes(&self) -> Vec<crate::process::Process> {
198        self.inner.processes.read().unwrap().clone()
199    }
200
201    /// An aggregate of this domain named `name` (lowercase by convention, like `cart`), whose
202    /// state starts as `initial`; see [`Aggregate`]. Example:
203    /// `let cart_aggregate = shop_domain.aggregate("cart", Cart::default());`.
204    ///
205    /// # Panics
206    ///
207    /// If the domain has an aggregate named `name` already.
208    pub fn aggregate<S: State>(&self, name: &str, initial: S) -> Aggregate<S> {
209        let taken = self.aggregates().iter().any(|a| a.name() == name);
210        assert!(
211            !taken,
212            "{} has an aggregate {name} already",
213            self.inner.name
214        );
215        let aggregate = Aggregate {
216            inner: Arc::new(AggregateInner {
217                domain: self.clone(),
218                name: name.to_owned(),
219                initial,
220                settings: Mutex::new((100, "1".to_owned())),
221                appliers: RwLock::default(),
222                handlers: RwLock::default(),
223                keys: RwLock::default(),
224                facts: RwLock::default(),
225                requires: RwLock::default(),
226            }),
227        };
228        self.inner
229            .aggregates
230            .write()
231            .unwrap()
232            .push(Arc::new(aggregate.clone()));
233        aggregate
234    }
235
236    /// A read model of this domain named `name`: builds a view from events and answers queries
237    /// from it; see [`Listener`]. Kept in memory and rebuilt from the first event on every start
238    /// (order 0; [`Listener::store`] keeps it in a file instead). Run it with
239    /// [`crate::Kernable::listener`] or in an app. Example:
240    /// `let carts_readmodel = shop_domain.read_model("carts");`.
241    ///
242    /// # Panics
243    ///
244    /// If the domain has a read model or reactor named `name` already.
245    pub fn read_model(&self, name: &str) -> Listener {
246        self.remember(Listener::new(self, name, 0, Some(0), 0, false))
247    }
248
249    /// A reactor of this domain named `name`: triggers side effects and follow-up commands; see
250    /// [`Listener`]. It starts at the newest event when it is new, then resumes after the last
251    /// acknowledged event (order 10). A settling submit from its handler waits for the
252    /// listeners before it (the read models), not for the reactor itself, which handles one
253    /// event at a time. Submit follow-ups with `ctx.submit` and a fixed ID, so a redelivered
254    /// event does not run the command twice; a rejected one parks the event (see
255    /// [`Listener::park_after`]). Run it with [`crate::Kernable::listener`] or in an app.
256    ///
257    /// # Panics
258    ///
259    /// If the domain has a read model or reactor named `name` already.
260    pub fn reactor(&self, name: &str) -> Listener {
261        self.remember(Listener::new(
262            self,
263            name,
264            10,
265            None,
266            crate::listener::PARK_AFTER,
267            true,
268        ))
269    }
270
271    fn remember(&self, listener: Listener) -> Listener {
272        let taken = self.listeners().iter().any(|l| l.name() == listener.name());
273        assert!(
274            !taken,
275            "{} has a listener {} already",
276            self.inner.name,
277            listener.name()
278        );
279        self.inner.listeners.write().unwrap().push(listener.clone());
280        listener
281    }
282
283    /// The aggregates created through this domain, in order.
284    pub(crate) fn aggregates(&self) -> Vec<Arc<dyn Runnable>> {
285        self.inner.aggregates.read().unwrap().clone()
286    }
287
288    /// The read models and reactors created through this domain, in order.
289    pub(crate) fn listeners(&self) -> Vec<Listener> {
290        self.inner.listeners.read().unwrap().clone()
291    }
292
293    pub(crate) fn event_def(&self, event_type: &str) -> Option<EventDef> {
294        self.inner.events.read().unwrap().get(event_type).cloned()
295    }
296
297    pub(crate) fn event_types(&self) -> Vec<String> {
298        self.inner.events.read().unwrap().keys().cloned().collect()
299    }
300
301    pub(crate) fn command_vault(&self, command_type: &str) -> Option<VaultFields> {
302        self.inner
303            .commands
304            .read()
305            .unwrap()
306            .get(command_type)
307            .cloned()
308    }
309
310    /// The aggregate `query_type` queries are about, as declared ([`Domain::query`]).
311    pub(crate) fn query_target(&self, query_type: &str) -> Option<QueryTarget> {
312        self.inner
313            .queries
314            .read()
315            .unwrap()
316            .get(query_type)
317            .cloned()
318            .flatten()
319    }
320
321    /// Runs a message type's `declare` on this domain once, unless its schema was declared by
322    /// name already ([`Domain::event`], [`Domain::command`], [`Domain::query`]).
323    pub(crate) fn declare_once(&self, message_type: &str, declare: fn(&Domain)) {
324        let by_name = self.event_def(message_type).is_some()
325            || self.command_vault(message_type).is_some()
326            || self
327                .inner
328                .queries
329                .read()
330                .unwrap()
331                .contains_key(message_type);
332        if self
333            .inner
334            .declared
335            .write()
336            .unwrap()
337            .insert(message_type.to_owned())
338            && !by_name
339        {
340            declare(self);
341        }
342    }
343
344    /// The payload version this domain writes `event_type` events at.
345    pub fn schema_of(&self, event_type: &str) -> u32 {
346        self.event_def(event_type).map_or(1, |d| d.schema)
347    }
348
349    /// `data` of an `event_type` event stored at `schema`, upcast to the version this domain
350    /// knows.
351    pub(crate) fn upcast(
352        &self,
353        event_type: &str,
354        schema: u32,
355        data: Value,
356    ) -> Result<Value, SchemaError> {
357        upcast(Some(self), &self.inner.name, event_type, schema, data)
358    }
359}
360
361fn unqualified(t: &str) -> bool {
362    !t.is_empty() && !t.contains(['.', '*'])
363}
364
365/// The payload format of one event type: its current version and the steps that bring older
366/// payloads up to it. Events are stored as written and never changed; readers upcast them.
367///
368/// Made with [`Domain::event`]; its methods return it, so they chain:
369/// `shop_domain.event("ItemAdded", 2).upcast(1, |mut d| { d["qty"] = json!(1); d });` or
370/// `shop_domain.event("CustomerRegistered", 1).personal(&["email"], |_, id| id.to_owned());`.
371/// A subject function gets the payload and the aggregate's ID, e.g.
372/// `|d, _| d["customerId"].as_str().unwrap_or_default().to_owned()`.
373pub struct EventSchema {
374    domain: Domain,
375    event_type: String,
376}
377
378impl EventSchema {
379    fn update(&self, f: impl FnOnce(&mut EventDef)) {
380        let mut events = self.domain.inner.events.write().unwrap();
381        f(events
382            .get_mut(&self.event_type)
383            .expect("declared by Domain::event"));
384    }
385
386    /// Keeps these top-level fields in the vault, as personal data of the subject `subject`
387    /// returns from the payload and the aggregate's ID (see [`EventSchema`] for examples).
388    /// Events then hold only references; the kernel hands the values to workers and to
389    /// listeners allowed to read them, until an event erases the subject.
390    pub fn personal(
391        self,
392        fields: &[&str],
393        subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static,
394    ) -> Self {
395        let fields = fields.iter().map(|f| (*f).to_owned()).collect();
396        self.update(|d| d.vault.personal.push((fields, Arc::new(subject))));
397        self
398    }
399
400    /// Makes this an erasing event: it deletes every vault value of the subject `subject`
401    /// returns, in every stream, and the snapshots that may hold them. Read models should drop
402    /// the subject's data when they see it; rebuilt, they read `null`.
403    pub fn erases(self, subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static) -> Self {
404        self.update(|d| d.eraser = Some(Arc::new(subject)));
405        self
406    }
407
408    /// Turns a payload of version `from` into one of version `from + 1`: `step` gets the old
409    /// payload and returns the new one. Declare one step per older version.
410    ///
411    /// # Panics
412    ///
413    /// If `from` is not a version below the current one.
414    pub fn upcast(self, from: u32, step: impl Fn(Value) -> Value + Send + Sync + 'static) -> Self {
415        self.update(|d| {
416            assert!(
417                from >= 1 && from < d.schema,
418                "upcast {} from a version between 1 and {}, not {from}",
419                self.event_type,
420                d.schema - 1
421            );
422            d.steps.insert(from, Arc::new(step));
423        });
424        self
425    }
426}
427
428/// How a command's payload is kept: which fields go to the vault. Made with
429/// [`Domain::command`]; its methods return it, so they chain:
430/// `shop_domain.command("Register").personal(&["email"], |_, id| id.to_owned()).secret(&["password"]);`.
431/// Clients that submit these commands need the domain: `kernable.with_domain(&shop_domain)`.
432pub struct CommandSchema {
433    domain: Domain,
434    command_type: String,
435}
436
437impl CommandSchema {
438    fn update(&self, f: impl FnOnce(&mut VaultFields)) {
439        let mut commands = self.domain.inner.commands.write().unwrap();
440        f(commands
441            .get_mut(&self.command_type)
442            .expect("declared by Domain::command"));
443    }
444
445    /// Keeps these top-level fields in the vault as personal data of `subject`; see
446    /// [`EventSchema::personal`].
447    pub fn personal(
448        self,
449        fields: &[&str],
450        subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static,
451    ) -> Self {
452        let fields = fields.iter().map(|f| (*f).to_owned()).collect();
453        self.update(|v| v.personal.push((fields, Arc::new(subject))));
454        self
455    }
456
457    /// Keeps these top-level fields (passwords, one-time tokens) in the vault only until the
458    /// command completed. The handler gets them in clear; the stored command keeps a reference.
459    pub fn secret(self, fields: &[&str]) -> Self {
460        self.update(|v| v.secret.extend(fields.iter().map(|f| (*f).to_owned())));
461        self
462    }
463}
464
465/// What a query type is about. Made with [`Domain::query`]:
466/// `shop_domain.query("GetOrder").target("order", "id");` (a `GetOrder` with `{"id": "o-17"}`
467/// is about order `o-17`). Clients that ask these queries by name need the domain:
468/// `kernable.with_domain(&shop_domain)`.
469pub struct QuerySchema {
470    domain: Domain,
471    query_type: String,
472}
473
474impl QuerySchema {
475    /// The query is about one aggregate of `aggregate_type` (`order`, of the query's domain, or
476    /// qualified: `shop.order`), whose ID is in the data's field `field` (as on the wire:
477    /// `orderId`). The SDK sends it with the query, signed, and a middleware decides on it as
478    /// on a command's aggregate ([`crate::Check::target`]). Data without a non-empty string in
479    /// `field` sends no target.
480    pub fn target(self, aggregate_type: &str, field: &str) -> Self {
481        self.domain.inner.queries.write().unwrap().insert(
482            self.query_type.clone(),
483            Some(QueryTarget {
484                aggregate_type: aggregate_type.to_owned(),
485                field: field.to_owned(),
486            }),
487        );
488        self
489    }
490}
491
492/// The aggregate a query is about, as its type declares it: [`QuerySchema::target`].
493#[derive(Clone, Debug, PartialEq, Eq)]
494pub struct QueryTarget {
495    /// `order` (of the query's domain) or qualified: `shop.order`.
496    pub aggregate_type: String,
497    /// The field of the query's data that holds the aggregate's ID, as on the wire: `orderId`.
498    pub field: String,
499}
500
501impl QueryTarget {
502    /// The wire target of a `domain` query with `data`: the type qualified, the ID from
503    /// `data`; none without a non-empty string ID, so a rule that needs one refuses.
504    pub(crate) fn wire(&self, domain: &str, data: &Value) -> Option<proto::Target> {
505        let id = data
506            .get(&self.field)?
507            .as_str()
508            .filter(|id| !id.is_empty())?;
509        let aggregate_type = if self.aggregate_type.contains('.') {
510            self.aggregate_type.clone()
511        } else {
512            format!("{domain}.{}", self.aggregate_type)
513        };
514        Some(proto::Target {
515            aggregate_type,
516            aggregate_id: id.to_owned(),
517        })
518    }
519}
520
521/// An event a process cannot read: its schema is newer than known, or a step is missing.
522#[derive(Debug)]
523pub(crate) struct SchemaError(pub String);
524
525impl std::fmt::Display for SchemaError {
526    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527        f.write_str(&self.0)
528    }
529}
530
531impl std::error::Error for SchemaError {}
532
533/// The schema of `event_type` that `known` declares: the newest this process reads (1 if it
534/// declares none). An event stored at a higher one was written by newer code.
535pub(crate) fn known_schema(known: Option<&Domain>, event_type: &str) -> u32 {
536    known.map_or(1, |d| d.schema_of(event_type))
537}
538
539/// `data` of a `domain.event_type` event stored at `schema`, upcast to the version `known`
540/// declares (1 if it declares none).
541pub(crate) fn upcast(
542    known: Option<&Domain>,
543    domain: &str,
544    event_type: &str,
545    schema: u32,
546    mut data: Value,
547) -> Result<Value, SchemaError> {
548    let def = known.and_then(|d| d.event_def(event_type));
549    let current = def.as_ref().map_or(1, |d| d.schema);
550    if schema > current {
551        return Err(SchemaError(format!(
552            "{domain}.{event_type} has schema {schema}, but this process knows it only up to {current}: update it"
553        )));
554    }
555    for v in schema..current {
556        let step = def.as_ref().and_then(|d| d.steps.get(&v)).ok_or_else(|| {
557            SchemaError(format!(
558                "no upcast for {domain}.{event_type} from schema {v}"
559            ))
560        })?;
561        data = step(data);
562    }
563    Ok(data)
564}
565
566/// An event returned by a command handler; `data` is stored as JSON. Make it with
567/// [`NewEvent::new`]: `NewEvent::new("ItemAdded", &item)`.
568#[derive(Clone, Debug, PartialEq)]
569pub struct NewEvent {
570    /// The event type within the aggregate's domain, e.g. `ItemAdded`.
571    pub event_type: String,
572    /// The payload.
573    pub data: Value,
574}
575
576impl NewEvent {
577    /// An `event_type` event with `data`; `()` stands for no data.
578    ///
579    /// # Panics
580    ///
581    /// If `data` cannot be represented as JSON (a map with non-string keys).
582    pub fn new(event_type: &str, data: impl Serialize) -> NewEvent {
583        NewEvent {
584            event_type: event_type.to_owned(),
585            data: serde_json::to_value(data).expect("event data is JSON"),
586        }
587    }
588}
589
590impl<E: EventType> From<E> for NewEvent {
591    /// The event of a message type: `Ok(vec![OrderPlaced { ... }.into()])`.
592    fn from(event: E) -> NewEvent {
593        NewEvent::new(E::TYPE, event)
594    }
595}
596
597/// What `apply` gets about an event besides its payload. Only fields known before the kernel
598/// stores the event, so a snapshot and a replay compute the same state; put a time into the
599/// data (`ctx.now()` in the command handler) if the state needs one.
600#[derive(Clone, Debug, Default, PartialEq, Eq)]
601pub struct EventMeta {
602    pub event_type: String,
603    /// The aggregate's version after this event: 1 for its first event.
604    pub version: u64,
605    pub tenant: String,
606    pub domain: String,
607    pub aggregate_type: String,
608    pub aggregate_id: String,
609    /// The command that caused the event.
610    pub command_id: String,
611}
612
613/// What `apply` gets besides state, data and the event's meta. No clock and no IDs: `apply`
614/// must compute the same state every time.
615#[derive(Clone, Debug, Default, PartialEq, Eq)]
616pub struct ApplyContext {
617    /// The request context of the command that caused the event.
618    pub request: RequestContext,
619}
620
621/// What a command handler gets about the command besides its payload.
622#[derive(Clone, Debug, Default, PartialEq, Eq)]
623pub struct CommandMeta {
624    /// The command's ID: given with [`crate::Submit::id`], else a new UUID.
625    pub command_id: String,
626    /// The command type within the domain.
627    pub command_type: String,
628    pub domain: String,
629    pub aggregate_type: String,
630    pub aggregate_id: String,
631    pub tenant: String,
632}
633
634/// What a command handler gets besides state, data and the command's meta: the request
635/// context, and the command's time and IDs.
636#[derive(Clone, Debug)]
637pub struct CommandContext {
638    /// Who sends the command: check permissions here.
639    pub request: RequestContext,
640    command_id: String,
641    received_at: Timestamp,
642    deadline: Timestamp,
643    ids: u64,
644    /// For [`Aggregate::handle`]: the aggregate and tenant its `CommandMeta` names.
645    target: (String, String),
646}
647
648impl CommandContext {
649    /// A context for calling a command handler directly, e.g. in a unit test with
650    /// [`Aggregate::handle`]; its deadline is 30 s after `received_at`.
651    pub fn new(
652        command_id: &str,
653        request: RequestContext,
654        received_at: Timestamp,
655    ) -> CommandContext {
656        CommandContext {
657            command_id: command_id.to_owned(),
658            request,
659            received_at,
660            deadline: Timestamp(received_at.0 + 30_000),
661            ids: 0,
662            target: (String::new(), String::new()),
663        }
664    }
665
666    /// For [`Aggregate::handle`]: the aggregate ID and tenant the handler's [`CommandMeta`]
667    /// names (default: empty), e.g. for a handler that checks them.
668    pub fn on(mut self, aggregate_id: &str, tenant: &str) -> CommandContext {
669        self.target = (aggregate_id.to_owned(), tenant.to_owned());
670        self
671    }
672
673    /// When the kernel received the command: the same every time the command runs. Use it
674    /// instead of the clock.
675    pub fn now(&self) -> Timestamp {
676        self.received_at
677    }
678
679    /// A new ID that is the same every time the command runs (1st call, 2nd call, ...). Use it
680    /// instead of random IDs.
681    pub fn id(&mut self) -> String {
682        self.ids += 1;
683        signing::derived_id(&self.command_id, self.ids - 1)
684    }
685
686    /// When the kernel hands the command to another worker if this one has not answered.
687    pub fn deadline(&self) -> Timestamp {
688        self.deadline
689    }
690}
691
692/// An event to fold with [`Aggregate::fold`]: type, payload version and data, and what `apply`
693/// learns about it (empty fields if unknown). `FoldEvent::new("ItemAdded", json!({ "qty": 2 }))`
694/// is enough for most tests.
695#[derive(Clone, Debug, Default)]
696pub struct FoldEvent {
697    pub event_type: String,
698    pub schema: u32,
699    pub data: Value,
700    pub meta: EventMeta,
701    /// The request context of the command that caused the event: `apply` gets it in its
702    /// [`ApplyContext`].
703    pub request: RequestContext,
704}
705
706impl FoldEvent {
707    /// An `event_type` event at version 1 of its payload.
708    pub fn new(event_type: &str, data: impl Serialize) -> FoldEvent {
709        FoldEvent {
710            event_type: event_type.to_owned(),
711            schema: 1,
712            data: serde_json::to_value(data).expect("event data is JSON"),
713            meta: EventMeta::default(),
714            request: RequestContext::default(),
715        }
716    }
717}
718
719/// What an aggregate's state must be: copied, and stored as JSON in snapshots. Every type that
720/// is `Clone + Serialize + DeserializeOwned + Send + Sync + 'static` is one, typically a struct
721/// with `#[derive(Clone, Default, Serialize, Deserialize)]`.
722pub trait State: Clone + Serialize + DeserializeOwned + Send + Sync + 'static {}
723
724impl<S: Clone + Serialize + DeserializeOwned + Send + Sync + 'static> State for S {}
725
726type Apply<S> =
727    Arc<dyn Fn(&mut S, Value, &EventMeta, &ApplyContext) -> Result<(), BoxError> + Send + Sync>;
728type Handle<S> = Arc<
729    dyn Fn(&S, Value, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Failure>
730        + Send
731        + Sync,
732>;
733
734type Fact<S> = Arc<dyn Fn(&S) -> bool + Send + Sync>;
735type KeyValues<S> = Arc<dyn Fn(&S) -> Vec<String> + Send + Sync>;
736type Requires<S> = Arc<dyn Fn(&S, Value) -> Result<Vec<Requirement>, Failure> + Send + Sync>;
737
738/// A unique key as declared: its values in a state, its scope and whose data the values are.
739struct KeyDef<S> {
740    name: String,
741    values: KeyValues<S>,
742    global: bool,
743    personal: Option<KeySubject<S>>,
744}
745
746impl<S> Clone for KeyDef<S> {
747    fn clone(&self) -> Self {
748        KeyDef {
749            name: self.name.clone(),
750            values: Arc::clone(&self.values),
751            global: self.global,
752            personal: self.personal.clone(),
753        }
754    }
755}
756
757struct AggregateInner<S> {
758    domain: Domain,
759    name: String,
760    initial: S,
761    /// Snapshot every this many events, and the state format.
762    settings: Mutex<(u64, String)>,
763    appliers: RwLock<HashMap<String, Apply<S>>>,
764    handlers: RwLock<HashMap<String, Handle<S>>>,
765    /// Unique keys and facts, in the order declared.
766    keys: RwLock<Vec<KeyDef<S>>>,
767    facts: RwLock<Vec<(String, Fact<S>)>>,
768    /// Command type -> the facts of other aggregates its commands require.
769    requires: RwLock<HashMap<String, Requires<S>>>,
770}
771
772/// An aggregate: how events change its state (`apply`) and which events a command produces
773/// (`command`). Handlers must be deterministic and free of side effects; they may run again.
774/// Create it with `domain(...).aggregate(...)`; cloning gives another handle to the same
775/// aggregate. The registering methods return the aggregate, so they chain.
776///
777/// `apply` handlers change the state in place:
778/// `cart_aggregate.apply("ItemAdded", |state, data: Item, _evt, _ctx| state.items += data.qty);`.
779/// `command` handlers return the new events or a [`Rejected`]:
780/// `cart_aggregate.command("AddItem", |state, data: Item, _cmd, _ctx| { if state.checked_out {
781/// return Err(Rejected::new("Cart is checked out")); } Ok(vec![NewEvent::new("ItemAdded", data)]) });`.
782/// The type of `data` (here `Item`, any `Deserialize` type, or `serde_json::Value`) says how
783/// the payload is read; a payload that does not fit fails the command with `handler_error`.
784/// Handlers are synchronous and must not block.
785///
786/// Unique keys, facts and requirements reach across aggregates; the kernel checks them
787/// atomically when a command commits. `unique` declares a key computed from the state, which
788/// no two aggregates hold with the same value: `customer_aggregate.unique("email", |s|
789/// s.email.clone(), Unique::tenant());`. `fact` declares a condition of the state that other
790/// aggregates' commands may require: `vehicle_aggregate.fact("open", |s| !s.wound_up);`.
791/// `requires` names the facts a command needs:
792/// `account_aggregate.requires("OpenAccount", |_state, data: Open| [Requirement::new("funds",
793/// "vehicle", &data.vehicle_id, "open")]);`. After every command, the worker sends the keys and
794/// facts of the new state, so an aggregate always holds exactly what its state yields.
795///
796/// Test without a kernel: `cart_aggregate.fold([FoldEvent::new("ItemAdded", json!({ "qty": 2 }))], None)?`
797/// returns the state, `cart_aggregate.handle(&state, "AddItem", json!({ "qty": 1 }), &mut ctx)`
798/// runs a command handler with a [`CommandContext::new`], and `cart_aggregate.index(&state)?`
799/// and `cart_aggregate.requirements(&state, "AddItem", json!({ "qty": 1 }))?` compute the keys,
800/// facts and requirements.
801pub struct Aggregate<S> {
802    inner: Arc<AggregateInner<S>>,
803}
804
805impl<S> Clone for Aggregate<S> {
806    fn clone(&self) -> Self {
807        Aggregate {
808            inner: Arc::clone(&self.inner),
809        }
810    }
811}
812
813/// Why a handler failed: a business rejection, or anything else (`handler_error`).
814#[derive(Debug)]
815pub(crate) enum Failure {
816    Rejected(Rejected),
817    Error(String),
818    /// This process cannot read the aggregate's events: not the command's fault.
819    Schema(String),
820}
821
822impl Failure {
823    /// As a test helper reports it.
824    fn into_error(self) -> Error {
825        match self {
826            Failure::Rejected(r) => Error::Rejected(r),
827            Failure::Error(m) | Failure::Schema(m) => Error::Config(m),
828        }
829    }
830}
831
832impl From<SchemaError> for Failure {
833    fn from(e: SchemaError) -> Failure {
834        Failure::Schema(e.0)
835    }
836}
837
838impl<S: State> Aggregate<S> {
839    /// The domain the aggregate belongs to.
840    pub fn domain(&self) -> &Domain {
841        &self.inner.domain
842    }
843
844    /// The aggregate's name within its domain, e.g. `cart`.
845    pub fn name(&self) -> &str {
846        &self.inner.name
847    }
848
849    /// The state before the first event.
850    pub fn initial(&self) -> &S {
851        &self.inner.initial
852    }
853
854    /// Sends a snapshot of the state every `events` events (default 100; 0 turns them off).
855    pub fn snapshot_every(&self, events: u64) -> Self {
856        self.inner.settings.lock().unwrap().0 = events;
857        self.clone()
858    }
859
860    /// Version of the state format (default "1"). Change it when `apply` produces differently
861    /// shaped state; older snapshots are then ignored and the state is rebuilt from the events.
862    pub fn schema(&self, schema: &str) -> Self {
863        self.inner.settings.lock().unwrap().1 = schema.to_owned();
864        self.clone()
865    }
866
867    /// How an event of `event_type` changes the state: `f(state, data, evt, ctx)` changes
868    /// `state` in place, or replaces it with `*state = …`. `data` is the event's payload as `D`,
869    /// upcast to the current version; `evt` is an [`EventMeta`], `ctx` an [`ApplyContext`].
870    /// `event_type` is a name, or an event type's constant (see [`crate::event`]), whose data
871    /// `D` then is: `order_aggregate.apply(OrderPlaced, |s, d, _evt, _ctx| ...)`. The same holds
872    /// for `command` and `requires`. See [`Aggregate`] for an example.
873    pub fn apply<D: DeserializeOwned>(
874        &self,
875        event_type: impl TypeKey<D>,
876        f: impl Fn(&mut S, D, &EventMeta, &ApplyContext) + Send + Sync + 'static,
877    ) -> Self {
878        let event_type = event_type.key().within(&self.inner.domain, "apply");
879        let event_type = event_type.as_str();
880        let apply: Apply<S> = Arc::new(move |state, data, meta, ctx| {
881            let data = serde_json::from_value(data)
882                .map_err(|e| format!("{} data: {e}", meta.event_type))?;
883            f(state, data, meta, ctx);
884            Ok(())
885        });
886        self.inner
887            .appliers
888            .write()
889            .unwrap()
890            .insert(event_type.to_owned(), apply);
891        self.clone()
892    }
893
894    /// Which events a `command_type` command produces: `f(state, data, cmd, ctx)` returns
895    /// them as `Ok(vec![NewEvent::new(…)])`, or `Err(Rejected::new(…))`. `data` is the
896    /// command's payload as `D`; `cmd` is a [`CommandMeta`], `ctx` a [`CommandContext`] with
897    /// the request context and deterministic `now()` and `id()`. See [`Aggregate`] for an
898    /// example.
899    ///
900    /// # Panics
901    ///
902    /// If `command_type` starts with `_reindex_`: those are reserved for the built-in command
903    /// of aggregates with unique keys or facts (see [`crate::reindex_type`]), and an aggregate
904    /// cannot see the other aggregate types of its domain.
905    pub fn command<D: DeserializeOwned>(
906        &self,
907        command_type: impl TypeKey<D>,
908        f: impl Fn(&S, D, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Rejected>
909        + Send
910        + Sync
911        + 'static,
912    ) -> Self {
913        let command_type = command_type.key().within(&self.inner.domain, "command");
914        let command_type = command_type.as_str();
915        assert!(
916            !command_type.starts_with("_reindex_"),
917            "{command_type}: command types starting with _reindex_ are reserved for the built-in \
918             command of aggregates with unique keys or facts; name yours otherwise"
919        );
920        let name = command_type.to_owned();
921        let handle: Handle<S> = Arc::new(move |state, data, cmd, ctx| {
922            let data = serde_json::from_value(data)
923                .map_err(|e| Failure::Error(format!("{name} data: {e}")))?;
924            f(state, data, cmd, ctx).map_err(Failure::Rejected)
925        });
926        self.inner
927            .handlers
928            .write()
929            .unwrap()
930            .insert(command_type.to_owned(), handle);
931        self.clone()
932    }
933
934    /// Declares a unique key named `name`: `values(state)` returns the values the aggregate
935    /// holds in that state, as anything that iterates over `String`s (values are strings by
936    /// type; format numbers yourself): `None` (holds nothing),
937    /// `Some(value)` (one value) or a `Vec` (several; repeated ones count once). No two
938    /// aggregates of this type hold the same value of the key at the same time; a command that
939    /// would make its aggregate hold a value another one holds is rejected with `unique_taken`.
940    /// The value is compared as is: normalize it in `values` (e.g. lowercase an email); an empty
941    /// string is a value like any other. `options` says where it is unique (within the tenant,
942    /// or [`Unique::global`]) and whether the value is personal ([`Unique::personal`]). Example:
943    /// `customer_aggregate.unique("email", |s| s.email.as_ref().map(|e| e.to_lowercase()),
944    /// Unique::tenant());`.
945    ///
946    /// The worker computes the keys from the state after every command, also one without
947    /// events; `values` must be deterministic like `apply`, and one that panics fails the command
948    /// with `handler_error`. An aggregate that had events before the key was declared holds
949    /// none of its values until it runs a command: [`crate::Kernable::reindex`] runs one.
950    ///
951    /// # Panics
952    ///
953    /// If `name` is empty, longer than 128 bytes or holds `.` or `*`, or the aggregate declares
954    /// a key named `name` already (a fact may have the same name).
955    pub fn unique<I: IntoIterator<Item = String>>(
956        &self,
957        name: &str,
958        values: impl Fn(&S) -> I + Send + Sync + 'static,
959        options: Unique<S>,
960    ) -> Self {
961        let taken = self
962            .inner
963            .keys
964            .read()
965            .unwrap()
966            .iter()
967            .any(|k| k.name == name);
968        self.declarable("key", name, taken);
969        self.inner.keys.write().unwrap().push(KeyDef {
970            name: name.to_owned(),
971            values: Arc::new(move |state| values(state).into_iter().collect()),
972            global: options.global,
973            personal: options.personal,
974        });
975        self.clone()
976    }
977
978    /// Declares a fact named `name`, which the aggregate holds while `holds(state)` is true.
979    /// Commands of other aggregates of the tenant may require it (see [`Aggregate::requires`]).
980    /// Computed like the keys (see [`Aggregate::unique`]). Example:
981    /// `vehicle_aggregate.fact("open", |s| !s.wound_up);`.
982    ///
983    /// # Panics
984    ///
985    /// If `name` is empty, longer than 128 bytes or holds `.` or `*`, or the aggregate declares
986    /// a fact named `name` already (a key may have the same name).
987    pub fn fact(&self, name: &str, holds: impl Fn(&S) -> bool + Send + Sync + 'static) -> Self {
988        let taken = self
989            .inner
990            .facts
991            .read()
992            .unwrap()
993            .iter()
994            .any(|(f, _)| f == name);
995        self.declarable("fact", name, taken);
996        self.inner
997            .facts
998            .write()
999            .unwrap()
1000            .push((name.to_owned(), Arc::new(holds)));
1001        self.clone()
1002    }
1003
1004    /// Which facts of other aggregates of the tenant a `command_type` command requires:
1005    /// `f(state, data)` returns [`Requirement`]s (anything that iterates over them), from the
1006    /// state before the command and its payload as `D`. The command commits only if each
1007    /// named aggregate holds its fact at that moment, otherwise it is rejected with
1008    /// `requirement_missing`; nothing is locked in between. Example:
1009    /// `account_aggregate.requires("OpenAccount", |_state, data: Open| [Requirement::new("funds",
1010    /// "vehicle", &data.vehicle_id, "open")]);`. A payload that is not a `D`, or an `f` that
1011    /// panics, fails the command with `handler_error`.
1012    ///
1013    /// # Panics
1014    ///
1015    /// If the aggregate has no `command_type` handler (declare it with
1016    /// [`Aggregate::command`] first).
1017    pub fn requires<D: DeserializeOwned, I: IntoIterator<Item = Requirement>>(
1018        &self,
1019        command_type: impl TypeKey<D>,
1020        f: impl Fn(&S, D) -> I + Send + Sync + 'static,
1021    ) -> Self {
1022        let command_type = command_type.key().within(&self.inner.domain, "requires");
1023        let command_type = command_type.as_str();
1024        assert!(
1025            self.handler(command_type).is_some(),
1026            "{} has no command {command_type} to require facts for: declare it first",
1027            self.inner.name
1028        );
1029        let name = command_type.to_owned();
1030        let requires: Requires<S> = Arc::new(move |state, data| {
1031            let data = serde_json::from_value(data)
1032                .map_err(|e| Failure::Error(format!("{name} data: {e}")))?;
1033            Ok(f(state, data).into_iter().collect())
1034        });
1035        self.inner
1036            .requires
1037            .write()
1038            .unwrap()
1039            .insert(command_type.to_owned(), requires);
1040        self.clone()
1041    }
1042
1043    /// Panics unless `name` can name a new key or fact (`kind`) of this aggregate; `taken`:
1044    /// one of that kind has the name already.
1045    fn declarable(&self, kind: &str, name: &str, taken: bool) {
1046        let aggregate = format!("{}.{}", self.inner.domain.name(), self.inner.name);
1047        assert!(
1048            unqualified(name) && name.len() <= 128,
1049            "{aggregate}: a {kind} name is 1 to 128 bytes without `.` or `*`, not {name:?}"
1050        );
1051        assert!(!taken, "{aggregate} declares a {kind} {name} already");
1052    }
1053
1054    /// Whether the aggregate declares unique keys or facts.
1055    fn indexed(&self) -> bool {
1056        !self.inner.keys.read().unwrap().is_empty() || !self.inner.facts.read().unwrap().is_empty()
1057    }
1058
1059    /// The unique keys and facts the aggregate holds in `state`, as the worker sends them after
1060    /// a command that leaves it in `state`; for tests without a kernel. [`Error::Config`] if a
1061    /// key or fact function panics.
1062    pub fn index(&self, state: &S) -> Result<Index, Error> {
1063        self.index_of(state).map_err(Failure::into_error)
1064    }
1065
1066    /// The requirements of a `command_type` command with `data` on `state` (none if it declares
1067    /// none, see [`Aggregate::requires`]); for tests without a kernel. [`Error::Config`] if
1068    /// `data` is not the function's `D` or it panics.
1069    pub fn requirements(
1070        &self,
1071        state: &S,
1072        command_type: &str,
1073        data: impl Serialize,
1074    ) -> Result<Vec<Requirement>, Error> {
1075        let data = serde_json::to_value(data)?;
1076        self.requirements_of(state, command_type, data)
1077            .map_err(Failure::into_error)
1078    }
1079
1080    fn index_of(&self, state: &S) -> Result<Index, Failure> {
1081        let keys = self.inner.keys.read().unwrap().clone();
1082        let facts = self.inner.facts.read().unwrap().clone();
1083        caught(|| {
1084            let mut index = Index::default();
1085            for key in &keys {
1086                let subject = match &key.personal {
1087                    None => None,
1088                    Some(subject) => match subject(state) {
1089                        Some(s) if !s.is_empty() => Some(s),
1090                        _ => continue,
1091                    },
1092                };
1093                let mut values: Vec<String> = Vec::new();
1094                for value in (key.values)(state) {
1095                    if !values.contains(&value) {
1096                        values.push(value);
1097                    }
1098                }
1099                index.keys.extend(values.into_iter().map(|value| UniqueKey {
1100                    name: key.name.clone(),
1101                    value,
1102                    global: key.global,
1103                    subject: subject.clone(),
1104                }));
1105            }
1106            index.facts = facts
1107                .iter()
1108                .filter(|(_, holds)| holds(state))
1109                .map(|(name, _)| name.clone())
1110                .collect();
1111            index
1112        })
1113    }
1114
1115    fn requirements_of(
1116        &self,
1117        state: &S,
1118        command_type: &str,
1119        data: Value,
1120    ) -> Result<Vec<Requirement>, Failure> {
1121        let requires = self
1122            .inner
1123            .requires
1124            .read()
1125            .unwrap()
1126            .get(command_type)
1127            .cloned();
1128        match requires {
1129            Some(requires) => caught(|| requires(state, data))?,
1130            None => Ok(Vec::new()),
1131        }
1132    }
1133
1134    /// State after `history`, starting from `from` (default: the initial state). Events are
1135    /// upcast first; events without an `apply` are skipped. For tests without a kernel.
1136    /// [`Error::Config`] if an `apply` fails (also a payload that is not its `D`, or a panic)
1137    /// or an event's schema is newer than known.
1138    pub fn fold(
1139        &self,
1140        history: impl IntoIterator<Item = FoldEvent>,
1141        from: Option<S>,
1142    ) -> Result<S, Error> {
1143        self.fold_inner(history, from).map_err(|f| match f {
1144            Failure::Rejected(r) => Error::Rejected(r),
1145            Failure::Error(m) | Failure::Schema(m) => Error::Config(m),
1146        })
1147    }
1148
1149    fn fold_inner(
1150        &self,
1151        history: impl IntoIterator<Item = FoldEvent>,
1152        from: Option<S>,
1153    ) -> Result<S, Failure> {
1154        let mut state = from.unwrap_or_else(|| self.inner.initial.clone());
1155        let appliers = self.inner.appliers.read().unwrap();
1156        for e in history {
1157            let Some(apply) = appliers.get(&e.event_type) else {
1158                continue;
1159            };
1160            let data = self.inner.domain.upcast(&e.event_type, e.schema, e.data)?;
1161            let meta = EventMeta {
1162                event_type: e.event_type,
1163                domain: if e.meta.domain.is_empty() {
1164                    self.inner.domain.name().to_owned()
1165                } else {
1166                    e.meta.domain
1167                },
1168                aggregate_type: if e.meta.aggregate_type.is_empty() {
1169                    self.inner.name.clone()
1170                } else {
1171                    e.meta.aggregate_type
1172                },
1173                ..e.meta
1174            };
1175            let ctx = ApplyContext { request: e.request };
1176            caught(|| apply(&mut state, data, &meta, &ctx))?
1177                .map_err(|e| Failure::Error(e.to_string()))?;
1178        }
1179        Ok(state)
1180    }
1181
1182    /// Runs the `command_type` handler on `state`, e.g. in a unit test. The handler's
1183    /// [`CommandMeta`] has the command ID of `ctx`, this aggregate's domain and name, and an empty
1184    /// aggregate ID and tenant. [`Error::Rejected`] if the handler rejects the command,
1185    /// [`Error::Config`] if there is no handler for `command_type` or it fails otherwise.
1186    pub fn handle(
1187        &self,
1188        state: &S,
1189        command_type: &str,
1190        data: impl Serialize,
1191        ctx: &mut CommandContext,
1192    ) -> Result<Vec<NewEvent>, Error> {
1193        let handler = self.handler(command_type).ok_or_else(|| {
1194            Error::Config(format!(
1195                "no handler for {command_type} on {}",
1196                self.inner.name
1197            ))
1198        })?;
1199        let data = serde_json::to_value(data)?;
1200        let cmd = CommandMeta {
1201            command_id: ctx.command_id.clone(),
1202            command_type: command_type.to_owned(),
1203            domain: self.inner.domain.name().to_owned(),
1204            aggregate_type: self.inner.name.clone(),
1205            aggregate_id: ctx.target.0.clone(),
1206            tenant: ctx.target.1.clone(),
1207        };
1208        match caught(|| handler(state, data, &cmd, ctx)).and_then(|r| r) {
1209            Ok(events) => Ok(events),
1210            Err(Failure::Rejected(r)) => Err(Error::Rejected(r)),
1211            Err(Failure::Error(m) | Failure::Schema(m)) => Err(Error::Config(m)),
1212        }
1213    }
1214
1215    fn handler(&self, command_type: &str) -> Option<Handle<S>> {
1216        self.inner
1217            .handlers
1218            .read()
1219            .unwrap()
1220            .get(command_type)
1221            .cloned()
1222    }
1223
1224    /// A rejection (`personal_in_clear`) if an event holds, in a field the event type does not
1225    /// declare personal, a non-null value under the name of a personal field of the command:
1226    /// it would be stored in the signed log in clear, for good.
1227    fn personal_in_clear(&self, command_type: &str, events: &[NewEvent]) -> Result<(), Failure> {
1228        let domain = &self.inner.domain;
1229        let Some(command) = domain.command_vault(command_type) else {
1230            return Ok(());
1231        };
1232        for e in events {
1233            let def = domain.event_def(&e.event_type);
1234            let declared = |field: &String| {
1235                def.as_ref()
1236                    .is_some_and(|d| d.vault.personal.iter().any(|(f, _)| f.contains(field)))
1237            };
1238            for field in command.personal.iter().flat_map(|(fields, _)| fields) {
1239                let held = e.data.get(field).is_some_and(|v| !v.is_null());
1240                if held && !declared(field) {
1241                    return Err(Failure::Rejected(
1242                        Rejected::new(format!(
1243                            "{command_type} declares {field} personal, but {event} does not: it \
1244                             would be stored in clear (declare it with Domain.event({event:?}, \
1245                             …).personal)",
1246                            event = e.event_type,
1247                        ))
1248                        .code("personal_in_clear"),
1249                    ));
1250                }
1251            }
1252        }
1253        Ok(())
1254    }
1255}
1256
1257/// `f()`, with a panic turned into an error.
1258fn caught<T>(f: impl FnOnce() -> T) -> Result<T, Failure> {
1259    catch_unwind(AssertUnwindSafe(f)).map_err(|panic| Failure::Error(panic_text(panic.as_ref())))
1260}
1261
1262/// What a panic said, as far as it can be shown.
1263pub(crate) fn panic_text(panic: &(dyn std::any::Any + Send)) -> String {
1264    panic
1265        .downcast_ref::<&str>()
1266        .map(|s| (*s).to_owned())
1267        .or_else(|| panic.downcast_ref::<String>().cloned())
1268        .unwrap_or_else(|| "handler panicked".into())
1269}
1270
1271/// What a worker sends back for a command it executed.
1272pub(crate) struct Executed {
1273    pub events: Vec<proto::NewEvent>,
1274    pub vault: Vec<proto::VaultValue>,
1275    /// Version, state format and state, if the events cross a multiple of `snapshot_every`.
1276    pub snapshot: Option<(u64, String, Vec<u8>)>,
1277    /// The unique keys and facts of the state after the events, and the facts the command
1278    /// requires of other aggregates.
1279    pub keys: Vec<proto::UniqueKey>,
1280    pub facts: Vec<String>,
1281    pub requires: Vec<proto::Requirement>,
1282}
1283
1284/// An aggregate as a worker runs it, whatever its state type.
1285pub(crate) trait Runnable: Send + Sync {
1286    fn domain(&self) -> &Domain;
1287    fn name(&self) -> &str;
1288    fn command_types(&self) -> Vec<String>;
1289    /// The event types it knows: applied ones and the domain's declared ones.
1290    fn event_types(&self) -> Vec<String>;
1291    fn execute(&self, x: &proto::Execute) -> Result<Executed, Failure>;
1292}
1293
1294impl<S: State> Runnable for Aggregate<S> {
1295    fn domain(&self) -> &Domain {
1296        &self.inner.domain
1297    }
1298
1299    fn name(&self) -> &str {
1300        &self.inner.name
1301    }
1302
1303    fn command_types(&self) -> Vec<String> {
1304        let mut types: Vec<String> = self
1305            .inner
1306            .handlers
1307            .read()
1308            .unwrap()
1309            .keys()
1310            .cloned()
1311            .collect();
1312        if self.indexed() {
1313            types.push(reindex_type(&self.inner.name));
1314        }
1315        types
1316    }
1317
1318    fn event_types(&self) -> Vec<String> {
1319        let mut types: Vec<String> = self
1320            .inner
1321            .appliers
1322            .read()
1323            .unwrap()
1324            .keys()
1325            .cloned()
1326            .collect();
1327        types.extend(self.inner.domain.event_types());
1328        types.sort();
1329        types.dedup();
1330        types
1331    }
1332
1333    fn execute(&self, x: &proto::Execute) -> Result<Executed, Failure> {
1334        let cmd = x.command.clone().unwrap_or_default();
1335        let (snapshot_every, schema) = self.inner.settings.lock().unwrap().clone();
1336        let from = match &x.snapshot {
1337            Some(s) if s.schema != schema => {
1338                return Err(Failure::Rejected(
1339                    Rejected::new(format!("snapshot schema {} is not {schema}", s.schema))
1340                        .code("snapshot_stale"),
1341                ));
1342            }
1343            Some(s) => Some(
1344                serde_json::from_slice(&s.state)
1345                    .map_err(|e| Failure::Error(format!("snapshot of {}: {e}", self.inner.name)))?,
1346            ),
1347            None => None,
1348        };
1349        let history = x.history.iter().map(|e| FoldEvent {
1350            event_type: e.event_type.clone(),
1351            schema: e.schema,
1352            data: vault::unseal(decode(&e.payload), &x.vault).0,
1353            meta: meta_of(&e.event_type, e.version, &cmd, &e.command_id),
1354            request: RequestContext::from_wire(e.context.as_ref()),
1355        });
1356        let state = self.fold_inner(history.collect::<Vec<_>>(), from)?;
1357        let request = RequestContext::from_wire(cmd.context.as_ref());
1358        let meta = CommandMeta {
1359            command_id: cmd.command_id.clone(),
1360            command_type: cmd.command_type.clone(),
1361            domain: cmd.domain.clone(),
1362            aggregate_type: cmd.aggregate_type.clone(),
1363            aggregate_id: cmd.aggregate_id.clone(),
1364            tenant: cmd.tenant_id.clone(),
1365        };
1366        let mut ctx = CommandContext {
1367            command_id: cmd.command_id.clone(),
1368            request: request.clone(),
1369            received_at: Timestamp(x.received_at),
1370            deadline: Timestamp(x.deadline),
1371            ids: 0,
1372            target: (cmd.aggregate_id.clone(), cmd.tenant_id.clone()),
1373        };
1374        let indexed = self.indexed();
1375        let handler = self.handler(&cmd.command_type);
1376        let data = vault::unseal(decode(&cmd.payload), &x.vault).0;
1377        let produced = match handler {
1378            Some(handler) => caught(|| handler(&state, data.clone(), &meta, &mut ctx))??,
1379            // Produces nothing, so the result carries the keys and facts of the current state.
1380            None if indexed && cmd.command_type == reindex_type(&self.inner.name) => Vec::new(),
1381            None => {
1382                return Err(Failure::Rejected(
1383                    Rejected::new(format!(
1384                        "no handler for {} on {}.{}",
1385                        cmd.command_type, cmd.domain, cmd.aggregate_type
1386                    ))
1387                    .code("unknown_command"),
1388                ));
1389            }
1390        };
1391        self.personal_in_clear(&cmd.command_type, &produced)?;
1392        let requires = self.requirements_of(&state, &cmd.command_type, data)?;
1393
1394        let mut events = Vec::with_capacity(produced.len());
1395        let mut values = Vec::new();
1396        for e in &produced {
1397            let def = self.inner.domain.event_def(&e.event_type);
1398            let sealed = vault::seal(&e.data, def.as_ref().map(|d| &d.vault), &cmd.aggregate_id)
1399                .map_err(Failure::Error)?;
1400            values.extend(sealed.values);
1401            let erases = def
1402                .as_ref()
1403                .and_then(|d| d.eraser.as_ref())
1404                .map(|subject| subject(&e.data, &cmd.aggregate_id))
1405                .unwrap_or_default();
1406            events.push(proto::NewEvent {
1407                event_type: e.event_type.clone(),
1408                schema: def.as_ref().map_or(1, |d| d.schema),
1409                payload: sealed.payload,
1410                vault_refs: sealed.refs,
1411                erases,
1412                origin_partition: String::new(),
1413                origin_position: 0,
1414                // The kernel sets it from the worker's deployment.
1415                deployment: String::new(),
1416            });
1417        }
1418
1419        let before = x.expected_version;
1420        let version = before + produced.len() as u64;
1421        let snapshot_due = snapshot_every != 0
1422            && !produced.is_empty()
1423            && version / snapshot_every != before / snapshot_every;
1424        let after = if produced.is_empty() || !(snapshot_due || indexed) {
1425            state
1426        } else {
1427            // Apply the events as they will be read back (a JSON round trip), so the snapshot
1428            // and the keys equal those of a replay.
1429            let read = produced.iter().enumerate().map(|(i, e)| FoldEvent {
1430                event_type: e.event_type.clone(),
1431                schema: self.inner.domain.schema_of(&e.event_type),
1432                data: decode(&encode(&e.data)),
1433                meta: meta_of(&e.event_type, before + i as u64 + 1, &cmd, &cmd.command_id),
1434                request: request.clone(),
1435            });
1436            self.fold_inner(read.collect::<Vec<_>>(), Some(state))?
1437        };
1438        let snapshot = if snapshot_due {
1439            let state = serde_json::to_vec(&after).map_err(|e| Failure::Error(e.to_string()))?;
1440            Some((version, schema, state))
1441        } else {
1442            None
1443        };
1444        let index = if indexed {
1445            self.index_of(&after)?
1446        } else {
1447            Index::default()
1448        };
1449        Ok(Executed {
1450            events,
1451            vault: values,
1452            snapshot,
1453            keys: index.keys.iter().map(UniqueKey::to_wire).collect(),
1454            facts: index.facts,
1455            requires: requires.iter().map(|q| q.to_wire(&cmd.domain)).collect(),
1456        })
1457    }
1458}
1459
1460/// What `apply` gets about an event of `cmd`'s aggregate, caused by command `command_id`.
1461fn meta_of(event_type: &str, version: u64, cmd: &proto::Command, command_id: &str) -> EventMeta {
1462    EventMeta {
1463        event_type: event_type.to_owned(),
1464        version,
1465        tenant: cmd.tenant_id.clone(),
1466        domain: cmd.domain.clone(),
1467        aggregate_type: cmd.aggregate_type.clone(),
1468        aggregate_id: cmd.aggregate_id.clone(),
1469        command_id: command_id.to_owned(),
1470    }
1471}
1472
1473/// JSON bytes of `data`; no data is `{}`.
1474pub(crate) fn encode(data: &Value) -> Vec<u8> {
1475    if data.is_null() {
1476        return b"{}".to_vec();
1477    }
1478    serde_json::to_vec(data).expect("a JSON value encodes")
1479}
1480
1481/// The JSON value of `payload`; an empty payload is `{}`.
1482pub(crate) fn decode(payload: &[u8]) -> Value {
1483    if payload.is_empty() {
1484        return Value::Object(Map::new());
1485    }
1486    serde_json::from_slice(payload).unwrap_or(Value::Null)
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491    use super::*;
1492
1493    #[test]
1494    fn a_panic_says_what_it_said_as_far_as_it_can() {
1495        let text = |f: fn()| panic_text(catch_unwind(f).unwrap_err().as_ref());
1496        std::panic::set_hook(Box::new(|_| {}));
1497        assert_eq!(text(|| panic!("plain")), "plain");
1498        assert_eq!(text(|| panic!("formatted {}", 7)), "formatted 7");
1499        assert_eq!(text(|| std::panic::panic_any(7)), "handler panicked");
1500        let _ = std::panic::take_hook();
1501        assert_eq!(SchemaError("too new".into()).to_string(), "too new");
1502    }
1503}