@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
@@ -17,6 +17,7 @@ import * as Util_Sury$Reventless from "@reventlessdev/reventless-spec/src/util/U
17
17
  import * as Message$ReventlessCore from "../../Message.res.mjs";
18
18
  import * as CommandSent$ReventlessCore from "../../CommandSent.res.mjs";
19
19
  import * as EffectLogger$ReventlessCore from "../../util/EffectLogger.res.mjs";
20
+ import * as CommandTopic_Helpers$ReventlessCore from "../CommandTopic/CommandTopic_Helpers.res.mjs";
20
21
  import * as AutomationSlice_Route$ReventlessCore from "./AutomationSlice_Route.res.mjs";
21
22
  import * as AutomationSlice_Schedules$ReventlessCore from "./AutomationSlice_Schedules.res.mjs";
22
23
 
@@ -36,6 +37,7 @@ let todoRowSchema = Sury.$schema(s => ({
36
37
  completedAt: s.m(Sury.$option(Sury.string)),
37
38
  retryCount: s.m(Sury.int32),
38
39
  maxRetries: s.m(Sury.$option(Sury.int32)),
40
+ lastError: s.m(Sury.$option(Sury.string)),
39
41
  source: s.m(Sury.$option(Message$ReventlessCore.flowSourceSchema))
40
42
  }));
41
43
 
@@ -48,6 +50,7 @@ function todoRowSchemaFor(itemSchema) {
48
50
  completedAt: s.m(Sury.$option(Sury.string)),
49
51
  retryCount: s.m(Sury.int32),
50
52
  maxRetries: s.m(Sury.$option(Sury.int32)),
53
+ lastError: s.m(Sury.$option(Sury.string)),
51
54
  source: s.m(Sury.$option(Message$ReventlessCore.flowSourceSchema))
52
55
  }));
53
56
  }
@@ -188,18 +191,30 @@ function Make(Spec) {
188
191
  return decode(data$1, key);
189
192
  };
190
193
  let processingTimeoutMs = 15 * 60 * 1000;
