made-core 0.3.0

Domain core of MADE: entities, value objects, events, ports. No IO.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
use crate::entities::CeremonyDefinition;

use super::{
    CeremonyChangeImpact, CeremonyChangeKind, CeremonyDefinitionChange, CeremonyInputDefinition,
    CeremonyValidationLocus, InputRequirement, StateId, TransitionTrigger,
};

fn is_required(input: &CeremonyInputDefinition) -> bool {
    matches!(input.requirement(), InputRequirement::Required)
}

/// Everything that differs between two definitions of one ceremony.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CeremonyDefinitionDiff {
    changes: Vec<CeremonyDefinitionChange>,
}

impl CeremonyDefinitionDiff {
    /// Compare two definitions, earlier first.
    ///
    /// The two need not be versions of the same ceremony: comparing
    /// unrelated documents is a strange thing to ask for but not a
    /// wrong one, and refusing it would mean deciding on the caller's
    /// behalf what counts as related.
    #[must_use]
    pub fn between(before: &CeremonyDefinition, after: &CeremonyDefinition) -> Self {
        let mut changes = Vec::new();
        diff_states(before, after, &mut changes);
        diff_transitions(before, after, &mut changes);
        diff_steps(before, after, &mut changes);
        diff_guards(before, after, &mut changes);
        diff_roles(before, after, &mut changes);
        diff_shape(before, after, &mut changes);
        Self { changes }
    }

    #[must_use]
    pub fn changes(&self) -> &[CeremonyDefinitionChange] {
        &self.changes
    }

    #[must_use]
    pub fn is_identical(&self) -> bool {
        self.changes.is_empty()
    }

    /// Whether any single change could strand a running session. One is
    /// enough: a version that can strand a session is not one to adopt
    /// mid-flight, however much else about it is harmless.
    #[must_use]
    pub fn strands_running_sessions(&self) -> bool {
        self.changes.iter().any(|change| change.impact().strands())
    }

    #[must_use]
    pub fn strand_count(&self) -> usize {
        self.changes
            .iter()
            .filter(|change| change.impact().strands())
            .count()
    }
}

fn record(
    changes: &mut Vec<CeremonyDefinitionChange>,
    kind: CeremonyChangeKind,
    locus: CeremonyValidationLocus,
    impact: CeremonyChangeImpact,
    detail: &'static str,
) {
    changes.push(CeremonyDefinitionChange::new(kind, locus, impact, detail));
}

fn diff_states(
    before: &CeremonyDefinition,
    after: &CeremonyDefinition,
    changes: &mut Vec<CeremonyDefinitionChange>,
) {
    for (id, state) in before.states() {
        match after.states().get(id) {
            // A session sitting in a state that no longer exists has
            // nowhere to be.
            None => record(
                changes,
                CeremonyChangeKind::Removed,
                CeremonyValidationLocus::state(id.clone()),
                CeremonyChangeImpact::Strands,
                "a session in this state would have nowhere to be",
            ),
            Some(now) if now.kind() != state.kind() => record(
                changes,
                CeremonyChangeKind::Altered,
                CeremonyValidationLocus::state(id.clone()),
                // Becoming terminal ends sessions early; ceasing to be
                // terminal leaves finished ones unfinished.
                CeremonyChangeImpact::Strands,
                "whether the session may start or finish here",
            ),
            Some(_) => {}
        }
    }
    for id in after.states().keys() {
        if !before.states().contains_key(id) {
            record(
                changes,
                CeremonyChangeKind::Added,
                CeremonyValidationLocus::state(id.clone()),
                CeremonyChangeImpact::Carries,
                "a state no running session is in yet",
            );
        }
    }
}

fn transition_key(from: &StateId, trigger: &TransitionTrigger) -> (String, String) {
    (from.as_str().to_owned(), trigger.as_str().to_owned())
}

