@reventlessdev/reventless-core 3.0.0-alpha.324 → 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 (40) hide show
  1. package/CHANGELOG.md +15 -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 +11 -3
  10. package/src/components/Aggregate/Aggregate_Callback.res.mjs +8 -6
  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 +205 -1
  33. package/tests/commandgenerator/OwnerActingTest.res.mjs +361 -0
  34. package/tests/commandtopic/CommandOutcomeHookTest.res +74 -2
  35. package/tests/commandtopic/CommandOutcomeHookTest.res.mjs +92 -0
  36. package/tests/commandtopic/CommandTopicHelpersRejectionTest.res.mjs +4 -4
  37. package/tests/logger/LoggerSinkTest.res +205 -0
  38. package/tests/logger/LoggerSinkTest.res.mjs +209 -0
  39. package/tests/projection/ViewChangeTest.res +173 -0
  40. 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 */
@@ -63,6 +63,9 @@ module Make = (
63
63
  Spec.eventSchema->S.castToUnknown,
64
64
  )
65
65
  let actsOnOwned = ownerFieldsByEventType->Dict.keysToArray->Array.length > 0
66
+ // An aggregate whose id is its owner (`Id.Owned`) needs no recorded event, so
67
+ // it keeps its snapshots.
68
+ let ownedById = Reventless.Owner.isOwnedById(Spec.Id.schema)
66
69
 
67
70
  let recordEventOwners = (owners, event: Spec.event) =>