191
- let afterFailedAttempt = row => {
194
+ let afterFailedAttempt = (row, lastError) => {
192
195
  let retryCount = row.retryCount + 1 | 0;
193
196
  let newrecord = {...row};
197
+ newrecord.lastError = lastError !== undefined ? lastError : row.lastError;
194
198
  newrecord.retryCount = retryCount;
195
199
  newrecord.status = retryCount >= Spec.maxRetries ? "Abandoned" : "Failed";
196
200
  return newrecord;
197
201
  };
202
+ let afterRefusal = (row, cause, lastError) => {
203
+ switch (cause) {
204
+ case "DomainRejection" :
205
+ case "InfrastructureFailure" :
206
+ return afterFailedAttempt(row, lastError);
207
+ case "AccessRefusal" :
208
+ let newrecord = {...afterFailedAttempt(row, lastError)};
209
+ newrecord.status = "Abandoned";
210
+ return newrecord;
211
+ }
212
+ };
198
213
  let abandonmentCommand = async (id, row) => {
199
214
  let match = await openRow(id, row);
200
215
  switch (match.TAG) {
201
216
  case "Open" :
202
- return Stdlib_Option.flatMap(Automation.onExhausted(match.key, match.item), param => {
217
+ return Stdlib_Option.flatMap(Automation.onExhausted(match.key, match.item, row.lastError), param => {
203
218
  let commandJson;
204
219
  try {
205
220
  commandJson = Util_Sury$Reventless.toJson(param[1], Spec.commandSchema);
@@ -326,8 +341,10 @@ function Make(Spec) {
326
341
  });
327
342
  scheduleChanges.contents = [];
328
343
  };
329
- let phase2 = async publishJsons => {
344
+ let phase2 = async (publishJsons, publishJsonsAndWait) => {
330
345
  let publishJsons$1 = CommandSent$ReventlessCore.announcing(`AutomationSlice(` + Spec.name + `)`, publishJsons);
346
+ let publishJsonsAndWait$1 = Stdlib_Option.map(publishJsonsAndWait, wait => CommandSent$ReventlessCore.announcingAndWaiting(`AutomationSlice(` + Spec.name + `)`, wait));
347
+ let rowOfMsgId = {};
331
348
  let currentTime = await Effect.runPromise(Clock.currentTimeMillis);
332
349
  let newlyAbandoned = [];
333
350
  Object.entries(todoItems).forEach(param => {
@@ -344,7 +361,7 @@ function Make(Spec) {
344
361
  if (currentTime - match$1 < processingTimeoutMs) {
345
362
  return;
346
363
  }
347
- let updated = afterFailedAttempt(row);
364
+ let updated = afterFailedAttempt(row, undefined);
348
365
  todoItems[id] = updated;
349
366
  if (updated.status === "Abandoned") {
350
367
  newlyAbandoned.push(id);
@@ -394,7 +411,7 @@ function Make(Spec) {
394
411
  let exn = Primitive_exceptions.internalToException(raw_exn);
395
412
  let errMsg = Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_JsExn.fromException(exn), Stdlib_JsExn.message), "unknown");
396
413
  Effect.runSync(EffectLogger$ReventlessCore.logError(`AutomationSlice(` + Spec.name + `)`, undefined, Stdlib_Option.map(row.source, EffectLogger$ReventlessCore.idsOfSource), `failed to encode command: ` + errMsg));
397
- let updated = afterFailedAttempt(row);
414
+ let updated = afterFailedAttempt(row, undefined);
398
415
  todoItems[id] = updated;
399
416
  if (updated.status === "Abandoned") {
400
417
  newlyAbandoned.push(id);
@@ -408,6 +425,7 @@ function Make(Spec) {
408
425
  meta: msg_meta,
409
426
  commandJson: commandJson
410
427
  };
428
+ rowOfMsgId[msg_meta.msgId] = id;
411
429
  commands.push(msg);
412
430
  });
413
431
  }
@@ -424,9 +442,42 @@ function Make(Spec) {
424
442
  break;
425
443
  }
426
444
  }
445
+ let recordOutcome = outcome => {
446
+ switch (outcome.TAG) {
447
+ case "Rejected" :
448
+ let match = Stdlib_Option.flatMap(rowOfMsgId[outcome.msgId], id => Stdlib_Option.map(todoItems[id], row => [
449
+ id,
450
+ row
451
+ ]));
452
+ if (match === undefined) {
453
+ return;
454
+ }
455
+ let row = match[1];
456
+ if (row.status !== "Processing") {
457
+ return;
458
+ }
459
+ let id = match[0];
460
+ let lastError = CommandTopic_Helpers$ReventlessCore.describeRefusal(outcome.errorCode, outcome.errorDetail);
461
+ let updated = afterRefusal(row, outcome.cause, lastError);
462
+ todoItems[id] = updated;
463
+ if (updated.status === "Abandoned") {
464
+ newlyAbandoned.push(id);
465
+ return;
466
+ } else {
467
+ return;
468
+ }
469
+ case "Accepted" :
470
+ case "Pending" :
471
+ return;
472
+ }
473
+ };
427
474
  if (commands.length !== 0) {
428
475
  try {
429
- await publishJsons$1(commands);
476
+ if (publishJsonsAndWait$1 !== undefined) {
477
+ (await publishJsonsAndWait$1(commands)).forEach(recordOutcome);
478
+ } else {
479
+ await publishJsons$1(commands);
480
+ }
430
481
  } catch (raw_exn$1) {
431
482
  let exn$1 = Primitive_exceptions.internalToException(raw_exn$1);
432
483
  let errMsg$1 = Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_JsExn.fromException(exn$1), Stdlib_JsExn.message), "unknown");
@@ -440,7 +491,7 @@ function Make(Spec) {
440
491
  if (current.status !== "Processing") {
441
492
  return;
442
493
  }
443
- let updated = afterFailedAttempt(param[1]);
494
+ let updated = afterFailedAttempt(param[1], undefined);
444
495
  todoItems[id] = updated;
445
496
  if (updated.status === "Abandoned") {
446
497
  newlyAbandoned.push(id);
@@ -66,7 +66,7 @@ function makeGenerateCommand(publishJsons, publishJsonsAndWait, serviceName, com
66
66
  let refusedBeforeHandler = (meta, reason, access) => {
67
67
  Effect.runSync(EffectLogger$ReventlessCore.logWarn(`CommandGenerator(` + serviceName + `)`, undefined, EffectLogger$ReventlessCore.idsOf(undefined, undefined, meta), `refused before its handler: ` + reason));
68
68
  if (access) {
69
- return CommandTopic_Helpers$ReventlessCore.fireCommandOutcome(serviceName, meta.msgId, meta.correlationId, undefined, {
69
+ return CommandTopic_Helpers$ReventlessCore.fireCommandOutcome(serviceName, meta.msgId, meta.correlationId, undefined, undefined, {
70
70
  TAG: "OutcomeRejected",
71
71
  errorCode: CommandOutcome$Reventless.code("Forbidden"),
72
72
  errorDetail: reason,
@@ -43,6 +43,8 @@ let acceptedResultChannel = CommandTopic_Helpers$ReventlessCore.acceptedResultCh
43
43
 
44
44
  let rejectedResultChannel = CommandTopic_Helpers$ReventlessCore.rejectedResultChannel;
45
45
 
46
+ let inlineWaiters = CommandTopic_Helpers$ReventlessCore.inlineWaiters;
47
+
46
48
  let ownershipRefusal = CommandTopic_Helpers$ReventlessCore.ownershipRefusal;
47
49
 
48
50
  let reportAccepted = CommandTopic_Helpers$ReventlessCore.reportAccepted;
@@ -51,6 +53,10 @@ let reportRejected = CommandTopic_Helpers$ReventlessCore.reportRejected;
51
53
 
52
54
  let commandOutcomeToJson = CommandTopic_Helpers$ReventlessCore.commandOutcomeToJson;
53
55
 
56
+ let commandOutcomeOfJson = CommandTopic_Helpers$ReventlessCore.commandOutcomeOfJson;
57
+
58
+ let describeRefusal = CommandTopic_Helpers$ReventlessCore.describeRefusal;
59
+
54
60
  let encodeCommandJson = CommandTopic_Helpers$ReventlessCore.encodeCommandJson;
55
61
 
56
62
  let runInlineAndCollect = CommandTopic_Helpers$ReventlessCore.runInlineAndCollect;
@@ -78,10 +84,13 @@ export {
78
84
  fireCommandOutcome,
79
85
  acceptedResultChannel,
80
86
  rejectedResultChannel,
87
+ inlineWaiters,
81
88
  ownershipRefusal,
82
89
  reportAccepted,
83
90
  reportRejected,
84
91
  commandOutcomeToJson,
92
+ commandOutcomeOfJson,
93
+ describeRefusal,
85
94
  encodeCommandJson,
86
95
  runInlineAndCollect,
87
96
  callHandlerWithArray,
@@ -18,18 +18,11 @@ is the JSON-stringified error payload (or empty string for payload-less variants
18
18
  */
19
19
  type rejectedResult = {errorCode: string, errorDetail: string}
20
20
 
21
- /**
22
- Why a command was refused.
23
-
24
- `DomainRejection` is `Decision.decide` returning `Error` — the model declining the command,
25
- which is the model working. `InfrastructureFailure` is the decision never landing: an event-log
26
- append that failed outright or exhausted its conflict retries. Both arrive on `reportRejected`,
27
- so without this a consumer would read a broken event log as a business rejection.
28
-
29
- `AccessRefusal` is the handler refusing before `decide` runs, because the caller does not
30
- own what the command acts on (`OwnerScope.decideActing`).
31
- */
32
- type refusalCause = DomainRejection | InfrastructureFailure | AccessRefusal
21
+ /** Why a command was refused; see `ReventlessInfra.CommandTopic.refusalCause`. */
22
+ type refusalCause = ReventlessInfra.CommandTopic.refusalCause =
23
+ | DomainRejection
24
+ | InfrastructureFailure
25
+ | AccessRefusal
33
26
 
34
27
  /** The `CommandRejectionCause` enum value a client sees for a cause. */
35
28
  let refusalCauseToGraphQL = (cause: refusalCause): string =>
@@ -58,6 +51,9 @@ type commandOutcomeReport = {
58
51
  when it sent the command. */
59
52
  causationId?: string,
60
53
  outcome: observedOutcome,
54
+ /** A refusal of a command the platform sent itself, which nobody waited on: no
55
+ person and no work item hears it. */
56
+ unheard?: bool,
61
57
  }
62
58
 
63
59
  type commandOutcomeHook = commandOutcomeReport => unit
@@ -110,15 +106,25 @@ let logOutcome = (r: commandOutcomeReport) => {
110
106
  ],
111
107
  )
112
108
  }
113
- EffectLogger.logInfo(
114
- ~comp=`CommandTopic(${r.component})`,
115
- ~ids={
116
- msgId: r.reference,
117
- correlationId: ?r.correlationId,
118
- causationId: ?r.causationId,
119
- },
120
- ~detail=JSON.Object(Dict.fromArray([("component", str(r.component))]->Array.concat(fields))),
121
- message,
109
+ let unheard = r.unheard->Option.getOr(false)
110
+ let ids: EffectLogger.ids = {
111
+ msgId: r.reference,
112
+ correlationId: ?r.correlationId,
113
+ causationId: ?r.causationId,
114
+ }
115
+ let detail = JSON.Object(
116
+ Dict.fromArray(
117
+ [("component", str(r.component))]
118
+ ->Array.concat(fields)
119
+ ->Array.concat(unheard ? [("unheard", JSON.Encode.bool(true))] : []),
120
+ ),
121
+ )
122
+ let comp = `CommandTopic(${r.component})`
123
+
124
+ (
125
+ unheard
126
+ ? EffectLogger.logWarn(~comp, ~ids, ~detail, `${message}, and nobody is told`)
127
+ : EffectLogger.logInfo(~comp, ~ids, ~detail, message)
122
128
  )->Effect.runSync
123
129
  }
124
130
 
@@ -135,9 +141,10 @@ let fireCommandOutcome = (
135
141
  ~reference: string,
136
142
  ~correlationId: option<string>=?,
137
143
  ~causationId: option<string>=?,
144
+ ~unheard: option<bool>=?,
138
145
  outcome: observedOutcome,
139
146
  ) => {
140
- let report = {component, reference, ?correlationId, ?causationId, outcome}
147
+ let report = {component, reference, ?correlationId, ?causationId, outcome, ?unheard}
141
148
  if outcomeLines.contents {
142
149
  try logOutcome(report) catch {
143
150
  | _ => ()
@@ -171,6 +178,15 @@ let acceptedResultChannel: ref<option<(string, acceptedResult) => unit>> = ref(N
171
178
  // to build `Rejected` outcomes that carry the real error code, detail and cause.
172
179
  let rejectedResultChannel: ref<option<(string, rejectedResult, refusalCause) => unit>> = ref(None)
173
180
 
181
+ /** Who is waiting inline for one command's outcome, keyed by its message id. Keyed
182
+ rather than one slot so two inline runs in one process, overlapping or nested,
183
+ each hear only their own commands. */
184
+ type inlineWaiter = {
185
+ onAccepted: acceptedResult => unit,
186
+ onRejected: (rejectedResult, refusalCause) => unit,
187
+ }
188
+ let inlineWaiters: dict<inlineWaiter> = Dict.make()
189
+
174
190
  /**
175
191
  Turn an `acting` verdict into the refusal a command handler reports, or `None` to let
176
192
  `decide` run.
@@ -219,6 +235,7 @@ let reportAccepted = (
219
235
  result: acceptedResult,
220
236
  ) => {
221
237
  acceptedResultChannel.contents->Option.forEach(cb => cb(reference, result))
238
+ inlineWaiters->Dict.get(reference)->Option.forEach(w => w.onAccepted(result))
222
239
  fireCommandOutcome(
223
240
  ~component,
224
241
  ~reference,
@@ -228,27 +245,40 @@ let reportAccepted = (
228
245
  )
229
246
  }
230
247
 
248
+ /** `~claimed` is whether the command carries a caller claim, as every command the
249
+ API generates does. A business or permission refusal of one without a claim that
250
+ nobody waits on inline is a refusal nobody hears: it is logged as a warning and
251
+ counted as `UnheardRefusal`. */
231
252
  let reportRejected = (
232
253
  ~component: string,
233
254
  ~cause: refusalCause,
234
255
  ~correlationId: option<string>=?,
235
256
  ~causationId: option<string>=?,
257
+ ~claimed: bool=true,
236
258
  reference: string,
237
259
  result: rejectedResult,
238
260
  ) => {
239
261
  rejectedResultChannel.contents->Option.forEach(cb => cb(reference, result, cause))
262
+ let waiter = inlineWaiters->Dict.get(reference)
263
+ waiter->Option.forEach(w => w.onRejected(result, cause))
264
+ // An infrastructure failure is not final: the queue delivers the command again.
265
+ let unheard = !claimed && waiter->Option.isNone && cause != InfrastructureFailure
266
+ if unheard {
267
+ Metrics.emitCount(~metric="UnheardRefusal", ~slice=component)
268
+ }
240
269
  fireCommandOutcome(
241
270
  ~component,
242
271
  ~reference,
243
272
  ~correlationId?,
244
273
  ~causationId?,
274
+ ~unheard,
245
275
  OutcomeRejected({errorCode: result.errorCode, errorDetail: result.errorDetail, cause}),
246
276
  )
247
277
  }
248
278
 
249
279
  // Placed here (rather than CommandTopic.res) so runInlineAndCollect can use commandOutcome
250
280
  // without importing Adapter.res → @pulumi/pulumi. Re-exported by CommandTopic via include.
251
- type commandOutcome =
281
+ type commandOutcome = ReventlessInfra.CommandTopic.commandOutcome =
252
282
  | Accepted({msgId: string, entityId?: string, eventCount: int})
253
283
  | Rejected({msgId: string, errorCode: string, errorDetail: option<string>, cause: refusalCause})
254
284
  | Pending({msgId: string})
@@ -288,7 +318,50 @@ let commandOutcomeToJson = (outcome: commandOutcome): JSON.t =>
288
318
  )
289
319
  }
290
320
 
291
- type publishJsonsAndWait = array<Reventless.Message.commandJson> => promise<array<commandOutcome>>
321
+ /** `commandOutcomeToJson` read back, for a caller that got the outcome over the wire.
322
+ `None` for a shape it does not write. */
323
+ let commandOutcomeOfJson = (json: JSON.t): option<commandOutcome> => {
324
+ let fields = json->JSON.Decode.object->Option.getOr(Dict.make())
325
+ let str = key => fields->Dict.get(key)->Option.flatMap(JSON.Decode.string)
326
+ switch (str("__typename"), str("msgId")) {
327
+ | (Some("CommandAccepted"), Some(msgId)) =>
328
+ Some(
329
+ Accepted({
330
+ msgId,
331
+ entityId: ?str("entityId"),
332
+ eventCount: fields
333
+ ->Dict.get("eventCount")
334
+ ->Option.flatMap(JSON.Decode.float)
335
+ ->Option.mapOr(0, Float.toInt),
336
+ }),
337
+ )
338
+ | (Some("CommandRejected"), Some(msgId)) =>
339
+ let cause = switch str("cause") {
340
+ | Some("DOMAIN") => DomainRejection
341
+ | Some("ACCESS") => AccessRefusal
342
+ | _ => InfrastructureFailure
343
+ }
344
+ Some(
345
+ Rejected({
346
+ msgId,
347
+ errorCode: str("errorCode")->Option.getOr(""),
348
+ errorDetail: str("errorDetail"),
349
+ cause,
350
+ }),
351
+ )
352
+ | (Some("CommandPending"), Some(msgId)) => Some(Pending({msgId: msgId}))
353
+ | _ => None
354
+ }
355
+ }
356
+
357
+ type publishJsonsAndWait = ReventlessInfra.CommandTopic.publishJsonsAndWait
358
+
359
+ /** A refusal as one line for a work item's `lastError`: the code, then the detail. */
360
+ let describeRefusal = (~errorCode: string, ~errorDetail: option<string>) =>
361
+ switch errorDetail {
362
+ | Some(detail) if detail != "" => `${errorCode}: ${detail}`
363
+ | _ => errorCode
364
+ }
292
365
 
293
366
  // Encode the full message body expected by CommandTopic_Callback: {id, meta, command}.
294
367
  // Shared by LocalCommandTopicChannel and CommandTopicChannel_SQS_Sync.
@@ -301,7 +374,7 @@ let encodeCommandJson = (cmdJson: Reventless.Message.commandJson): JSON.t =>
301
374
  ]),
302
375
  )
303
376
 
304
- // Runs handleCmds inline, manages the acceptedResultChannel side-channel, and maps
377
+ // Runs handleCmds inline, waits on each command's outcome by its message id, and maps
305
378
  // results to commandOutcome. Shared by LocalCommandTopicChannel and CommandTopicChannel_SQS_Sync.
306
379
  let runInlineAndCollect = async (
307
380
  jsons: array<Reventless.Message.commandJson>,
@@ -314,15 +387,27 @@ let runInlineAndCollect = async (
314
387
  })
315
388
  let acceptedResults: dict<acceptedResult> = Dict.make()
316
389
  let rejectedResults: dict<(rejectedResult, refusalCause)> = Dict.make()
317
- acceptedResultChannel.contents = Some(
318
- (reference, result) => acceptedResults->Dict.set(reference, result),
319
- )
320
- rejectedResultChannel.contents = Some(
321
- (reference, result, cause) => rejectedResults->Dict.set(reference, (result, cause)),
390
+ let references = items->Array.map(item => item.reference)
391
+ references->Array.forEach(reference =>
392
+ inlineWaiters->Dict.set(
393
+ reference,
394
+ {
395
+ onAccepted: result => acceptedResults->Dict.set(reference, result),
396
+ onRejected: (result, cause) => rejectedResults->Dict.set(reference, (result, cause)),
397
+ },
398
+ )
322
399
  )
323
- let results = await handleCmds(Stream.fromIterable(items))->Effect.runPromise
324
- acceptedResultChannel.contents = None
325
- rejectedResultChannel.contents = None
400
+ let stopWaiting = () =>
401
+ references->Array.forEach(reference => inlineWaiters->Dict.delete(reference))
402
+ let results = try await handleCmds(Stream.fromIterable(items))->Effect.runPromise catch {
403
+ | JsExn(e) =>
404
+ stopWaiting()
405
+ JsExn.throw(e)
406
+ | exn =>
407
+ stopWaiting()
408
+ throw(exn)
409
+ }
410
+ stopWaiting()
326
411
  jsons->Array.mapWithIndex((cmdJson, i) => {
327
412
  let msgId = cmdJson.meta.msgId
328
413
  // A reported rejection takes precedence over both Accepted and the
@@ -1,6 +1,8 @@
1
1
  // Generated by ReScript, PLEASE EDIT WITH CARE
2
2
 
3
3
  import * as Effect from "@reventlessdev/rescript-effect/src/Effect.res.mjs";
4
+ import * as Stdlib_Dict from "@rescript/runtime/lib/es6/Stdlib_Dict.js";
5
+ import * as Stdlib_JSON from "@rescript/runtime/lib/es6/Stdlib_JSON.js";
4
6
  import * as Stdlib_JsExn from "@rescript/runtime/lib/es6/Stdlib_JsExn.js";
5
7
  import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
6
8
  import * as Stream from "effect/Stream";
@@ -8,6 +10,7 @@ import * as DcbTag$Reventless from "@reventlessdev/reventless-spec/src/component
8
10
  import * as Message$Reventless from "@reventlessdev/reventless-spec/src/types/Message.res.mjs";
9
11
  import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.js";
10
12
  import * as Util_Sury$Reventless from "@reventlessdev/reventless-spec/src/util/Util_Sury.res.mjs";
13
+ import * as Metrics$ReventlessCore from "../../util/Metrics.res.mjs";
11
14
  import * as CommandOutcome$Reventless from "@reventlessdev/reventless-spec/src/components/CommandOutcome.res.mjs";
12
15
  import * as EffectLogger$ReventlessCore from "../../util/EffectLogger.res.mjs";
13
16
 
@@ -85,23 +88,35 @@ function logOutcome(r) {
85
88
  ]
86
89
  ]
87
90
  ];
88
- Effect.runSync(EffectLogger$ReventlessCore.logInfo(`CommandTopic(` + r.component + `)`, Object.fromEntries([[
91
+ let message = match$1[0];
92
+ let unheard = Stdlib_Option.getOr(r.unheard, false);
93
+ let ids_msgId = r.reference;
94
+ let ids_correlationId = r.correlationId;
95
+ let ids_causationId = r.causationId;
96
+ let ids = {
97
+ msgId: ids_msgId,
98
+ correlationId: ids_correlationId,
99
+ causationId: ids_causationId
100
+ };
101
+ let detail = Object.fromEntries([[
89
102
  "component",
90
103
  r.component
91
- ]].concat(match$1[1])), {
92
- msgId: r.reference,
93
- correlationId: r.correlationId,
94
- causationId: r.causationId
95
- }, match$1[0]));
104
+ ]].concat(match$1[1]).concat(unheard ? [[
105
+ "unheard",
106
+ true
107
+ ]] : []));
108
+ let comp = `CommandTopic(` + r.component + `)`;
109
+ Effect.runSync(unheard ? EffectLogger$ReventlessCore.logWarn(comp, detail, ids, message + `, and nobody is told`) : EffectLogger$ReventlessCore.logInfo(comp, detail, ids, message));
96
110
  }
97
111
 
98
- function fireCommandOutcome(component, reference, correlationId, causationId, outcome) {
112
+ function fireCommandOutcome(component, reference, correlationId, causationId, unheard, outcome) {
99
113
  let report = {
100
114
  component: component,
101
115
  reference: reference,
102
116
  correlationId: correlationId,
103
117
  causationId: causationId,
104
- outcome: outcome
118
+ outcome: outcome,
119
+ unheard: unheard
105
120
  };
106
121
  if (outcomeLines.contents) {
107
122
  try {
@@ -133,6 +148,8 @@ let rejectedResultChannel = {
133
148
  contents: undefined
134
149
  };
135
150
 
151
+ let inlineWaiters = {};
152
+
136
153
  function ownershipRefusal(verdict, component, command) {
137
154
  let refuse = (isDefectOpt, why) => {
138
155
  let isDefect = isDefectOpt !== undefined ? isDefectOpt : false;
@@ -163,16 +180,24 @@ function ownershipRefusal(verdict, component, command) {
163
180
 
164
181
  function reportAccepted(component, correlationId, causationId, reference, result) {
165
182
  Stdlib_Option.forEach(acceptedResultChannel.contents, cb => cb(reference, result));
166
- fireCommandOutcome(component, reference, correlationId, causationId, {
183
+ Stdlib_Option.forEach(inlineWaiters[reference], w => w.onAccepted(result));
184
+ fireCommandOutcome(component, reference, correlationId, causationId, undefined, {
167
185
  TAG: "OutcomeAccepted",
168
186
  entityId: result.entityId,
169
187
  eventCount: result.eventCount
170
188
  });
171
189
  }
172
190
 
173
- function reportRejected(component, cause, correlationId, causationId, reference, result) {
191
+ function reportRejected(component, cause, correlationId, causationId, claimedOpt, reference, result) {
192
+ let claimed = claimedOpt !== undefined ? claimedOpt : true;
174
193
  Stdlib_Option.forEach(rejectedResultChannel.contents, cb => cb(reference, result, cause));
175
- fireCommandOutcome(component, reference, correlationId, causationId, {
194
+ let waiter = inlineWaiters[reference];
195
+ Stdlib_Option.forEach(waiter, w => w.onRejected(result, cause));
196
+ let unheard = !claimed && Stdlib_Option.isNone(waiter) && cause !== "InfrastructureFailure";
197
+ if (unheard) {
198
+ Metrics$ReventlessCore.emitCount("UnheardRefusal", component, undefined);
199
+ }
200
+ fireCommandOutcome(component, reference, correlationId, causationId, unheard, {
176
201
  TAG: "OutcomeRejected",
177
202
  errorCode: result.errorCode,
178
203
  errorDetail: result.errorDetail,
@@ -238,6 +263,75 @@ function commandOutcomeToJson(outcome) {
238
263
  }
239
264
  }
240
265
 
266
+ function commandOutcomeOfJson(json) {
267
+ let fields = Stdlib_Option.getOr(Stdlib_JSON.Decode.object(json), {});
268
+ let str = key => Stdlib_Option.flatMap(fields[key], Stdlib_JSON.Decode.string);
269
+ let match = str("__typename");
270
+ let match$1 = str("msgId");
271
+ if (match === undefined) {
272
+ return;
273
+ }
274
+ switch (match) {
275
+ case "CommandAccepted" :
276
+ if (match$1 !== undefined) {
277
+ return {
278
+ TAG: "Accepted",
279
+ msgId: match$1,
280
+ entityId: str("entityId"),
281
+ eventCount: Stdlib_Option.mapOr(Stdlib_Option.flatMap(fields["eventCount"], Stdlib_JSON.Decode.float), 0, prim => prim | 0)
282
+ };
283
+ } else {
284
+ return;
285
+ }
286
+ case "CommandPending" :
287
+ if (match$1 !== undefined) {
288
+ return {
289
+ TAG: "Pending",
290
+ msgId: match$1
291
+ };
292
+ } else {
293
+ return;
294
+ }
295
+ case "CommandRejected" :
296
+ if (match$1 === undefined) {
297
+ return;
298
+ }
299
+ let match$2 = str("cause");
300
+ let cause;
301
+ if (match$2 !== undefined) {
302
+ switch (match$2) {
303
+ case "ACCESS" :
304
+ cause = "AccessRefusal";
305
+ break;
306
+ case "DOMAIN" :
307
+ cause = "DomainRejection";
308
+ break;
309
+ default:
310
+ cause = "InfrastructureFailure";
311
+ }
312
+ } else {
313
+ cause = "InfrastructureFailure";
314
+ }
315
+ return {
316
+ TAG: "Rejected",
317
+ msgId: match$1,
318
+ errorCode: Stdlib_Option.getOr(str("errorCode"), ""),
319
+ errorDetail: str("errorDetail"),
320
+ cause: cause
321
+ };
322
+ default:
323
+ return;
324
+ }
325
+ }
326
+
327
+ function describeRefusal(errorCode, errorDetail) {
328
+ if (errorDetail !== undefined && errorDetail !== "") {
329
+ return errorCode + `: ` + errorDetail;
330
+ } else {
331
+ return errorCode;
332
+ }
333
+ }
334
+
241
335
  function encodeCommandJson(cmdJson) {
242
336
  return Object.fromEntries([
243
337
  [
@@ -265,18 +359,36 @@ async function runInlineAndCollect(jsons, handleCmds) {
265
359
  });
266
360
  let acceptedResults = {};
267
361
  let rejectedResults = {};
268
- acceptedResultChannel.contents = (reference, result) => {
269
- acceptedResults[reference] = result;
270
- };
271
- rejectedResultChannel.contents = (reference, result, cause) => {
272
- rejectedResults[reference] = [
273
- result,
274
- cause
275
- ];
362
+ let references = items.map(item => item.reference);
363
+ references.forEach(reference => {
364
+ inlineWaiters[reference] = {
365
+ onAccepted: result => {
366
+ acceptedResults[reference] = result;
367
+ },
368
+ onRejected: (result, cause) => {
369
+ rejectedResults[reference] = [
370
+ result,
371
+ cause
372
+ ];
373
+ }
374
+ };
375
+ });
376
+ let stopWaiting = () => {
377
+ references.forEach(reference => Stdlib_Dict.$$delete(inlineWaiters, reference));
276
378
  };
277
- let results = await Effect.runPromise(handleCmds(Stream.fromIterable(items)));
278
- acceptedResultChannel.contents = undefined;
279
- rejectedResultChannel.contents = undefined;
379
+ let results;
380
+ try {
381
+ results = await Effect.runPromise(handleCmds(Stream.fromIterable(items)));
382
+ } catch (raw_e) {
383
+ let e = Primitive_exceptions.internalToException(raw_e);
384
+ if (e.RE_EXN_ID === "JsExn") {
385
+ stopWaiting();
386
+ throw e._1;
387
+ }
388
+ stopWaiting();
389
+ throw e;
390
+ }
391
+ stopWaiting();
280
392
  return jsons.map((cmdJson, i) => {
281
393
  let msgId = cmdJson.meta.msgId;
282
394
  let match = rejectedResults[msgId];
@@ -356,10 +468,13 @@ export {
356
468
  fireCommandOutcome,
357
469
  acceptedResultChannel,
358
470
  rejectedResultChannel,
471
+ inlineWaiters,
359
472
  ownershipRefusal,
360
473
  reportAccepted,
361
474
  reportRejected,
362
475
  commandOutcomeToJson,
476
+ commandOutcomeOfJson,
477
+ describeRefusal,
363
478
  encodeCommandJson,
364
479
  runInlineAndCollect,
365
480
  callHandlerWithArray,