@reventlessdev/reventless-core 3.0.0-alpha.325 → 3.0.0-alpha.326

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/package.json +7 -7
  3. package/src/Message.res +46 -0
  4. package/src/Message.res.mjs +45 -0
  5. package/src/Projection.res +269 -131
  6. package/src/Projection.res.mjs +338 -224
  7. package/src/ViewChange.res +194 -0
  8. package/src/ViewChange.res.mjs +235 -0
  9. package/src/components/Aggregate/Aggregate_Callback.res +6 -1
  10. package/src/components/Aggregate/Aggregate_Callback.res.mjs +6 -5
  11. package/src/components/AutomationSlice/AutomationSlice_Callback.res +21 -9
  12. package/src/components/AutomationSlice/AutomationSlice_Callback.res.mjs +19 -8
  13. package/src/components/CommandTopic/CommandTopic.res.mjs +5 -2
  14. package/src/components/CommandTopic/CommandTopic_Helpers.res +56 -26
  15. package/src/components/CommandTopic/CommandTopic_Helpers.res.mjs +35 -16
  16. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Builder.res +6 -2
  17. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Builder.res.mjs +6 -2
  18. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Callback.res +25 -12
  19. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Callback.res.mjs +20 -7
  20. package/src/components/ReadModel/ReadModel_Callback.res +23 -3
  21. package/src/components/ReadModel/ReadModel_Callback.res.mjs +14 -2
  22. package/src/components/StateChangeSlice/StateChangeSlice_Callback.res +7 -0
  23. package/src/components/StateChangeSlice/StateChangeSlice_Callback.res.mjs +7 -7
  24. package/src/components/StateViewSlice/StateViewSlice_Builder.res +14 -2
  25. package/src/components/StateViewSlice/StateViewSlice_Builder.res.mjs +13 -2
  26. package/src/components/StateViewSlice/StateViewSlice_Callback.res +29 -4
  27. package/src/components/StateViewSlice/StateViewSlice_Callback.res.mjs +9 -2
  28. package/src/util/EffectLogger.res +30 -29
  29. package/src/util/EffectLogger.res.mjs +13 -22
  30. package/src/util/Logger.res +231 -35
  31. package/src/util/Logger.res.mjs +263 -42
  32. package/tests/commandgenerator/OwnerActingTest.res +3 -1
  33. package/tests/commandtopic/CommandOutcomeHookTest.res +74 -2
  34. package/tests/commandtopic/CommandOutcomeHookTest.res.mjs +92 -0
  35. package/tests/commandtopic/CommandTopicHelpersRejectionTest.res.mjs +4 -4
  36. package/tests/logger/LoggerSinkTest.res +205 -0
  37. package/tests/logger/LoggerSinkTest.res.mjs +209 -0
  38. package/tests/projection/ViewChangeTest.res +173 -0
  39. package/tests/projection/ViewChangeTest.res.mjs +292 -0
