@reventlessdev/reventless-core 3.0.0-alpha.333 → 3.0.0-alpha.335

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 (38) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +6 -6
  3. package/src/CommandSent.res +10 -0
  4. package/src/CommandSent.res.mjs +8 -0
  5. package/src/components/Aggregate/Aggregate_Callback.res +3 -0
  6. package/src/components/Aggregate/Aggregate_Callback.res.mjs +3 -3
  7. package/src/components/AutomationSlice/AutomationSlice.res +3 -0
  8. package/src/components/AutomationSlice/AutomationSlice_Builder.res +24 -8
  9. package/src/components/AutomationSlice/AutomationSlice_Builder.res.mjs +109 -102
  10. package/src/components/AutomationSlice/AutomationSlice_Callback.res +75 -8
  11. package/src/components/AutomationSlice/AutomationSlice_Callback.res.mjs +58 -7
  12. package/src/components/CommandGenerator/CommandGenerator_Callback.res.mjs +1 -1
  13. package/src/components/CommandTopic/CommandTopic.res.mjs +9 -0
  14. package/src/components/CommandTopic/CommandTopic_Helpers.res +118 -33
  15. package/src/components/CommandTopic/CommandTopic_Helpers.res.mjs +137 -22
  16. package/src/components/Dcb/Dcb_Builder.res +16 -0
  17. package/src/components/Dcb/Dcb_Builder.res.mjs +6 -3
  18. package/src/components/InboundTranslationSlice/InboundTranslationSlice.res +3 -0
  19. package/src/components/InboundTranslationSlice/InboundTranslationSlice_Builder.res +17 -6
  20. package/src/components/InboundTranslationSlice/InboundTranslationSlice_Builder.res.mjs +46 -41
  21. package/src/components/InboundTranslationSlice/InboundTranslationSlice_Callback.res +37 -8
  22. package/src/components/InboundTranslationSlice/InboundTranslationSlice_Callback.res.mjs +33 -13
  23. package/src/components/InboundTranslationSlice/InboundTranslationSlice_Webhook.res +3 -0
  24. package/src/components/InboundTranslationSlice/InboundTranslationSlice_Webhook.res.mjs +14 -2
  25. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice.res +3 -0
  26. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Builder.res +30 -9
  27. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Builder.res.mjs +10 -5
  28. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Callback.res +40 -2
  29. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Callback.res.mjs +57 -11
  30. package/src/components/StateChangeSlice/StateChangeSlice_Callback.res +20 -2
  31. package/src/components/StateChangeSlice/StateChangeSlice_Callback.res.mjs +12 -6
  32. package/tests/commandtopic/CommandOutcomeLineTest.res.mjs +3 -3
  33. package/tests/commandtopic/CommandTopicHelpersRejectionTest.res +102 -0
  34. package/tests/commandtopic/CommandTopicHelpersRejectionTest.res.mjs +101 -3
  35. package/tests/dcb/DcbReadsNothingTest.res +111 -0
  36. package/tests/dcb/DcbReadsNothingTest.res.mjs +234 -0
  37. package/tests/plugin/PluginStructureAccessTest.res +6 -1
  38. package/tests/plugin/PluginStructureAccessTest.res.mjs +1 -1
@@ -98,6 +98,7 @@ type phase1<'event> = (
98
98
  type phase2 = (
99
99
  ReventlessInfra.CommandTopic.publishJsons,
100
100
  ~capabilities: Reventless.Capabilities.t,
101
+ ~publishJsonsAndWait: CommandTopic_Helpers.publishJsonsAndWait=?,
101
102
  ) => promise<unit>
102
103
 