fn diff_transitions(
    before: &CeremonyDefinition,
    after: &CeremonyDefinition,
    changes: &mut Vec<CeremonyDefinitionChange>,
) {
    for old in before.transitions() {
        let key = transition_key(old.from(), old.trigger());
        let now = after
            .transitions()
            .iter()
            .find(|candidate| transition_key(candidate.from(), candidate.trigger()) == key);
        let locus = CeremonyValidationLocus::transition(old.from().clone(), old.trigger().clone());
        match now {
            // A session may have been counting on exactly this move.
            None => record(
                changes,
                CeremonyChangeKind::Removed,
                locus,
                CeremonyChangeImpact::Strands,
                "a way out of the state it leaves",
            ),
            Some(now) if now.to() != old.to() => record(
                changes,
                CeremonyChangeKind::Altered,
                locus,
                CeremonyChangeImpact::Strands,
                "where it leads",
            ),
            Some(now) if now.required_guards() != old.required_guards() => {
                // Guards added can block a session that was about to
                // move; guards dropped only ever let it through.
                let impact = if now.required_guards().is_superset(old.required_guards()) {
                    CeremonyChangeImpact::Strands
                } else {
                    CeremonyChangeImpact::Carries
                };
                record(
                    changes,
                    CeremonyChangeKind::Altered,
                    locus,
                    impact,
                    "what has to hold before it can fire",
                );
            }
            Some(_) => {}
        }
    }
    for now in after.transitions() {
        let key = transition_key(now.from(), now.trigger());
        if !before
            .transitions()
            .iter()
            .any(|candidate| transition_key(candidate.from(), candidate.trigger()) == key)
        {
            record(
                changes,
                CeremonyChangeKind::Added,
                CeremonyValidationLocus::transition(now.from().clone(), now.trigger().clone()),
                CeremonyChangeImpact::Carries,
                "another way out of a state",
            );
        }
    }
}

fn diff_steps(
    before: &CeremonyDefinition,
    after: &CeremonyDefinition,
    changes: &mut Vec<CeremonyDefinitionChange>,
) {
    for (id, old) in before.steps() {
        let locus = CeremonyValidationLocus::step(id.clone());
        let Some(now) = after.steps().get(id) else {
            // A guard that waits on this step will wait forever, and a
            // session that has not run it never will.
            record(
                changes,
                CeremonyChangeKind::Removed,
                locus,
                CeremonyChangeImpact::Strands,
                "work a session may not have done yet",
            );
            continue;
        };
        if now.state_id() != old.state_id() {
            record(
                changes,
                CeremonyChangeKind::Altered,
                locus.clone(),
                CeremonyChangeImpact::Strands,
                "the state it belongs to",
            );
        }
        if now.handler_kind() != old.handler_kind() {
            record(
                changes,
                CeremonyChangeKind::Altered,
                locus.clone(),
                CeremonyChangeImpact::Carries,
                "who does the work",
            );
        }
        if now.handler_config() != old.handler_config() {
            record(
                changes,
                CeremonyChangeKind::Altered,
                locus.clone(),
                CeremonyChangeImpact::Carries,
                "how the work is asked for",
            );
        }
        if now.retry_policy() != old.retry_policy()
            || now.timeout() != old.timeout()
            || now.repeat_policy() != old.repeat_policy()
        {
            record(
                changes,
                CeremonyChangeKind::Altered,
                locus,
                CeremonyChangeImpact::Carries,
                "how long it may take, how often it may be retried, or when repetition stops",
            );
        }
    }
    for id in after.steps().keys() {
        if !before.steps().contains_key(id) {
            // Added work is not harmless: a session already past this
            // step's state will never run it, and a guard waiting on
            // it would never be satisfied.
            record(
                changes,
                CeremonyChangeKind::Added,
                CeremonyValidationLocus::step(id.clone()),
                CeremonyChangeImpact::Strands,
                "work a session may already have moved past",
            );
        }
    }
}