@@ -0,0 +1,194 @@
1
+ // What a projection changed in a view: one row created, changed or removed, and
2
+ // the events that led to it.
3
+ //
4
+ // Each change becomes an info log line `view changed` carrying the view, the
5
+ // row's key, the kind of change, the names of the fields that changed, and the
6
+ // events' message ids and entities, never the values: a log group cannot be swept
7
+ // for one person. A listener registered here (a platform that serves a watching
8
+ // tool, say) receives the change with the row before and after, as JSON, and
9
+ // redacts them itself if it sends them anywhere.
10
+
11
+ type kind = Projection.changeKind
12
+
13
+ /** One row change, as the log line and the listeners see it. */
14
+ type t = {
15
+ view: string,
16
+ key: string,
17
+ subId?: string,
18
+ kind: kind,
19
+ /** The top-level fields whose values differ; every field of the row where
20
+ only one side is known. */
21
+ fields: array<string>,
22
+ before?: JSON.t,
23
+ after?: JSON.t,
24
+ sources: array<Projection.changeSource>,
25
+ /** The flow the events share, when they all share one. */
26
+ correlationId?: string,
27
+ }
28
+
29
+ type listener = t => unit
30
+
31
+ type registered = {id: int, listener: listener}
32
+
33
+ let listeners: ref<array<registered>> = ref([])
34
+ let nextId = ref(0)
35
+
36
+ /** Adds a listener and returns the function that removes it. */
37
+ let register = (listener: listener): (unit => unit) => {
38
+ nextId := nextId.contents + 1
39
+ let id = nextId.contents
40
+ listeners := listeners.contents->Array.concat([{id, listener}])
41
+ () => listeners := listeners.contents->Array.filter(l => l.id != id)
42
+ }
43
+
44
+ /** Removes every listener. */
45
+ let clear = () => listeners := []
46
+
47
+ let kindLabel = (kind: kind) =>
48
+ switch kind {
49
+ | Created => "created"
50
+ | Changed => "changed"
51
+ | Removed => "removed"
52
+ }
53
+
54
+ /** The names of the top-level fields that differ between the two sides. */
55
+ let changedFields = (~before: option<JSON.t>, ~after: option<JSON.t>): array<string> => {
56
+ let objectOf = side => side->Option.flatMap(JSON.Decode.object)
57
+ switch (objectOf(before), objectOf(after)) {
58
+ | (Some(b), Some(a)) =>
59
+ let names = a->Dict.keysToArray
60
+ b
61
+ ->Dict.keysToArray
62
+ ->Array.forEach(name =>
63
+ if !(names->Array.includes(name)) {
64
+ names->Array.push(name)
65
+ }
66
+ )
67
+ names->Array.filter(name => b->Dict.get(name) != a->Dict.get(name))
68
+ | (None, Some(one)) | (Some(one), None) => one->Dict.keysToArray
69
+ | (None, None) => []
70
+ }
71
+ }
72
+
73
+ let sharedCorrelationId = (sources: array<Projection.changeSource>): option<string> =>
74
+ switch sources->Array.map(s => s.correlationId) {
75
+ | [] => None
76
+ | ids =>
77
+ let first = ids->Array.getUnsafe(0)
78
+ ids->Array.every(id => id == first) ? first : None
79
+ }
80
+
81
+ let sourceToJson = (s: Projection.changeSource): JSON.t =>
82
+ [("msgId", JSON.Encode.string(s.msgId))]
83
+ ->Array.concat(s.correlationId->Option.mapOr([], c => [("correlationId", JSON.Encode.string(c))]))
84
+ ->Array.concat(s.entityId->Option.mapOr([], e => [("entityId", JSON.Encode.string(e))]))
85
+ ->Array.concat(s.entityType->Option.mapOr([], e => [("entityType", JSON.Encode.string(e))]))
86
+ ->Dict.fromArray
87
+ ->JSON.Encode.object
88
+
89
+ /** The fields both the log line's detail and a feed line carry: everything but
90
+ the values. */
91
+ let summaryFields = (c: t): array<(string, JSON.t)> =>
92
+ [("view", JSON.Encode.string(c.view)), ("key", JSON.Encode.string(c.key))]
93
+ ->Array.concat(c.subId->Option.mapOr([], s => [("subId", JSON.Encode.string(s))]))
94
+ ->Array.concat([
95
+ ("change", JSON.Encode.string(kindLabel(c.kind))),
96
+ ("fields", c.fields->Array.map(JSON.Encode.string)->JSON.Encode.array),
97
+ ("sources", c.sources->Array.map(sourceToJson)->JSON.Encode.array),
98
+ ])
99
+
100
+ let logLine = (~comp: string, c: t) =>
101
+ Logger.emit(
102
+ ~level=Info,
103
+ ~comp,
104
+ ~annotations=c.correlationId->Option.mapOr(Dict.make(), id =>
105
+ Dict.fromArray([("correlationId", id)])
106
+ ),
107
+ ~detail=c->summaryFields->Dict.fromArray->JSON.Encode.object,
108
+ "view changed",
109
+ )
110
+
111
+ /**
112
+ The `~onChange` a projection's caller passes to `Projection.handleAction`:
113
+ logs each change and hands it to the listeners. `stateToJson` encodes a row the
114
+ way the view stores it; a row it cannot encode counts as unknown. Nothing is
115
+ encoded when the line is below its level and nobody listens.
116
+ */
117
+ let reporter = (~comp: string, ~view: string, ~stateToJson: 'state => JSON.t): (
118
+ Projection.rowChange<'state> => unit
119
+ ) =>
120
+ change => {
121
+ let logs = Logger.shouldLog(Info, ~comp, ())
122
+ let listening = listeners.contents != []
123
+ if logs || listening {
124
+ let toJson = state =>
125
+ switch stateToJson(state) {
126
+ | json => Some(json)
127
+ | exception _ => None
128
+ }
129
+ let before = change.before->Option.flatMap(toJson)
130
+ let after = change.after->Option.flatMap(toJson)
131
+ let fields = changedFields(~before, ~after)
132
+ // An update that wrote the row as it was changed nothing a reader can see.
133
+ let unchanged = switch (change.kind, before, after) {
134
+ | (Changed, Some(_), Some(_)) => fields == []
135
+ | _ => false
136
+ }
137
+ if !unchanged {
138
+ let c = {
139
+ view,
140
+ key: change.key,
141
+ subId: ?change.subId,
142
+ kind: change.kind,
143
+ fields,
144
+ ?before,
145
+ ?after,
146
+ sources: change.sources,
147
+ correlationId: ?sharedCorrelationId(change.sources),
148
+ }
149
+ if logs {
150
+ logLine(~comp, c)
151
+ }
152
+ listeners.contents->Array.forEach(({listener}) =>
153
+ try listener(c) catch {
154
+ | exn =>
155
+ Console.error(
156
+ `a view-change listener failed and is skipped for that change: ${exn
157
+ ->JsExn.fromException
158
+ ->Option.flatMap(JsExn.message)
159
+ ->Option.getOr("unknown")}`,
160
+ )
161
+ }
162
+ )
163
+ }
164
+ }
165
+ }
166
+
167
+ /** The source of a change from an event's meta and the entity it is about. */
168
+ let sourceOf = (
169
+ ~meta: Reventless.Message.meta,
170
+ ~entityId: option<string>=?,
171
+ ~entityType: option<string>=?,
172
+ (),
173
+ ): Projection.changeSource => {
174
+ msgId: meta.msgId,
175
+ correlationId: meta.correlationId,
176
+ ?entityId,
177
+ ?entityType,
178
+ }
179
+
180
+ /** The entity a stored event's envelope is about: its first tag (value and key)
181
+ when it has tags, a DCB event; otherwise its `id`, an aggregate's. */
182
+ let entityOfEnvelope = (envelope: dict<JSON.t>): (option<string>, option<string>) => {
183
+ let firstTag =
184
+ envelope
185
+ ->Dict.get("tags")
186
+ ->Option.flatMap(JSON.Decode.array)
187
+ ->Option.flatMap(tags => tags->Array.get(0))
188
+ ->Option.flatMap(JSON.Decode.object)
189
+ let string = (d, k) => d->Dict.get(k)->Option.flatMap(JSON.Decode.string)
190
+ switch firstTag {
191
+ | Some(tag) => (string(tag, "value"), string(tag, "key"))
192
+ | None => (string(envelope, "id"), None)
193
+ }
194
+ }
@@ -0,0 +1,235 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Stdlib_JSON from "@rescript/runtime/lib/es6/Stdlib_JSON.js";
4
+ import * as Stdlib_JsExn from "@rescript/runtime/lib/es6/Stdlib_JsExn.js";
5
+ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
6
+ import * as Primitive_object from "@rescript/runtime/lib/es6/Primitive_object.js";
7
+ import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.js";
8
+ import * as Logger$ReventlessCore from "./util/Logger.res.mjs";
9
+
10
+ let listeners = {
11
+ contents: []
12
+ };
13
+
14
+ let nextId = {
15
+ contents: 0
16
+ };
17
+
18
+ function register(listener) {
19
+ nextId.contents = nextId.contents + 1 | 0;
20
+ let id = nextId.contents;
21
+ listeners.contents = listeners.contents.concat([{
22
+ id: id,
23
+ listener: listener
24
+ }]);
25
+ return () => {
26
+ listeners.contents = listeners.contents.filter(l => l.id !== id);
27
+ };
28
+ }
29
+
30
+ function clear() {
31
+ listeners.contents = [];
32
+ }
33
+
34
+ function kindLabel(kind) {
35
+ switch (kind) {
36
+ case "Created" :
37
+ return "created";
38
+ case "Changed" :
39
+ return "changed";
40
+ case "Removed" :
41
+ return "removed";
42
+ }
43
+ }
44
+
45
+ function changedFields(before, after) {
46
+ let match = Stdlib_Option.flatMap(before, Stdlib_JSON.Decode.object);
47
+ let match$1 = Stdlib_Option.flatMap(after, Stdlib_JSON.Decode.object);
48
+ if (match === undefined) {
49
+ if (match$1 !== undefined) {
50
+ return Object.keys(match$1);
51
+ } else {
52
+ return [];
53
+ }
54
+ }
55
+ if (match$1 === undefined) {
56
+ return Object.keys(match);
57
+ }
58
+ let names = Object.keys(match$1);
59
+ Object.keys(match).forEach(name => {
60
+ if (!names.includes(name)) {
61
+ names.push(name);
62
+ return;
63
+ }
64
+ });
65
+ return names.filter(name => Primitive_object.notequal(match[name], match$1[name]));
66
+ }
67
+
68
+ function sharedCorrelationId(sources) {
69
+ let ids = sources.map(s => s.correlationId);
70
+ if (ids.length === 0) {
71
+ return;
72
+ }
73
+ let first = ids[0];
74
+ if (ids.every(id => Primitive_object.equal(id, first))) {
75
+ return first;
76
+ }
77
+ }
78
+
79
+ function sourceToJson(s) {
80
+ return Object.fromEntries([[
81
+ "msgId",
82
+ s.msgId
83
+ ]].concat(Stdlib_Option.mapOr(s.correlationId, [], c => [[
84
+ "correlationId",
85
+ c
86
+ ]])).concat(Stdlib_Option.mapOr(s.entityId, [], e => [[
87
+ "entityId",
88
+ e
89
+ ]])).concat(Stdlib_Option.mapOr(s.entityType, [], e => [[
90
+ "entityType",
91
+ e
92
+ ]])));
93
+ }
94
+
95
+ function summaryFields(c) {
96
+ return [
97
+ [
98
+ "view",
99
+ c.view
100
+ ],
101
+ [
102
+ "key",
103
+ c.key
104
+ ]
105
+ ].concat(Stdlib_Option.mapOr(c.subId, [], s => [[
106
+ "subId",
107
+ s
108
+ ]])).concat([
109
+ [
110
+ "change",
111
+ kindLabel(c.kind)
112
+ ],
113
+ [
114
+ "fields",
115
+ c.fields.map(prim => prim)
116
+ ],
117
+ [
118
+ "sources",
119
+ c.sources.map(sourceToJson)
120
+ ]
121
+ ]);
122
+ }
123
+
124
+ function logLine(comp, c) {
125
+ Logger$ReventlessCore.emit("Info", comp, undefined, Object.fromEntries(summaryFields(c)), Stdlib_Option.mapOr(c.correlationId, {}, id => Object.fromEntries([[
126
+ "correlationId",
127
+ id
128
+ ]])), "view changed");
129
+ }
130
+
131
+ function reporter(comp, view, stateToJson) {
132
+ return change => {
133
+ let logs = Logger$ReventlessCore.shouldLog("Info", undefined, comp, undefined);
134
+ let listening = Primitive_object.notequal(listeners.contents, []);
135
+ if (!(logs || listening)) {
136
+ return;
137
+ }
138
+ let toJson = state => {
139
+ let json;
140
+ try {
141
+ json = stateToJson(state);
142
+ } catch (exn) {
143
+ return;
144
+ }
145
+ return json;
146
+ };
147
+ let before = Stdlib_Option.flatMap(change.before, toJson);
148
+ let after = Stdlib_Option.flatMap(change.after, toJson);
149
+ let fields = changedFields(before, after);
150
+ let match = change.kind;
151
+ let unchanged;
152
+ switch (match) {
153
+ case "Changed" :
154
+ unchanged = before !== undefined && after !== undefined ? Primitive_object.equal(fields, []) : false;
155
+ break;
156
+ case "Created" :
157
+ case "Removed" :
158
+ unchanged = false;
159
+ break;
160
+ }
161
+ if (unchanged) {
162
+ return;
163
+ }
164
+ let c_key = change.key;
165
+ let c_subId = change.subId;
166
+ let c_kind = change.kind;
167
+ let c_sources = change.sources;
168
+ let c_correlationId = sharedCorrelationId(change.sources);
169
+ let c = {
170
+ view: view,
171
+ key: c_key,
172
+ subId: c_subId,
173
+ kind: c_kind,
174
+ fields: fields,
175
+ before: before,
176
+ after: after,
177
+ sources: c_sources,
178
+ correlationId: c_correlationId
179
+ };
180
+ if (logs) {
181
+ logLine(comp, c);
182
+ }
183
+ listeners.contents.forEach(param => {
184
+ try {
185
+ return param.listener(c);
186
+ } catch (raw_exn) {
187
+ let exn = Primitive_exceptions.internalToException(raw_exn);
188
+ console.error(`a view-change listener failed and is skipped for that change: ` + Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_JsExn.fromException(exn), Stdlib_JsExn.message), "unknown"));
189
+ return;
190
+ }
191
+ });
192
+ };
193
+ }
194
+
195
+ function sourceOf(meta, entityId, entityType, param) {
196
+ return {
197
+ msgId: meta.msgId,
198
+ correlationId: meta.correlationId,
199
+ entityId: entityId,
200
+ entityType: entityType
201
+ };
202
+ }
203
+
204
+ function entityOfEnvelope(envelope) {
205
+ let firstTag = Stdlib_Option.flatMap(Stdlib_Option.flatMap(Stdlib_Option.flatMap(envelope["tags"], Stdlib_JSON.Decode.array), tags => tags[0]), Stdlib_JSON.Decode.object);
206
+ let string = (d, k) => Stdlib_Option.flatMap(d[k], Stdlib_JSON.Decode.string);
207
+ if (firstTag !== undefined) {
208
+ return [
209
+ string(firstTag, "value"),
210
+ string(firstTag, "key")
211
+ ];
212
+ } else {
213
+ return [
214
+ string(envelope, "id"),
215
+ undefined
216
+ ];
217
+ }
218
+ }
219
+
220
+ export {
221
+ listeners,
222
+ nextId,
223
+ register,
224
+ clear,
225
+ kindLabel,
226
+ changedFields,
227
+ sharedCorrelationId,
228
+ sourceToJson,
229
+ summaryFields,
230
+ logLine,
231
+ reporter,
232
+ sourceOf,
233
+ entityOfEnvelope,
234
+ }
235
+ /* Stdlib_JsExn Not a pure module */
@@ -414,11 +414,12 @@ module Make = (
414
414
  ~appendedEventCount: int,
415
415
  ~appendErrorDetail: string="",
416
416
  ): array<result<string, string>> =>
