@reventlessdev/reventless-gwt 1.0.0-alpha.292 → 1.0.0-alpha.294

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Flow_GWT.res CHANGED
@@ -16,27 +16,34 @@ open ReventlessCore
16
16
  // command step honors DCB tag filtering so downstream deciders never see
17
17
  // phantom cross-entity events.
18
18
  //
19
- // The chain is built from per-step functors (one per slice), threaded with
20
- // pipe-first so it reads top-to-bottom:
21
- //
22
- // module Place = Flow_GWT.CommandStep(PlaceOrder, PlaceOrder_Decision)
23
- // module Auto = Flow_GWT.AutomationSlice(AutoShipOrder, AutoShipOrder_Automation)
24
- // module Ship = Flow_GWT.CommandStep(ShipOrder, ShipOrder_Decision)
25
- // module View = Flow_GWT.ViewStep(Orders, Orders_Projection)
19
+ // The chain is built from one step per part, each a `…Step` functor applied to
20
+ // the part, threaded with pipe-first so it reads top-to-bottom. A plugin's
21
+ // generated `Flow` module (its tests/Flow.res) offers every part's step under
22
+ // the part's own name:
26
23
  //
27
24
  // start
28
- // ->Sync.givenEvents([CatalogProductSynced({...})])
29
- // ->Place.whenCommand(PlaceOrder({...}))->Place.thenEvents([OrderPlaced({...})])
30
- // ->Auto.whenReacts->Auto.thenIssuesCommand(ShipOrder({...}))
31
- // ->Ship.whenCommand(ShipOrder({...}))->Ship.thenEvents([OrderShipped({...})])
32
- // ->View.thenViewState("o1", {...})
25
+ // ->Flow.SyncCatalogProduct.givenEvents([CatalogProductSynced({...})])
26
+ // ->Flow.PlaceOrder.whenCommand(PlaceOrder({...}))
27
+ // ->Flow.PlaceOrder.thenEvents([OrderPlaced({...})])
28
+ // ->Flow.AutoShipOrder.whenReacts
29
+ // ->Flow.AutoShipOrder.thenIssuesCommand(ShipOrder({...}))
30
+ // ->Flow.Orders.thenRow("o1", {...})
31
+ //
32
+ // A part no plugin generates a step for is set up by hand:
33
+ // `module Place = DecisionStep(PlaceOrder, PlaceOrder_Decision)`.
33
34
  //
34
- // Cross-plugin flows (Phase 3) add two boundary steps — `ExtensionPointStep`
35
- // and `ExtensionStep` — that continue a flow from one plugin into the next
36
- // through the ExtensionPoint mapping / Extension delegate, exactly as the
37
- // runtime routes it across the plugin boundary.
35
+ // Across plugins, `ExtensionPointStep` and `ExtensionStep` continue a flow from
36
+ // one plugin into the next through the extension point mapping and the
37
+ // extension, as the runtime routes it across the plugin boundary.
38
38
  //
39
- // See `docs/plans/done/gwt-flow-and-extension-test-kinds.md` Phases 2–3.
39
+ // Every step counts itself as the flow passes it, so a failure names its step:
40
+ // *step 6 of 8, ShipOrder.thenEvent*.
41
+
42
+ // Who acts in a flow: `Caller.owner(c1)`, `Caller.inRoles([…])`, `Caller.operator`.
43
+ module Caller = Decision_GWT.Caller
44
+
45
+ // What stands in for the outside services a way out reaches: `Fakes.make(…)`.
46
+ module Fakes = Capabilities_Fake
40
47
 
41
48
  module EPMapping = ReventlessInfra.ExtensionPointMapping
42
49
  module ExtMapping = ReventlessInfra.ExtensionMapping
@@ -48,17 +55,26 @@ module ExtMapping = ReventlessInfra.ExtensionMapping
48
55
  // runtime), the encoded event JSON, and — for events emitted by an aggregate
49
56
  // step — the producing aggregate-ID. DCB step entries leave `aggregateId` as
50
57
  // `None`; aggregate step entries set it to `Some(id)` so the matching
51
- // `AggregateCommandStep` can rebuild per-aggregate history without DCB tag
58
+ // `AggregateStep` can rebuild per-aggregate history without DCB tag
52
59
  // inference. Filtering by `aggregateId` and filtering by DCB tags are mutually
53
60
  // exclusive: DCB queries look only at `eventType` + `tags`, and the aggregate
54
- // decoder looks only at `aggregateId` + `eventType`.
61
+ // decoder looks only at `aggregateId` + `eventType`. `at` is when the event was
62
+ // recorded, in milliseconds since 1970: the flow's time at the step.
55
63
  type logEntry = {
56
64
  eventType: string,
57
65
  tags: array<Reventless.DcbTag.tag>,
58
66
  json: JSON.t,
59
67
  aggregateId: option<string>,
68
+ at: float,
69
+ // The id the event was recorded under, which every part that reacts to it is
70
+ // given as its source id: an aggregate's id; a public event's, the one its
71
+ // mapping published it with; a DCB event's, the value of its first indexed
72
+ // tag, as the local runtime records it.
73
+ id: string,
60
74
  }
61
75
 
76
+ let sourceIdOf = (entry: logEntry) => entry.id
77
+
62
78
  // The flow state threaded through every step. `outcome` accumulates assertions
63
79
  // (first failure wins); the `last*` fields carry the most recent `when*`
64
80
  // result for the matching `then*` to read.
@@ -69,18 +85,70 @@ type flowState = {
69
85
  lastError: option<JSON.t>, // encoded error from the last command step
70
86
  lastCommands: array<JSON.t>, // encoded commands from the last automation / extension reaction
71
87
  lastPublic: array<JSON.t>, // encoded public EP events from the last ExtensionPoint step
72
- // The producing aggregate-ID for `lastEvents`, when the producer was an
73
- // `AggregateCommandStep`. Aggregate-style EP mappings reference the source
74
- // aggregate-ID inside `mapOutgoingEvent` (e.g. the catalog Product EP uses
75
- // it as `productId`); the next `ExtensionPointStep` reads this field and
76
- // threads it through. DCB `CommandStep` events leave it `None` and the EP
77
- // step falls back to the synthetic `gwt-id` so the existing DCB Flow tests
78
- // are unchanged.
79
- lastAggregateId: option<string>,
88
+ // The ids `lastEvents` were recorded under, in order: what an extension point
89
+ // mapping is given for each, as the runtime gives it.
90
+ lastIds: array<string>,
80
91
  // Why the last inbound step produced no commands, when it was refused.
81
92
  lastRefusal: option<string>,
93
+ // How many steps the flow has passed, the one it is at, and the one its first
94
+ // failure was found at.
95
+ steps: int,
96
+ at: option<Outcome.step>,
97
+ failedAt: option<Outcome.step>,
98
+ // The flow's time, in milliseconds since 1970. It starts at 0 and moves only
99
+ // forward, when a step says when it happens.
100
+ now: float,
101
+ // Who takes the steps a person takes, from `asCaller` on; none is the
102
+ // platform acting for itself.
103
+ caller: option<Caller.t>,
104
+ // The last command was refused before its decision ran: by its rule, or
105
+ // because the caller does not own what it acts on.
106
+ lastForbidden: bool,
107
+ // What each reacting part has already reacted to, by part: an automation's
108
+ // to-do items, an extension's entries of the record. A reaction reports what
109
+ // is new since then.
110
+ handled: dict<array<string>>,
111
+ // The reacting parts the flow named, by key.
112
+ named: array<string>,
113
+ // What the last way out asked of the outside services it stands for.
114
+ lastSent: array<Capabilities_Fake.call>,
115
+ // The rows the last query returned, and what the last side effect did.
116
+ lastRows: array<JSON.t>,
117
+ lastCalls: array<JSON.t>,
82
118
  }
83
119
 
120
+ // One command a reacting part sends, and the part it is meant for when it says.
121
+ type reaction = {target: option<string>, command: JSON.t}
122
+
123
+ // A part that reacts to the record: what it sends that it has not sent yet,
124
+ // and the flow with that marked as sent.
125
+ type reacting = {
126
+ key: string,
127
+ part: Outcome.part,
128
+ react: flowState => promise<(flowState, array<reaction>)>,
129
+ }
130
+
131
+ // A part that decides: runs a sent command when it reads it, as the platform.
132
+ type deciding = {
133
+ name: string,
134
+ run: (flowState, JSON.t) => option<flowState>,
135
+ }
136
+
137
+ // A system's reacting and deciding parts, as its generated `Flow` module lists
138
+ // them.
139
+ type parts = {reacting: array<reacting>, deciding: array<deciding>}
140
+
141
+ let handledBy = (s: flowState, key) => s.handled->Dict.get(key)->Option.getOr([])
142
+
143
+ let markHandled = (s: flowState, key, ids: array<string>) => {
144
+ let handled = s.handled->Dict.copy
145
+ handled->Dict.set(key, s->handledBy(key)->Array.concat(ids))
146
+ {...s, handled}
147
+ }
148
+
149
+ let markNamed = (s: flowState, key) =>
150
+ s.named->Array.includes(key) ? s : {...s, named: s.named->Array.concat([key])}
151
+
84
152
  type flow = promise<flowState>
85
153
 
86
154
  let emptyState = {
@@ -90,8 +158,19 @@ let emptyState = {
90
158
  lastError: None,
91
159
  lastCommands: [],
92
160
  lastPublic: [],
93
- lastAggregateId: None,
161
+ lastIds: [],
94
162
  lastRefusal: None,
163
+ steps: 0,
164
+ at: None,
165
+ failedAt: None,
166
+ now: 0.0,
167
+ caller: None,
168
+ lastForbidden: false,
169
+ handled: Dict.make(),
170
+ named: [],
171
+ lastSent: [],
172
+ lastRows: [],
173
+ lastCalls: [],
95
174
  }
96
175
 
97
176
  // Entry point for a chain — an empty flow with no prior history.
@@ -100,10 +179,43 @@ let start: flow = Promise.resolve(emptyState)
100
179
  // First failure wins: once the flow has recorded a mismatch, later assertions
101
180
  // keep it rather than overwrite with a (possibly spurious) downstream result.
102
181
  let recordOutcome = (s: flowState, o: Outcome.outcome): flowState =>
103
- switch s.outcome {
104
- | Error(_) => s
105
- | Ok() => {...s, outcome: o}
182
+ switch (s.outcome, o) {
183
+ | (Error(_), _) | (Ok(), Ok()) => s
184
+ | (Ok(), Error(_)) => {...s, outcome: o, failedAt: s.at}
185
+ }
186
+
187
+ // An instant as the examples write one: no milliseconds when there are none.
188
+ let iso = (millis: float) => millis->Date.fromTime->Date.toISOString->String.replace(".000Z", "Z")
189
+
190
+ // Every step counts itself as the flow passes it, so a failure can say where. A
191
+ // step that says when it happens (`~at`, an ISO instant) moves the flow's time
192
+ // there; one that says nothing happens at the time of the step before it.
193
+ let enter = async (flowP: flow, ~verb, ~part=?, ~at=?) => {
194
+ let s = await flowP
195
+ let number = s.steps + 1
196
+ let s = {...s, steps: number, at: Some({Outcome.number, total: 0, verb, ?part})}
197
+ switch at {
198
+ | None => s
199
+ | Some(text) =>
200
+ let millis = Date.fromString(text)->Date.getTime
201
+ if Float.isNaN(millis) {
202
+ s->recordOutcome(Outcome.fail(Throw({error: `~at="${text}" is not an instant`, stack: ""})))
203
+ } else if millis < s.now {
204
+ s->recordOutcome(
205
+ Outcome.fail(
206
+ Throw({
207
+ error: `~at="${text}" is before the flow's time, ${iso(
208
+ s.now,
209
+ )}: time only moves forward`,
210
+ stack: "",
211
+ }),
212
+ ),
213
+ )
214
+ } else {
215
+ {...s, now: millis}
216
+ }
106
217
  }
218
+ }
107
219
 
108
220
  // Mirror the in-memory DCB event log's `matchesQuery`: an empty query matches
109
221
  // everything; otherwise an entry matches if ANY clause matches (its event type
@@ -128,44 +240,61 @@ let entryMatchesQuery = (entry: logEntry, query: Reventless.DcbTag.query) =>
128
240
  })