fn diff_guards(
    before: &CeremonyDefinition,
    after: &CeremonyDefinition,
    changes: &mut Vec<CeremonyDefinitionChange>,
) {
    for (name, old) in before.guards() {
        let locus = CeremonyValidationLocus::guard(name.clone());
        match after.guards().get(name) {
            None => record(
                changes,
                CeremonyChangeKind::Removed,
                locus,
                CeremonyChangeImpact::Carries,
                "a condition no longer asked for",
            ),
            // An automated guard turned human now waits on a person who
            // was never asked; a human guard turned automated discards
            // an approval already given.
            Some(now) if now.condition() != old.condition() => record(
                changes,
                CeremonyChangeKind::Altered,
                locus,
                CeremonyChangeImpact::Strands,
                "what satisfies it",
            ),
            Some(_) => {}
        }
    }
    for name in after.guards().keys() {
        if !before.guards().contains_key(name) {
            record(
                changes,
                CeremonyChangeKind::Added,
                CeremonyValidationLocus::guard(name.clone()),
                CeremonyChangeImpact::Carries,
                "a condition that only matters where a transition asks for it",
            );
        }
    }
}

fn diff_roles(
    before: &CeremonyDefinition,
    after: &CeremonyDefinition,
    changes: &mut Vec<CeremonyDefinitionChange>,
) {
    for (id, old) in before.roles() {
        let locus = CeremonyValidationLocus::role(id.clone());
        match after.roles().get(id) {
            None => record(
                changes,
                CeremonyChangeKind::Removed,
                locus,
                CeremonyChangeImpact::Strands,
                "whoever was acting as this role can no longer act",
            ),
            Some(now) if now.allowed_actions() != old.allowed_actions() => {
                // Only narrowing takes something away.
                let impact = if old.allowed_actions().is_subset(now.allowed_actions()) {
                    CeremonyChangeImpact::Carries
                } else {
                    CeremonyChangeImpact::Strands
                };
                record(
                    changes,
                    CeremonyChangeKind::Altered,
                    locus,
                    impact,
                    "what this role is allowed to do",
                );
            }
            Some(_) => {}
        }
    }
    for id in after.roles().keys() {
        if !before.roles().contains_key(id) {
            record(
                changes,
                CeremonyChangeKind::Added,
                CeremonyValidationLocus::role(id.clone()),
                CeremonyChangeImpact::Carries,
                "another role at the table",
            );
        }
    }
}