68
71
  if actsOnOwned {
@@ -127,11 +130,11 @@ module Make = (
127
130
  // Before `decide`, second: an owner-marked aggregate refuses a caller who
128
131
  // does not own the stream.
129
132
  let refusal =
130
- repeated || !actsOnOwned
133
+ repeated || !(actsOnOwned || ownedById)
131
134
  ? None
132
135
  : Reventless.OwnerScope.decideActing(
133
136
  ~claim=command'.meta.callerClaim,
134
- ~recordedOwners=Some(owners),
137
+ ~recordedOwners=Some(owners->Reventless.Owner.streamOwners(~ownedById, ~id)),
135
138
  )->CommandTopic_Helpers.ownershipRefusal(~component=Spec.name, ~command=cmdVariant)
136
139
  switch refusal {
137
140
  | _ if repeated =>
@@ -411,11 +414,12 @@ module Make = (
411
414
  ~appendedEventCount: int,
412
415
  ~appendErrorDetail: string="",
413
416
  ): array<result<string, string>> =>
414
- outcomes->Array.map(((reference, outcome, _meta)) =>
417
+ outcomes->Array.map(((reference, outcome, meta: Message.meta)) =>
415
418
  switch outcome {
416
419
  | CmdRejected({errorCode, errorDetail}) =>
417
420
  CommandTopic_Helpers.reportRejected(
418
421
  ~component=Spec.name,
422
+ ~correlationId=meta.correlationId,
419
423
  ~cause=DomainRejection,
420
424
  reference,
421
425
  {errorCode, errorDetail},
@@ -424,6 +428,7 @@ module Make = (
424
428
  | CmdRefused({rejected}) =>
425
429
  CommandTopic_Helpers.reportRejected(
426
430
  ~component=Spec.name,
431
+ ~correlationId=meta.correlationId,
427
432
  ~cause=AccessRefusal,
428
433
  reference,
429
434
  rejected,
@@ -432,6 +437,7 @@ module Make = (
432
437
  | CmdOk(_) if appendSucceeded =>
433
438
  CommandTopic_Helpers.reportAccepted(
434
439
  ~component=Spec.name,
440
+ ~correlationId=meta.correlationId,
435
441
  reference,
436
442
  {entityId, eventCount: appendedEventCount},
437
443
  )
@@ -439,6 +445,7 @@ module Make = (
439
445
  | CmdRepeated =>
440
446
  CommandTopic_Helpers.reportAccepted(
441
447
  ~component=Spec.name,
448
+ ~correlationId=meta.correlationId,
442
449
  reference,
443
450
  {entityId, eventCount: 0},
444
451
  )
@@ -447,6 +454,7 @@ module Make = (
447
454
  // The decision succeeded and the append did not — infrastructure, not the model.
448
455
  CommandTopic_Helpers.reportRejected(
449
456
  ~component=Spec.name,
457
+ ~correlationId=meta.correlationId,
450
458
  ~cause=InfrastructureFailure,
451
459
  reference,
452
460
  {errorCode: Reventless.CommandOutcome.code(AppendFailed), errorDetail: appendErrorDetail},
@@ -34,6 +34,7 @@ function Make(Spec) {
34
34
  ]));
35
35
  let ownerFieldsByEventType = Owner$Reventless.fieldNamesByVariant(Spec.eventSchema);
36
36
  let actsOnOwned = Object.keys(ownerFieldsByEventType).length !== 0;
37
+ let ownedById = Owner$Reventless.isOwnedById(Spec.Id.schema);
37
38
  let recordEventOwners = (owners, event) => {
38
39
  if (!actsOnOwned) {
39
40
  return owners;
@@ -59,7 +60,7 @@ function Make(Spec) {
59
60
  let cmdName = LogFormat$ReventlessCore.bold(cmdVariant);
60
61
  Effect.runSync(EffectLogger$ReventlessCore.logDebug(comp, undefined, `deciding: id=` + id + ` seq=` + seq.toString() + ` cmd=` + cmdName));
61
62
  let repeated = Message$ReventlessCore.hasStableMsgId(command$p.meta) && causes.includes(command$p.meta.msgId);
62
- let refusal = repeated || !actsOnOwned ? undefined : CommandTopic_Helpers$ReventlessCore.ownershipRefusal(OwnerScope$Reventless.decideActing(command$p.meta.callerClaim, owners), Spec.name, cmdVariant);
63
+ let refusal = repeated || !(actsOnOwned || ownedById) ? undefined : CommandTopic_Helpers$ReventlessCore.ownershipRefusal(OwnerScope$Reventless.decideActing(command$p.meta.callerClaim, Owner$Reventless.streamOwners(owners, ownedById, id)), Spec.name, cmdVariant);
63
64
  if (repeated) {
64
65
  Effect.runSync(EffectLogger$ReventlessCore.logInfo(comp, undefined, `repeat dropped: ` + cmdName + `(` + id + `) msgId=` + command$p.meta.msgId + ` already caused events`));
65
66
  return {
@@ -276,10 +277,11 @@ function Make(Spec) {
276
277
  let reportFinalOutcomes = (outcomes, entityId, appendSucceeded, appendedEventCount, appendErrorDetailOpt) => {
277
278
  let appendErrorDetail = appendErrorDetailOpt !== undefined ? appendErrorDetailOpt : "";
278
279
  return outcomes.map(param => {
280
+ let meta = param[2];
279
281
  let outcome = param[1];
280
282
  let reference = param[0];
281
283
  if (typeof outcome !== "object") {
282
- CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, reference, {
284
+ CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, meta.correlationId, reference, {
283
285
  entityId: entityId,
284
286
  eventCount: 0
285
287
  });
@@ -291,7 +293,7 @@ function Make(Spec) {
291
293
  switch (outcome.TAG) {
292
294
  case "CmdOk" :
293
295
  if (appendSucceeded) {
294
- CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, reference, {
296
+ CommandTopic_Helpers$ReventlessCore.reportAccepted(Spec.name, meta.correlationId, reference, {
295
297
  entityId: entityId,
296
298
  eventCount: appendedEventCount
297
299
  });
@@ -300,7 +302,7 @@ function Make(Spec) {
300
302
  _0: reference
301
303
  };
302
304
  } else {
303
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", reference, {
305
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", meta.correlationId, reference, {
304
306
  errorCode: CommandOutcome$Reventless.code("AppendFailed"),
305
307
  errorDetail: appendErrorDetail
306
308
  });
@@ -310,7 +312,7 @@ function Make(Spec) {
310
312
  };
311
313
  }
312
314
  case "CmdRejected" :
313
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "DomainRejection", reference, {
315
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "DomainRejection", meta.correlationId, reference, {
314
316
  errorCode: outcome.errorCode,
315
317
  errorDetail: outcome.errorDetail
316
318
  });
@@ -319,7 +321,7 @@ function Make(Spec) {
319
321
  _0: reference
320
322
  };
321
323
  case "CmdRefused" :
322
- 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);
323
325
  return {
324
326
  TAG: "Ok",
325
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)