129
241
  }
130
242
 
243
+ // One event as an entry of the log, encoded and tagged, recorded at `at` under
244
+ // the id `~id`, or the aggregate's, or the value of its first tag `~tagKeys`
245
+ // indexes for its type (any tag when no keys are given).
246
+ let entryOf = (
247
+ ev: 'e,
248
+ schema: S.t<'e>,
249
+ ~at: float,
250
+ ~aggregateId=?,
251
+ ~id=?,
252
+ ~tagKeys: option<dict<array<string>>>=?,
253
+ ): logEntry => {
254
+ let json = ev->Message.encode(schema)
255
+ let eventType = json->Reventless.Message.variantNameOfJson
256
+ let tags = Reventless.DcbTag.extractTagsExpanded(schema, ev)
257
+ let indexed = switch tagKeys->Option.flatMap(keys => keys->Dict.get(eventType)) {
258
+ | Some(keys) => tags->Array.filter(t => keys->Array.includes(t.key))
259
+ | None => tags
260
+ }
261
+ {
262
+ eventType,
263
+ tags,
264
+ json,
265
+ aggregateId,
266
+ at,
267
+ id: switch (id, aggregateId) {
268
+ | (Some(id), _) | (None, Some(id)) => id
269
+ | (None, None) => indexed->Array.get(0)->Option.mapOr("", t => t.value)
270
+ },
271
+ }
272
+ }
273
+
131
274
  // Encode + tag a batch of typed events and append them to the log.
132
- let appendEvents = (log: array<logEntry>, events: array<'e>, schema: S.t<'e>): array<logEntry> =>
133
- Array.concat(
134
- log,
135
- events->Array.map(ev => {
136
- let json = ev->Message.encode(schema)
137
- {
138
- eventType: json->Reventless.Message.variantNameOfJson,
139
- tags: Reventless.DcbTag.extractTagsExpanded(schema, ev),
140
- json,
141
- aggregateId: None,
142
- }
143
- }),
144
- )
275
+ let appendEvents = (
276
+ log: array<logEntry>,
277
+ ~at: float,
278
+ ~tagKeys=?,
279
+ events: array<'e>,
280
+ schema: S.t<'e>,
281
+ ): array<logEntry> =>
282
+ Array.concat(log, events->Array.map(ev => entryOf(ev, schema, ~at, ~tagKeys?)))
145
283
 
146
- // Aggregate-style append: encode + tag with the producing aggregate-ID so
147
- // `decodeAggregateMatching` can rebuild that aggregate's history later. DCB
148
- // tags are intentionally still extracted (cheap and lets a downstream DCB
149
- // step pick the events up if any are tagged), but the `aggregateId` is the
284
+ // Aggregate-style append: the producing aggregate's id is the entry's, and the
150
285
  // authoritative filter for aggregate consumers.
151
286
  let appendAggregateEvents = (
152
287
  log: array<logEntry>,
153
288
  ~id: string,
289
+ ~at: float,
154
290
  events: array<'e>,
155
291
  schema: S.t<'e>,
156
292
  ): array<logEntry> =>
157
- Array.concat(
158
- log,
159
- events->Array.map(ev => {
160
- let json = ev->Message.encode(schema)
161
- {
162
- eventType: json->Reventless.Message.variantNameOfJson,
163
- tags: Reventless.DcbTag.extractTagsExpanded(schema, ev),
164
- json,
165
- aggregateId: Some(id),
166
- }
167
- }),
168
- )
293
+ Array.concat(log, events->Array.map(ev => entryOf(ev, schema, ~at, ~aggregateId=id)))
294
+
295
+ // The ids the last `n` entries were recorded under.
296
+ let lastIdsOf = (log: array<logEntry>, n) =>
297
+ log->Array.slice(~start=log->Array.length - n)->Array.map(e => e.id)
169
298
 
170
299
  // Decode the log entries a consumer cares about. `query` filters by event type
171
300
  // and DCB tags (use `[]` to take all of the consumer's event types); the
