Skip to main content

kernable/
process.rs

1//! Business processes (design/processes.md): a flow across commands, events and queries, defined
2//! in code next to the domain, built into a model the kernel runs.
3//!
4//! [`crate::Domain::process`] returns a [`Process`]; its methods add the steps in the order
5//! written, each returning the process, so they chain:
6//!
7//! ```
8//! use kernable::{command, domain, event, query};
9//! use kernable::process::{Ask, Decide, Send, Start, Wait, value};
10//!
11//! #[event("shop")]
12//! pub struct OrderSubmitted { pub total: i64 }
13//! #[event("shop")]
14//! pub struct OrderApproved {}
15//! #[event("payments")]
16//! pub struct PaymentReceived { pub order_id: String, pub at: i64 }
17//! #[command("shop", aggregate = "order")]
18//! pub struct Confirm {}
19//! #[command("shop", aggregate = "order")]
20//! pub struct Ship {}
21//! #[command("shop", aggregate = "order")]
22//! pub struct NotifyDelay {}
23//! #[command("shop", aggregate = "order")]
24//! pub struct Cancel { pub reason: String }
25//! #[query("shop", answer = bool)]
26//! pub struct NeedsApproval { pub order_id: String }
27//!
28//! let shop = domain("shop");
29//! let fulfilment = shop
30//!     .process("fulfilment")
31//!     .start::<OrderSubmitted>(Start::key("aggregate_id").data([("order_id", "aggregate_id"), ("total", "data.total")]))
32//!     .command::<Confirm>("confirm", Send::aggregate("case.order_id"))
33//!     .decide("large", Decide::when("case.total > 1000", "approval").otherwise("paid"))
34//!     .query::<NeedsApproval>("approval", Ask::data([("order_id", "case.order_id")]).path(true, "approved").path(false, "paid"))
35//!     .wait::<OrderApproved>("approved", Wait::key("aggregate_id"))
36//!     .wait::<PaymentReceived>("paid", Wait::key("data.order_id").data([("paid_at", "data.at")]).timeout("3d", "cancel"))
37//!     .command::<Ship>("ship", Send::aggregate("case.order_id").rejected("out_of_stock", "notify").next("done"))
38//!     .command::<NotifyDelay>("notify", Send::aggregate("case.order_id").next("done"))
39//!     .command::<Cancel>("cancel", Send::aggregate("case.order_id").data([("reason", value("unpaid"))]))
40//!     .end("done");
41//! assert_eq!(fulfilment.model().unwrap()["name"], "shop.fulfilment");
42//! ```
43//!
44//! - **Steps run in the order written**, unless a step names `next`; a `decide` without
45//!   `otherwise` goes on with the next step written. Step names are required (letters, digits,
46//!   `_`, `-`): they are the stable IDs of versions, the UI and the statistics.
47//! - **References** are strings: `aggregate_id` and `data.<field>` (the event being handled, in
48//!   `start` and `wait`), `case.<field>` (the case's data) and, in a query step, `answer` or
49//!   `answer.<field>`. Field names are written in Rust's style (`case.order_id`); the model has
50//!   the wire names (`case.orderId`), as the log does. A literal is [`value`].
51//! - **Conditions** (`decide`) are small expressions: references to `case.<field>`, literals,
52//!   `== != < <= > >=`, `and`, `or`, `not`. The kernel parses them when the process registers.
53//! - **Durations** are `30s`, `15m`, `12h`, `3d`.
54//! - **Messages** are types (`command::<Confirm>`), or names (`command_named("confirm",
55//!   "order.Confirm", ...)`, unqualified: of the process's domain).
56//!
57//! An app registers its domains' processes ([`crate::Kernable::app`]);
58//! [`crate::Kernable::register_process`] registers one alone. Import the option types from this
59//! module: `Send` and `Wait` share their names with `std::marker::Send` and [`crate::Wait`].
60
61use std::sync::{Arc, Mutex};
62
63use serde::Serialize;
64use serde_json::{Map, Value, json};
65
66use crate::{CommandType, Error, EventType, QueryType};
67
68/// A literal in a mapping, where a string would be a reference:
69/// `Send::aggregate("case.order_id").data([("reason", value("unpaid"))])`.
70///
71/// # Panics
72///
73/// If `literal` cannot be represented as JSON.
74pub fn value(literal: impl Serialize) -> Source {
75    Source(Repr::Value(
76        serde_json::to_value(literal).expect("a literal is JSON"),
77    ))
78}
79
80/// What a mapping's field gets: a reference (a string, e.g. `"case.order_id"`) or a literal
81/// ([`value`]).
82#[derive(Clone, Debug, PartialEq)]
83pub struct Source(Repr);
84
85#[derive(Clone, Debug, PartialEq)]
86enum Repr {
87    Ref(String),
88    Value(Value),
89}
90
91impl From<&str> for Source {
92    fn from(reference: &str) -> Source {
93        Source(Repr::Ref(reference.to_owned()))
94    }
95}
96
97impl From<String> for Source {
98    fn from(reference: String) -> Source {
99        Source(Repr::Ref(reference))
100    }
101}
102
103type Mapping = Vec<(String, Source)>;
104
105fn mapping<K: AsRef<str>, V: Into<Source>>(fields: impl IntoIterator<Item = (K, V)>) -> Mapping {
106    fields
107        .into_iter()
108        .map(|(k, v)| (k.as_ref().to_owned(), v.into()))
109        .collect()
110}
111
112/// How a case starts: where its key is in the event, and the case's data from the event.
113/// `Start::key("aggregate_id").data([("order_id", "aggregate_id"), ("total", "data.total")])`.
114#[derive(Clone, Debug)]
115pub struct Start {
116    key: String,
117    data: Mapping,
118}
119
120impl Start {
121    /// The case's key: `aggregate_id`, or a field of the event's data (`data.order_id`). One
122    /// case runs per key.
123    pub fn key(reference: &str) -> Start {
124        Start {
125            key: reference.to_owned(),
126            data: Vec::new(),
127        }
128    }
129
130    /// The case's data from the event: field → reference (`aggregate_id`, `data.<field>`) or
131    /// [`value`].
132    pub fn data<K: AsRef<str>, V: Into<Source>>(
133        mut self,
134        fields: impl IntoIterator<Item = (K, V)>,
135    ) -> Start {
136        self.data.extend(mapping(fields));
137        self
138    }
139}
140
141/// A command step: the aggregate it goes to, its data, the paths for rejections, and the next
142/// step. `Send::aggregate("case.order_id").rejected("out_of_stock", "notify").next("done")`.
143#[derive(Clone, Debug)]
144pub struct Send {
145    aggregate: String,
146    data: Mapping,
147    rejected: Vec<(String, String)>,
148    next: Option<String>,
149}
150
151impl Send {
152    /// The command's aggregate ID: a reference to the case's data (`case.order_id`).
153    pub fn aggregate(reference: &str) -> Send {
154        Send {
155            aggregate: reference.to_owned(),
156            data: Vec::new(),
157            rejected: Vec::new(),
158            next: None,
159        }
160    }
161
162    /// The command's data: field → reference (`case.<field>`) or [`value`].
163    pub fn data<K: AsRef<str>, V: Into<Source>>(
164        mut self,
165        fields: impl IntoIterator<Item = (K, V)>,
166    ) -> Send {
167        self.data.extend(mapping(fields));
168        self
169    }
170
171    /// A rejection with `code` goes on with `step`. A rejection without a path stops the case
172    /// with an incident.
173    pub fn rejected(mut self, code: &str, step: &str) -> Send {
174        self.rejected.push((code.to_owned(), step.to_owned()));
175        self
176    }
177
178    /// The step after it; default: the next step written.
179    pub fn next(mut self, step: &str) -> Send {
180        self.next = Some(step.to_owned());
181        self
182    }
183}
184
185/// A wait step: where this case's key is in the awaited event, what the event adds to the case,
186/// how long to wait. `Wait::key("data.order_id").timeout("3d", "cancel")`.
187#[derive(Clone, Debug)]
188pub struct Wait {
189    key: String,
190    data: Mapping,
191    timeout: Option<(String, String)>,
192    next: Option<String>,
193}
194
195impl Wait {
196    /// Where the event names the case's key: `aggregate_id`, or `data.<field>`.
197    pub fn key(reference: &str) -> Wait {
198        Wait {
199            key: reference.to_owned(),
200            data: Vec::new(),
201            timeout: None,
202            next: None,
203        }
204    }
205
206    /// Merged into the case's data from the event: field → reference (`aggregate_id`,
207    /// `data.<field>`, `case.<field>`) or [`value`].
208    pub fn data<K: AsRef<str>, V: Into<Source>>(
209        mut self,
210        fields: impl IntoIterator<Item = (K, V)>,
211    ) -> Wait {
212        self.data.extend(mapping(fields));
213        self
214    }
215
216    /// Without the event within `duration` (`30s`, `15m`, `12h`, `3d`), the case goes on with
217    /// `step`.
218    pub fn timeout(mut self, duration: &str, step: &str) -> Wait {
219        self.timeout = Some((duration.to_owned(), step.to_owned()));
220        self
221    }
222
223    /// The step after the event; default: the next step written.
224    pub fn next(mut self, step: &str) -> Wait {
225        self.next = Some(step.to_owned());
226        self
227    }
228}
229
230/// A timer step: waits a while (`Timer::after("12h")`) or until a time in the case's data, in
231/// ms since epoch (`Timer::at("case.due_at")`).
232#[derive(Clone, Debug)]
233pub struct Timer {
234    after: Option<String>,
235    at: Option<String>,
236    next: Option<String>,
237}
238
239impl Timer {
240    /// Waits `duration`: `30s`, `15m`, `12h`, `3d`.
241    pub fn after(duration: &str) -> Timer {
242        Timer {
243            after: Some(duration.to_owned()),
244            at: None,
245            next: None,
246        }
247    }
248
249    /// Waits until the time (ms since epoch) a reference to the case's data names:
250    /// `case.due_at`.
251    pub fn at(reference: &str) -> Timer {
252        Timer {
253            after: None,
254            at: Some(reference.to_owned()),
255            next: None,
256        }
257    }
258
259    /// The step after it; default: the next step written.
260    pub fn next(mut self, step: &str) -> Timer {
261        self.next = Some(step.to_owned());
262        self
263    }
264}
265
266/// A decision on the case's data: the first condition that holds picks the path.
267/// `Decide::when("case.total > 1000", "approval").or_when("case.total > 100", "check").otherwise("paid")`.
268#[derive(Clone, Debug)]
269pub struct Decide {
270    when: Vec<(String, String)>,
271    otherwise: Option<String>,
272}
273
274impl Decide {
275    /// If `condition` holds, the case goes on with `step`.
276    pub fn when(condition: &str, step: &str) -> Decide {
277        Decide {
278            when: vec![(condition.to_owned(), step.to_owned())],
279            otherwise: None,
280        }
281    }
282
283    /// Another condition, tried after the ones before it.
284    pub fn or_when(mut self, condition: &str, step: &str) -> Decide {
285        self.when.push((condition.to_owned(), step.to_owned()));
286        self
287    }
288
289    /// Where the case goes if no condition holds; default: the next step written.
290    pub fn otherwise(mut self, step: &str) -> Decide {
291        self.otherwise = Some(step.to_owned());
292        self
293    }
294}
295
296/// A query step: asks a read model; the answer picks the path.
297/// `Ask::data([("order_id", "case.order_id")]).path(true, "approved").path(false, "paid")`.
298#[derive(Clone, Debug, Default)]
299pub struct Ask {
300    data: Mapping,
301    answer: Option<String>,
302    paths: Vec<(Value, String)>,
303    into: Option<String>,
304    otherwise: Option<String>,
305}
306
307impl Ask {
308    /// A query without data; add paths with [`Ask::path`].
309    pub fn new() -> Ask {
310        Ask::default()
311    }
312
313    /// A query with data: field → reference (`case.<field>`) or [`value`].
314    pub fn data<K: AsRef<str>, V: Into<Source>>(fields: impl IntoIterator<Item = (K, V)>) -> Ask {
315        Ask {
316            data: mapping(fields),
317            ..Ask::default()
318        }
319    }
320
321    /// The field of an object answer the paths match (`status`); default: the answer itself (a
322    /// boolean, string or number).
323    pub fn answer(mut self, field: &str) -> Ask {
324        self.answer = Some(field.to_owned());
325        self
326    }
327
328    /// An answer equal to `value` goes on with `step`.
329    ///
330    /// # Panics
331    ///
332    /// If `value` cannot be represented as JSON.
333    pub fn path(mut self, value: impl Serialize, step: &str) -> Ask {
334        let value = serde_json::to_value(value).expect("a path's value is JSON");
335        self.paths.push((value, step.to_owned()));
336        self
337    }
338
339    /// Keeps the answer in this field of the case's data.
340    pub fn into_field(mut self, field: &str) -> Ask {
341        self.into = Some(field.to_owned());
342        self
343    }
344
345    /// Where the case goes if no path matches; without it, an incident.
346    pub fn otherwise(mut self, step: &str) -> Ask {
347        self.otherwise = Some(step.to_owned());
348        self
349    }
350}
351
352#[derive(Clone, Debug)]
353enum Step {
354    Command { command: String, send: Send },
355    Wait { event: String, wait: Wait },
356    Timer(Timer),
357    Decide(Decide),
358    Query { query: String, ask: Ask },
359    End,
360}
361
362struct Def {
363    /// Qualified: `shop.fulfilment`.
364    name: String,
365    domain: String,
366    start: Option<(String, Start)>,
367    steps: Vec<(String, Step)>,
368    /// Events that end a running case: event type, key reference, end step.
369    cancels: Vec<(String, String, String)>,
370}
371
372/// A business process of a domain, made with [`crate::Domain::process`]: its start and steps,
373/// added in the order written (see the [module](self) for an example). Cloning gives another
374/// handle to the same process. [`Process::model`] builds the model the kernel registers.
375#[derive(Clone)]
376pub struct Process {
377    inner: Arc<Mutex<Def>>,
378}
379
380impl std::fmt::Debug for Process {
381    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382        f.debug_struct("Process")
383            .field("name", &self.name())
384            .finish()
385    }
386}
387
388/// Registered by [`crate::Kernable::register_process`]: the process's version.
389#[derive(Clone, Debug, PartialEq, Eq)]
390pub struct Registered {
391    /// Qualified: `shop.fulfilment`.
392    pub name: String,
393    /// From 1: the kernel numbers the versions.
394    pub version: u32,
395    /// `false` if the model equals the newest version: nothing new was registered.
396    pub new: bool,
397}
398
399impl Process {
400    pub(crate) fn new(domain: &str, name: &str) -> Process {
401        Process {
402            inner: Arc::new(Mutex::new(Def {
403                name: format!("{domain}.{name}"),
404                domain: domain.to_owned(),
405                start: None,
406                steps: Vec::new(),
407                cancels: Vec::new(),
408            })),
409        }
410    }
411
412    /// Its qualified name: `shop.fulfilment`.
413    pub fn name(&self) -> String {
414        self.inner.lock().unwrap().name.clone()
415    }
416
417    fn with(&self, f: impl FnOnce(&mut Def)) -> Process {
418        f(&mut self.inner.lock().unwrap());
419        self.clone()
420    }
421
422    fn step(&self, name: &str, step: Step) -> Process {
423        self.with(|d| d.steps.push((name.to_owned(), step)))
424    }
425
426    /// Starts a case when an `E` event commits; see [`Start`].
427    pub fn start<E: EventType>(&self, start: Start) -> Process {
428        self.start_named(&format!("{}.{}", E::DOMAIN, E::TYPE), start)
429    }
430
431    /// [`Process::start`] with the event type by name: `shop.OrderSubmitted`, or `OrderSubmitted`
432    /// of the process's domain.
433    pub fn start_named(&self, event_type: &str, start: Start) -> Process {
434        self.with(|d| d.start = Some((qualify(&d.domain, event_type, 1), start)))
435    }
436
437    /// A step `name` that sends a `C` command as the process; see [`Send`].
438    pub fn command<C: CommandType>(&self, name: &str, send: Send) -> Process {
439        let command = format!("{}.{}.{}", C::DOMAIN, C::AGGREGATE, C::TYPE);
440        self.step(name, Step::Command { command, send })
441    }
442
443    /// [`Process::command`] with the command type by name: `shop.order.Confirm`, or
444    /// `order.Confirm` of the process's domain.
445    pub fn command_named(&self, name: &str, command_type: &str, send: Send) -> Process {
446        let domain = self.inner.lock().unwrap().domain.clone();
447        let command = qualify(&domain, command_type, 2);
448        self.step(name, Step::Command { command, send })
449    }
450
451    /// A step `name` that waits for an `E` event of this case; see [`Wait`].
452    pub fn wait<E: EventType>(&self, name: &str, wait: Wait) -> Process {
453        let event = format!("{}.{}", E::DOMAIN, E::TYPE);
454        self.step(name, Step::Wait { event, wait })
455    }
456
457    /// [`Process::wait`] with the event type by name: `payments.PaymentReceived`, or a type of
458    /// the process's domain.
459    pub fn wait_named(&self, name: &str, event_type: &str, wait: Wait) -> Process {
460        let domain = self.inner.lock().unwrap().domain.clone();
461        let event = qualify(&domain, event_type, 1);
462        self.step(name, Step::Wait { event, wait })
463    }
464
465    /// A step `name` that waits for a time; see [`Timer`].
466    pub fn timer(&self, name: &str, timer: Timer) -> Process {
467        self.step(name, Step::Timer(timer))
468    }
469
470    /// A step `name` that picks a path by the case's data; see [`Decide`].
471    pub fn decide(&self, name: &str, decide: Decide) -> Process {
472        self.step(name, Step::Decide(decide))
473    }
474
475    /// A step `name` that asks a `Q` query; its answer picks the path; see [`Ask`].
476    pub fn query<Q: QueryType>(&self, name: &str, ask: Ask) -> Process {
477        let query = format!("{}.{}", Q::DOMAIN, Q::TYPE);
478        self.step(name, Step::Query { query, ask })
479    }
480
481    /// [`Process::query`] with the query type by name: `shop.NeedsApproval`, or a type of the
482    /// process's domain.
483    pub fn query_named(&self, name: &str, query_type: &str, ask: Ask) -> Process {
484        let domain = self.inner.lock().unwrap().domain.clone();
485        let query = qualify(&domain, query_type, 1);
486        self.step(name, Step::Query { query, ask })
487    }
488
489    /// A step `name` that ends the case.
490    pub fn end(&self, name: &str) -> Process {
491        self.step(name, Step::End)
492    }
493
494    /// Ends a running case at once when an `E` event of its key commits, whatever step it is
495    /// at: `key` is where the case's key is in the event (`aggregate_id` or `data.<field>`),
496    /// `end` an `end` step. Its timer is withdrawn, an outcome it still awaits is ignored, an
497    /// incident ends with it. Events the case's own commands cause do not count.
498    pub fn cancel_on<E: EventType>(&self, key: &str, end: &str) -> Process {
499        self.cancel_on_named(&format!("{}.{}", E::DOMAIN, E::TYPE), key, end)
500    }
501
502    /// [`Process::cancel_on`] with the event type by name: `accounts.AccountClosed`, or a type
503    /// of the process's domain.
504    pub fn cancel_on_named(&self, event_type: &str, key: &str, end: &str) -> Process {
505        self.with(|d| {
506            let event = qualify(&d.domain, event_type, 1);
507            d.cancels.push((event, key.to_owned(), end.to_owned()));
508        })
509    }
510
511    /// The model the kernel registers (design/processes.md "The model format"): steps in the
512    /// order written, each but `end` with its explicit successors, field names as on the wire.
513    /// [`Error::Config`] naming the process and the step if it has no start, a step name is
514    /// invalid or taken, a target names no step, a step other than `end` has no successor, a
515    /// reference or duration is malformed, or a decision or query has no paths. The kernel
516    /// checks the rest when it registers the model (conditions, types, grants).
517    pub fn model(&self) -> Result<Value, Error> {
518        let d = self.inner.lock().unwrap();
519        let fail = |step: Option<&str>, reason: String| {
520            Error::Config(match step {
521                Some(step) => format!("process {}, step {step}: {reason}", d.name),
522                None => format!("process {}: {reason}", d.name),
523            })
524        };
525        let Some((on, start)) = &d.start else {
526            return Err(fail(None, "no start: add one with start".into()));
527        };
528        let mut names: Vec<&str> = Vec::new();
529        for (name, _) in &d.steps {
530            let valid = !name.is_empty()
531                && name
532                    .chars()
533                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
534            if !valid {
535                return Err(fail(
536                    Some(name),
537                    "a step name is letters, digits, `_` and `-`".into(),
538                ));
539            }
540            if names.contains(&name.as_str()) {
541                return Err(fail(Some(name), "the name is taken by another step".into()));
542            }
543            names.push(name);
544        }
545        if d.steps.is_empty() {
546            return Err(fail(None, "no steps".into()));
547        }
548        const EVENT: &[&str] = &["aggregateId", "data"];
549        const EVENT_OR_CASE: &[&str] = &["aggregateId", "data", "case"];
550        const CASE: &[&str] = &["case"];
551        let start_model = {
552            let mut m = Map::new();
553            m.insert("on".into(), json!(on));
554            m.insert(
555                "key".into(),
556                json!(reference(&start.key, EVENT).map_err(|e| fail(None, format!("start: {e}")))?),
557            );
558            if !start.data.is_empty() {
559                m.insert(
560                    "data".into(),
561                    mapped(&start.data, EVENT).map_err(|e| fail(None, format!("start: {e}")))?,
562                );
563            }
564            Value::Object(m)
565        };
566        let mut steps = Vec::new();
567        for (i, (name, step)) in d.steps.iter().enumerate() {
568            let at = Some(name.as_str());
569            let following = d.steps.get(i + 1).map(|(n, _)| n.clone());
570            let target = |what: &str, step: &str| -> Result<Value, Error> {
571                if names.contains(&step) {
572                    Ok(json!(step))
573                } else {
574                    Err(fail(at, format!("{what} names no step: {step}")))
575                }
576            };
577            let successor = |explicit: &Option<String>| -> Result<Value, Error> {
578                match explicit.as_ref().or(following.as_ref()) {
579                    Some(next) => target("next", next),
580                    None => Err(fail(
581                        at,
582                        "no step after it: name one with next, or end the process".into(),
583                    )),
584                }
585            };
586            let refs = |r: &str, allowed: &[&str]| reference(r, allowed).map_err(|e| fail(at, e));
587            let map = |m: &Mapping, allowed: &[&str]| mapped(m, allowed).map_err(|e| fail(at, e));
588            let duration = |text: &str| millis(text).map_err(|e| fail(at, e));
589            let mut m = Map::new();
590            m.insert("name".into(), json!(name));
591            match step {
592                Step::Command { command, send } => {
593                    m.insert("kind".into(), json!("command"));
594                    m.insert("command".into(), json!(command));
595                    m.insert("aggregate".into(), json!(refs(&send.aggregate, CASE)?));
596                    if !send.data.is_empty() {
597                        m.insert("data".into(), map(&send.data, CASE)?);
598                    }
599                    if !send.rejected.is_empty() {
600                        let mut rejected = Map::new();
601                        for (code, step) in &send.rejected {
602                            rejected.insert(code.clone(), target("rejected", step)?);
603                        }
604                        m.insert("rejected".into(), Value::Object(rejected));
605                    }
606                    m.insert("next".into(), successor(&send.next)?);
607                }
608                Step::Wait { event, wait } => {
609                    m.insert("kind".into(), json!("wait"));
610                    m.insert("event".into(), json!(event));
611                    m.insert("key".into(), json!(refs(&wait.key, EVENT)?));
612                    if !wait.data.is_empty() {
613                        m.insert("data".into(), map(&wait.data, EVENT_OR_CASE)?);
614                    }
615                    if let Some((after, step)) = &wait.timeout {
616                        m.insert("timeoutMs".into(), json!(duration(after)?));
617                        m.insert("onTimeout".into(), target("timeout", step)?);
618                    }
619                    m.insert("next".into(), successor(&wait.next)?);
620                }
621                Step::Timer(timer) => {
622                    m.insert("kind".into(), json!("timer"));
623                    match (&timer.after, &timer.at) {
624                        (Some(after), _) => {
625                            m.insert("afterMs".into(), json!(duration(after)?));
626                        }
627                        (None, Some(time)) => {
628                            m.insert("at".into(), json!(refs(time, CASE)?));
629                        }
630                        (None, None) => unreachable!("made with Timer::after or Timer::at"),
631                    }
632                    m.insert("next".into(), successor(&timer.next)?);
633                }
634                Step::Decide(decide) => {
635                    m.insert("kind".into(), json!("decide"));
636                    let mut when = Vec::new();
637                    for (condition, step) in &decide.when {
638                        if condition.trim().is_empty() {
639                            return Err(fail(at, "an empty condition".into()));
640                        }
641                        when.push(json!({ "if": condition_names(condition), "next": target("when", step)? }));
642                    }
643                    m.insert("when".into(), Value::Array(when));
644                    let otherwise = match &decide.otherwise {
645                        Some(step) => target("otherwise", step)?,
646                        None => successor(&None)?,
647                    };
648                    m.insert("otherwise".into(), otherwise);
649                }
650                Step::Query { query, ask } => {
651                    m.insert("kind".into(), json!("query"));
652                    m.insert("query".into(), json!(query));
653                    if !ask.data.is_empty() {
654                        m.insert("data".into(), map(&ask.data, CASE)?);
655                    }
656                    if let Some(field) = &ask.answer {
657                        m.insert("answer".into(), json!(path(field)));
658                    }
659                    if ask.paths.is_empty() {
660                        return Err(fail(
661                            at,
662                            "a query step needs paths: add them with Ask::path".into(),
663                        ));
664                    }
665                    let mut paths = Vec::new();
666                    for (value, step) in &ask.paths {
667                        paths.push(json!({ "value": value, "next": target("path", step)? }));
668                    }
669                    m.insert("paths".into(), Value::Array(paths));
670                    if let Some(field) = &ask.into {
671                        m.insert("into".into(), json!(path(field)));
672                    }
673                    if let Some(step) = &ask.otherwise {
674                        m.insert("otherwise".into(), target("otherwise", step)?);
675                    }
676                }
677                Step::End => {
678                    m.insert("kind".into(), json!("end"));
679                }
680            }
681            steps.push(Value::Object(m));
682        }
683        let mut model = json!({ "name": d.name, "start": start_model, "steps": steps });
684        if !d.cancels.is_empty() {
685            let mut cancels = Vec::new();
686            for (event, key, end) in &d.cancels {
687                match d.steps.iter().find(|(n, _)| n == end) {
688                    Some((_, Step::End)) => {}
689                    Some(_) => return Err(fail(None, format!("cancel_on: {end} is no end step"))),
690                    None => return Err(fail(None, format!("cancel_on: {end} names no step"))),
691                }
692                let key =
693                    reference(key, EVENT).map_err(|e| fail(None, format!("cancel_on: {e}")))?;
694                cancels.push(json!({ "event": event, "key": key, "end": end }));
695            }
696            model["cancelOn"] = Value::Array(cancels);
697        }
698        Ok(model)
699    }
700}
701
702/// `type_name` qualified with `domain` unless it has `dots` dots already (an event or query: 1,
703/// a command: 2).
704fn qualify(domain: &str, type_name: &str, dots: usize) -> String {
705    if type_name.matches('.').count() >= dots {
706        type_name.to_owned()
707    } else {
708        format!("{domain}.{type_name}")
709    }
710}
711
712/// `order_id` → `orderId`, as the message attributes write field names.
713fn camel(name: &str) -> String {
714    let mut out = String::new();
715    let mut upper = false;
716    for c in name.chars() {
717        if c == '_' {
718            upper = !out.is_empty();
719        } else if upper {
720            out.extend(c.to_uppercase());
721            upper = false;
722        } else {
723            out.push(c);
724        }
725    }
726    out
727}
728
729/// A dotted field path with each part's wire name.
730fn path(dotted: &str) -> String {
731    dotted.split('.').map(camel).collect::<Vec<_>>().join(".")
732}
733
734/// A reference with wire names, if well-formed and of a kind in `allowed` (`aggregateId`,
735/// `data`, `case`, `answer`).
736fn reference(r: &str, allowed: &[&str]) -> Result<String, String> {
737    let wire = path(r);
738    let (head, rest) = wire.split_once('.').unwrap_or((&wire, ""));
739    let parts_ok = rest.is_empty() || rest.split('.').all(|p| !p.is_empty());
740    let shape_ok = match head {
741        "aggregateId" => rest.is_empty() && !r.contains('.'),
742        "data" | "case" => !rest.is_empty() && parts_ok,
743        "answer" => parts_ok,
744        _ => false,
745    };
746    if shape_ok && allowed.contains(&head) {
747        Ok(wire)
748    } else {
749        let kinds: Vec<String> = allowed
750            .iter()
751            .map(|k| match *k {
752                "aggregateId" => "aggregate_id".to_owned(),
753                "answer" => "answer".to_owned(),
754                k => format!("{k}.<field>"),
755            })
756            .collect();
757        Err(format!(
758            "{r:?} is not a reference here ({})",
759            kinds.join(", ")
760        ))
761    }
762}
763
764/// A mapping with wire names: field → reference or `{"value": literal}`.
765fn mapped(m: &Mapping, allowed: &[&str]) -> Result<Value, String> {
766    let mut out = Map::new();
767    for (field, source) in m {
768        if field.is_empty() {
769            return Err("a mapping's field has no name".into());
770        }
771        let value = match &source.0 {
772            Repr::Ref(r) => json!(reference(r, allowed)?),
773            Repr::Value(v) => json!({ "value": v }),
774        };
775        out.insert(path(field), value);
776    }
777    Ok(Value::Object(out))
778}
779
780/// `30s`, `15m`, `12h`, `3d` in ms.
781fn millis(text: &str) -> Result<i64, String> {
782    let bad = || format!("{text:?} is not a duration (30s, 15m, 12h, 3d)");
783    let unit = match text.chars().last() {
784        Some('s') => 1_000,
785        Some('m') => 60_000,
786        Some('h') => 3_600_000,
787        Some('d') => 86_400_000,
788        _ => return Err(bad()),
789    };
790    let number = &text[..text.len() - 1];
791    if number.is_empty() || !number.bytes().all(|b| b.is_ascii_digit()) {
792        return Err(bad());
793    }
794    let n: i64 = number.parse().map_err(|_| bad())?;
795    match n.checked_mul(unit) {
796        Some(ms) if ms > 0 => Ok(ms),
797        _ => Err(format!("{text:?} is not a positive duration")),
798    }
799}
800
801/// A condition with the wire names of its references (`case.`, `data.`, `answer.`); string
802/// literals stay as written.
803fn condition_names(condition: &str) -> String {
804    let mut out = String::new();
805    let mut chars = condition.chars().peekable();
806    while let Some(c) = chars.next() {
807        if c == '\'' || c == '"' {
808            out.push(c);
809            for s in chars.by_ref() {
810                out.push(s);
811                if s == c {
812                    break;
813                }
814            }
815        } else if c.is_ascii_alphabetic() || c == '_' {
816            let mut word = c.to_string();
817            while let Some(&n) = chars.peek() {
818                if n.is_ascii_alphanumeric() || n == '_' || n == '.' {
819                    word.push(n);
820                    chars.next();
821                } else {
822                    break;
823                }
824            }
825            let reference = ["case.", "data.", "answer."]
826                .iter()
827                .any(|p| word.starts_with(p));
828            out.push_str(&if reference { path(&word) } else { word });
829        } else {
830            out.push(c);
831        }
832    }
833    out
834}
835
836#[cfg(test)]
837mod tests {
838    use serde_json::Value;
839
840    use super::*;
841    use crate::{command, domain, event, query};
842
843    #[event("shop")]
844    pub struct OrderSubmitted {
845        pub total: i64,
846    }
847    #[event("shop")]
848    pub struct OrderApproved {}
849    #[event("payments")]
850    pub struct PaymentReceived {
851        pub order_id: String,
852        pub at: i64,
853    }
854    #[command("shop", aggregate = "order")]
855    pub struct Confirm {}
856    #[command("shop", aggregate = "order")]
857    pub struct Ship {}
858    #[command("shop", aggregate = "order")]
859    pub struct NotifyDelay {}
860    #[command("shop", aggregate = "order")]
861    pub struct Cancel {
862        pub reason: String,
863    }
864    #[query("shop", answer = bool)]
865    pub struct NeedsApproval {
866        pub order_id: String,
867    }
868
869    fn fixture() -> Value {
870        let path = concat!(
871            env!("CARGO_MANIFEST_DIR"),
872            "/../../proto/test-vectors/process-model.json"
873        );
874        let v: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
875        v["model"].clone()
876    }
877
878    #[test]
879    fn the_design_s_example_builds_the_shared_model() {
880        let shop = domain("shop");
881        let fulfilment = shop
882            .process("fulfilment")
883            .start::<OrderSubmitted>(
884                Start::key("aggregate_id")
885                    .data([("order_id", "aggregate_id"), ("total", "data.total")]),
886            )
887            .command::<Confirm>("confirm", Send::aggregate("case.order_id"))
888            .decide(
889                "large",
890                Decide::when("case.total > 1000", "approval").otherwise("paid"),
891            )
892            .query::<NeedsApproval>(
893                "approval",
894                Ask::data([("order_id", "case.order_id")])
895                    .path(true, "approved")
896                    .path(false, "paid"),
897            )
898            .wait::<OrderApproved>("approved", Wait::key("aggregate_id"))
899            .wait::<PaymentReceived>(
900                "paid",
901                Wait::key("data.order_id")
902                    .data([("paid_at", "data.at")])
903                    .timeout("3d", "cancel"),
904            )
905            .command::<Ship>(
906                "ship",
907                Send::aggregate("case.order_id")
908                    .rejected("out_of_stock", "notify")
909                    .next("done"),
910            )
911            .command::<NotifyDelay>("notify", Send::aggregate("case.order_id").next("done"))
912            .command::<Cancel>(
913                "cancel",
914                Send::aggregate("case.order_id").data([("reason", value("unpaid"))]),
915            )
916            .end("done");
917        assert_eq!(fulfilment.model().unwrap(), fixture());
918        assert_eq!(fulfilment.name(), "shop.fulfilment");
919        // The domain remembers it, for apps.
920        assert_eq!(shop.processes().len(), 1);
921    }
922
923    #[test]
924    fn cancel_on_ends_at_an_end_step() {
925        let build = |end: &str| {
926            domain("accounts")
927                .process("onboarding")
928                .start_named("AccountOpened", Start::key("aggregate_id"))
929                .wait_named(
930                    "email",
931                    "EmailConfirmed",
932                    Wait::key("aggregate_id").next("onboarded"),
933                )
934                .end("onboarded")
935                .end("closed")
936                .cancel_on_named("AccountClosed", "aggregate_id", end)
937                .model()
938        };
939        assert_eq!(
940            build("closed").unwrap()["cancelOn"],
941            json!([{"event": "accounts.AccountClosed", "key": "aggregateId", "end": "closed"}])
942        );
943        assert!(
944            build("email")
945                .unwrap_err()
946                .to_string()
947                .contains("no end step")
948        );
949        assert!(
950            build("nowhere")
951                .unwrap_err()
952                .to_string()
953                .contains("names no step")
954        );
955    }
956
957    #[test]
958    fn messages_by_name_build_the_same_model() {
959        let shop = domain("shop");
960        let by_name = shop
961            .process("fulfilment")
962            .start_named(
963                "OrderSubmitted",
964                Start::key("aggregate_id")
965                    .data([("order_id", "aggregate_id"), ("total", "data.total")]),
966            )
967            .command_named("confirm", "order.Confirm", Send::aggregate("case.order_id"))
968            .decide(
969                "large",
970                Decide::when("case.total > 1000", "approval").otherwise("paid"),
971            )
972            .query_named(
973                "approval",
974                "shop.NeedsApproval",
975                Ask::data([("order_id", "case.order_id")])
976                    .path(true, "approved")
977                    .path(false, "paid"),
978            )
979            .wait_named("approved", "OrderApproved", Wait::key("aggregate_id"))
980            .wait_named(
981                "paid",
982                "payments.PaymentReceived",
983                Wait::key("data.orderId")
984                    .data([("paidAt", "data.at")])
985                    .timeout("72h", "cancel"),
986            )
987            .command_named(
988                "ship",
989                "shop.order.Ship",
990                Send::aggregate("case.order_id")
991                    .rejected("out_of_stock", "notify")
992                    .next("done"),
993            )
994            .command_named(
995                "notify",
996                "order.NotifyDelay",
997                Send::aggregate("case.order_id").next("done"),
998            )
999            .command_named(
1000                "cancel",
1001                "order.Cancel",
1002                Send::aggregate("case.order_id").data([("reason", value("unpaid"))]),
1003            )
1004            .end("done");
1005        assert_eq!(by_name.model().unwrap(), fixture());
1006    }
1007
1008    #[test]
1009    fn steps_follow_in_the_order_written_and_conditions_get_wire_names() {
1010        let p = domain("ops")
1011            .process("p")
1012            .start_named("Started", Start::key("data.case_id"))
1013            .timer("pause", Timer::after("15m"))
1014            .decide(
1015                "big",
1016                Decide::when("case.line_total > 10 and case.kind == 'big_one'", "later")
1017                    .or_when("not case.is_vip", "done"),
1018            )
1019            .timer("later", Timer::at("case.due_at"))
1020            .query_named(
1021                "check",
1022                "Check",
1023                Ask::new()
1024                    .answer("check_status")
1025                    .path("ok", "done")
1026                    .into_field("check_result")
1027                    .otherwise("done"),
1028            )
1029            .end("done");
1030        let model = p.model().unwrap();
1031        let steps = &model["steps"];
1032        assert_eq!(
1033            model["start"],
1034            json!({ "on": "ops.Started", "key": "data.caseId" })
1035        );
1036        assert_eq!(steps[0]["afterMs"], 900_000);
1037        assert_eq!(steps[0]["next"], "big");
1038        assert_eq!(
1039            steps[1]["when"],
1040            json!([
1041                { "if": "case.lineTotal > 10 and case.kind == 'big_one'", "next": "later" },
1042                { "if": "not case.isVip", "next": "done" },
1043            ])
1044        );
1045        // Without otherwise, a decision goes on with the next step written.
1046        assert_eq!(steps[1]["otherwise"], "later");
1047        assert_eq!(steps[2]["at"], "case.dueAt");
1048        assert_eq!(steps[2]["next"], "check");
1049        assert_eq!(
1050            steps[3],
1051            json!({
1052                "name": "check", "kind": "query", "query": "ops.Check", "answer": "checkStatus",
1053                "paths": [{ "value": "ok", "next": "done" }], "into": "checkResult", "otherwise": "done",
1054            })
1055        );
1056        assert_eq!(steps[4], json!({ "name": "done", "kind": "end" }));
1057    }
1058
1059    fn refused(p: &Process, needle: &str) {
1060        match p.model() {
1061            Err(Error::Config(m)) => assert!(m.contains(needle), "{m}"),
1062            other => panic!("expected an error with {needle:?}, got {other:?}"),
1063        }
1064    }
1065
1066    fn started(name: &str) -> Process {
1067        domain("ops")
1068            .process(name)
1069            .start_named("Started", Start::key("aggregate_id"))
1070    }
1071
1072    #[test]
1073    fn a_process_without_a_start_or_steps_is_refused() {
1074        refused(
1075            &domain("ops").process("p").end("done"),
1076            "process ops.p: no start",
1077        );
1078        refused(&started("p"), "process ops.p: no steps");
1079    }
1080
1081    #[test]
1082    fn a_step_name_is_valid_and_unique() {
1083        refused(
1084            &started("p").end("done").end("done"),
1085            "process ops.p, step done: the name is taken",
1086        );
1087        refused(&started("p").end("not ok"), "step not ok: a step name is");
1088    }
1089
1090    #[test]
1091    fn every_target_names_a_step() {
1092        refused(
1093            &started("p")
1094                .command_named("a", "order.Do", Send::aggregate("case.id").next("nowhere"))
1095                .end("done"),
1096            "process ops.p, step a: next names no step: nowhere",
1097        );
1098        refused(
1099            &started("p")
1100                .command_named(
1101                    "a",
1102                    "order.Do",
1103                    Send::aggregate("case.id").rejected("x", "gone"),
1104                )
1105                .end("done"),
1106            "step a: rejected names no step: gone",
1107        );
1108        refused(
1109            &started("p")
1110                .wait_named("w", "Done", Wait::key("aggregate_id").timeout("1d", "gone"))
1111                .end("done"),
1112            "step w: timeout names no step: gone",
1113        );
1114        refused(
1115            &started("p")
1116                .decide("d", Decide::when("case.x", "gone"))
1117                .end("done"),
1118            "step d: when names no step: gone",
1119        );
1120        refused(
1121            &started("p")
1122                .query_named("q", "Q", Ask::new().path(1, "gone"))
1123                .end("done"),
1124            "step q: path names no step: gone",
1125        );
1126    }
1127
1128    #[test]
1129    fn a_step_other_than_end_needs_a_successor() {
1130        refused(
1131            &started("p").timer("t", Timer::after("1s")),
1132            "process ops.p, step t: no step after it",
1133        );
1134        refused(
1135            &started("p").decide("d", Decide::when("case.x", "d")),
1136            "step d: no step after it",
1137        );
1138        refused(
1139            &started("p").query_named("q", "Q", Ask::new()).end("done"),
1140            "step q: a query step needs paths",
1141        );
1142    }
1143
1144    #[test]
1145    fn durations_and_references_are_checked() {
1146        for bad in ["3", "d", "3w", "-1d", "0s", "1.5h", ""] {
1147            refused(
1148                &started("p").timer("t", Timer::after(bad)).end("done"),
1149                "step t:",
1150            );
1151        }
1152        assert_eq!(millis("30s"), Ok(30_000));
1153        assert_eq!(millis("3d"), Ok(259_200_000));
1154        refused(
1155            &started("p")
1156                .command_named("a", "order.Do", Send::aggregate("data.id"))
1157                .end("done"),
1158            "step a: \"data.id\" is not a reference here (case.<field>)",
1159        );
1160        refused(
1161            &domain("ops")
1162                .process("p")
1163                .start_named("Started", Start::key("case.id"))
1164                .end("done"),
1165            "process ops.p: start: \"case.id\" is not a reference",
1166        );
1167        refused(
1168            &started("p")
1169                .command_named("a", "order.Do", Send::aggregate("case."))
1170                .end("done"),
1171            "step a:",
1172        );
1173    }
1174}