Skip to main content

domainforge_core/projection/domain/
ir.rs

1//! Language-neutral Domain IR encoding the SEA → DDD/CQRS mapping.
2//!
3//! Every renderer ([`crate::projection::domain`]) consumes exactly this IR;
4//! no renderer re-derives a name or reads the [`crate::graph::Graph`]. The
5//! mapping is normative (see the plan + `docs/how-tos/project-domain-code.md`):
6//!
7//! | SEA element        | Domain construct                                                |
8//! | ------------------ | --------------------------------------------------------------- |
9//! | `@namespace`       | Package name (`slug` / `pascal`)                                |
10//! | `Entity`           | DDD Entity (id + name; fields from `instance of`)               |
11//! | `Resource`         | Aggregate root + Repository port + Quantity unit                |
12//! | `Flow` (default)   | Command + Event + aggregate method                              |
13//! | `Flow @cqrs cmd`   | Command + aggregate method (no event)                           |
14//! | `Flow @cqrs event` | Event only (no command, no method)                              |
15//! | `Policy`           | Domain error `<Pascal>Violation` + `check_<slug>()` guard       |
16//! | `Metric`           | Query `get_<slug>()` on `<Ns>ReadModel`                         |
17//! | `Pattern`          | Value object validating against the regex                       |
18//! | `Role`             | Enum `Role { <Pascal>, ... }`; commands carry `issued_by: Role` |
19//! | `Relation`         | Doc-comment line on the Role enum                               |
20
21use crate::graph::Graph;
22use crate::projection::flows::ResolvedFlow;
23use crate::projection::flows::{collect_flows, model_namespace};
24use crate::projection::ids::{pascal, slug, NameRegistrar};
25use std::collections::BTreeMap;
26
27/// One aggregate method minted from a flow (the CQRS write path:
28/// command → aggregate → event).
29#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
30pub struct GuardCheck {
31    /// `check_<slug(policy)>` — the no-op guard hook the method calls.
32    pub check_method: String,
33    /// `<Pascal>Violation` — the error the guard may raise.
34    pub error: String,
35}
36
37/// A method on an aggregate root, minted from one flow.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct MethodIr {
40    /// `transfer_to_<slug(to)>`.
41    pub name: String,
42    /// Command this method dispatches (`None` for event-only flows).
43    pub command: Option<String>,
44    /// Event this method returns (`None` for command-only flows).
45    pub event: Option<String>,
46    pub from_entity: String,
47    pub to_entity: String,
48    pub quantity: String,
49    /// Every policy guards every method in v1 (no-op bodies).
50    pub guard_checks: Vec<GuardCheck>,
51}
52
53/// An aggregate root minted from a resource.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct AggregateIr {
56    /// `<Pascal(resource)>` (the aggregate root type name).
57    pub name: String,
58    pub resource_name: String,
59    /// Unit symbol carried by the shared Quantity value object.
60    pub unit: String,
61    pub methods: Vec<MethodIr>,
62}
63
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub struct EntityIr {
66    /// `<Pascal(entity)>`.
67    pub name: String,
68    /// `(field, "str")` — v1 is string-typed; fields gathered from `instance of`.
69    pub fields: Vec<(String, String)>,
70}
71
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct CommandIr {
74    /// `Transfer<Resource>From<From>To<To>`.
75    pub name: String,
76    pub aggregate: String,
77    pub from_entity: String,
78    pub to_entity: String,
79    pub quantity: String,
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub struct EventIr {
84    /// `<Resource>TransferredFrom<From>To<To>`.
85    pub name: String,
86    pub aggregate: String,
87    pub from_entity: String,
88    pub to_entity: String,
89    pub quantity: String,
90}
91
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub struct ErrorIr {
94    /// `<Pascal(policy)>Violation`.
95    pub name: String,
96    pub policy_name: String,
97    /// `check_<slug(policy)>` — the no-op guard hook.
98    pub check_method: String,
99    pub rationale: Option<String>,
100}
101
102#[derive(Clone, Debug, PartialEq, Eq)]
103pub struct QueryIr {
104    /// `get_<slug(metric)>`.
105    pub name: String,
106    pub metric_name: String,
107    pub unit: Option<String>,
108    pub threshold: Option<String>,
109}
110
111#[derive(Clone, Debug, PartialEq, Eq)]
112pub struct ValueObjectIr {
113    /// `<Pascal(pattern)>`.
114    pub name: String,
115    pub regex: String,
116    /// `Invalid<Pascal(pattern)>`.
117    pub error_name: String,
118}
119
120#[derive(Clone, Debug, PartialEq, Eq)]
121pub struct InstanceIr {
122    pub name: String,
123    /// `<Pascal(entity_type)>`.
124    pub entity: String,
125    /// `(field, literal-value-as-string)`.
126    pub fields: Vec<(String, String)>,
127}
128
129/// The complete language-neutral domain model. All names are pre-sanitized
130/// through [`NameRegistrar`]; all collections are sorted for determinism.
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct DomainIr {
133    pub namespace: String,
134    /// `slug(namespace)` — package/module directory fragment.
135    pub package_slug: String,
136    /// `pascal(namespace)` — `<Ns>ReadModel`, Python class prefixes.
137    pub package_pascal: String,
138    pub entities: Vec<EntityIr>,
139    pub aggregates: Vec<AggregateIr>,
140    pub commands: Vec<CommandIr>,
141    pub events: Vec<EventIr>,
142    pub errors: Vec<ErrorIr>,
143    pub queries: Vec<QueryIr>,
144    pub value_objects: Vec<ValueObjectIr>,
145    /// `<Pascal(role)>` variants.
146    pub roles: Vec<String>,
147    /// `subject —predicate→ object` doc-comment lines.
148    pub relations_doc: Vec<String>,
149    pub instances: Vec<InstanceIr>,
150}
151
152/// Read the fixture file relative to the crate root (CARGO_MANIFEST_DIR).
153#[cfg(test)]
154fn fixture_source() -> String {
155    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
156        .join("../fixtures/projection_cell/basic/model.sea");
157    std::fs::read_to_string(&path)
158        .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()))
159}
160
161impl DomainIr {
162    /// Build the IR from a graph. The single place DDD semantics are decided.
163    pub fn from_graph(graph: &Graph) -> Result<DomainIr, String> {
164        let namespace = model_namespace(graph)?;
165        let package_slug = slug(&namespace);
166        let package_pascal = pascal(&namespace);
167        let flows = collect_flows(graph)?;
168        let mut reg = NameRegistrar::new();
169
170        // Roles (enum variants).
171        let mut roles: Vec<String> = graph
172            .all_roles()
173            .iter()
174            .map(|r| reg.register("ident", &pascal(r.name())))
175            .collect();
176        roles.sort();
177
178        // Role ConceptId -> display name, for relation doc-comments.
179        let role_name: BTreeMap<String, String> = graph
180            .all_roles()
181            .iter()
182            .map(|r| (r.id().to_string(), r.name().to_string()))
183            .collect();
184        let mut relations_doc: Vec<String> = graph
185            .all_relations()
186            .iter()
187            .map(|rel| {
188                let subj = role_name
189                    .get(&rel.subject_role().to_string())
190                    .cloned()
191                    .unwrap_or_else(|| rel.subject_role().to_string());
192                let obj = role_name
193                    .get(&rel.object_role().to_string())
194                    .cloned()
195                    .unwrap_or_else(|| rel.object_role().to_string());
196                let pred = rel.predicate();
197                format!("{subj} \u{2014}{pred}\u{2192} {obj}")
198            })
199            .collect();
200        relations_doc.sort();
201
202        // Errors from policies (each policy -> one domain error + one guard hook).
203        let mut errors: Vec<ErrorIr> = graph
204            .all_policies()
205            .iter()
206            .map(|p| {
207                let name = reg.register("ident", &format!("{}Violation", pascal(&p.name)));
208                ErrorIr {
209                    name,
210                    policy_name: p.name.clone(),
211                    check_method: format!("check_{}", slug(&p.name)),
212                    rationale: p.rationale.clone(),
213                }
214            })
215            .collect();
216        errors.sort_by(|a, b| a.name.cmp(&b.name));
217        let guard_checks: Vec<GuardCheck> = errors
218            .iter()
219            .map(|e| GuardCheck {
220                check_method: e.check_method.clone(),
221                error: e.name.clone(),
222            })
223            .collect();
224
225        // Value objects from patterns.
226        let mut value_objects: Vec<ValueObjectIr> = graph
227            .all_patterns()
228            .iter()
229            .map(|p| {
230                let pname = pascal(p.name());
231                ValueObjectIr {
232                    name: reg.register("ident", &pname),
233                    regex: p.regex().to_string(),
234                    error_name: format!("Invalid{pname}"),
235                }
236            })
237            .collect();
238        value_objects.sort_by(|a, b| a.name.cmp(&b.name));
239
240        // Queries from metrics.
241        let mut queries: Vec<QueryIr> = graph
242            .all_metrics()
243            .iter()
244            .map(|m| QueryIr {
245                name: format!("get_{}", slug(&m.name)),
246                metric_name: m.name.clone(),
247                unit: m.unit.clone(),
248                threshold: m.threshold.map(|d| d.to_string()),
249            })
250            .collect();
251        queries.sort_by(|a, b| a.name.cmp(&b.name));
252
253        // Entities (fields gathered from `instance of <entity>`).
254        let mut entity_fields: BTreeMap<String, BTreeMap<String, ()>> = BTreeMap::new();
255        for inst in graph.all_entity_instances() {
256            let entry = entity_fields
257                .entry(inst.entity_type().to_string())
258                .or_default();
259            for k in inst.fields().keys() {
260                // `id` and `name` are the entity's built-in identity fields.
261                if k != "id" && k != "name" {
262                    entry.insert(k.clone(), ());
263                }
264            }
265        }
266        let mut entities: Vec<EntityIr> = graph
267            .all_entities()
268            .iter()
269            .map(|e| {
270                let fields: Vec<(String, String)> = entity_fields
271                    .get(e.name())
272                    .map(|m| {
273                        let mut v: Vec<(String, String)> =
274                            m.keys().map(|k| (k.clone(), "str".to_string())).collect();
275                        v.sort();
276                        v
277                    })
278                    .unwrap_or_default();
279                EntityIr {
280                    name: reg.register("ident", &pascal(e.name())),
281                    fields,
282                }
283            })
284            .collect();
285        entities.sort_by(|a, b| a.name.cmp(&b.name));
286
287        // Aggregates from resources; methods from the resource's flows.
288        let mut aggregates: Vec<AggregateIr> = Vec::new();
289        for resource in graph.all_resources() {
290            let agg_name = reg.register("ident", &pascal(resource.name()));
291            let mut methods: Vec<MethodIr> = flows
292                .iter()
293                .filter(|f| f.resource == resource.name() && cqrs_kind(f) != CqrsKind::EventOnly)
294                .map(|f| method_from_flow(f, &guard_checks, &mut reg))
295                .collect();
296            methods.sort_by(|a, b| a.name.cmp(&b.name));
297            aggregates.push(AggregateIr {
298                name: agg_name,
299                resource_name: resource.name().to_string(),
300                unit: resource.unit_symbol().to_string(),
301                methods,
302            });
303        }
304        aggregates.sort_by(|a, b| a.name.cmp(&b.name));
305
306        // Commands + events from flows (driven by the @cqrs kind switch).
307        let mut commands: Vec<CommandIr> = Vec::new();
308        let mut events: Vec<EventIr> = Vec::new();
309        for f in &flows {
310            let kind = cqrs_kind(f);
311            let aggregate = pascal(&f.resource);
312            let from_entity = pascal(&f.from);
313            let to_entity = pascal(&f.to);
314            if kind != CqrsKind::EventOnly {
315                commands.push(CommandIr {
316                    name: reg.register(
317                        "ident",
318                        &format!("Transfer{aggregate}From{from_entity}To{to_entity}"),
319                    ),
320                    aggregate: aggregate.clone(),
321                    from_entity: from_entity.clone(),
322                    to_entity: to_entity.clone(),
323                    quantity: f.quantity.clone(),
324                });
325            }
326            if kind != CqrsKind::CommandOnly {
327                events.push(EventIr {
328                    name: reg.register(
329                        "ident",
330                        &format!("{aggregate}TransferredFrom{from_entity}To{to_entity}"),
331                    ),
332                    aggregate,
333                    from_entity,
334                    to_entity,
335                    quantity: f.quantity.clone(),
336                });
337            }
338        }
339        commands.sort_by(|a, b| a.name.cmp(&b.name));
340        events.sort_by(|a, b| a.name.cmp(&b.name));
341
342        // Instances (example constructions for smoke tests).
343        let mut instances: Vec<InstanceIr> = graph
344            .all_entity_instances()
345            .iter()
346            .map(|inst| {
347                let mut fields: Vec<(String, String)> = inst
348                    .fields()
349                    .iter()
350                    .map(|(k, v)| (k.clone(), value_to_string(v)))
351                    .collect();
352                fields.sort();
353                InstanceIr {
354                    name: inst.name().to_string(),
355                    entity: pascal(inst.entity_type()),
356                    fields,
357                }
358            })
359            .collect();
360        instances.sort_by(|a, b| a.name.cmp(&b.name));
361
362        Ok(DomainIr {
363            namespace,
364            package_slug,
365            package_pascal,
366            entities,
367            aggregates,
368            commands,
369            events,
370            errors,
371            queries,
372            value_objects,
373            roles,
374            relations_doc,
375            instances,
376        })
377    }
378}
379
380#[derive(PartialEq, Eq)]
381enum CqrsKind {
382    /// Default (no annotation, or unknown kind): command + event + method.
383    CommandAndEvent,
384    /// `@cqrs { "kind": "command" }`: command + method, no event.
385    CommandOnly,
386    /// `@cqrs { "kind": "event" }`: event only, no command, no method.
387    EventOnly,
388}
389
390fn cqrs_kind(flow: &ResolvedFlow) -> CqrsKind {
391    match flow
392        .annotations
393        .get("cqrs")
394        .and_then(|v| v.get("kind"))
395        .and_then(|v| v.as_str())
396    {
397        Some("command") => CqrsKind::CommandOnly,
398        Some("event") => CqrsKind::EventOnly,
399        _ => CqrsKind::CommandAndEvent,
400    }
401}
402
403fn method_from_flow(
404    flow: &ResolvedFlow,
405    guard_checks: &[GuardCheck],
406    reg: &mut NameRegistrar,
407) -> MethodIr {
408    let kind = cqrs_kind(flow);
409    let from_entity = pascal(&flow.from);
410    let to_entity = pascal(&flow.to);
411    let resource = pascal(&flow.resource);
412    let command = if kind != CqrsKind::EventOnly {
413        Some(reg.register(
414            "ident",
415            &format!("Transfer{resource}From{from_entity}To{to_entity}"),
416        ))
417    } else {
418        None
419    };
420    let event = if kind != CqrsKind::CommandOnly {
421        Some(reg.register(
422            "ident",
423            &format!("{resource}TransferredFrom{from_entity}To{to_entity}"),
424        ))
425    } else {
426        None
427    };
428    MethodIr {
429        name: reg.register("ident", &format!("transfer_to_{}", slug(&flow.to))),
430        command,
431        event,
432        from_entity,
433        to_entity,
434        quantity: flow.quantity.clone(),
435        guard_checks: guard_checks.to_vec(),
436    }
437}
438
439/// Render a JSON instance value as a plain string literal (v1 is string-typed).
440fn value_to_string(v: &serde_json::Value) -> String {
441    match v {
442        serde_json::Value::String(s) => s.clone(),
443        other => other.to_string(),
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450    use crate::parser::parse_to_graph;
451
452    fn ir_from_fixture() -> DomainIr {
453        let g = parse_to_graph(&fixture_source()).expect("fixture parses");
454        DomainIr::from_graph(&g).expect("IR builds")
455    }
456
457    #[test]
458    fn fixture_namespace_and_package() {
459        let ir = ir_from_fixture();
460        assert_eq!(ir.namespace, "procurement");
461        assert_eq!(ir.package_slug, "procurement");
462        assert_eq!(ir.package_pascal, "Procurement");
463    }
464
465    #[test]
466    fn fixture_entities() {
467        let ir = ir_from_fixture();
468        let names: Vec<&str> = ir.entities.iter().map(|e| e.name.as_str()).collect();
469        assert_eq!(names, ["Approver", "Buyer", "Supplier"]);
470        // Fields come from the `instance acme_supplier of "Supplier"`; `name` is the
471        // entity's built-in identity field, so only `region` is added here.
472        let supplier = ir.entities.iter().find(|e| e.name == "Supplier").unwrap();
473        assert_eq!(supplier.fields, [("region".to_string(), "str".to_string())]);
474    }
475
476    #[test]
477    fn fixture_aggregates() {
478        let ir = ir_from_fixture();
479        let names: Vec<&str> = ir.aggregates.iter().map(|a| a.name.as_str()).collect();
480        assert_eq!(names, ["Payment", "PurchaseOrder"]);
481        let po = ir
482            .aggregates
483            .iter()
484            .find(|a| a.name == "PurchaseOrder")
485            .unwrap();
486        assert_eq!(po.unit, "units");
487        assert_eq!(po.methods.len(), 1);
488        assert_eq!(po.methods[0].name, "transfer_to_supplier");
489    }
490
491    #[test]
492    fn fixture_commands_and_events_exact_names() {
493        let ir = ir_from_fixture();
494        let cmds: Vec<&str> = ir.commands.iter().map(|c| c.name.as_str()).collect();
495        let evs: Vec<&str> = ir.events.iter().map(|e| e.name.as_str()).collect();
496        assert_eq!(
497            cmds,
498            [
499                "TransferPaymentFromBuyerToSupplier",
500                "TransferPurchaseOrderFromBuyerToSupplier",
501            ]
502        );
503        assert_eq!(
504            evs,
505            [
506                "PaymentTransferredFromBuyerToSupplier",
507                "PurchaseOrderTransferredFromBuyerToSupplier",
508            ]
509        );
510    }
511
512    #[test]
513    fn fixture_error_with_rationale() {
514        let ir = ir_from_fixture();
515        assert_eq!(ir.errors.len(), 1);
516        let e = &ir.errors[0];
517        assert_eq!(e.name, "RequireApprovalViolation");
518        assert_eq!(e.policy_name, "require_approval");
519        assert_eq!(e.check_method, "check_require_approval");
520        assert_eq!(
521            e.rationale.as_deref(),
522            Some("every order must be approved before payment")
523        );
524        // Every method guards against this error.
525        let po = ir
526            .aggregates
527            .iter()
528            .find(|a| a.name == "PurchaseOrder")
529            .unwrap();
530        assert!(po.methods.iter().all(|m| m
531            .guard_checks
532            .iter()
533            .any(|g| g.error == "RequireApprovalViolation"
534                && g.check_method == "check_require_approval")));
535    }
536
537    #[test]
538    fn fixture_query() {
539        let ir = ir_from_fixture();
540        assert_eq!(ir.queries.len(), 1);
541        let q = &ir.queries[0];
542        assert_eq!(q.name, "get_order_count");
543        assert_eq!(q.metric_name, "order_count");
544        assert_eq!(q.unit.as_deref(), Some("orders"));
545        assert_eq!(q.threshold.as_deref(), Some("100"));
546    }
547
548    #[test]
549    fn fixture_value_object() {
550        let ir = ir_from_fixture();
551        assert_eq!(ir.value_objects.len(), 1);
552        let vo = &ir.value_objects[0];
553        assert_eq!(vo.name, "OrderNumber");
554        assert_eq!(vo.regex, "^[A-Z]{3}-[0-9]+$");
555        assert_eq!(vo.error_name, "InvalidOrderNumber");
556    }
557
558    #[test]
559    fn fixture_roles_and_relation() {
560        let ir = ir_from_fixture();
561        assert_eq!(ir.roles, ["Authorizer", "Requester"]);
562        assert_eq!(
563            ir.relations_doc,
564            ["Requester \u{2014}orders\u{2192} Authorizer"]
565        );
566    }
567
568    #[test]
569    fn fixture_instance() {
570        let ir = ir_from_fixture();
571        assert_eq!(ir.instances.len(), 1);
572        let inst = &ir.instances[0];
573        assert_eq!(inst.name, "acme_supplier");
574        assert_eq!(inst.entity, "Supplier");
575        assert_eq!(
576            inst.fields,
577            [
578                ("name".to_string(), "Acme Corp".to_string()),
579                ("region".to_string(), "NA".to_string())
580            ]
581        );
582    }
583
584    #[test]
585    fn fixture_deterministic() {
586        assert_eq!(ir_from_fixture(), ir_from_fixture());
587    }
588
589    // --- @cqrs kind switch (inline sources; the fixture has no annotations) ---
590
591    #[test]
592    fn cqrs_command_kind_emits_command_only() {
593        let src = r#"
594@namespace "p"
595Entity "A" in p
596Entity "B" in p
597Resource "R" units in p
598Flow "R" @cqrs { "kind": "command" } from "A" to "B" quantity 1
599"#;
600        let ir = DomainIr::from_graph(&parse_to_graph(src).unwrap()).unwrap();
601        assert_eq!(ir.commands.len(), 1);
602        assert!(ir.events.is_empty(), "command-kind must emit no event");
603    }
604
605    #[test]
606    fn cqrs_event_kind_emits_event_only() {
607        let src = r#"
608@namespace "p"
609Entity "A" in p
610Entity "B" in p
611Resource "R" units in p
612Flow "R" @cqrs { "kind": "event" } from "A" to "B" quantity 1
613"#;
614        let ir = DomainIr::from_graph(&parse_to_graph(src).unwrap()).unwrap();
615        assert!(ir.commands.is_empty(), "event-kind must emit no command");
616        assert_eq!(ir.events.len(), 1);
617        // Event-only flow mints no aggregate method.
618        let agg = &ir.aggregates[0];
619        assert!(agg.methods.is_empty(), "event-kind must mint no method");
620    }
621}