@@ -212,89 +341,217 @@ let decodeAggregateMatching = (
212
341
 
213
342
  let describe = JestBind.describe
214
343
 
215
- // The chain returns a `flow`; `test` awaits it and reports the accumulated
216
- // outcome. Bodies read top-to-bottom and end on the last `then*`.
217
- let test = (name, ~timeout=?, body: unit => flow) =>
344
+ // A finished flow's outcome. A failure carries the step it was found at, among
345
+ // all the steps the flow passed.
346
+ let outcomeOf = (s: flowState): Outcome.outcome =>
347
+ switch (s.outcome, s.failedAt) {
348
+ | (Error(m), Some(step)) => Error(m->Outcome.atStep({...step, total: s.steps}))
349
+ | (outcome, _) => outcome
350
+ }
351
+
352
+ // The groups whose members read every row and act for anyone, as a deployment
353
+ // names them. A flow's test gives them (`~elevated`); none by default.
354
+ let elevated: ref<array<string>> = ref([])
355
+
356
+ // This file's flows, by the title of their test, so that one can start after
357
+ // another.
358
+ let flows: dict<unit => flow> = Dict.make()
359
+
360
+ // The chain returns a `flow`; `test` awaits it and reports its outcome. Bodies
361
+ // read top-to-bottom and end on the last `then*`. `~tells` names what the flow
362
+ // tells, for a reader of its steps file; the flow itself does nothing with it.
363
+ let test = (
364
+ name,
365
+ ~tells as _: option<string>=?,
366
+ ~elevated as groups: array<string>=[],
367
+ ~timeout=?,
368
+ body: unit => flow,
369
+ ) => {
370
+ flows->Dict.set(name, body)
218
371
  JestBind.testPromise(~slice="Flow", name, ~timeout?, async () => {
219
- let s = await body()
220
- s.outcome
372
+ elevated := groups
373
+ let outcome = outcomeOf(await body())
374
+ elevated := []
375
+ outcome
221
376
  })
377
+ }
222
378
 
223
- // -- Boundary scope ----------------------------------------------------------
379
+ // In place of `start`: the record and the time where the flow titled `title`,
380
+ // in this file, ended. That flow must pass; if it fails, this one is not run,
381
+ // and says so rather than failing on what the other left undone.
382
+ let after = async (title: string): flowState => {
383
+ let notRun = why => {...emptyState, outcome: Outcome.fail(Throw({error: why, stack: ""}))}
384
+ switch flows->Dict.get(title) {
385
+ | None => notRun(`after("${title}"): no flow of that title in this file`)
386
+ | Some(body) =>
387
+ let before = await body()
388
+ switch outcomeOf(before) {
389
+ | Error(_) => notRun(`not run: the flow it starts after, "${title}", failed`)
390
+ | Ok() => {...emptyState, log: before.log, now: before.now, handled: before.handled}
391
+ }
392
+ }
393
+ }
224
394
 
225
- // Assert that a DCB consistency boundary derives its tag scope.
226
- //
227
- // Every other step here tests slices; this one tests the set of them, and it is
228
- // in the flow DSL because a flow is the only test kind that already reasons
229
- // about more than one slice at a time. The rest of the harness derives scope
230
- // per slice (`DcbScopeInference.crossPartitionForSlice`), which cannot fail the
231
- // way a boundary fails: a single slice always resolves, so the all-or-nothing
232
- // fallback in `deriveEffectiveScope` — one unresolvable slice discarding the
233
- // derived scope for every slice beside it — has no per-slice symptom at all. The
234
- // slices keep passing their own tests and the platform rejects valid commands.
235
- //
236
- // Takes the generated `<Plugin>.Plugin.dcbSliceSchemas`, so it asserts over the
237
- // boundary as deployed rather than over the steps a given flow happens to name.
238
- let thenBoundaryScopeResolves = async (
239
- flowP: flow,
240
- ~name: string,
241
- slices: array<Reventless.DcbTag.sliceSchemas>,
242
- ) => {
243
- let s = await flowP
244
- let scope = Reventless.DcbTag.deriveEffectiveScope(slices)
245
- // Deploy and boot derive the storage partition from the same slices and refuse
246
- // the boundary when it fails, so the test fails with their reasons.
247
- let partitionReasons = {
248
- let shapes = slices->Array.map(Reventless.DcbTag.sliceShape)
249
- let hints = Reventless.DcbValidation.validatePartitionHintsVsInference(~shapes)
250
- let arms = Reventless.DcbValidation.validateCrossPartitionArms(
251
- ~shapes,
252
- ~inferred=Reventless.DcbScopeInference.infer(shapes),
253
- )
254
- let contradictions =
255
- hints.contradictions
256
- ->Array.concat(arms.contradictions)
257
- ->Array.map(e => `${e.sliceName}: ${e.message}`)
258
- switch Reventless.DcbTag.deriveBoundaryPartition(slices) {
259
- | _ => contradictions
260
- | exception JsExn(err) =>
261
- contradictions->Array.concat([
262
- JsExn.message(err)->Option.getOr("partition derivation failed"),
263
- ])
395
+ // Who takes the steps a person takes from here on: commands are checked against
396
+ // their rule and the owners their history records, and a view shows only the
397
+ // rows this caller may read. What an automation or an extension sends is still
398
+ // run by the platform.
399
+ let asCaller = async (flowP: flow, who: Caller.t) => {
400
+ ...await flowP->enter(~verb="asCaller"),
401
+ caller: Some(who),
402
+ }
403
+
404
+ // -- What a decision returned ------------------------------------------------
405
+
406
+ let eventsWere = (s: flowState, expectedJson: array<JSON.t>) =>
407
+ s->recordOutcome(
408
+ switch s.lastError {
409
+ | Some(err) =>
410
+ Outcome.fail(
411
+ ErrorMismatch({expected: JSON.Encode.null, actual: Some(err), actualEvents: s.lastEvents}),
412
+ )
413
+ | None =>
414
+ s.lastEvents == expectedJson
415
+ ? Outcome.pass
416
+ : Outcome.fail(EventsMismatch({expected: expectedJson, actual: s.lastEvents}))
417
+ },
418
+ )
419
+
420
+ let errorWas = (s: flowState, expJson: JSON.t) =>
421
+ s->recordOutcome(
422
+ switch s.lastError {
423
+ | None =>
424
+ Outcome.fail(ErrorMismatch({expected: expJson, actual: None, actualEvents: s.lastEvents}))
425
+ | Some(actual) =>
426
+ actual == expJson
427
+ ? Outcome.pass
428
+ : Outcome.fail(
429
+ ErrorMismatch({expected: expJson, actual: Some(actual), actualEvents: s.lastEvents}),
430
+ )
431
+ },
432
+ )
433
+
434
+ let noEventWas = (s: flowState) =>
435
+ s->recordOutcome(
436
+ switch s.lastError {
437
+ | Some(err) =>
438
+ Outcome.fail(
439
+ ErrorMismatch({expected: JSON.Encode.null, actual: Some(err), actualEvents: s.lastEvents}),
440
+ )
441
+ | None =>
442
+ s.lastEvents->Array.length == 0
443
+ ? Outcome.pass
444
+ : Outcome.fail(NoEventExpected({actual: s.lastEvents}))
445
+ },
446
+ )
447
+
448
+ // The decision did not refuse; its events are not compared. For a flow written
449
+ // with no author present, whose worked-out values nobody has confirmed yet.
450
+ let acceptedWas = (s: flowState) =>
451
+ s->recordOutcome(
452
+ switch s.lastError {
453
+ | Some(err) =>
454
+ Outcome.fail(
455
+ ErrorMismatch({expected: JSON.Encode.null, actual: Some(err), actualEvents: s.lastEvents}),
456
+ )
457
+ | None => Outcome.pass
458
+ },
459
+ )
460
+
461
+ let forbiddenCode = Reventless.CommandOutcome.code(Forbidden)
462
+
463
+ let forbidden = (s: flowState, refusal: option<JSON.t>) => {
464
+ ...s,
465
+ lastEvents: [],
466
+ lastError: refusal,
467
+ lastForbidden: true,
468
+ }
469
+
470
+ let forbiddenWas = (s: flowState) =>
471
+ s->recordOutcome(
472
+ s.lastForbidden
473
+ ? Outcome.pass
474
+ : Outcome.fail(
475
+ ErrorMismatch({
476
+ expected: JSON.Encode.object(
477
+ Dict.fromArray([("errorCode", JSON.Encode.string(forbiddenCode))]),
478
+ ),
479
+ actual: s.lastError,
480
+ actualEvents: s.lastEvents,
481
+ }),
482
+ ),
483
+ )
484
+
485
+ // -- What the step before sent -----------------------------------------------
486
+
487
+ // The commands the step before sent, read by the decision that runs them: all of
488
+ // them, or the one `~only` names (the first is 1). Read strictly, so a command
489
+ // the decision cannot read fails here rather than being filled in.
490
+ let issued = (s: flowState, ~only=?, ~name, schema: S.t<'c>): result<array<'c>, string> => {
491
+ let sent = s.lastCommands
492
+ let picked = switch only {
493
+ | None => Ok(sent)
494
+ | Some(n) =>
495
+ switch sent->Array.get(n - 1) {
496
+ | Some(c) => Ok([c])
497
+ | None =>
498
+ Error(
499
+ `~only=${n->Int.toString}, but ${sent->Array.length->Int.toString} command(s) were sent`,
500
+ )
264
501
  }
265
502
  }
266
- // Beyond that, an ambiguity that costs nothing is not a failure: a boundary whose
267
- // fallback carries every derived key reads exactly as the derivation would. What
268
- // fails is losing a key, because that is the case where the runtime answers wrongly.
269
- let outcome = if partitionReasons->Array.length > 0 {
270
- Outcome.fail(PartitionUnresolved({boundary: name, reasons: partitionReasons}))
271
- } else if scope.droppedCrossPartitionTagKeys->Array.length > 0 {
272
- Outcome.fail(
273
- ScopeDegraded({
274
- boundary: name,
275
- dropped: scope.droppedCrossPartitionTagKeys,
276
- ambiguities: scope.ambiguities->Array.map(((slice, reason)) => `${slice}: ${reason}`),
277
- }),
503
+ picked->Result.flatMap(sent =>
504
+ sent->Array.length == 0
505
+ ? Error("the step before sent no command")
506
+ : sent->Array.reduce(Ok([]), (acc, json) =>
507
+ acc->Result.flatMap(
508
+ commands =>
509
+ switch json->Reventless.Util_Sury.fromJson(schema) {
510
+ | command => Ok(commands->Array.concat([command]))
511
+ | exception S.Exn(e) =>
512
+ Error(`${name} cannot read ${JSON.stringify(json)}: ${e.message}`)
513
+ | exception _ => Error(`${name} cannot read ${JSON.stringify(json)}`)
514
+ },
515
+ )
516
+ )
517
+ )
518
+ }
519
+
520
+ // Run the sent commands in order. The step's events are all of theirs; the
521
+ // first refusal ends it.
522
+ let runIssued = (s: flowState, commands: result<array<'c>, string>, decideOne) =>
523
+ switch commands {
524
+ | Error(reason) =>
525
+ {...s, lastEvents: [], lastError: None}->recordOutcome(
526
+ Outcome.fail(
527
+ TranslateError({expected: "a command the decision reads", actual: Some(reason)}),
528
+ ),
529
+ )
530
+ | Ok(commands) =>
531
+ commands->Array.reduce({...s, lastEvents: [], lastError: None}, (acc, command) =>
532
+ switch acc.lastError {
533
+ | Some(_) => acc
534
+ | None =>
535
+ let next = acc->decideOne(command)
536
+ {...next, lastEvents: acc.lastEvents->Array.concat(next.lastEvents)}
537
+ }
278
538
  )
279
- } else {
280
- Outcome.pass
281
539
  }
282
- s->recordOutcome(outcome)
283
- }
284
540
 
285
- // -- CommandStep: a StateChangeSlice / Aggregate decider ---------------------
541
+ // -- DecisionStep: a StateChangeSlice / Aggregate decider ---------------------
286
542
 
287
- module CommandStep = (
543
+ module DecisionStep = (
288
544
  Spec: Decision_GWT.DecisionSpec,
289
545
  Decision: Decision_GWT.Decision with module Spec := Spec,
290
546
  ) => {
547
+ let part: Outcome.part = {kind: Decision, name: Spec.name}
291
548
  let consumedDecoder = Reventless.DcbDecode.makeDecoder(Spec.consumedEventSchema)
292
549
  let consumedEventTypes = consumedDecoder.eventTypes
293
550
 
294
551
  // Seed prior history with events this slice can emit.
295
- let givenEvents = async (flowP: flow, events: array<Spec.event>) => {
296
- let s = await flowP
297
- {...s, log: s.log->appendEvents(events, Spec.eventSchema)}
552
+ let givenEvents = async (flowP: flow, ~at=?, events: array<Spec.event>) => {
553
+ let s = await flowP->enter(~verb="givenEvents", ~part, ~at?)
554
+ {...s, log: s.log->appendEvents(~at=s.now, events, Spec.eventSchema)}
298
555
  }
299
556
 
300
557
  // Filter the log by the command's DCB tags, fold `evolve`, run `decide`, and
@@ -330,73 +587,116 @@ module CommandStep = (
330
587
  ~crossPartitionTagKeys,
331
588
  )
332
589
 
333
- let whenCommand = async (flowP: flow, command: Spec.command) => {
334
- let s = await flowP
335
- let query = Reventless.DcbTag.buildQueryFromCommand(
336
- ~eventTypes=consumedEventTypes,
337
- ~schema=Spec.commandSchema,
338
- ~value=command,
339
- ~tagKeysByEventType,
340
- ~crossPartitionTagKeys,
341
- ~payloadTagKeys,
590
+ let historyFor = (s: flowState, command: Spec.command) =>
591
+ decodeMatching(
592
+ s.log,
593
+ consumedDecoder,
594
+ Reventless.DcbTag.buildQueryFromCommand(
595
+ ~eventTypes=consumedEventTypes,
596
+ ~schema=Spec.commandSchema,
597
+ ~value=command,
598
+ ~tagKeysByEventType,
599
+ ~crossPartitionTagKeys,
600
+ ~payloadTagKeys,
601
+ ),
342
602
  )
343
- let history = decodeMatching(s.log, consumedDecoder, query)
603
+
604
+ module Guard = Decision_GWT.Acting({
605
+ let name = Spec.name
606
+ type history = Spec.consumedEvent
607
+ let historySchema = Spec.consumedEventSchema
608
+ type command = Spec.command
609
+ let commandSchema = Spec.commandSchema
610
+ type role = Spec.role
611
+ let authorizationOf = Spec.authorizationOf
612
+ let ownedById = false
613
+ })
614
+
615
+ let decideOne = (s: flowState, command: Spec.command) => {
616
+ let history = s->historyFor(command)
344
617
  let state = history->Array.reduce(Decision.initialState, Decision.evolve)
345
618
  switch Decision.decide(state, command) {
346
- | Ok(events) => {
619
+ | Ok(events) =>
620
+ let log =
621
+ s.log->appendEvents(~at=s.now, ~tagKeys=tagKeysByEventType, events, Spec.eventSchema)
622
+ {
347
623
  ...s,
348
- log: s.log->appendEvents(events, Spec.eventSchema),
624
+ log,
349
625
  lastEvents: events->Array.map(e => e->Message.encode(Spec.eventSchema)),
350
626
  lastError: None,
351
- lastAggregateId: None,
627
+ lastIds: log->lastIdsOf(events->Array.length),
628
+ lastForbidden: false,
352
629
  }
353
630
  | Error(error) => {
354
631
  ...s,
355
632
  lastEvents: [],
356
633
  lastError: Some(error->Message.encode(Spec.errorSchema)),
357
- lastAggregateId: None,
634
+ lastIds: [],
635
+ lastForbidden: false,
358
636
  }
359
637
  }
360
638
  }
361
639
 
362
- let thenEvents = async (flowP: flow, expected: array<Spec.event>) => {
363
- let s = await flowP
364
- let expectedJson = expected->Array.map(e => e->Message.encode(Spec.eventSchema))
365
- let o = switch s.lastError {
366
- | Some(err) =>
367
- Outcome.fail(
368
- ErrorMismatch({expected: JSON.Encode.null, actual: Some(err), actualEvents: s.lastEvents}),
369
- )
370
- | None =>
371
- s.lastEvents == expectedJson
372
- ? Outcome.pass
373
- : Outcome.fail(EventsMismatch({expected: expectedJson, actual: s.lastEvents}))
640
+ // A person's command: refused before its decision runs, as the platform
641
+ // refuses it, when the caller may not issue it.
642
+ let whenCommand = async (flowP: flow, ~at=?, command: Spec.command) => {
643
+ let s = await flowP->enter(~verb="whenCommand", ~part, ~at?)
644
+ switch s.caller {
645
+ | None => s->decideOne(command)
646
+ | Some(who) =>
647
+ Guard.asCaller(
648
+ [],
649
+ {...who, claim: who->Caller.claimWith(~elevated=elevated.contents)},
650
+ )->ignore
651
+ Guard.refuses(s->historyFor(command), command)
652
+ ? s->forbidden(Guard.refusal.contents->Option.map(Guard.encRefusal))
653
+ : s->decideOne(command)
374
654
  }
375
- s->recordOutcome(o)
376
655
  }
377
656
 
378
- let thenEvent = (flowP, event) => thenEvents(flowP, [event])
657
+ // Runs the commands the step before sent, as this decision reads them.
658
+ let whenIssued = async (flowP: flow, ~only=?, ~at=?) => {
659
+ let s = await flowP->enter(~verb="whenIssued", ~part, ~at?)
660
+ s->runIssued(s->issued(~only?, ~name=Spec.name, Spec.commandSchema), decideOne)
661
+ }
379
662
 
380
- let thenError = async (flowP: flow, expected: Spec.error) => {
381
- let s = await flowP
382
- let expJson = expected->Message.encode(Spec.errorSchema)
383
- let o = switch s.lastError {
384
- | None =>
385
- Outcome.fail(ErrorMismatch({expected: expJson, actual: None, actualEvents: s.lastEvents}))
386
- | Some(actual) =>
387
- actual == expJson
388
- ? Outcome.pass
389
- : Outcome.fail(
390
- ErrorMismatch({expected: expJson, actual: Some(actual), actualEvents: s.lastEvents}),
391
- )
392
- }
393
- s->recordOutcome(o)
663
+ let deciding: deciding = {
664
+ name: Spec.name,
665
+ run: (s, json) =>
666
+ switch json->Reventless.Util_Sury.fromJson(Spec.commandSchema) {
667
+ | command => Some(s->decideOne(command))
668
+ | exception _ => None
669
+ },
394
670
  }
671
+
672
+ let thenEvents = async (flowP: flow, expected: array<Spec.event>) =>
673
+ (await flowP->enter(~verb="thenEvents", ~part))->eventsWere(
674
+ expected->Array.map(e => e->Message.encode(Spec.eventSchema)),
675
+ )
676
+
677
+ let thenEvent = async (flowP: flow, event: Spec.event) =>
678
+ (await flowP->enter(~verb="thenEvent", ~part))->eventsWere([
679
+ event->Message.encode(Spec.eventSchema),
680
+ ])
681
+
682
+ let thenError = async (flowP: flow, expected: Spec.error) =>
683
+ (await flowP->enter(~verb="thenError", ~part))->errorWas(
684
+ expected->Message.encode(Spec.errorSchema),
685
+ )
686
+
687
+ let thenNoEvent = async (flowP: flow) =>
688
+ (await flowP->enter(~verb="thenNoEvent", ~part))->noEventWas
689
+
690
+ let thenAccepted = async (flowP: flow) =>
691
+ (await flowP->enter(~verb="thenAccepted", ~part))->acceptedWas
692
+
693
+ let thenForbidden = async (flowP: flow) =>
694
+ (await flowP->enter(~verb="thenForbidden", ~part))->forbiddenWas
395
695
  }
396
696
 
397
- // -- AggregateCommandStep: an Aggregate decider partitioned by aggregate-ID --
697
+ // -- AggregateStep: an Aggregate decider partitioned by aggregate-ID --
398
698
  //
399
- // Mirror of `CommandStep` for `Reventless.Decision.T` (the aggregate-flavor
699
+ // Mirror of `DecisionStep` for `Reventless.Decision.T` (the aggregate-flavor
400
700
  // decision). Differences from the slice form:
401
701
  // * No `consumedEvent` distinction — aggregates fold their own `event`
402
702
  // stream; the decoder uses `Spec.eventSchema`.
@@ -409,208 +709,339 @@ module CommandStep = (
409
709
  // state across the chain; sequencing them for different `~id` keeps their
410
710
  // histories isolated (a `Place` on `o2` does not see the events of `o1`).
411
711
 
412
- module AggregateCommandStep = (
712
+ module AggregateStep = (
413
713
  Spec: Decision_GWT.AggregateDeciderSpec,
414
714
  Decision: Reventless.Decision.T with module Spec = Spec,
415
715
  ) => {
716
+ let part: Outcome.part = {kind: Aggregate, name: Spec.name}
416
717
  let aggregateDecoder = Reventless.DcbDecode.makeDecoder(Spec.eventSchema)
417
718
 
418
719
  // Seed `id`'s history before the first `whenCommand`. Useful when a flow
419
720
  // starts mid-stream (e.g. the order is already Placed when the test begins).
420
- let givenEvents = async (flowP: flow, ~id: string, events: array<Spec.event>) => {
421
- let s = await flowP
422
- {...s, log: s.log->appendAggregateEvents(~id, events, Spec.eventSchema)}
721
+ let givenEvents = async (flowP: flow, ~id: string, ~at=?, events: array<Spec.event>) => {
722
+ let s = await flowP->enter(~verb="givenEvents", ~part, ~at?)
723
+ {...s, log: s.log->appendAggregateEvents(~id, ~at=s.now, events, Spec.eventSchema)}
423
724
  }
424
725
 
425
726
  // Rebuild `id`'s state from the log, run `decide`, then either append the
426
727
  // emitted events (still tagged with `~id`) or remember the error for the
427
728
  // next `thenError`.
428
- let whenCommand = async (flowP: flow, ~id: string, command: Spec.command) => {
429
- let s = await flowP
729
+ module Guard = Decision_GWT.Acting({
730
+ let name = Spec.name
731
+ type history = Spec.event
732
+ let historySchema = Spec.eventSchema
733
+ type command = Spec.command
734
+ let commandSchema = Spec.commandSchema
735
+ type role = Spec.role
736
+ let authorizationOf = Spec.authorizationOf
737
+ let ownedById = false
738
+ })
739
+
740
+ let decideOne = (s: flowState, ~id: string, command: Spec.command) => {
430
741
  let history = decodeAggregateMatching(s.log, ~id, aggregateDecoder)
431
742
  let state = history->Array.reduce(Decision.initialState, Decision.evolve)
432
743
  switch Decision.decide(state, command) {
433
744
  | Ok(events) => {
434
745
  ...s,
435
- log: s.log->appendAggregateEvents(~id, events, Spec.eventSchema),
746
+ log: s.log->appendAggregateEvents(~id, ~at=s.now, events, Spec.eventSchema),
436
747
  lastEvents: events->Array.map(e => e->Message.encode(Spec.eventSchema)),
437
748
  lastError: None,
438
- lastAggregateId: Some(id),
749
+ lastIds: events->Array.map(_ => id),
750
+ lastForbidden: false,
439
751
  }
440
752
  | Error(error) => {
441
753
  ...s,
442
754
  lastEvents: [],
443
755
  lastError: Some(error->Message.encode(Spec.errorSchema)),
444
- lastAggregateId: Some(id),
756
+ lastIds: [],
757
+ lastForbidden: false,
445
758
  }
446
759
  }
447
760
  }
448
761
 
449
- let thenEvents = async (flowP: flow, expected: array<Spec.event>) => {
450
- let s = await flowP
451
- let expectedJson = expected->Array.map(e => e->Message.encode(Spec.eventSchema))
452
- let o = switch s.lastError {
453
- | Some(err) =>
454
- Outcome.fail(
455
- ErrorMismatch({expected: JSON.Encode.null, actual: Some(err), actualEvents: s.lastEvents}),
456
- )
457
- | None =>
458
- s.lastEvents == expectedJson
459
- ? Outcome.pass
460
- : Outcome.fail(EventsMismatch({expected: expectedJson, actual: s.lastEvents}))
762
+ let whenCommand = async (flowP: flow, ~id: string, ~at=?, command: Spec.command) => {
763
+ let s = await flowP->enter(~verb="whenCommand", ~part, ~at?)
764
+ switch s.caller {
765
+ | None => s->decideOne(~id, command)
766
+ | Some(who) =>
767
+ Guard.asCaller(
768
+ [],
769
+ {...who, claim: who->Caller.claimWith(~elevated=elevated.contents)},
770
+ )->ignore
771
+ Guard.refuses(decodeAggregateMatching(s.log, ~id, aggregateDecoder), command)
772
+ ? s->forbidden(Guard.refusal.contents->Option.map(Guard.encRefusal))
773
+ : s->decideOne(~id, command)
461
774
  }
462
- s->recordOutcome(o)
463
775
  }
464
776
 
465
- let thenEvent = (flowP, event) => thenEvents(flowP, [event])
466
-
467
- let thenNoEvent = async (flowP: flow) => {
468
- let s = await flowP
469
- let o = switch s.lastError {
470
- | Some(err) =>
471
- Outcome.fail(
472
- ErrorMismatch({expected: JSON.Encode.null, actual: Some(err), actualEvents: s.lastEvents}),
473
- )
474
- | None =>
475
- s.lastEvents->Array.length == 0
476
- ? Outcome.pass
477
- : Outcome.fail(NoEventExpected({actual: s.lastEvents}))
478
- }
479
- s->recordOutcome(o)
777
+ // Runs the commands the step before sent, as this aggregate reads them.
778
+ let whenIssued = async (flowP: flow, ~id: string, ~only=?, ~at=?) => {
779
+ let s = await flowP->enter(~verb="whenIssued", ~part, ~at?)
780
+ s->runIssued(s->issued(~only?, ~name=Spec.name, Spec.commandSchema), (s, c) =>
781
+ s->decideOne(~id, c)
782
+ )
480
783
  }
481
784
 
482
- let thenError = async (flowP: flow, expected: Spec.error) => {
483
- let s = await flowP
484
- let expJson = expected->Message.encode(Spec.errorSchema)
485
- let o = switch s.lastError {
486
- | None =>
487
- Outcome.fail(ErrorMismatch({expected: expJson, actual: None, actualEvents: s.lastEvents}))
488
- | Some(actual) =>
489
- actual == expJson
490
- ? Outcome.pass
491
- : Outcome.fail(
492
- ErrorMismatch({expected: expJson, actual: Some(actual), actualEvents: s.lastEvents}),
493
- )
494
- }
495
- s->recordOutcome(o)
496
- }
497
- }
785
+ let thenEvents = async (flowP: flow, expected: array<Spec.event>) =>
786
+ (await flowP->enter(~verb="thenEvents", ~part))->eventsWere(
787
+ expected->Array.map(e => e->Message.encode(Spec.eventSchema)),
788
+ )
498
789
 
499
- // -- AutomationStep: a policy that reacts to log events and issues a command --
790
+ let thenEvent = async (flowP: flow, event: Spec.event) =>
791
+ (await flowP->enter(~verb="thenEvent", ~part))->eventsWere([
792
+ event->Message.encode(Spec.eventSchema),
793
+ ])
500
794
 
501
- // Deprecated: takes an adapter. Use `AutomationSlice`; this goes one release
502
- // after the examples have moved.
503
- module AutomationStep = (Spec: Automation_GWT.SliceSpec) => {
504
- let consumedDecoder = Reventless.DcbDecode.makeDecoder(Spec.consumedEventSchema)
795
+ let thenNoEvent = async (flowP: flow) =>
796
+ (await flowP->enter(~verb="thenNoEvent", ~part))->noEventWas
505
797
 
506
- // Sweep the log: collect todos, drop the ones resolved within the same
507
- // stream, process the remainder into commands.
508
- let whenReacts = async (flowP: flow) => {
509
- let s = await flowP
510
- let events = decodeMatching(s.log, consumedDecoder, [])
511
- let collected = events->Array.map(e => e->Spec.collect)->Array.flat
512
- let resolvedIds = events->Array.filterMap(e => e->Spec.resolve)
513
- let pending = collected->Array.filter(((id, _)) => !(resolvedIds->Array.includes(id)))
514
- let now = Automation_GWT.clockNow()
515
- let commands = pending->Array.filterMap(((id, todo)) => Spec.process(id, todo, ~now))
516
- {
517
- ...s,
518
- lastCommands: commands->Array.map(((_id, cmd)) => cmd->Message.encode(Spec.commandSchema)),
519
- }
520
- }
798
+ let thenAccepted = async (flowP: flow) =>
799
+ (await flowP->enter(~verb="thenAccepted", ~part))->acceptedWas
521
800
 
522
- let thenIssuesCommands = async (flowP: flow, expected: array<Spec.command>) => {
523
- let s = await flowP
524
- let expJson = expected->Array.map(c => c->Message.encode(Spec.commandSchema))
525
- let o =
526
- s.lastCommands == expJson
527
- ? Outcome.pass
528
- : Outcome.fail(EventsMismatch({expected: expJson, actual: s.lastCommands}))
529
- s->recordOutcome(o)
530
- }
801
+ let thenForbidden = async (flowP: flow) =>
802
+ (await flowP->enter(~verb="thenForbidden", ~part))->forbiddenWas
531
803
 
532
- let thenIssuesCommand = (flowP, command) => thenIssuesCommands(flowP, [command])
533
- let thenIssuesNoCommand = flowP => thenIssuesCommands(flowP, [])
804
+ let thenError = async (flowP: flow, expected: Spec.error) =>
805
+ (await flowP->enter(~verb="thenError", ~part))->errorWas(
806
+ expected->Message.encode(Spec.errorSchema),
807
+ )
534
808
  }
535
809
 
536
810
  // -- ViewStep: a StateViewSlice / projection over the log --------------------
537
811
 
812
+ // The view step's former verbs, kept only so that a flow using one fails to
813
+ // build with a message naming the new verb.
814
+ type renamedToThenRow
815
+ type renamedToThenRows
816
+
538
817
  module ViewStep = (
539
818
  Spec: Projection_GWT.Spec,
540
819
  Projection: Projection_GWT.Projection with module Spec := Spec,
541
820
  ) => {
542
821
  module P = Projection_GWT.Make(Spec, Projection)
822
+ let part: Outcome.part = {kind: View, name: Spec.name}
543
823
  let consumedDecoder = Reventless.DcbDecode.makeDecoder(Spec.consumedEventSchema)
544
824
 
545
825
  let encState = (st: Spec.state) => st->Message.encode(Spec.stateSchema)
546
826
 
547
- // Fold the projection over every consumed event in the log and assert the
548
- // row(s) for `id`.
549
- let thenViewStates = async (flowP: flow, id, expected: array<Spec.state>) => {
550
- let s = await flowP
551
- let events = decodeMatching(s.log, consumedDecoder, [])
552
- let store = await P.givenEvents(events)
553
- let actual = store->Dict.get(id)->Option.getOr([])->Array.map(encState)
554
- let expectedJson = expected->Array.map(encState)
555
- let o =
556
- actual == expectedJson
827
+ // Fold the projection over every consumed event in the log: the row(s) for `id`.
828
+ // Each event projected at the time it was recorded.
829
+ let rowsOf = async (s: flowState, id) => {
830
+ let events =
831
+ s.log->Array.flatMap(entry =>
832
+ decodeMatching([entry], consumedDecoder, [])->Array.map(e => (e, iso(entry.at)))
833
+ )
834
+ let store = await P.givenEventsAt(events)
835
+ let rows = store->Dict.get(id)->Option.getOr([])
836
+ switch s.caller {
837
+ | None => rows
838
+ | Some(who) => rows->P.readableBy(who, ~elevated=elevated.contents)
839
+ }
840
+ }
841
+
842
+ let compared = (s: flowState, id, ~expected: array<JSON.t>, ~actual: array<JSON.t>) =>
843
+ s->recordOutcome(
844
+ actual == expected
557
845
  ? Outcome.pass
558
846
  : Outcome.fail(
559
847
  StateMismatch({
560
848
  key: id,
561
- expected: Some(JSON.Encode.array(expectedJson)),
849
+ expected: Some(JSON.Encode.array(expected)),
562
850
  actual: Some(JSON.Encode.array(actual)),
851
+ fold: Project,
563
852
  }),
564
- )
565
- s->recordOutcome(o)
853
+ ),
854
+ )
855
+
856
+ let rowsAre = async (s: flowState, id, expected: array<Spec.state>) =>
857
+ s->compared(
858
+ id,
859
+ ~expected=expected->Array.map(encState),
860
+ ~actual=(await s->rowsOf(id))->Array.map(encState),
861
+ )
862
+
863
+ let thenRows = async (flowP: flow, id, expected: array<Spec.state>) =>
864
+ await (await flowP->enter(~verb="thenRows", ~part))->rowsAre(id, expected)
865
+ let thenRow = async (flowP: flow, id, row: Spec.state) =>
866
+ await (await flowP->enter(~verb="thenRow", ~part))->rowsAre(id, [row])
867
+
868
+ let thenNoRow = async (flowP: flow, id) =>
869
+ await (await flowP->enter(~verb="thenNoRow", ~part))->rowsAre(id, [])
870
+
871
+ // Some fields of the row: `pick` takes them from the row as built, and they
872
+ // are compared with `expected`. A field `pick` leaves out is built and not
873
+ // compared; the view's own test states the whole row.
874
+ let thenRowShows = async (flowP: flow, id, pick: Spec.state => 'shown, expected: 'shown) => {
875
+ let s = await flowP->enter(~verb="thenRowShows", ~part)
876
+ let shown = (await s->rowsOf(id))->Array.map(pick)
877
+ // What `pick` returns has no schema; it is shown as the value it is.
878
+ let asJson = (v: 'shown): JSON.t => Obj.magic(v)
879
+ shown == [expected]
880
+ ? s->recordOutcome(Outcome.pass)
881
+ : s->compared(id, ~expected=[asJson(expected)], ~actual=shown->Array.map(asJson))
566
882
  }
567
883
 
568
- let thenViewState = (flowP, id, state) => thenViewStates(flowP, id, [state])
884
+ @deprecated("Renamed thenRow.")
885
+ let thenViewState = (_: renamedToThenRow, _: renamedToThenRow, _: renamedToThenRow) => ()
886
+ @deprecated("Renamed thenRows.")
887
+ let thenViewStates = (_: renamedToThenRows, _: renamedToThenRows, _: renamedToThenRows) => ()
569
888
  }
570
889
 
571
- // -- OutboundStep: an OutboundTranslationSlice's `collect` over the log -------
890
+ // -- QueryStep: a query over a view ------------------------------------------
891
+
892
+ // A view's spec as a query reads it: its rows and the indexes they are queried by.
893
+ module type QueryableView = {
894
+ include Projection_GWT.Spec
895
+ let config: Reventless.ReadModel.config
896
+ }
572
897
 
573
- // Deprecated: takes an adapter. Use `OutboundSlice`; this goes one release
574
- // after the examples have moved.
575
- module OutboundStep = (Spec: OutboundTranslation_GWT.SliceSpec) => {
898
+ module QueryStep = (
899
+ Spec: QueryableView,
900
+ Projection: Projection_GWT.Projection with module Spec := Spec,
901
+ ) => {
902
+ module P = Projection_GWT.Make(Spec, Projection)
903
+ module Q = Query_GWT.Make({
904
+ let name = Spec.name
905
+ type state = Spec.state
906
+ let stateSchema = Spec.stateSchema
907
+ let config = Spec.config
908
+ let subIdConfig = Spec.subIdConfig
909
+ type role = Spec.role
910
+ let authorization = Spec.authorization
911
+ })
912
+ let part: Outcome.part = {kind: Query, name: Spec.name}
576
913
  let consumedDecoder = Reventless.DcbDecode.makeDecoder(Spec.consumedEventSchema)
914
+ let encState = (st: Spec.state) => st->Message.encode(Spec.stateSchema)
577
915
 
578
- let encItems = (arr: array<(string, Spec.outboundItem)>) =>
579
- arr->Array.map(((id, item)) => (id, item->Message.encode(Spec.outboundItemSchema)))
916
+ // Every row of the view, built from the record at the times of its events, and
917
+ // read as the flow's caller.
918
+ let rowsOf = async (s: flowState) => {
919
+ let store = await P.givenEventsAt(
920
+ s.log->Array.flatMap(entry =>
921
+ decodeMatching([entry], consumedDecoder, [])->Array.map(e => (e, iso(entry.at)))
922
+ ),
923
+ )
924
+ store
925
+ ->Dict.toArray
926
+ ->Array.flatMap(((id, rows)) => {
927
+ let rows = switch s.caller {
928
+ | None => rows
929
+ | Some(who) => rows->P.readableBy(who, ~elevated=elevated.contents)
930
+ }
931
+ rows->Array.map(row => (id, row))
932
+ })
933
+ }
580
934
 
581
- // Assert the outbound effects the slice would fire — the `collect` result.
582
- // (The async `translate` leg hits an external service, so it is exercised
583
- // only by the dedicated `OutboundTranslation_GWT`, not the flow.)
584
- let thenOutbound = async (flowP: flow, expected: array<(string, Spec.outboundItem)>) => {
585
- let s = await flowP
586
- let events = decodeMatching(s.log, consumedDecoder, [])
587
- // The flow log carries decoded events, not their envelopes, so there is no
588
- // entity id to thread here. A collect that keys off `~sourceId` (an
589
- // aggregate source) should be exercised by the dedicated
590
- // `OutboundTranslation_GWT`, which can supply one.
591
- let collected = events->Array.map(e => e->Spec.collect(~sourceId=""))->Array.flat
592
- let actual = encItems(collected)
593
- let expectedJson = encItems(expected)
594
- let o =
595
- actual == expectedJson
935
+ // A query as the view's doors answer it: by a field, through the index that
936
+ // covers it, filtered and limited. An index the view lacks fails the step.
937
+ let whenQueried = async (flowP: flow, args: Query_GWT.queryArgs<Spec.state>) => {
938
+ let s = await flowP->enter(~verb="whenQueried", ~part)
939
+ switch (await s->rowsOf)->Q.givenStore->Q.whenQuery(args) {
940
+ | Ok(rows) => {...s, lastRows: rows->Array.map(encState)}
941
+ | Error(mismatch) => {...s, lastRows: []}->recordOutcome(Error(mismatch))
942
+ }
943
+ }
944
+
945
+ let listed = (s: flowState, expected: array<JSON.t>) =>
946
+ s->recordOutcome(
947
+ s.lastRows == expected
596
948
  ? Outcome.pass
597
- : Outcome.fail(TodoMismatch({expected: expectedJson, actual}))
598
- s->recordOutcome(o)
949
+ : Outcome.fail(QueryRowsMismatch({expected, actual: s.lastRows})),
950
+ )
951
+
952
+ let thenListed = async (flowP: flow, expected: array<Spec.state>) =>
953
+ (await flowP->enter(~verb="thenListed", ~part))->listed(expected->Array.map(encState))
954
+
955
+ let thenCounted = async (flowP: flow, count: int) => {
956
+ let s = await flowP->enter(~verb="thenCounted", ~part)
957
+ s->recordOutcome(
958
+ s.lastRows->Array.length == count
959
+ ? Outcome.pass
960
+ : Outcome.fail(
961
+ StateMismatch({
962
+ key: "count",
963
+ expected: Some(JSON.Encode.int(count)),
964
+ actual: Some(JSON.Encode.int(s.lastRows->Array.length)),
965
+ }),
966
+ ),
967
+ )
968
+ }
969
+ }
970
+
971
+ // -- SideEffectStep: an aggregate's side effect over the record --------------
972
+
973
+ module SideEffectStep = (SE: Reventless.SideEffect.T) => {
974
+ // A side effect has no name of its own; its file's is the one it is known by.
975
+ let name =
976
+ SE.moduleUrl
977
+ ->String.split("/")
978
+ ->Array.at(-1)
979
+ ->Option.flatMap(file => file->String.split(".")->Array.get(0))
980
+ ->Option.getOr("SideEffect")
981
+ let part: Outcome.part = {kind: SideEffect, name}
982
+ let decoder = Reventless.DcbDecode.makeDecoder(SE.Source.eventSchema)
983
+ let key = "sideEffect:" ++ name
984
+
985
+ // The side effect runs for each of its source's events on the record it has
986
+ // not run for yet, with the id the event was recorded under and the flow's
987
+ // time. What it did is what its mock recorded meanwhile.
988
+ let whenRuns = async (flowP: flow, mock: SideEffect_GWT.mock<'call>) => {
989
+ let s = await flowP->enter(~verb="whenRuns", ~part)
990
+ let handled = s->handledBy(key)
991
+ let fresh =
992
+ s.log
993
+ ->Array.mapWithIndex((entry, i) => (Int.toString(i), entry))
994
+ ->Array.filterMap(((i, entry)) =>
995
+ handled->Array.includes(i)
996
+ ? None
997
+ : decodeMatching([entry], decoder, [])->Array.get(0)->Option.map(ev => (i, entry, ev))
998
+ )
999
+ let before = mock.snapshot()->Array.length
1000
+ let rec run = async i =>
1001
+ switch fresh->Array.get(i) {
1002
+ | None => ()
1003
+ | Some((_, entry, event)) =>
1004
+ await SE.execute(
1005
+ SE.Source.Id.makeFromString(entry->sourceIdOf),
1006
+ {...StubRuntime.meta, time: iso(entry.at)},
1007
+ event,
1008
+ SideEffect_GWT.stubQueryEngine,
1009
+ )
1010
+ await run(i + 1)
1011
+ }
1012
+ await run(0)
1013
+ {
1014
+ ...s->markHandled(key, fresh->Array.map(((i, _, _)) => i)),
1015
+ lastCalls: mock.snapshot()->Array.slice(~start=before)->Array.map(mock.encode),
1016
+ }
599
1017
  }
600
1018
 
601
- let thenOutboundNothing = flowP => thenOutbound(flowP, [])
1019
+ // What the side effect did, by the mock's own record of it.
1020
+ let thenDid = async (flowP: flow, mock: SideEffect_GWT.mock<'call>, expected: array<'call>) => {
1021
+ let s = await flowP->enter(~verb="thenDid", ~part)
1022
+ let expectedJson = expected->Array.map(mock.encode)
1023
+ s->recordOutcome(
1024
+ s.lastCalls == expectedJson
1025
+ ? Outcome.pass
1026
+ : Outcome.fail(EventsMismatch({expected: expectedJson, actual: s.lastCalls})),
1027
+ )
1028
+ }
1029
+
1030
+ let thenDidNothing = async (flowP: flow) => {
1031
+ let s = await flowP->enter(~verb="thenDidNothing", ~part)
1032
+ s->recordOutcome(
1033
+ s.lastCalls == [] ? Outcome.pass : Outcome.fail(NoEventExpected({actual: s.lastCalls})),
1034
+ )
1035
+ }
602
1036
  }
603
1037
 
604
- // -- Slice-as-written steps --------------------------------------------------
1038
+ // -- Automation, way out, way in ---------------------------------------------
605
1039
  //
606
- // The same steps over a slice's `Spec` and body, with no adapter. The log keeps
607
- // no source name, so every mapping is offered every entry; the source id is the
608
- // producing aggregate's, or "" for a DCB event, which names its own subject.
609
-
610
- let sourceIdOf = (entry: logEntry) => entry.aggregateId->Option.getOr("")
1040
+ // Each takes the slice as written: its `Spec` and its body. The log keeps no
1041
+ // source name, so every mapping is offered every entry; the source id is the id
1042
+ // the entry was recorded under.
611
1043
 
612
- let encodedCommandsMatch = async (flowP: flow, expJson: array<JSON.t>) => {
613
- let s = await flowP
1044
+ let encodedCommandsMatch = (s: flowState, expJson: array<JSON.t>) => {
614
1045
  let o = switch s.lastRefusal {
615
1046
  | Some(reason) => Outcome.fail(TranslateError({expected: "(commands)", actual: Some(reason)}))
616
1047
  | None =>
@@ -621,53 +1052,154 @@ let encodedCommandsMatch = async (flowP: flow, expJson: array<JSON.t>) => {
621
1052
  s->recordOutcome(o)
622
1053
  }
623
1054
 
624
- module AutomationSlice = (
1055
+ module AutomationStep = (
625
1056
  Spec: Reventless.AutomationSlice.Spec,
626
1057
  Automation: Reventless.AutomationSlice.Automation with module Spec := Spec,
627
1058
  ) => {
628
1059
  module A = Automation_GWT.FromSlice(Spec, Automation)
629
-
630
- let whenReacts = async (flowP: flow) => {
631
- let s = await flowP
632
- let routed =
633
- s.log->Array.flatMap(entry =>
634
- A.Route.dispatches->Array.filterMap(d =>
635
- d.handle(entry.json, ~sourceId=entry->sourceIdOf, A.testContext)
1060
+ let part: Outcome.part = {kind: Automation, name: Spec.name}
1061
+
1062
+ // Each entry routed as the runtime delivers it, recorded at its own time.
1063
+ let routedLog = (s: flowState) =>
1064
+ s.log->Array.map(entry => (
1065
+ entry,
1066
+ A.Route.dispatches->Array.filterMap(d =>
1067
+ d.handle(
1068
+ entry.json,
1069
+ ~sourceId=entry->sourceIdOf,
1070
+ A.testContext->A.withRecordedAt(Some(entry.at)),
1071
+ )
1072
+ ),
1073
+ ))
1074
+
1075
+ let key = "automation:" ++ Spec.name
1076
+
1077
+ // The schedules due between `from` and the flow's time, as ticks: the
1078
+ // declared one, and those the record's events set.
1079
+ let dueTicks = (s: flowState, log, ~from) => {
1080
+ let rows = A.declaredRows(~now=0.0)
1081
+ log->Array.forEach(((
1082
+ entry: logEntry,
1083
+ routed: array<AutomationSlice_Route.routed<Spec.todoItem>>,
1084
+ )) =>
1085
+ routed->Array.forEach(r =>
1086
+ r.rescheduled->Array.forEach(
1087
+ change =>
1088
+ rows
1089
+ ->AutomationSlice_Schedules.apply(change, ~setBy="flow", ~recordedAt=entry.at)
1090
+ ->ignore,
636
1091
  )
637
1092
  )
638
- let {commands, _} = A.sweep(routed, ~now=Automation_GWT.clockNow())
639
- {
640
- ...s,
641
- lastCommands: commands->Array.map(((_id, cmd)) => cmd->Message.encode(Spec.commandSchema)),
642
- lastRefusal: None,
1093
+ )
1094
+ let firings =
1095
+ rows
1096
+ ->Dict.valuesToArray
1097
+ ->Array.flatMap(row =>
1098
+ switch row->AutomationSlice_Schedules.timeOf {
1099
+ | None => []
1100
+ | Some(time) =>
1101
+ let rec due = (after, acc, tries) =>
1102
+ switch time->ScheduleTime.nextFiring(~after) {
1103
+ | Some(next) if next <= s.now && tries < 1000 =>
1104
+ due(next, acc->Array.concat([(row.key, next)]), tries + 1)
1105
+ | _ => acc
1106
+ }
1107
+ due(from, [], 0)
1108
+ }
1109
+ )
1110
+ ->Array.toSorted(((_, a), (_, b)) => Float.compare(a, b))
1111
+ A.routeEach(
1112
+ firings->Array.map(((key, at)) => A.tick(~key, at)),
1113
+ A.testContext,
1114
+ )->Array.flatMap(((_, routed)) => routed)
1115
+ }
1116
+
1117
+ // A sweep of the record at the flow's time, and of the ticks given: the
1118
+ // to-do items it has not acted on yet, now marked as acted on.
1119
+ let reactWith = (s: flowState, ~ticks=[]) => {
1120
+ let fromLog = s->routedLog->Array.flatMap(((_, routed)) => routed)
1121
+ let handled = s->handledBy(key)
1122
+ let commands =
1123
+ A.sweep(fromLog->Array.concat(ticks), ~now=s.now).commands->Array.filter(((id, _)) =>
1124
+ !(handled->Array.includes(id))
1125
+ )
1126
+ (s->markHandled(key, commands->Array.map(((id, _)) => id)), commands)
1127
+ }
1128
+
1129
+ let sent = (s: flowState, commands: array<(string, Spec.command)>) => {
1130
+ ...s,
1131
+ lastCommands: commands->Array.map(((_id, cmd)) => cmd->Message.encode(Spec.commandSchema)),
1132
+ lastRefusal: None,
1133
+ }
1134
+
1135
+ // The automation sweeps the record at the flow's time and sends what is new
1136
+ // since its last step.
1137
+ let whenReacts = async (flowP: flow, ~at=?) => {
1138
+ let s = await flowP->enter(~verb="whenReacts", ~part, ~at?)
1139
+ let (s, commands) = s->markNamed(key)->reactWith
1140
+ s->sent(commands)
1141
+ }
1142
+
1143
+ // The flow's time moves to `until`, and every schedule that comes due on the
1144
+ // way fires in turn: the declared one, and those the record's events set. The
1145
+ // commands the firings make are what the step sent.
1146
+ let whenTimePasses = async (flowP: flow, ~until) => {
1147
+ let from = (await flowP).now
1148
+ let s = await flowP->enter(~verb="whenTimePasses", ~part, ~at=until)
1149
+ switch s.outcome {
1150
+ | Error(_) => s
1151
+ | Ok() =>
1152
+ let (s, commands) = s->markNamed(key)->reactWith(~ticks=s->dueTicks(s->routedLog, ~from))
1153
+ s->sent(commands)
643
1154
  }
644
1155
  }
645
1156
 
646
- let thenIssuesCommands = (flowP, expected: array<Spec.command>) =>
647
- encodedCommandsMatch(flowP, expected->Array.map(c => c->Message.encode(Spec.commandSchema)))
648
- let thenIssuesCommand = (flowP, command) => thenIssuesCommands(flowP, [command])
649
- let thenIssuesNoCommand = flowP => thenIssuesCommands(flowP, [])
1157
+ let reacting: reacting = {
1158
+ key,
1159
+ part,
1160
+ react: async s => {
1161
+ let (s, commands) = s->reactWith
1162
+ (
1163
+ s,
1164
+ commands->Array.map(((_, cmd)) => {
1165
+ target: Some(Spec.targetName),
1166
+ command: cmd->Message.encode(Spec.commandSchema),
1167
+ }),
1168
+ )
1169
+ },
1170
+ }
1171
+
1172
+ let issued = async (flowP: flow, ~verb, expected: array<Spec.command>) =>
1173
+ (await flowP->enter(~verb, ~part))->encodedCommandsMatch(
1174
+ expected->Array.map(c => c->Message.encode(Spec.commandSchema)),
1175
+ )
1176
+ let thenIssuesCommands = (flowP, expected) => issued(flowP, ~verb="thenIssuesCommands", expected)
1177
+ let thenIssuesCommand = (flowP, command) => issued(flowP, ~verb="thenIssuesCommand", [command])
1178
+ let thenIssuesNoCommand = flowP => issued(flowP, ~verb="thenIssuesNoCommand", [])
650
1179
  }
651
1180
 
652
- module OutboundSlice = (
1181
+ module OutboundStep = (
653
1182
  Spec: Reventless.OutboundTranslationSlice.Spec,
654
1183
  Translation: Reventless.OutboundTranslationSlice.Translation with module Spec := Spec,
655
1184
  ) => {
1185
+ let part: Outcome.part = {kind: Outbound, name: Spec.name}
656
1186
  let consumedDecoder = Reventless.DcbDecode.makeDecoder(Spec.consumedEventSchema)
657
1187
 
658
1188
  let encItems = (arr: array<(string, Spec.outboundItem)>) =>
659
1189
  arr->Array.map(((id, item)) => (id, item->Message.encode(Spec.outboundItemSchema)))
660
1190
 
661
- // Asserts what `collect` queues; `translate` is the slice test's to run.
662
- let thenOutbound = async (flowP: flow, expected: array<(string, Spec.outboundItem)>) => {
663
- let s = await flowP
664
- let collected =
665
- s.log->Array.flatMap(entry =>
666
- decodeMatching([entry], consumedDecoder, [])->Array.flatMap(e =>
667
- Translation.collect(e, ~sourceId=entry->sourceIdOf)
668
- )
1191
+ // What `collect` queues over the record, each entry with the id it was
1192
+ // recorded under.
1193
+ let collected = (s: flowState) =>
1194
+ s.log->Array.flatMap(entry =>
1195
+ decodeMatching([entry], consumedDecoder, [])->Array.flatMap(e =>
1196
+ Translation.collect(e, ~sourceId=entry->sourceIdOf)
669
1197
  )
670
- let actual = encItems(collected)
1198
+ )
1199
+
1200
+ let outbound = async (flowP: flow, ~verb, expected: array<(string, Spec.outboundItem)>) => {
1201
+ let s = await flowP->enter(~verb, ~part)
1202
+ let actual = encItems(s->collected)
671
1203
  let expectedJson = encItems(expected)
672
1204
  let o =
673
1205
  actual == expectedJson
@@ -676,18 +1208,76 @@ module OutboundSlice = (
676
1208
  s->recordOutcome(o)
677
1209
  }
678
1210
 
679
- let thenOutboundNothing = flowP => thenOutbound(flowP, [])
1211
+ let key = "outbound:" ++ Spec.name
1212
+
1213
+ // The way out sends what it queued and has not sent yet: its own `translate`,
1214
+ // against fakes that stand in for the outside services (`Capabilities_Fake`).
1215
+ // What the answers become are the step's sent commands, for `whenIssued`; a
1216
+ // translate that fails is what `thenIssues…` reports.
1217
+ let whenSent = async (flowP: flow, ~fakes=Capabilities_Fake.make(), ~at=?) => {
1218
+ let s = await flowP->enter(~verb="whenSent", ~part, ~at?)
1219
+ let handled = s->handledBy(key)
1220
+ let items = s->collected->Array.filter(((id, _)) => !(handled->Array.includes(id)))
1221
+ let rec send = async (i, commands, refusal) =>
1222
+ switch (items->Array.get(i), refusal) {
1223
+ | (None, _) | (_, Some(_)) => (commands, refusal)
1224
+ | (Some((id, item)), None) =>
1225
+ switch await Translation.translate(id, item, ~capabilities=fakes.capabilities) {
1226
+ | Ok(Some((_, command))) => await send(i + 1, commands->Array.concat([command]), None)
1227
+ | Ok(None) => await send(i + 1, commands, None)
1228
+ | Error(reason) => (commands, Some(`translate failed: ${reason}`))
1229
+ | exception JsExn(e) => (
1230
+ commands,
1231
+ Some(`translate threw: ${e->JsExn.message->Option.getOr("an exception")}`),
1232
+ )
1233
+ }
1234
+ }
1235
+ let (commands, refusal) = await send(0, [], None)
1236
+ {
1237
+ ...s->markHandled(key, items->Array.map(((id, _)) => id)),
1238
+ lastCommands: commands->Array.map(c => c->Message.encode(Spec.inboundCommandSchema)),
1239
+ lastRefusal: refusal,
1240
+ lastSent: fakes.calls(),
1241
+ }
1242
+ }
1243
+
1244
+ // What the way out asked of the outside services, in order.
1245
+ let thenSent = async (flowP: flow, expected: array<Capabilities_Fake.call>) => {
1246
+ let s = await flowP->enter(~verb="thenSent", ~part)
1247
+ s->recordOutcome(
1248
+ s.lastSent == expected
1249
+ ? Outcome.pass
1250
+ : Outcome.fail(
1251
+ EventsMismatch({
1252
+ expected: expected->Array.map(Capabilities_Fake.toJson),
1253
+ actual: s.lastSent->Array.map(Capabilities_Fake.toJson),
1254
+ }),
1255
+ ),
1256
+ )
1257
+ }
1258
+
1259
+ let issued = async (flowP: flow, ~verb, expected: array<Spec.inboundCommand>) =>
1260
+ (await flowP->enter(~verb, ~part))->encodedCommandsMatch(
1261
+ expected->Array.map(c => c->Message.encode(Spec.inboundCommandSchema)),
1262
+ )
1263
+ let thenIssuesCommands = (flowP, expected) => issued(flowP, ~verb="thenIssuesCommands", expected)
1264
+ let thenIssuesCommand = (flowP, command) => issued(flowP, ~verb="thenIssuesCommand", [command])
1265
+ let thenIssuesNoCommand = flowP => issued(flowP, ~verb="thenIssuesNoCommand", [])
1266
+
1267
+ let thenOutbound = (flowP, expected) => outbound(flowP, ~verb="thenOutbound", expected)
1268
+ let thenOutboundNothing = flowP => outbound(flowP, ~verb="thenOutboundNothing", [])
680
1269
  }
681
1270
 
682
- module InboundSlice = (
1271
+ module InboundStep = (
683
1272
  Spec: Reventless.InboundTranslationSlice.Spec,
684
1273
  Translation: Reventless.InboundTranslationSlice.Translation with module Spec := Spec,
685
1274
  ) => {
686
1275
  module I = InboundTranslation_GWT.FromSlice(Spec, Translation)
1276
+ let part: Outcome.part = {kind: Inbound, name: Spec.name}
687
1277
 
688
1278
  // Received input becomes the flow's next commands, as an automation's do.
689
- let whenReceived = async (flowP: flow, json: JSON.t, ~fakes=?) => {
690
- let s = await flowP
1279
+ let whenReceived = async (flowP: flow, ~at=?, json: JSON.t, ~fakes=?) => {
1280
+ let s = await flowP->enter(~verb="whenReceived", ~part, ~at?)
691
1281
  switch (await I.whenReceived(json, ~fakes?)).outcome {
692
1282
  | Translated(pairs) => {
693
1283
  ...s,
@@ -699,13 +1289,20 @@ module InboundSlice = (
699
1289
  }
700
1290
  }
701
1291
 
702
- let thenIssuesCommands = (flowP, expected: array<Spec.command>) =>
703
- encodedCommandsMatch(flowP, expected->Array.map(c => c->Message.encode(Spec.commandSchema)))
704
- let thenIssuesCommand = (flowP, command) => thenIssuesCommands(flowP, [command])
705
- let thenIssuesNoCommand = flowP => thenIssuesCommands(flowP, [])
1292
+ let issued = async (flowP: flow, ~verb, expected: array<Spec.command>) =>
1293
+ (await flowP->enter(~verb, ~part))->encodedCommandsMatch(
1294
+ expected->Array.map(c => c->Message.encode(Spec.commandSchema)),
1295
+ )
1296
+ let thenIssuesCommands = (flowP, expected) => issued(flowP, ~verb="thenIssuesCommands", expected)
1297
+ let thenIssuesCommand = (flowP, command) => issued(flowP, ~verb="thenIssuesCommand", [command])
1298
+ let thenIssuesNoCommand = flowP => issued(flowP, ~verb="thenIssuesNoCommand", [])
706
1299
  }
707
1300
 
708
- // -- Cross-plugin boundary steps (Phase 3) -----------------------------------
1301
+ // -- Across plugins ----------------------------------------------------------
1302
+
1303
+ // An extension point is named under its system (`Catalog.Products`); its part
1304
+ // is the last segment, as the steps file names it.
1305
+ let portName = (name: string) => name->String.split(".")->Array.at(-1)->Option.getOr(name)
709
1306
 
710
1307
  // Order-independent comparison for published actions — fan-out order is
711
1308
  // non-deterministic, so compare sorted by stringified JSON.
@@ -718,29 +1315,28 @@ let sortJson = (arr: array<JSON.t>) =>
718
1315
  // fan-out). The public events are appended to the shared log and remembered
719
1316
  // for `thenPublicEvent(s)` / the following `ExtensionStep`.
720
1317
  module ExtensionPointStep = (M: EPMapping.Mapping) => {
1318
+ let part: Outcome.part = {kind: ExtensionPoint, name: portName(M.ExtensionPoint.name)}
721
1319
  let delegateDecoder = Reventless.DcbDecode.makeDecoder(M.Delegate.eventSchema)
722
1320
 
723
- // Aggregate-style EP mappings address the source aggregate's identity via
724
- // the first arg (e.g. catalog Product → ProductBecameAvailable uses it as
725
- // `productId`). DCB upstreams don't set `lastAggregateId` and fall back to
726
- // the synthetic `gwt-id` so existing DCB Flow tests keep their behavior.
727
- let runMapping = async (sourceId: string, events: array<M.Delegate.event>): array<
1321
+ // Each event the step before recorded, mapped with the id it was recorded
1322
+ // under, as the runtime gives it; each public event appended with the id the
1323
+ // mapping published it with.
1324
+ let runMapping = async (events: array<(string, M.Delegate.event)>): array<(
1325
+ string,
728
1326
  M.ExtensionPoint.event,
729
- > =>
1327
+ )> =>
730
1328
  switch M.mapOutgoingEvent {
731
1329
  | None => []
732
1330
  | Some(f) =>
733
1331
  let actions =
734
1332
  events
735
- ->Array.map(ev => f(sourceId, ev, StubRuntime.meta, StubRuntime.queryEngine))
1333
+ ->Array.map(((sourceId, ev)) => f(sourceId, ev, StubRuntime.meta, StubRuntime.queryEngine))
736
1334
  ->Array.flat
737
1335
  let nested = await actions
738
1336
  ->Array.map(async action =>
739
1337
  switch action {
740
- | EPMapping.PublishEvent(_id, e) => [e]
741
- | EPMapping.PublishEventAsync(p) =>
742
- let (_id, e) = await p
743
- [e]
1338
+ | EPMapping.PublishEvent(id, e) => [(id, e)]
1339
+ | EPMapping.PublishEventAsync(p) => [await p]
744
1340
  | EPMapping.HandleDirective(_, _) => []
745
1341
  }
746
1342
  )
@@ -748,26 +1344,37 @@ module ExtensionPointStep = (M: EPMapping.Mapping) => {
748
1344
  nested->Array.flat
749
1345
  }
750
1346
 
751
- let whenPublishedThrough = async (flowP: flow) => {
752
- let s = await flowP
753
- let delegateEvents = s.lastEvents->Array.filterMap(json => {
754
- let data = switch json {
755
- | Object(d) => d
756
- | _ => Dict.make()
757
- }
758
- delegateDecoder.decode(~eventType=json->Reventless.Message.variantNameOfJson, ~data)
759
- })
760
- let sourceId = s.lastAggregateId->Option.getOr("gwt-id")
761
- let publicEvents = await runMapping(sourceId, delegateEvents)
1347
+ let whenPublished = async (flowP: flow, ~at=?) => {
1348
+ let s = await flowP->enter(~verb="whenPublished", ~part, ~at?)
1349
+ let delegateEvents =
1350
+ s.lastEvents
1351
+ ->Array.mapWithIndex((json, i) => (s.lastIds->Array.get(i)->Option.getOr(""), json))
1352
+ ->Array.filterMap(((id, json)) => {
1353
+ let data = switch json {
1354
+ | Object(d) => d
1355
+ | _ => Dict.make()
1356
+ }
1357
+ delegateDecoder.decode(
1358
+ ~eventType=json->Reventless.Message.variantNameOfJson,
1359
+ ~data,
1360
+ )->Option.map(ev => (id, ev))
1361
+ })
1362
+ let publicEvents = await runMapping(delegateEvents)
762
1363
  {
763
1364
  ...s,
764
- log: s.log->appendEvents(publicEvents, M.ExtensionPoint.eventSchema),
765
- lastPublic: publicEvents->Array.map(e => e->Message.encode(M.ExtensionPoint.eventSchema)),
1365
+ log: s.log->Array.concat(
1366
+ publicEvents->Array.map(((id, e)) =>
1367
+ entryOf(e, M.ExtensionPoint.eventSchema, ~at=s.now, ~id)
1368
+ ),
1369
+ ),
1370
+ lastPublic: publicEvents->Array.map(((_, e)) =>
1371
+ e->Message.encode(M.ExtensionPoint.eventSchema)
1372
+ ),
766
1373
  }
767
1374
  }
768
1375
 
769
- let thenPublicEvents = async (flowP: flow, expected: array<M.ExtensionPoint.event>) => {
770
- let s = await flowP
1376
+ let published = async (flowP: flow, ~verb, expected: array<M.ExtensionPoint.event>) => {
1377
+ let s = await flowP->enter(~verb, ~part)
771
1378
  let expJson = expected->Array.map(e => e->Message.encode(M.ExtensionPoint.eventSchema))
772
1379
  let o =
773
1380
  sortJson(s.lastPublic) == sortJson(expJson)
@@ -776,31 +1383,40 @@ module ExtensionPointStep = (M: EPMapping.Mapping) => {
776
1383
  s->recordOutcome(o)
777
1384
  }
778
1385
 
779
- let thenPublicEvent = (flowP, event) => thenPublicEvents(flowP, [event])
1386
+ let thenPublicEvents = (flowP, expected) => published(flowP, ~verb="thenPublicEvents", expected)
1387
+ let thenPublicEvent = (flowP, event) => published(flowP, ~verb="thenPublicEvent", [event])
780
1388
  }
781
1389
 
782
1390
  // ExtensionStep: runs an Extension delegate's `mapIncomingEvent` over the public
783
1391
  // EP events the last ExtensionPoint step produced, surfacing the commands the
784
- // extension issues onto its own plugin's slices. The next `CommandStep` then
1392
+ // extension issues onto its own plugin's slices. The next `DecisionStep` then
785
1393
  // executes the asserted command.
786
1394
  module ExtensionStep = (M: ExtMapping.Mapping) => {
1395
+ let part: Outcome.part = {kind: Extension, name: portName(M.ExtensionPoint.name)}
787
1396
  let epDecoder = Reventless.DcbDecode.makeDecoder(M.ExtensionPoint.eventSchema)
788
1397
  let encCmd = (c: M.Delegate.command) => c->Message.encode(M.Delegate.commandSchema)
789
1398
 
790
- let whenExtensionReacts = async (flowP: flow) => {
791
- let s = await flowP
792
- let epEvents = s.lastPublic->Array.filterMap(json => {
793
- let data = switch json {
794
- | Object(d) => d
795
- | _ => Dict.make()
796
- }
797
- epDecoder.decode(~eventType=json->Reventless.Message.variantNameOfJson, ~data)
798
- })
1399
+ let key = "extension:" ++ part.name
1400
+
1401
+ // The extension point's events on the record it has not reacted to yet, and
1402
+ // the commands it sends for them; the events now marked as reacted to.
1403
+ let reactWith = async (s: flowState) => {
1404
+ let handled = s->handledBy(key)
1405
+ let fresh =
1406
+ s.log
1407
+ ->Array.mapWithIndex((entry, i) => (Int.toString(i), entry))
1408
+ ->Array.filterMap(((i, entry)) =>
1409
+ handled->Array.includes(i)
1410
+ ? None
1411
+ : decodeMatching([entry], epDecoder, [])
1412
+ ->Array.get(0)
1413
+ ->Option.map(ev => (i, entry.id, ev))
1414
+ )
799
1415
  let actions =
800
- epEvents
801
- ->Array.map(ev =>
1416
+ fresh
1417
+ ->Array.map(((_, sourceId, ev)) =>
802
1418
  M.mapIncomingEvent(
803
- "gwt-id",
1419
+ sourceId,
804
1420
  ev,
805
1421
  StubRuntime.meta,
806
1422
  StubRuntime.pluginDefinition,
@@ -828,11 +1444,27 @@ module ExtensionStep = (M: ExtMapping.Mapping) => {
828
1444
  }
829
1445
  )
830
1446
  ->Promise.all
831
- {...s, lastCommands: nested->Array.flat}
1447
+ (s->markHandled(key, fresh->Array.map(((i, _, _)) => i)), nested->Array.flat)
832
1448
  }
833
1449
 
834
- let thenIssuesCommands = async (flowP: flow, expected: array<M.Delegate.command>) => {
835
- let s = await flowP
1450
+ // The extension reacts to the extension point's events it has not reacted to.
1451
+ let whenReacts = async (flowP: flow, ~at=?) => {
1452
+ let s = await flowP->enter(~verb="whenReacts", ~part, ~at?)
1453
+ let (s, commands) = await s->markNamed(key)->reactWith
1454
+ {...s, lastCommands: commands}
1455
+ }
1456
+
1457
+ let reacting: reacting = {
1458
+ key,
1459
+ part,
1460
+ react: async s => {
1461
+ let (s, commands) = await s->reactWith
1462
+ (s, commands->Array.map(command => {target: Some(M.Delegate.name), command}))
1463
+ },
1464
+ }
1465
+
1466
+ let issued = async (flowP: flow, ~verb, expected: array<M.Delegate.command>) => {
1467
+ let s = await flowP->enter(~verb, ~part)
836
1468
  let expJson = expected->Array.map(encCmd)
837
1469
  let o =
838
1470
  sortJson(s.lastCommands) == sortJson(expJson)
@@ -841,6 +1473,169 @@ module ExtensionStep = (M: ExtMapping.Mapping) => {
841
1473
  s->recordOutcome(o)
842
1474
  }
843
1475
 
844
- let thenIssuesCommand = (flowP, command) => thenIssuesCommands(flowP, [command])
845
- let thenIssuesNoCommand = flowP => thenIssuesCommands(flowP, [])
1476
+ let thenIssuesCommands = (flowP, expected) => issued(flowP, ~verb="thenIssuesCommands", expected)
1477
+ let thenIssuesCommand = (flowP, command) => issued(flowP, ~verb="thenIssuesCommand", [command])
1478
+ let thenIssuesNoCommand = flowP => issued(flowP, ~verb="thenIssuesNoCommand", [])
1479
+ }
1480
+
1481
+ // -- What else reacts --------------------------------------------------------
1482
+
1483
+ // Each reacting part of `systems` over the flow, in turn: the flow after them,
1484
+ // and what each sent.
1485
+ let reactAll = async (s: flowState, reacting: array<reacting>) => {
1486
+ let rec go = async (s, i, sent) =>
1487
+ switch reacting->Array.get(i) {
1488
+ | None => (s, sent)
1489
+ | Some(r) =>
1490
+ let (s, reactions) = await r.react(s)
1491
+ await go(s, i + 1, sent->Array.concat(reactions->Array.map(x => (r, x))))
1492
+ }
1493
+ await go(s, 0, [])
1494
+ }
1495
+
1496
+ // Every reacting part of the systems given that the flow did not name, run over
1497
+ // the record: one that would send a command fails the flow, and is named.
1498
+ let thenNothingElseReacts = async (flowP: flow, systems: array<parts>) => {
1499
+ let s = await flowP->enter(~verb="thenNothingElseReacts")
1500
+ let unnamed =
1501
+ systems->Array.flatMap(p => p.reacting)->Array.filter(r => !(s.named->Array.includes(r.key)))
1502
+ let (_, sent) = await s->reactAll(unnamed)
1503
+ // The failure points at the first part that would send.
1504
+ let s = switch sent[0] {
1505
+ | Some((r, _)) => {...s, at: s.at->Option.map(step => {...step, part: r.part})}
1506
+ | None => s
1507
+ }
1508
+ s->recordOutcome(
1509
+ switch sent {
1510
+ | [] => Outcome.pass
1511
+ | sent =>
1512
+ Outcome.fail(
1513
+ PublishedActionsMismatch({
1514
+ expected: [],
1515
+ actual: sent->Array.map(((r, {command})) =>
1516
+ JSON.Encode.object(
1517
+ Dict.fromArray([("reacts", JSON.Encode.string(r.part.name)), ("sends", command)]),
1518
+ )
1519
+ ),
1520
+ }),
1521
+ )
1522
+ },
1523
+ )
846
1524
  }
1525
+
1526
+ // How many rounds of reacting and deciding a flow settles within.
1527
+ let settleBound = 20
1528
+
1529
+ // The app does the rest: the systems' reacting parts react, the commands they
1530
+ // send are decided by the part that reads them (the one they are meant for
1531
+ // first), and again, until nothing is sent. A flow still sending after
1532
+ // `settleBound` rounds fails: it loops. The step's events are all of theirs.
1533
+ let whenSettled = async (flowP: flow, systems: array<parts>) => {
1534
+ let s = await flowP->enter(~verb="whenSettled")
1535
+ let reacting = systems->Array.flatMap(p => p.reacting)
1536
+ let deciding = systems->Array.flatMap(p => p.deciding)
1537
+ let decide = (s, {target, command}: reaction) =>
1538
+ switch target
1539
+ ->Option.flatMap(t => deciding->Array.find(d => d.name == t))
1540
+ ->Option.flatMap(d => d.run(s, command)) {
1541
+ | Some(s) => Some(s)
1542
+ | None => deciding->Array.findMap(d => d.run(s, command))
1543
+ }
1544
+ let rec round = async (s: flowState, n, events, commands) => {
1545
+ let (s, sent) = await s->reactAll(reacting)
1546
+ let s = reacting->Array.reduce(s, (s, r) => s->markNamed(r.key))
1547
+ switch sent {
1548
+ | [] => {...s, lastEvents: events, lastCommands: commands}
1549
+ | _ if n >= settleBound =>
1550
+ s->recordOutcome(
1551
+ Outcome.fail(
1552
+ Throw({
1553
+ error: `the flow does not settle: still sending after ${settleBound->Int.toString} rounds`,
1554
+ stack: "",
1555
+ }),
1556
+ ),
1557
+ )
1558
+ | sent =>
1559
+ let (s, events, unread) = sent->Array.reduce((s, events, None), (
1560
+ (s, events, unread),
1561
+ (_, reaction),
1562
+ ) =>
1563
+ switch unread {
1564
+ | Some(_) => (s, events, unread)
1565
+ | None =>
1566
+ switch s->decide(reaction) {
1567
+ | Some(next) => (next, events->Array.concat(next.lastEvents), None)
1568
+ | None => (s, events, Some(reaction.command))
1569
+ }
1570
+ }
1571
+ )
1572
+ switch unread {
1573
+ | Some(command) =>
1574
+ s->recordOutcome(
1575
+ Outcome.fail(
1576
+ TranslateError({
1577
+ expected: "a decision of the systems given that reads the command",
1578
+ actual: Some(`no decision reads ${JSON.stringify(command)}`),
1579
+ }),
1580
+ ),
1581
+ )
1582
+ | None =>
1583
+ await round(
1584
+ s,
1585
+ n + 1,
1586
+ events,
1587
+ commands->Array.concat(sent->Array.map(((_, {command})) => command)),
1588
+ )
1589
+ }
1590
+ }
1591
+ }
1592
+ await round({...s, lastEvents: [], lastError: None}, 0, [], [])
1593
+ }
1594
+
1595
+ // -- Old names ---------------------------------------------------------------
1596
+ //
1597
+ // Each old step name stays for one release so that a flow using it fails to
1598
+ // build with a message naming the new step. None of them runs.
1599
+
1600
+ type renamedToDecisionStep
1601
+ type movedToGeneratedBoundaryTest
1602
+ type renamedToAggregateStep
1603
+ type renamedToAutomationStep
1604
+ type renamedToOutboundStep
1605
+ type renamedToInboundStep
1606
+
1607
+ module type RenamedToDecisionStep = {
1608
+ type renamedToDecisionStep = renamedToDecisionStep
1609
+ }
1610
+ module type RenamedToAggregateStep = {
1611
+ type renamedToAggregateStep = renamedToAggregateStep
1612
+ }
1613
+ module type RenamedToAutomationStep = {
1614
+ type renamedToAutomationStep = renamedToAutomationStep
1615
+ }
1616
+ module type RenamedToOutboundStep = {
1617
+ type renamedToOutboundStep = renamedToOutboundStep
1618
+ }
1619
+ module type RenamedToInboundStep = {
1620
+ type renamedToInboundStep = renamedToInboundStep
1621
+ }
1622
+
1623
+ @deprecated("Renamed DecisionStep.")
1624
+ module CommandStep = (_: RenamedToDecisionStep, _: RenamedToDecisionStep) => {}
1625
+ @deprecated("Renamed AggregateStep.")
1626
+ module AggregateCommandStep = (_: RenamedToAggregateStep, _: RenamedToAggregateStep) => {}
1627
+ @deprecated("Renamed AutomationStep.")
1628
+ module AutomationSlice = (_: RenamedToAutomationStep, _: RenamedToAutomationStep) => {}
1629
+ @deprecated("Renamed OutboundStep.")
1630
+ module OutboundSlice = (_: RenamedToOutboundStep, _: RenamedToOutboundStep) => {}
1631
+ @deprecated("Renamed InboundStep.")
1632
+ module InboundSlice = (_: RenamedToInboundStep, _: RenamedToInboundStep) => {}
1633
+
1634
+ // A system's boundary is checked by the test `generate-plugin` writes for it
1635
+ // (`Boundary_GWT`), not in a flow.
1636
+ @deprecated("Moved: generate-plugin writes each system's boundary test (Boundary_GWT).")
1637
+ let thenBoundaryScopeResolves = (
1638
+ _: movedToGeneratedBoundaryTest,
1639
+ ~name as _: movedToGeneratedBoundaryTest,
1640
+ _: movedToGeneratedBoundaryTest,
1641
+ ) => ()