/// Everything that is not the graph: what the ceremony says it needs
/// and what it says it produces.
fn diff_shape(
    before: &CeremonyDefinition,
    after: &CeremonyDefinition,
    changes: &mut Vec<CeremonyDefinitionChange>,
) {
    for name in before.inputs().keys() {
        if !after.inputs().contains_key(name) {
            record(
                changes,
                CeremonyChangeKind::Removed,
                CeremonyValidationLocus::input(name.clone()),
                CeremonyChangeImpact::Carries,
                "an input no longer asked for",
            );
        }
    }
    for (name, now) in after.inputs() {
        match before.inputs().get(name) {
            None => record(
                changes,
                CeremonyChangeKind::Added,
                CeremonyValidationLocus::input(name.clone()),
                // A session started without it cannot go back and
                // supply it.
                if is_required(now) {
                    CeremonyChangeImpact::Strands
                } else {
                    CeremonyChangeImpact::Carries
                },
                "an input the ceremony now asks for",
            ),
            Some(was) if is_required(was) != is_required(now) => record(
                changes,
                CeremonyChangeKind::Altered,
                CeremonyValidationLocus::input(name.clone()),
                if is_required(now) {
                    CeremonyChangeImpact::Strands
                } else {
                    CeremonyChangeImpact::Carries
                },
                "whether it has to be supplied",
            ),
            Some(_) => {}
        }
    }
    for name in before.outputs().keys() {
        if !after.outputs().contains_key(name) {
            record(
                changes,
                CeremonyChangeKind::Removed,
                CeremonyValidationLocus::output(name.clone()),
                CeremonyChangeImpact::Carries,
                "an output no longer produced",
            );
        }
    }
    for name in after.outputs().keys() {
        if !before.outputs().contains_key(name) {
            record(
                changes,
                CeremonyChangeKind::Added,
                CeremonyValidationLocus::output(name.clone()),
                CeremonyChangeImpact::Carries,
                "an output not produced before",
            );
        }
    }
    if before.description() != after.description() {
        record(
            changes,
            CeremonyChangeKind::Altered,
            CeremonyValidationLocus::Definition,
            CeremonyChangeImpact::Carries,
            "what the ceremony says it is for",
        );
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use super::*;
    use crate::value_objects::{
        CeremonyGuard, CeremonyName, CeremonyRole, CeremonyState, CeremonyStep, CeremonyTransition,
        CeremonyVersion, GuardCondition, GuardName, RepeatUntilCondition, RetryPolicy, RoleAction,
        RoleId, StepHandlerConfig, StepHandlerKind, StepId, StepIteration, StepOutputField,
        StepRepeatPolicy,
    };

    fn state(id: &str) -> StateId {
        StateId::new(id).unwrap()
    }

    fn trigger(name: &str) -> TransitionTrigger {
        TransitionTrigger::new(name).unwrap()
    }

    fn guard_name(name: &str) -> GuardName {
        GuardName::new(name).unwrap()
    }

    fn step_id(id: &str) -> StepId {
        StepId::new(id).unwrap()
    }

    fn step(id: &str, in_state: &str, handler: &str) -> CeremonyStep {
        CeremonyStep::new(
            step_id(id),
            state(in_state),
            StepHandlerKind::new(handler).unwrap(),
            StepHandlerConfig::empty(),
            RetryPolicy::default(),
            None,
        )
    }

    fn transition(from: &str, to: &str, on: &str, guards: Vec<GuardName>) -> CeremonyTransition {
        CeremonyTransition::new(state(from), state(to), trigger(on), guards).unwrap()
    }

    fn role(id: &str, actions: BTreeSet<RoleAction>) -> CeremonyRole {
        CeremonyRole::new(RoleId::new(id).unwrap(), actions).unwrap()
    }

    fn facilitator_actions() -> BTreeSet<RoleAction> {
        BTreeSet::from([
            RoleAction::step(step_id("work")),
            RoleAction::transition(trigger("finish")),
        ])
    }

    /// One state to work in, one to finish in, one step, one guard on
    /// the way out, one role allowed to do both.
    struct Draft {
        states: Vec<CeremonyState>,
        transitions: Vec<CeremonyTransition>,
        steps: Vec<CeremonyStep>,
        guards: Vec<CeremonyGuard>,
        roles: Vec<CeremonyRole>,
    }

    impl Draft {
        fn baseline() -> Self {
            Self {
                states: vec![
                    CeremonyState::initial(state("OPEN")),
                    CeremonyState::terminal(state("DONE")),
                ],
                transitions: vec![transition(
                    "OPEN",
                    "DONE",
                    "finish",
                    vec![guard_name("work_done")],
                )],
                steps: vec![step("work", "OPEN", "noop")],
                guards: vec![CeremonyGuard::new(
                    guard_name("work_done"),
                    GuardCondition::AllStepsCompleted,
                )],
                roles: vec![role("FACILITATOR", facilitator_actions())],
            }
        }

        fn build(self) -> CeremonyDefinition {
            CeremonyDefinition::new(
                CeremonyName::new("diffed_ceremony").unwrap(),
                CeremonyVersion::v1(),
                None,
                Vec::new(),
                Vec::new(),
                self.states,
                self.transitions,
                self.steps,
                self.guards,
                self.roles,
            )
            .unwrap()
        }
    }

    fn baseline() -> CeremonyDefinition {
        Draft::baseline().build()
    }

    #[test]
    fn a_definition_does_not_differ_from_itself() {
        let diff = CeremonyDefinitionDiff::between(&baseline(), &baseline());

        assert!(diff.is_identical());
        assert!(!diff.strands_running_sessions());
    }

    #[test]
    fn removing_a_state_strands_whoever_is_in_it() {
        let mut draft = Draft::baseline();
        draft.states = vec![
            CeremonyState::initial(state("OPEN")),
            CeremonyState::terminal(state("ELSEWHERE")),
        ];
        draft.transitions = vec![transition(
            "OPEN",
            "ELSEWHERE",
            "finish",
            vec![guard_name("work_done")],
        )];

        let diff = CeremonyDefinitionDiff::between(&baseline(), &draft.build());

        assert!(diff.strands_running_sessions());
        let removed = diff
            .changes()
            .iter()
            .find(|change| {
                change.kind() == CeremonyChangeKind::Removed
                    && change.locus() == &CeremonyValidationLocus::state(state("DONE"))
            })
            .expect("the state that went away should be reported");
        assert!(removed.impact().strands());
    }

    #[test]
    fn tightening_a_transition_can_block_a_session_and_relaxing_one_cannot() {
        let mut stricter = Draft::baseline();
        stricter.guards.push(CeremonyGuard::new(
            guard_name("human_approved"),
            GuardCondition::HumanApproval,
        ));
        stricter.transitions = vec![transition(
            "OPEN",
            "DONE",
            "finish",
            vec![guard_name("work_done"), guard_name("human_approved")],
        )];
        assert!(
            CeremonyDefinitionDiff::between(&baseline(), &stricter.build())
                .strands_running_sessions(),
            "a session about to move can be blocked by a guard that was not there"
        );

        let mut looser = Draft::baseline();
        looser.transitions = vec![transition("OPEN", "DONE", "finish", Vec::new())];
        looser.guards = Vec::new();
        assert!(
            !CeremonyDefinitionDiff::between(&baseline(), &looser.build())
                .strands_running_sessions(),
            "dropping a condition only ever lets a session through"
        );
    }

    #[test]
    fn narrowing_a_role_takes_something_away_and_widening_it_does_not() {
        let mut narrowed = Draft::baseline();
        narrowed.roles = vec![role(
            "FACILITATOR",
            BTreeSet::from([RoleAction::step(step_id("work"))]),
        )];
        assert!(
            CeremonyDefinitionDiff::between(&baseline(), &narrowed.build())
                .strands_running_sessions()
        );

        let mut widened = Draft::baseline();
        let mut actions = facilitator_actions();
        actions.insert(RoleAction::request_intervention());
        widened.roles = vec![role("FACILITATOR", actions)];
        assert!(
            !CeremonyDefinitionDiff::between(&baseline(), &widened.build())
                .strands_running_sessions()
        );
    }

    #[test]
    fn changing_how_the_work_is_done_leaves_a_session_where_it_was() {
        let mut draft = Draft::baseline();
        draft.steps = vec![step("work", "OPEN", "deliberation")];

        let diff = CeremonyDefinitionDiff::between(&baseline(), &draft.build());

        assert!(!diff.is_identical());
        assert!(
            !diff.strands_running_sessions(),
            "who does the work is not where the session is"
        );
        assert_eq!(diff.changes().len(), 1);
        assert_eq!(diff.changes()[0].detail(), "who does the work");
    }

    #[test]
    fn changing_repeat_policy_is_a_material_step_change() {
        let mut draft = Draft::baseline();
        draft.steps = vec![
            step("work", "OPEN", "noop").with_repeat_policy(StepRepeatPolicy::new(
                RepeatUntilCondition::output_field_equals(
                    StepOutputField::new("ready").unwrap(),
                    serde_json::json!(true),
                ),
                StepIteration::new(3).unwrap(),
            )),
        ];

        let diff = CeremonyDefinitionDiff::between(&baseline(), &draft.build());

        assert_eq!(diff.changes().len(), 1);
        assert_eq!(
            diff.changes()[0].detail(),
            "how long it may take, how often it may be retried, or when repetition stops"
        );
    }

    #[test]
    fn a_step_added_is_work_a_session_may_already_have_moved_past() {
        let mut draft = Draft::baseline();
        draft.steps.push(step("review", "OPEN", "noop"));
        let mut actions = facilitator_actions();
        actions.insert(RoleAction::step(step_id("review")));
        draft.roles = vec![role("FACILITATOR", actions)];

        let diff = CeremonyDefinitionDiff::between(&baseline(), &draft.build());

        // Counter-intuitive but the honest reading: a guard waiting on
        // every step to complete would never be satisfied for a session
        // already past the state this one sits in.
        assert!(diff.strands_running_sessions());
        assert_eq!(diff.strand_count(), 1);
    }
}