103
104
  /** The whole protocol as a value — what a driver holding a built callback needs,
@@ -176,6 +177,20 @@ module Make = (
176
177
  }
177
178
  }
178
179
 
180
+ /** The row after the target refused the command `translate` produced. Only an
181
+ infrastructure failure is retried: a retry runs `translate` again, and the
182
+ outside service has already acted once. A business or permission refusal
183
+ ends the row, with the target's reason. */
184
+ let afterRefusal = (
185
+ row: todoRow,
186
+ ~cause: CommandTopic_Helpers.refusalCause,
187
+ ~lastError: string,
188
+ ): todoRow =>
189
+ switch cause {
190
+ | InfrastructureFailure => row->afterFailedAttempt(~lastError)
191
+ | DomainRejection | AccessRefusal => {...row->afterFailedAttempt(~lastError), status: Abandoned}
192
+ }
193
+
179
194
  /** Ask the slice whether abandonment is worth telling the domain about, and
180
195
  publish what it says. Failing to publish here cannot mark the row for retry
181
196
  — the budget is what ran out — so the loss is logged and the row stays
@@ -301,11 +316,16 @@ module Make = (
301
316
  let phase2 = async (
302
317
  publishJsons: ReventlessInfra.CommandTopic.publishJsons,
303
318
  ~capabilities: Reventless.Capabilities.t,
319
+ ~publishJsonsAndWait: option<CommandTopic_Helpers.publishJsonsAndWait>=?,
304
320
  ) => {
305
321
  let publishJsons = CommandSent.announcing(
306
322
  ~comp=`OutboundTranslationSlice(${Spec.name})`,
307
323
  publishJsons,
308
324
  )
325
+ let publishJsonsAndWait =
326
+ publishJsonsAndWait->Option.map(wait =>
327
+ CommandSent.announcingAndWaiting(~comp=`OutboundTranslationSlice(${Spec.name})`, wait)
328
+ )
309
329
  // Ids that ran out of budget during this pass, announced once at the end so
310
330
  // one item's abandonment cannot interleave with another's attempt.
311
331
  let newlyAbandoned: array<string> = []
@@ -423,8 +443,26 @@ module Make = (
423
443
  meta: makeMeta(row),
424
444
  commandJson,
425
445
  }
426
- await publishJsons([msg])
427
- todoItems->Dict.set(id, {...row, status: Completed, completedAt: now()})
446
+ let refusal = switch publishJsonsAndWait {
447
+ | Some(wait) =>
448
+ switch (await wait([msg]))->Array.get(0) {
449
+ | Some(Rejected({errorCode, errorDetail, cause})) =>
450
+ Some((cause, CommandTopic_Helpers.describeRefusal(~errorCode, ~errorDetail)))
451
+ | Some(Accepted(_) | Pending(_)) | None => None
452
+ }
453
+ | None =>
454
+ await publishJsons([msg])
455
+ None
456
+ }
457
+ switch refusal {
458
+ | Some((cause, lastError)) =>
459
+ let updated = row->afterRefusal(~cause, ~lastError)
460
+ todoItems->Dict.set(id, updated)
461
+ if updated.status == Abandoned {
462
+ newlyAbandoned->Array.push(id)
463
+ }
464
+ | None => todoItems->Dict.set(id, {...row, status: Completed, completedAt: now()})
465
+ }
428
466
  } catch {
429
467
  | exn =>
430
468
  let errMsg =
@@ -14,6 +14,7 @@ import * as Util_Sury$Reventless from "@reventlessdev/reventless-spec/src/util/U
14
14
  import * as Message$ReventlessCore from "../../Message.res.mjs";
15
15
  import * as CommandSent$ReventlessCore from "../../CommandSent.res.mjs";
16
16
  import * as EffectLogger$ReventlessCore from "../../util/EffectLogger.res.mjs";
17
+ import * as CommandTopic_Helpers$ReventlessCore from "../CommandTopic/CommandTopic_Helpers.res.mjs";
17
18
 
18
19
  let todoStatusSchema = Sury.union([
19
20
  Sury.literal("Pending"),
@@ -69,6 +70,18 @@ function Make(Spec) {
69
70
  newrecord.status = retryCount >= Spec.maxRetries ? "Abandoned" : "Failed";
70
71
  return newrecord;
71
72
  };
73
+ let afterRefusal = (row, cause, lastError) => {
74
+ switch (cause) {
75
+ case "InfrastructureFailure" :
76
+ return afterFailedAttempt(row, lastError);
77
+ case "DomainRejection" :
78
+ case "AccessRefusal" :
79
+ break;
80
+ }
81
+ let newrecord = {...afterFailedAttempt(row, lastError)};
82
+ newrecord.status = "Abandoned";
83
+ return newrecord;
84
+ };
72
85
  let announceAbandonment = async (id, row, publishJsons) => {
73
86
  let item;
74
87
  try {
@@ -157,8 +170,9 @@ function Make(Spec) {
157
170
  }
158
171
  }
159
172
  };
160
- let phase2 = async (publishJsons, capabilities) => {
173
+ let phase2 = async (publishJsons, capabilities, publishJsonsAndWait) => {
161
174
  let publishJsons$1 = CommandSent$ReventlessCore.announcing(`OutboundTranslationSlice(` + Spec.name + `)`, publishJsons);
175
+ let publishJsonsAndWait$1 = Stdlib_Option.map(publishJsonsAndWait, wait => CommandSent$ReventlessCore.announcingAndWaiting(`OutboundTranslationSlice(` + Spec.name + `)`, wait));
162
176
  let newlyAbandoned = [];
163
177
  Object.entries(todoItems).forEach(param => {
164
178
  let row = param[1];
@@ -286,7 +300,39 @@ function Make(Spec) {
286
300
  meta: msg_meta,
287
301
  commandJson: commandJson
288
302
  };
289
- await publishJsons$1([msg$1]);
303
+ let refusal;
304
+ if (publishJsonsAndWait$1 !== undefined) {
305
+ let match$2 = (await publishJsonsAndWait$1([msg$1]))[0];
306
+ if (match$2 !== undefined) {
307
+ switch (match$2.TAG) {
308
+ case "Rejected" :
309
+ refusal = [
310
+ match$2.cause,
311
+ CommandTopic_Helpers$ReventlessCore.describeRefusal(match$2.errorCode, match$2.errorDetail)
312
+ ];
313
+ break;
314
+ case "Accepted" :
315
+ case "Pending" :
316
+ refusal = undefined;
317
+ break;
318
+ }
319
+ } else {
320
+ refusal = undefined;
321
+ }
322
+ } else {
323
+ await publishJsons$1([msg$1]);
324
+ refusal = undefined;
325
+ }
326
+ if (refusal !== undefined) {
327
+ let updated$1 = afterRefusal(row, refusal[0], refusal[1]);
328
+ todoItems[id] = updated$1;
329
+ if (updated$1.status === "Abandoned") {
330
+ newlyAbandoned.push(id);
331
+ return;
332
+ } else {
333
+ return;
334
+ }
335
+ }
290
336
  let newrecord$2 = {...row};
291
337
  newrecord$2.completedAt = new Date().toISOString();
292
338
  newrecord$2.status = "Completed";
@@ -296,9 +342,9 @@ function Make(Spec) {
296
342
  let exn$3 = Primitive_exceptions.internalToException(raw_exn$3);
297
343
  let errMsg$2 = Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_JsExn.fromException(exn$3), Stdlib_JsExn.message), "unknown");
298
344
  Effect.runSync(EffectLogger$ReventlessCore.logError(`OutboundTranslationSlice(` + Spec.name + `)`, undefined, Stdlib_Option.map(row.source, EffectLogger$ReventlessCore.idsOfSource), `failed to publish command: ` + errMsg$2));
299
- let updated$1 = afterFailedAttempt(row, errMsg$2);
300
- todoItems[id] = updated$1;
301
- if (updated$1.status === "Abandoned") {
345
+ let updated$2 = afterFailedAttempt(row, errMsg$2);
346
+ todoItems[id] = updated$2;
347
+ if (updated$2.status === "Abandoned") {
302
348
  newlyAbandoned.push(id);
303
349
  return;
304
350
  } else {
@@ -306,9 +352,9 @@ function Make(Spec) {
306
352
  }
307
353
  }
308
354
  } else {
309
- let updated$2 = afterFailedAttempt(row, undefined);
310
- todoItems[id] = updated$2;
311
- if (updated$2.status === "Abandoned") {
355
+ let updated$3 = afterFailedAttempt(row, undefined);
356
+ todoItems[id] = updated$3;
357
+ if (updated$3.status === "Abandoned") {
312
358
  newlyAbandoned.push(id);
313
359
  return;
314
360
  } else {
@@ -323,9 +369,9 @@ function Make(Spec) {
323
369
  return;
324
370
  }
325
371
  } else {
326
- let updated$3 = afterFailedAttempt(row, result._0);
327
- todoItems[id] = updated$3;
328
- if (updated$3.status === "Abandoned") {
372
+ let updated$4 = afterFailedAttempt(row, result._0);
373
+ todoItems[id] = updated$4;
374
+ if (updated$4.status === "Abandoned") {
329
375
  newlyAbandoned.push(id);
330
376
  return;
331
377
  } else {
@@ -413,7 +413,14 @@ module Make = (
413
413
  | AlwaysEventual => false
414
414
  }
415
415
 
416
- dcbEventLog.readStream(~query, ~after=?afterPos, ~strongConsistency)
416
+ // A slice that consumes nothing (`consumedEvent = unit`) reads nothing: the store is
417
+ // not asked at all.
418
+
419
+ (
420
+ Reventless.DcbTag.readsNothing(query)
421
+ ? Stream.empty
422
+ : dcbEventLog.readStream(~query, ~after=?afterPos, ~strongConsistency)
423
+ )
417
424
  ->Stream.mapEffect(openRaw)
418
425
  // The head accumulator starts at `afterPos` (the seeded head), not `None`,
419
426
  // so an empty delta read keeps the cached head — the append must condition
@@ -509,6 +516,7 @@ module Make = (
509
516
  CommandTopic_Helpers.reportRejected(
510
517
  ~component=Spec.name,
511
518
  ~correlationId=cmdJson.meta.correlationId,
519
+ ~claimed=cmdJson.meta.callerClaim->Option.isSome,
512
520
  ~causationId=?cmdJson.meta.causationId,
513
521
  ~cause=AccessRefusal,
514
522
  cmdJson.meta.msgId,
@@ -552,6 +560,7 @@ module Make = (
552
560
  CommandTopic_Helpers.reportRejected(
553
561
  ~component=Spec.name,
554
562
  ~correlationId=cmdJson.meta.correlationId,
563
+ ~claimed=cmdJson.meta.callerClaim->Option.isSome,
555
564
  ~causationId=?cmdJson.meta.causationId,
556
565
  ~cause=InfrastructureFailure,
557
566
  cmdJson.meta.msgId,
@@ -589,7 +598,14 @@ module Make = (
589
598
  `produced ${eventCount} event(s): [${eventDetails}]`,
590
599
  )
591
600
  ->Effect.flatMap(
592
- _ => Effect.promise(() => dcbEventLog.append(rawEvents, ~condition)),
601
+ _ =>
602
+ Effect.promise(
603
+ () =>
604
+ // What it did not read cannot have changed under it: no condition.
605
+ Reventless.DcbTag.readsNothing(query)
606
+ ? dcbEventLog.append(rawEvents)
607
+ : dcbEventLog.append(rawEvents, ~condition),
608
+ ),
593
609
  )
594
610
  ->Effect.flatMap(
595
611
  appendResult =>
@@ -658,6 +674,7 @@ module Make = (
658
674
  CommandTopic_Helpers.reportRejected(
659
675
  ~component=Spec.name,
660
676
  ~correlationId=cmdJson.meta.correlationId,
677
+ ~claimed=cmdJson.meta.callerClaim->Option.isSome,
661
678
  ~causationId=?cmdJson.meta.causationId,
662
679
  ~cause=InfrastructureFailure,
663
680
  cmdJson.meta.msgId,
@@ -686,6 +703,7 @@ module Make = (
686
703
  CommandTopic_Helpers.reportRejected(
687
704
  ~component=Spec.name,
688
705
  ~correlationId=cmdJson.meta.correlationId,
706
+ ~claimed=cmdJson.meta.callerClaim->Option.isSome,
689
707
  ~causationId=?cmdJson.meta.causationId,
690
708
  ~cause=DomainRejection,
691
709
  cmdJson.meta.msgId,
@@ -266,7 +266,7 @@ function Make(Spec) {
266
266
  strongConsistency = false;
267
267
  break;
268
268
  }
269
- return Effect$1.flatMap(Effect$1.tap(Stream.runFold(Stream.mapEffect(dcbEventLog.readStream(query, afterPos, strongConsistency), openRaw), [
269
+ return Effect$1.flatMap(Effect$1.tap(Stream.runFold(Stream.mapEffect(DcbTag$Reventless.readsNothing(query) ? Stream$1.empty : dcbEventLog.readStream(query, afterPos, strongConsistency), openRaw), [
270
270
  match$1[0],
271
271
  afterPos,
272
272
  [],
@@ -332,7 +332,7 @@ function Make(Spec) {
332
332
  headPosition,
333
333
  owners
334
334
  ]);
335
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "AccessRefusal", cmdJson.meta.correlationId, cmdJson.meta.causationId, cmdJson.meta.msgId, rejected);
335
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "AccessRefusal", cmdJson.meta.correlationId, cmdJson.meta.causationId, Stdlib_Option.isSome(cmdJson.meta.callerClaim), cmdJson.meta.msgId, rejected);
336
336
  let line = `refused: ` + rejected.errorDetail + ` id=` + Stdlib_Option.getOr(entityId, "-");
337
337
  return Effect$1.map(match.isDefect ? EffectLogger$ReventlessCore.logError(comp, undefined, ids, line) : EffectLogger$ReventlessCore.logWarn(comp, undefined, ids, line), () => ({
338
338
  TAG: "Ok",
@@ -392,7 +392,13 @@ function Make(Spec) {
392
392
  query: query,
393
393
  after: headPosition
394
394
  };
395
- return Effect$1.flatMap(Effect$1.flatMap(EffectLogger$ReventlessCore.logInfo(comp, eventJsons, ids, `produced ` + eventCount + ` event(s): [` + eventDetails + `]`), () => Effect$1.promise(() => dcbEventLog.append(rawEvents, condition))), appendResult => {
395
+ return Effect$1.flatMap(Effect$1.flatMap(EffectLogger$ReventlessCore.logInfo(comp, eventJsons, ids, `produced ` + eventCount + ` event(s): [` + eventDetails + `]`), () => Effect$1.promise(() => {
396
+ if (DcbTag$Reventless.readsNothing(query)) {
397
+ return dcbEventLog.append(rawEvents, undefined);
398
+ } else {
399
+ return dcbEventLog.append(rawEvents, condition);
400
+ }
401
+ })), appendResult => {
396
402
  if (appendResult.TAG === "Ok") {
397
403
  cachePut([
398
404
  state,
@@ -434,7 +440,7 @@ function Make(Spec) {
434
440
  if (errorCode === CommandOutcome$Reventless.code("Conflict")) {
435
441
  Metrics$ReventlessCore.emitCount("AppendConflict", Spec.name, undefined);
436
442
  }
437
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", cmdJson.meta.correlationId, cmdJson.meta.causationId, cmdJson.meta.msgId, {
443
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", cmdJson.meta.correlationId, cmdJson.meta.causationId, Stdlib_Option.isSome(cmdJson.meta.callerClaim), cmdJson.meta.msgId, {
438
444
  errorCode: errorCode,
439
445
  errorDetail: errDetail
440
446
  });
@@ -451,7 +457,7 @@ function Make(Spec) {
451
457
  headPosition,
452
458
  owners
453
459
  ]);
454
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", cmdJson.meta.correlationId, cmdJson.meta.causationId, cmdJson.meta.msgId, {
460
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", cmdJson.meta.correlationId, cmdJson.meta.causationId, Stdlib_Option.isSome(cmdJson.meta.callerClaim), cmdJson.meta.msgId, {
455
461
  errorCode: CommandOutcome$Reventless.code("AppendFailed"),
456
462
  errorDetail: detail
457
463
  });
@@ -471,7 +477,7 @@ function Make(Spec) {
471
477
  let match$1 = Message$ReventlessCore.splitMessage(errorJson);
472
478
  let payloadDict = match$1[1];
473
479
  let errorDetail = Object.entries(payloadDict).length === 0 ? "" : JSON.stringify(payloadDict);
474
- CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "DomainRejection", cmdJson.meta.correlationId, cmdJson.meta.causationId, cmdJson.meta.msgId, {
480
+ CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "DomainRejection", cmdJson.meta.correlationId, cmdJson.meta.causationId, Stdlib_Option.isSome(cmdJson.meta.callerClaim), cmdJson.meta.msgId, {
475
481
  errorCode: errorCode,
476
482
  errorDetail: errorDetail
477
483
  });
@@ -69,7 +69,7 @@ function outcomeLines(lines) {
69
69
  }
70
70
 
71
71
  globalThis.test("an accepted command is written with its ids, entity and event count", () => {
72
- let lines = outcomeLines(captureLogs(() => CommandTopic_Helpers$ReventlessCore.fireCommandOutcome("Order", "c-1", "c-1", undefined, {
72
+ let lines = outcomeLines(captureLogs(() => CommandTopic_Helpers$ReventlessCore.fireCommandOutcome("Order", "c-1", "c-1", undefined, undefined, {
73
73
  TAG: "OutcomeAccepted",
74
74
  entityId: "o-1",
75
75
  eventCount: 2
@@ -98,7 +98,7 @@ globalThis.test("an accepted command is written with its ids, entity and event c
98
98
  });
99
99
 
100
100
  globalThis.test("a rejected command is written with its code and cause", () => {
101
- let lines = outcomeLines(captureLogs(() => CommandTopic_Helpers$ReventlessCore.fireCommandOutcome("Order", "c-2", "k-1", "e-1", {
101
+ let lines = outcomeLines(captureLogs(() => CommandTopic_Helpers$ReventlessCore.fireCommandOutcome("Order", "c-2", "k-1", "e-1", undefined, {
102
102
  TAG: "OutcomeRejected",
103
103
  errorCode: "Forbidden",
104
104
  errorDetail: "secret",
@@ -132,7 +132,7 @@ globalThis.test("a rejected command is written with its code and cause", () => {
132
132
 
133
133
  globalThis.test("a platform that carries outcomes another way writes no line", () => {
134
134
  CommandTopic_Helpers$ReventlessCore.outcomeLines.contents = false;
135
- let lines = outcomeLines(captureLogs(() => CommandTopic_Helpers$ReventlessCore.fireCommandOutcome("Order", "c-3", undefined, undefined, {
135
+ let lines = outcomeLines(captureLogs(() => CommandTopic_Helpers$ReventlessCore.fireCommandOutcome("Order", "c-3", undefined, undefined, undefined, {
136
136
  TAG: "OutcomeAccepted",
137
137
  entityId: undefined,
138
138
  eventCount: 1
@@ -156,3 +156,105 @@ describe("CommandTopic_Helpers.commandOutcomeToJson:", () => {
156
156
  expect(json->JSON.Decode.object->Option.flatMap(o => o->Dict.get("cause")))->toEqual(None)
157
157
  })
158
158
  })
159
+
160
+ describe("CommandTopic_Helpers.runInlineAndCollect, two runs:", () => {
161
+ // An automation's inline run can start while another is still deciding, in the
162
+ // same process. Ending the inner run must not stop the outer one hearing its own.
163
+ testPromise("a nested inline run leaves the outer run's outcomes to it", async () => {
164
+ let refuse = reference =>
165
+ CommandTopic_Helpers.reportRejected(
166
+ ~component="TestService",
167
+ ~cause=DomainRejection,
168
+ reference,
169
+ {errorCode: "OuterRefused", errorDetail: ""},
170
+ )
171
+ let inner: CommandTopic_Helpers.jsonCommandsHandler = stream =>
172
+ stream->Stream.runCollect->Effect.map(items => items->Array.map(item => Ok(item.reference)))
173
+ let outer: CommandTopic_Helpers.jsonCommandsHandler = stream =>
174
+ stream
175
+ ->Stream.runCollect
176
+ ->Effect.flatMap(
177
+ items =>
178
+ Effect.promise(
179
+ async () => {
180
+ let _ = await CommandTopic_Helpers.runInlineAndCollect([cmdJson("inner-1")], inner)
181
+ items->Array.forEach(item => refuse(item.reference))
182
+ items->Array.map(item => Ok(item.reference))
183
+ },
184
+ ),
185
+ )
186
+
187
+ let outcomes = await CommandTopic_Helpers.runInlineAndCollect([cmdJson("outer-1")], outer)
188
+ switch outcomes->Array.getUnsafe(0) {
189
+ | Rejected({errorCode}) => expect(errorCode)->toEqual("OuterRefused")
190
+ | Accepted(_) | Pending(_) => expect("expected Rejected")->toEqual("got other")
191
+ }
192
+ })
193
+ })
194
+
195
+ // A refusal of a command the platform sent itself, which nobody waited on, is the one
196
+ // a person would otherwise never see: a warning, and an `UnheardRefusal` count.
197
+ describe("CommandTopic_Helpers.reportRejected, a refusal nobody hears:", () => {
198
+ let observe = async (~claimed, ~cause, ~inline) => {
199
+ let reports = ref([])
200
+ let remove = CommandTopic_Helpers.registerCommandOutcome(r =>
201
+ reports := reports.contents->Array.concat([r])
202
+ )
203
+ let counts = Metrics.Counts.make()
204
+ Metrics.Sink.install(Metrics.Counts.sink(counts))
205
+ let refuse = reference =>
206
+ CommandTopic_Helpers.reportRejected(
207
+ ~component="TestService",
208
+ ~cause,
209
+ ~claimed,
210
+ reference,
211
+ {errorCode: "Refused", errorDetail: ""},
212
+ )
213
+ if inline {
214
+ let handler: CommandTopic_Helpers.jsonCommandsHandler = stream =>
215
+ stream
216
+ ->Stream.runCollect
217
+ ->Effect.map(items => {
218
+ items->Array.forEach(item => refuse(item.reference))
219
+ items->Array.map(item => Ok(item.reference))
220
+ })
221
+ let _ = await CommandTopic_Helpers.runInlineAndCollect([cmdJson("m-1")], handler)
222
+ } else {
223
+ refuse("m-1")
224
+ }
225
+ remove()
226
+ Metrics.Sink.reset()
227
+ let unheardCount =
228
+ counts
229
+ ->Metrics.Counts.read(~now=Date.now())
230
+ ->Array.filter(s => s.metric == "UnheardRefusal")
231
+ ->Array.reduce(0, (n, s) => n + s.count)
232
+ (reports.contents->Array.map(r => r.unheard->Option.getOr(false)), unheardCount)
233
+ }
234
+
235
+ testPromise("an unclaimed command refused with nobody waiting is unheard", async () => {
236
+ expect(await observe(~claimed=false, ~cause=DomainRejection, ~inline=false))->toEqual((
237
+ [true],
238
+ 1,
239
+ ))
240
+ expect(await observe(~claimed=false, ~cause=AccessRefusal, ~inline=false))->toEqual(([true], 1))
241
+ })
242
+
243
+ testPromise("a caller's command, or one a slice waited on, is heard", async () => {
244
+ expect(await observe(~claimed=true, ~cause=DomainRejection, ~inline=false))->toEqual((
245
+ [false],
246
+ 0,
247
+ ))
248
+ expect(await observe(~claimed=false, ~cause=DomainRejection, ~inline=true))->toEqual((
249
+ [false],
250
+ 0,
251
+ ))
252
+ })
253
+
254
+ testPromise("an infrastructure failure is not final, so not unheard", async () => {
255
+ expect(await observe(~claimed=false, ~cause=InfrastructureFailure, ~inline=false))->toEqual((
256
+ [false],
257
+ 0,
258
+ ))
259
+ })
260
+ })
@@ -1,9 +1,11 @@
1
1
  // Generated by ReScript, PLEASE EDIT WITH CARE
2
2
 
3
3
  import * as Stdlib_JSON from "@rescript/runtime/lib/es6/Stdlib_JSON.js";
4
+ import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.js";
4
5
  import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
5
6
  import * as Effect from "effect/Effect";
6
7
  import * as Stream from "effect/Stream";
8
+ import * as Metrics$ReventlessCore from "../../src/util/Metrics.res.mjs";
7
9
  import * as CommandTopic_Helpers$ReventlessCore from "../../src/components/CommandTopic/CommandTopic_Helpers.res.mjs";
8
10
 
9
11
  function metaWithMsgId(msgId) {
@@ -36,7 +38,7 @@ globalThis.describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
36
38
  entityId: "agg-1",
37
39
  eventCount: 0
38
40
  });
39
- CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "DomainRejection", undefined, undefined, item.reference, {
41
+ CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "DomainRejection", undefined, undefined, undefined, item.reference, {
40
42
  errorCode: "AlreadyExists",
41
43
  errorDetail: ""
42
44
  });
@@ -64,7 +66,7 @@ globalThis.describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
64
66
  });
65
67
  globalThis.test("Rejected from rejectedResultChannel beats Error result (synthesized Conflict)", async () => {
66
68
  let handler = stream => Effect.map(Stream.runCollect(stream), items => {
67
- items.forEach(item => CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "DomainRejection", undefined, undefined, item.reference, {
69
+ items.forEach(item => CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "DomainRejection", undefined, undefined, undefined, item.reference, {
68
70
  errorCode: "BusinessRuleViolated",
69
71
  errorDetail: "{\"reason\":\"x\"}"
70
72
  }));
@@ -106,7 +108,7 @@ globalThis.describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
106
108
  });
107
109
  globalThis.test("a reported access refusal keeps its cause", async () => {
108
110
  let handler = stream => Effect.map(Stream.runCollect(stream), items => {
109
- items.forEach(item => CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "AccessRefusal", undefined, undefined, item.reference, {
111
+ items.forEach(item => CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "AccessRefusal", undefined, undefined, undefined, item.reference, {
110
112
  errorCode: "Forbidden",
111
113
  errorDetail: "not the owner"
112
114
  }));
@@ -153,6 +155,102 @@ globalThis.describe("CommandTopic_Helpers.commandOutcomeToJson:", () => {
153
155
  });
154
156
  });
155
157
 
158
+ globalThis.describe("CommandTopic_Helpers.runInlineAndCollect, two runs:", () => {
159
+ globalThis.test("a nested inline run leaves the outer run's outcomes to it", async () => {
160
+ let inner = stream => Effect.map(Stream.runCollect(stream), items => items.map(item => ({
161
+ TAG: "Ok",
162
+ _0: item.reference
163
+ })));
164
+ let outer = stream => Effect.flatMap(Stream.runCollect(stream), items => Effect.promise(async () => {
165
+ await CommandTopic_Helpers$ReventlessCore.runInlineAndCollect([cmdJson("inner-1")], inner);
166
+ items.forEach(item => {
167
+ let reference = item.reference;
168
+ CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "DomainRejection", undefined, undefined, undefined, reference, {
169
+ errorCode: "OuterRefused",
170
+ errorDetail: ""
171
+ });
172
+ });
173
+ return items.map(item => ({
174
+ TAG: "Ok",
175
+ _0: item.reference
176
+ }));
177
+ }));
178
+ let outcomes = await CommandTopic_Helpers$ReventlessCore.runInlineAndCollect([cmdJson("outer-1")], outer);
179
+ let match = outcomes[0];
180
+ switch (match.TAG) {
181
+ case "Rejected" :
182
+ globalThis.expect(match.errorCode).toEqual("OuterRefused");
183
+ return;
184
+ case "Accepted" :
185
+ case "Pending" :
186
+ globalThis.expect("expected Rejected").toEqual("got other");
187
+ return;
188
+ }
189
+ });
190
+ });
191
+
192
+ globalThis.describe("CommandTopic_Helpers.reportRejected, a refusal nobody hears:", () => {
193
+ let observe = async (claimed, cause, inline) => {
194
+ let reports = {
195
+ contents: []
196
+ };
197
+ let remove = CommandTopic_Helpers$ReventlessCore.registerCommandOutcome(r => {
198
+ reports.contents = reports.contents.concat([r]);
199
+ });
200
+ let counts = Metrics$ReventlessCore.Counts.make();
201
+ Metrics$ReventlessCore.Sink.install(Metrics$ReventlessCore.Counts.sink(counts));
202
+ let refuse = reference => CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", cause, undefined, undefined, claimed, reference, {
203
+ errorCode: "Refused",
204
+ errorDetail: ""
205
+ });
206
+ if (inline) {
207
+ let handler = stream => Effect.map(Stream.runCollect(stream), items => {
208
+ items.forEach(item => refuse(item.reference));
209
+ return items.map(item => ({
210
+ TAG: "Ok",
211
+ _0: item.reference
212
+ }));
213
+ });
214
+ await CommandTopic_Helpers$ReventlessCore.runInlineAndCollect([cmdJson("m-1")], handler);
215
+ } else {
216
+ refuse("m-1");
217
+ }
218
+ remove();
219
+ Metrics$ReventlessCore.Sink.reset();
220
+ let unheardCount = Stdlib_Array.reduce(Metrics$ReventlessCore.Counts.read(counts, Date.now(), undefined).filter(s => s.metric === "UnheardRefusal"), 0, (n, s) => n + s.count | 0);
221
+ return [
222
+ reports.contents.map(r => Stdlib_Option.getOr(r.unheard, false)),
223
+ unheardCount
224
+ ];
225
+ };
226
+ globalThis.test("an unclaimed command refused with nobody waiting is unheard", async () => {
227
+ globalThis.expect(await observe(false, "DomainRejection", false)).toEqual([
228
+ [true],
229
+ 1
230
+ ]);
231
+ globalThis.expect(await observe(false, "AccessRefusal", false)).toEqual([
232
+ [true],
233
+ 1
234
+ ]);
235
+ });
236
+ globalThis.test("a caller's command, or one a slice waited on, is heard", async () => {
237
+ globalThis.expect(await observe(true, "DomainRejection", false)).toEqual([
238
+ [false],
239
+ 0
240
+ ]);
241
+ globalThis.expect(await observe(false, "DomainRejection", true)).toEqual([
242
+ [false],
243
+ 0
244
+ ]);
245
+ });
246
+ globalThis.test("an infrastructure failure is not final, so not unheard", async () => {
247
+ globalThis.expect(await observe(false, "InfrastructureFailure", false)).toEqual([
248
+ [false],
249
+ 0
250
+ ]);
251
+ });
252
+ });
253
+
156
254
  export {
157
255
  metaWithMsgId,
158
256
  cmdJson,