417
- outcomes->Array.map(((reference, outcome, _meta)) =>
417
+ outcomes->Array.map(((reference, outcome, meta: Message.meta)) =>
418
418
  switch outcome {
419
419
  | CmdRejected({errorCode, errorDetail}) =>
420
420
  CommandTopic_Helpers.reportRejected(
421
421
  ~component=Spec.name,
422
+ ~correlationId=meta.correlationId,
422
423
  ~cause=DomainRejection,
423
424
  reference,
424
425
  {errorCode, errorDetail},
@@ -427,6 +428,7 @@ module Make = (
427
428
  | CmdRefused({rejected}) =>
428
429
  CommandTopic_Helpers.reportRejected(
429
430
  ~component=Spec.name,
431
+ ~correlationId=meta.correlationId,
430
432
  ~cause=AccessRefusal,
431
433
  reference,
432
434
  rejected,
@@ -435,6 +437,7 @@ module Make = (
435
437
  | CmdOk(_) if appendSucceeded =>
436
438
  CommandTopic_Helpers.reportAccepted(
437
439
  ~component=Spec.name,
440
+ ~correlationId=meta.correlationId,
438
441
  reference,
439
442
  {entityId, eventCount: appendedEventCount},
440
443
  )
@@ -442,6 +445,7 @@ module Make = (
442
445
  | CmdRepeated =>
443
446
  CommandTopic_Helpers.reportAccepted(
444
447
  ~component=Spec.name,
448
+ ~correlationId=meta.correlationId,
445
449
  reference,
446
450
  {entityId, eventCount: 0},
447
451
  )
@@ -450,6 +454,7 @@ module Make = (
450
454
  // The decision succeeded and the append did not — infrastructure, not the model.
451
455
  CommandTopic_Helpers.reportRejected(
452
456
  ~component=Spec.name,
457
+ ~correlationId=meta.correlationId,
453
458
  ~cause=InfrastructureFailure,
454
459
  reference,
455
460
  {errorCode: Reventless.CommandOutcome.code(AppendFailed), errorDetail: appendErrorDetail},
@@ -277,10 +277,11 @@ function Make(Spec) {
277
277
  let reportFinalOutcomes = (outcomes, entityId, appendSucceeded, appendedEventCount, appendErrorDetailOpt) => {
278
278
  let appendErrorDetail = appendErrorDetailOpt !== undefined ? appendErrorDetailOpt : "";
279
279
  return outcomes.map(param => {
280
+ let meta = param[2];
280
281
  let outcome = param[1];
281
282
  let reference = param[0];
282
283
  if (typeof outcome !== "object") {
283
- CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, reference, {
284
+ CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, meta.correlationId, reference, {
284
285
  entityId: entityId,
285
286
  eventCount: 0
286
287
  });
@@ -292,7 +293,7 @@ function Make(Spec) {
292
293
  switch (outcome.TAG) {
293
294
  case "CmdOk" :
294
295
  if (appendSucceeded) {
295
- CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, reference, {
296
+ CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, meta.correlationId, reference, {
296
297
  entityId: entityId,
297
298
  eventCount: appendedEventCount
298
299
  });
@@ -301,7 +302,7 @@ function Make(Spec) {
301
302
  _0: reference
302
303
  };
303
304
  } else {
304
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", reference, {
305
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", meta.correlationId, reference, {
305
306
  errorCode: CommandOutcome$Reventless.code("AppendFailed"),
306
307
  errorDetail: appendErrorDetail
307
308
  });
@@ -311,7 +312,7 @@ function Make(Spec) {
311
312
  };
312
313
  }
313
314
  case "CmdRejected" :
314
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "DomainRejection", reference, {
315
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "DomainRejection", meta.correlationId, reference, {
315
316
  errorCode: outcome.errorCode,
316
317
  errorDetail: outcome.errorDetail
317
318
  });
@@ -320,7 +321,7 @@ function Make(Spec) {
320
321
  _0: reference
321
322
  };
322
323
  case "CmdRefused" :
323
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "AccessRefusal", reference, outcome._0.rejected);
324
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "AccessRefusal", meta.correlationId, reference, outcome._0.rejected);
324
325
  return {
325
326
  TAG: "Ok",
326
327
  _0: reference
@@ -38,6 +38,9 @@ type todoRow = {
38
38
  rehydrated through `S.parseOrThrow`, and a required field would fail that
39
39
  decode — silently, since the restore swallows it per row. */
40
40
  maxRetries?: int,
41
+ /** The event that created the row, so the commands sent for it continue its
42
+ flow. Absent on rows written before it existed, and on rows a tick created. */
43
+ source?: Message.flowSource,
41
44
  }
42
45
 
43
46
  /** The item schema seen through the `JSON.t` the row actually stores.
@@ -69,6 +72,7 @@ let todoRowSchemaFor = (itemSchema: S.t<'item>): S.t<todoRow> =>
69
72
  completedAt: ?s.matches(S.option(S.string)),
70
73
  retryCount: s.matches(S.int),
71
74
  maxRetries: ?s.matches(S.option(S.int)),
75
+ source: ?s.matches(S.option(Message.flowSourceSchema)),
72
76
  })
73
77
 
74
78
  /**
@@ -170,17 +174,20 @@ module Make = (
170
174
 
171
175
  let now = () => Date.make()->Date.toISOString
172
176
 
173
- // Root meta for commands emitted by this AutomationSlice. The triggering
174
- // event's meta is not currently threaded from phase1 → phase2 (todoItems
175
- // only carries `item` data), so causation across the automation hop is
176
- // lost — emitted commands are roots of a fresh correlation chain. If we
177
- // later thread source meta through todoItems, switch to deriveMeta.
177
+ // Meta for a command emitted for a row: derived from the event that created
178
+ // the row, so the command continues its flow (its correlation id, the event's
179
+ // message id as causation, its user and trace parent). A row without a source
180
+ // (written before rows kept one, or created by a tick) starts a new flow.
178
181
  // `service` names the command's TARGET, matching the API path
179
182
  // (`CommandGenerator_Callback` passes `~serviceName=AggregateSpec.name`). An
180
183
  // aggregate derives its event meta from the command's, and ReadModel /
181
184
  // AutomationSlice callbacks dispatch mappings on `meta.service` — so naming
182
185
  // the slice here makes the target's own events unmatchable, silently.
183
- let makeMeta = (): Reventless.Message.meta => Message.generateMeta(~service=Spec.targetName)
186
+ let makeMeta = (row: todoRow): Reventless.Message.meta =>
187
+ switch row.source {
188
+ | Some(source) => Message.deriveMetaFromSource(source, ~service=Spec.targetName)
189
+ | None => Message.generateMeta(~service=Spec.targetName)
190
+ }
184
191
 
185
192
  // A work item that carries personal data is stored the way an event is: its
186
193
  // marked fields sealed, its row keyed by a fingerprint of the key the mapping
@@ -296,7 +303,7 @@ module Make = (
296
303
  | Open({key, item}) =>
297
304
  Automation.onExhausted(key, item)->Option.flatMap(((targetId, command)) =>
298
305
  switch command->Reventless.Util_Sury.toJson(Spec.commandSchema) {
299
- | commandJson => Some({Reventless.Message.id: targetId, meta: makeMeta(), commandJson})
306
+ | commandJson => Some({Reventless.Message.id: targetId, meta: makeMeta(row), commandJson})
300
307
  | exception _ =>
301
308
  EffectLogger.logError(
302
309
  ~comp=`AutomationSlice(${Spec.name})`,
@@ -326,6 +333,7 @@ module Make = (
326
333
  let apply = async (
327
334
  {collected, resolved}: AutomationSlice_Route.routed<Spec.todoItem>,
328
335
  ~capabilities,
336
+ ~source: option<Message.flowSource>,
329
337
  ) => {
330
338
  for i in 0 to collected->Array.length - 1 {
331
339
  let (key, item) = collected->Array.getUnsafe(i)
@@ -346,6 +354,7 @@ module Make = (
346
354
  createdAt: now(),
347
355
  retryCount: 0,
348
356
  maxRetries: Spec.maxRetries,
357
+ ?source,
349
358
  }
350
359
  todoItems->Dict.set(id, row)
351
360
  }
@@ -410,8 +419,11 @@ module Make = (
410
419
  }
411
420
  // Multiple mappings can share a sourceName; all matching dispatches run.
412
421
  let routed = Route.route(eventPayload, ~sourceName, ~sourceId=context.id, ctx)
422
+ // A tick's meta is made up as it fires, so a row it creates starts a flow.
423
+ let source =
424
+ sourceName == Reventless.Clock.name ? None : Some(Message.flowSourceOf(context.meta))
413
425
  for j in 0 to routed->Array.length - 1 {
414
- await apply(routed->Array.getUnsafe(j), ~capabilities)
426
+ await apply(routed->Array.getUnsafe(j), ~capabilities, ~source)
415
427
  }
416
428
  reschedule(
417
429
  routed,
@@ -523,7 +535,7 @@ module Make = (
523
535
  commandJson->Option.forEach(commandJson => {
524
536
  let msg: Reventless.Message.commandJson = {
525
537
  id: targetId,
526
- meta: makeMeta(),
538
+ meta: makeMeta(row),
527
539
  commandJson,
528
540
  }
529
541
  let _ = commands->Array.push(msg)
@@ -34,7 +34,8 @@ let todoRowSchema = Sury.$schema(s => ({
34
34
  processedAt: s.m(Sury.$option(Sury.string)),
35
35
  completedAt: s.m(Sury.$option(Sury.string)),
36
36
  retryCount: s.m(Sury.int32),
37
- maxRetries: s.m(Sury.$option(Sury.int32))
37
+ maxRetries: s.m(Sury.$option(Sury.int32)),
38
+ source: s.m(Sury.$option(Message$ReventlessCore.flowSourceSchema))
38
39
  }));
39
40
 
40
41
  function todoRowSchemaFor(itemSchema) {
@@ -45,7 +46,8 @@ function todoRowSchemaFor(itemSchema) {
45
46
  processedAt: s.m(Sury.$option(Sury.string)),
46
47
  completedAt: s.m(Sury.$option(Sury.string)),
47
48
  retryCount: s.m(Sury.int32),
48
- maxRetries: s.m(Sury.$option(Sury.int32))
49
+ maxRetries: s.m(Sury.$option(Sury.int32)),
50
+ source: s.m(Sury.$option(Message$ReventlessCore.flowSourceSchema))
49
51
  }));
50
52
  }
51
53
 
@@ -84,7 +86,14 @@ function Make(Spec) {
84
86
  return changes;
85
87
  };
86
88
  let readsClock = Automation.mappings.some(M => M.sourceName === Clock$Reventless.name);
87
- let makeMeta = () => Message$ReventlessCore.generateMeta(Spec.targetName, undefined, undefined, undefined, undefined, undefined, undefined);
89
+ let makeMeta = row => {
90
+ let source = row.source;
91
+ if (source !== undefined) {
92
+ return Message$ReventlessCore.deriveMetaFromSource(source, Spec.targetName);
93
+ } else {
94
+ return Message$ReventlessCore.generateMeta(Spec.targetName, undefined, undefined, undefined, undefined, undefined, undefined);
95
+ }
96
+ };
88
97
  let personalFields = Pii$Reventless.recordFields(Spec.todoItemSchema);
89
98
  let keyField = "$key";
90
99
  let fingerprintPurpose = `automationWorkItem:` + Spec.name;
@@ -199,7 +208,7 @@ function Make(Spec) {
199
208
  }
200
209
  return {
201
210
  id: param[0],
202
- meta: makeMeta(),
211
+ meta: makeMeta(row),
203
212
  commandJson: commandJson
204
213
  };
205
214
  });
@@ -219,7 +228,7 @@ function Make(Spec) {
219
228
  return millis;
220
229
  }
221
230
  };
222
- let apply = async (param, capabilities) => {
231
+ let apply = async (param, capabilities, source) => {
223
232
  let collected = param.collected;
224
233
  for (let i = 0, i_finish = collected.length; i < i_finish; ++i) {
225
234
  let match = collected[i];
@@ -236,7 +245,8 @@ function Make(Spec) {
236
245
  status: "Pending",
237
246
  createdAt: row_createdAt,
238
247
  retryCount: 0,
239
- maxRetries: row_maxRetries
248
+ maxRetries: row_maxRetries,
249
+ source: source
240
250
  };
241
251
  todoItems[id] = row;
242
252
  } else {
@@ -284,8 +294,9 @@ function Make(Spec) {
284
294
  let dict = Stdlib_JSON.Decode.object(json);
285
295
  let eventPayload = dict !== undefined ? Stdlib_Option.getOr(dict["event"], json) : json;
286
296
  let routed = Route.route(eventPayload, sourceName, context.id, ctx);
297
+ let source = sourceName === Clock$Reventless.name ? undefined : Message$ReventlessCore.flowSourceOf(context.meta);
287
298
  for (let j = 0, j_finish = routed.length; j < j_finish; ++j) {
288
- await apply(routed[j], capabilities);
299
+ await apply(routed[j], capabilities, source);
289
300
  }
290
301
  reschedule(routed, context.meta.msgId, Stdlib_Option.getOr(ctx.recordedAt, Date.now()));
291
302
  if (sourceName === Clock$Reventless.name) {
@@ -385,7 +396,7 @@ function Make(Spec) {
385
396
  commandJson = undefined;
386
397
  }
387
398
  Stdlib_Option.forEach(commandJson, commandJson => {
388
- let msg_meta = makeMeta();
399
+ let msg_meta = makeMeta(row);
389
400
  let msg = {
390
401
  id: targetId,
391
402
  meta: msg_meta,