@reventlessdev/reventless-core 3.0.0-alpha.302 → 3.0.0-alpha.304

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,26 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # 3.0.0-alpha.304 (2026-10-21)
7
+
8
+ ### Bug Fixes
9
+
10
+ * **core:** a typed id links to the view in its own chapter ([5420e30](https://github.com/ReventlessDev/reventless-core/commit/5420e302b835e11f6b85293239869776068120da))
11
+
12
+
13
+ # 3.0.0-alpha.303 (2026-10-21)
14
+
15
+ * feat!: a rejected command says whether the model, the access check or the platform said no ([6a8a6b0](https://github.com/ReventlessDev/reventless-core/commit/6a8a6b0f2f31e766ae26a944c23b0904e51a5865))
16
+
17
+ ### BREAKING CHANGES
18
+
19
+ * a type error variant with one of those names fails to
20
+ compile; rename it for what the model means, such as AlreadyBooked. On
21
+ AWS, rebuild every plugin against this release before a client selects
22
+ cause: a plugin built earlier answers it with a non-null error.
23
+
24
+
25
+
6
26
  # 3.0.0-alpha.302 (2026-10-21)
7
27
 
8
28
  * feat!: a state view's row key is module Id ([08c9726](https://github.com/ReventlessDev/reventless-core/commit/08c972659a3d689a39fd5e2f2026597155e92210))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reventlessdev/reventless-core",
3
- "version": "3.0.0-alpha.302",
3
+ "version": "3.0.0-alpha.304",
4
4
  "description": "Core package for Reventless framework",
5
5
  "license": "Apache-2.0",
6
6
  "jest": {
@@ -29,21 +29,21 @@
29
29
  "sury": "11.0.0",
30
30
  "uuid": "^13.0.0",
31
31
  "@reventlessdev/rescript-effect": "1.0.0-alpha.1",
32
- "@reventlessdev/rescript-hash-object": "1.2.0-alpha.15",
33
32
  "@reventlessdev/rescript-fast-csv": "2.0.0-alpha.23",
34
33
  "@reventlessdev/rescript-jest": "1.0.0-alpha.13",
35
34
  "@reventlessdev/rescript-node": "2.0.0-alpha.23",
35
+ "@reventlessdev/rescript-hash-object": "1.2.0-alpha.15",
36
36
  "@reventlessdev/rescript-pulumi-pulumi": "3.0.0-alpha.0",
37
37
  "@reventlessdev/rescript-ssh2": "2.0.0-alpha.24",
38
38
  "@reventlessdev/rescript-uuid": "2.0.0-alpha.1",
39
- "@reventlessdev/reventless-infra": "3.0.0-alpha.199",
39
+ "@reventlessdev/reventless-infra": "3.0.0-alpha.201",
40
40
  "@reventlessdev/reventless-interop": "3.0.0-alpha.42",
41
- "@reventlessdev/reventless-spec": "3.0.0-alpha.171"
41
+ "@reventlessdev/reventless-spec": "3.0.0-alpha.173"
42
42
  },
43
43
  "devDependencies": {
44
44
  "rescript": "12.3.1",
45
45
  "sury-ppx": "11.0.0",
46
- "@reventlessdev/reventless-ppx": "1.0.0-alpha.104"
46
+ "@reventlessdev/reventless-ppx": "1.0.0-alpha.106"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "rescript": "^12.3.1"
@@ -392,7 +392,7 @@ module Make = (
392
392
  ~component=Spec.name,
393
393
  ~cause=InfrastructureFailure,
394
394
  reference,
395
- {errorCode: "AppendFailed", errorDetail: appendErrorDetail},
395
+ {errorCode: Reventless.CommandOutcome.code(AppendFailed), errorDetail: appendErrorDetail},
396
396
  )
397
397
  Error(reference)
398
398
  }
@@ -15,6 +15,7 @@ import * as Util_Sury$Reventless from "@reventlessdev/reventless-spec/src/util/U
15
15
  import * as OwnerScope$Reventless from "@reventlessdev/reventless-spec/src/types/OwnerScope.res.mjs";
16
16
  import * as Message$ReventlessCore from "../../Message.res.mjs";
17
17
  import * as LogFormat$ReventlessCore from "../../util/LogFormat.res.mjs";
18
+ import * as CommandOutcome$Reventless from "@reventlessdev/reventless-spec/src/components/CommandOutcome.res.mjs";
18
19
  import * as EffectLogger$ReventlessCore from "../../util/EffectLogger.res.mjs";
19
20
  import * as SchemaWalker$ReventlessCore from "../../plugin/component/SchemaWalker.res.mjs";
20
21
  import * as CommandTopic_Helpers$ReventlessCore from "../CommandTopic/CommandTopic_Helpers.res.mjs";
@@ -254,7 +255,7 @@ function Make(Spec) {
254
255
  };
255
256
  } else {
256
257
  CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", reference, {
257
- errorCode: "AppendFailed",
258
+ errorCode: CommandOutcome$Reventless.code("AppendFailed"),
258
259
  errorDetail: appendErrorDetail
259
260
  });
260
261
  return {
@@ -12,17 +12,26 @@ let log = Logger.fromEnv()
12
12
  // fragments. These SDL declarations are injected into any fragment that emits
13
13
  // at least one mutation field; the stitcher dedupes by type name so
14
14
  // concatenating across plugin + admin fragments stays safe.
15
+ //
16
+ // `cause` says which no a rejection is: the model's (DOMAIN, `errorCode` is the
17
+ // declared error), the caller's (ACCESS) or the platform's (INFRASTRUCTURE).
15
18
  let commandResultSdlTypes: array<string> = [
16
19
  `union CommandResult = CommandAccepted | CommandRejected | CommandPending`,
17
20
  `type CommandAccepted {
18
21
  msgId: ID!
19
22
  entityId: ID
20
23
  eventCount: Int!
24
+ }`,
25
+ `enum CommandRejectionCause {
26
+ DOMAIN
27
+ ACCESS
28
+ INFRASTRUCTURE
21
29
  }`,
22
30
  `type CommandRejected {
23
31
  msgId: ID!
24
32
  errorCode: String!
25
33
  errorDetail: String
34
+ cause: CommandRejectionCause!
26
35
  }`,
27
36
  `type CommandPending {
28
37
  msgId: ID!
@@ -22,11 +22,17 @@ let commandResultSdlTypes = [
22
22
  msgId: ID!
23
23
  entityId: ID
24
24
  eventCount: Int!
25
+ }`,
26
+ `enum CommandRejectionCause {
27
+ DOMAIN
28
+ ACCESS
29
+ INFRASTRUCTURE
25
30
  }`,
26
31
  `type CommandRejected {
27
32
  msgId: ID!
28
33
  errorCode: String!
29
34
  errorDetail: String
35
+ cause: CommandRejectionCause!
30
36
  }`,
31
37
  `type CommandPending {
32
38
  msgId: ID!
@@ -23,6 +23,8 @@ function filter(allCommandTopics, names) {
23
23
 
24
24
  let componentType = "CommandTopic";
25
25
 
26
+ let refusalCauseToGraphQL = CommandTopic_Helpers$ReventlessCore.refusalCauseToGraphQL;
27
+
26
28
  let commandOutcomeHook = CommandTopic_Helpers$ReventlessCore.commandOutcomeHook;
27
29
 
28
30
  let registerCommandOutcome = CommandTopic_Helpers$ReventlessCore.registerCommandOutcome;
@@ -60,6 +62,7 @@ let getHandlers = CommandTopic_Helpers$ReventlessCore.getHandlers;
60
62
  export {
61
63
  componentType,
62
64
  NotPublishedToChannel,
65
+ refusalCauseToGraphQL,
63
66
  commandOutcomeHook,
64
67
  registerCommandOutcome,
65
68
  clearCommandOutcome,
@@ -31,6 +31,14 @@ own what the command acts on (`OwnerScope.decideActing`).
31
31
  */
32
32
  type refusalCause = DomainRejection | InfrastructureFailure | AccessRefusal
33
33
 
34
+ /** The `CommandRejectionCause` enum value a client sees for a cause. */
35
+ let refusalCauseToGraphQL = (cause: refusalCause): string =>
36
+ switch cause {
37
+ | DomainRejection => "DOMAIN"
38
+ | AccessRefusal => "ACCESS"
39
+ | InfrastructureFailure => "INFRASTRUCTURE"
40
+ }
41
+
34
42
  /**
35
43
  What became of one command. Constructors are prefixed to stay clear of `commandOutcome`'s
36
44
  `Accepted`/`Rejected` below — that type is the producer-facing result shape (and the GraphQL
@@ -91,10 +99,9 @@ let fireCommandOutcome = (~component: string, ~reference: string, outcome: obser
91
99
  // Callback implementations call reportAccepted during inline dispatch.
92
100
  let acceptedResultChannel: ref<option<(string, acceptedResult) => unit>> = ref(None)
93
101
 
94
- // Sibling side-channel for domain rejections — populated by callbacks when
95
- // `Decision.decide` returns `Error`. Read by runInlineAndCollect to build
96
- // `Rejected` outcomes that carry the real error code and detail.
97
- let rejectedResultChannel: ref<option<(string, rejectedResult) => unit>> = ref(None)
102
+ // Sibling side-channel for rejections, with their cause. Read by runInlineAndCollect
103
+ // to build `Rejected` outcomes that carry the real error code, detail and cause.
104
+ let rejectedResultChannel: ref<option<(string, rejectedResult, refusalCause) => unit>> = ref(None)
98
105
 
99
106
  /**
100
107
  Turn an `acting` verdict into the refusal a command handler reports, or `None` to let
@@ -112,7 +119,10 @@ let ownershipRefusal = (
112
119
  ~command: string,
113
120
  ): option<ownershipRefusal> => {
114
121
  let refuse = (~isDefect=false, why) => Some({
115
- rejected: {errorCode: "Forbidden", errorDetail: `${component}.${command}: ${why}`},
122
+ rejected: {
123
+ errorCode: Reventless.CommandOutcome.code(Forbidden),
124
+ errorDetail: `${component}.${command}: ${why}`,
125
+ },
116
126
  isDefect,
117
127
  })
118
128
  switch verdict {
@@ -148,7 +158,7 @@ let reportRejected = (
148
158
  reference: string,
149
159
  result: rejectedResult,
150
160
  ) => {
151
- rejectedResultChannel.contents->Option.forEach(cb => cb(reference, result))
161
+ rejectedResultChannel.contents->Option.forEach(cb => cb(reference, result, cause))
152
162
  fireCommandOutcome(
153
163
  ~component,
154
164
  ~reference,
@@ -160,7 +170,7 @@ let reportRejected = (
160
170
  // without importing Adapter.res → @pulumi/pulumi. Re-exported by CommandTopic via include.
161
171
  type commandOutcome =
162
172
  | Accepted({msgId: string, entityId?: string, eventCount: int})
163
- | Rejected({msgId: string, errorCode: string, errorDetail: option<string>})
173
+ | Rejected({msgId: string, errorCode: string, errorDetail: option<string>, cause: refusalCause})
164
174
  | Pending({msgId: string})
165
175
 
166
176
  // Serialise a commandOutcome to the JSON shape the CommandResult GraphQL union
@@ -179,13 +189,14 @@ let commandOutcomeToJson = (outcome: commandOutcome): JSON.t =>
179
189
  ("eventCount", JSON.Number(eventCount->Int.toFloat)),
180
190
  ]),
181
191
  )
182
- | Rejected({msgId, errorCode, errorDetail}) =>
192
+ | Rejected({msgId, errorCode, errorDetail, cause}) =>
183
193
  JSON.Object(
184
194
  Dict.fromArray([
185
195
  ("__typename", JSON.String("CommandRejected")),
186
196
  ("msgId", JSON.String(msgId)),
187
197
  ("errorCode", JSON.String(errorCode)),
188
198
  ("errorDetail", errorDetail->Option.map(s => JSON.String(s))->Option.getOr(JSON.Null)),
199
+ ("cause", JSON.String(refusalCauseToGraphQL(cause))),
189
200
  ]),
190
201
  )
191
202
  | Pending({msgId}) =>
@@ -222,27 +233,34 @@ let runInlineAndCollect = async (
222
233
  item
223
234
  })
224
235
  let acceptedResults: dict<acceptedResult> = Dict.make()
225
- let rejectedResults: dict<rejectedResult> = Dict.make()
236
+ let rejectedResults: dict<(rejectedResult, refusalCause)> = Dict.make()
226
237
  acceptedResultChannel.contents = Some(
227
238
  (reference, result) => acceptedResults->Dict.set(reference, result),
228
239
  )
229
240
  rejectedResultChannel.contents = Some(
230
- (reference, result) => rejectedResults->Dict.set(reference, result),
241
+ (reference, result, cause) => rejectedResults->Dict.set(reference, (result, cause)),
231
242
  )
232
243
  let results = await handleCmds(Stream.fromIterable(items))->Effect.runPromise
233
244
  acceptedResultChannel.contents = None
234
245
  rejectedResultChannel.contents = None
235
246
  jsons->Array.mapWithIndex((cmdJson, i) => {
236
247
  let msgId = cmdJson.meta.msgId
237
- // Domain rejection from Decision.decide takes precedence over both Accepted
238
- // and the synthesized "Conflict" — it carries the most informative error.
248
+ // A reported rejection takes precedence over both Accepted and the
249
+ // synthesized "Conflict" — it carries the most informative error.
239
250
  switch rejectedResults->Dict.get(msgId) {
240
- | Some({errorCode, errorDetail}) =>
251
+ | Some(({errorCode, errorDetail}, cause)) =>
241
252
  let detail = errorDetail == "" ? None : Some(errorDetail)
242
- Rejected({msgId, errorCode, errorDetail: detail})
253
+ Rejected({msgId, errorCode, errorDetail: detail, cause})
243
254
  | None =>
244
255
  switch results->Array.get(i) {
245
- | Some(Error(msg)) => Rejected({msgId, errorCode: "Conflict", errorDetail: Some(msg)})
256
+ // The handler failed outright: the platform, not the model.
257
+ | Some(Error(msg)) =>
258
+ Rejected({
259
+ msgId,
260
+ errorCode: Reventless.CommandOutcome.code(Conflict),
261
+ errorDetail: Some(msg),
262
+ cause: InfrastructureFailure,
263
+ })
246
264
  | _ =>
247
265
  let ar = acceptedResults->Dict.get(msgId)->Option.getOr({eventCount: 0})
248
266
  switch ar.entityId {
@@ -8,8 +8,20 @@ import * as DcbTag$Reventless from "@reventlessdev/reventless-spec/src/component
8
8
  import * as Message$Reventless from "@reventlessdev/reventless-spec/src/types/Message.res.mjs";
9
9
  import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.js";
10
10
  import * as Util_Sury$Reventless from "@reventlessdev/reventless-spec/src/util/Util_Sury.res.mjs";
11
+ import * as CommandOutcome$Reventless from "@reventlessdev/reventless-spec/src/components/CommandOutcome.res.mjs";
11
12
  import * as EffectLogger$ReventlessCore from "../../util/EffectLogger.res.mjs";
12
13
 
14
+ function refusalCauseToGraphQL(cause) {
15
+ switch (cause) {
16
+ case "DomainRejection" :
17
+ return "DOMAIN";
18
+ case "InfrastructureFailure" :
19
+ return "INFRASTRUCTURE";
20
+ case "AccessRefusal" :
21
+ return "ACCESS";
22
+ }
23
+ }
24
+
13
25
  let commandOutcomeHook = {
14
26
  contents: undefined
15
27
  };
@@ -51,7 +63,7 @@ function ownershipRefusal(verdict, component, command) {
51
63
  let isDefect = isDefectOpt !== undefined ? isDefectOpt : false;
52
64
  return {
53
65
  rejected: {
54
- errorCode: "Forbidden",
66
+ errorCode: CommandOutcome$Reventless.code("Forbidden"),
55
67
  errorDetail: component + `.` + command + `: ` + why
56
68
  },
57
69
  isDefect: isDefect
@@ -84,7 +96,7 @@ function reportAccepted(component, reference, result) {
84
96
  }
85
97
 
86
98
  function reportRejected(component, cause, reference, result) {
87
- Stdlib_Option.forEach(rejectedResultChannel.contents, cb => cb(reference, result));
99
+ Stdlib_Option.forEach(rejectedResultChannel.contents, cb => cb(reference, result, cause));
88
100
  fireCommandOutcome(component, reference, {
89
101
  TAG: "OutcomeRejected",
90
102
  errorCode: result.errorCode,
@@ -131,6 +143,10 @@ function commandOutcomeToJson(outcome) {
131
143
  [
132
144
  "errorDetail",
133
145
  Stdlib_Option.getOr(Stdlib_Option.map(outcome.errorDetail, s => (s)), null)
146
+ ],
147
+ [
148
+ "cause",
149
+ refusalCauseToGraphQL(outcome.cause)
134
150
  ]
135
151
  ]);
136
152
  case "Pending" :
@@ -177,8 +193,11 @@ async function runInlineAndCollect(jsons, handleCmds) {
177
193
  acceptedResultChannel.contents = (reference, result) => {
178
194
  acceptedResults[reference] = result;
179
195
  };
180
- rejectedResultChannel.contents = (reference, result) => {
181
- rejectedResults[reference] = result;
196
+ rejectedResultChannel.contents = (reference, result, cause) => {
197
+ rejectedResults[reference] = [
198
+ result,
199
+ cause
200
+ ];
182
201
  };
183
202
  let results = await Effect.runPromise(handleCmds(Stream.fromIterable(items)));
184
203
  acceptedResultChannel.contents = undefined;
@@ -187,22 +206,25 @@ async function runInlineAndCollect(jsons, handleCmds) {
187
206
  let msgId = cmdJson.meta.msgId;
188
207
  let match = rejectedResults[msgId];
189
208
  if (match !== undefined) {
190
- let errorDetail = match.errorDetail;
209
+ let match$1 = match[0];
210
+ let errorDetail = match$1.errorDetail;
191
211
  let detail = errorDetail === "" ? undefined : errorDetail;
192
212
  return {
193
213
  TAG: "Rejected",
194
214
  msgId: msgId,
195
- errorCode: match.errorCode,
196
- errorDetail: detail
215
+ errorCode: match$1.errorCode,
216
+ errorDetail: detail,
217
+ cause: match[1]
197
218
  };
198
219
  }
199
- let match$1 = results[i];
200
- if (match$1 !== undefined && match$1.TAG !== "Ok") {
220
+ let match$2 = results[i];
221
+ if (match$2 !== undefined && match$2.TAG !== "Ok") {
201
222
  return {
202
223
  TAG: "Rejected",
203
224
  msgId: msgId,
204
- errorCode: "Conflict",
205
- errorDetail: match$1._0
225
+ errorCode: CommandOutcome$Reventless.code("Conflict"),
226
+ errorDetail: match$2._0,
227
+ cause: "InfrastructureFailure"
206
228
  };
207
229
  }
208
230
  let ar = Stdlib_Option.getOr(acceptedResults[msgId], {
@@ -249,6 +271,7 @@ function getHandlers(typeName) {
249
271
  }
250
272
 
251
273
  export {
274
+ refusalCauseToGraphQL,
252
275
  commandOutcomeHook,
253
276
  registerCommandOutcome,
254
277
  clearCommandOutcome,
@@ -19,6 +19,17 @@ type auditRow = {
19
19
  door?: ReventlessInfra.InboundTranslationSlice.door,
20
20
  }
21
21
 
22
+ /** A refused caller is access, a failed publish the platform; anything else is
23
+ the translation refusing its input. */
24
+ let rejectionCauseOf = (errorCode: string): CommandTopic_Helpers.refusalCause =>
25
+ if errorCode == Reventless.CommandOutcome.code(Forbidden) {
26
+ AccessRefusal
27
+ } else if errorCode == Reventless.CommandOutcome.code(PublishFailed) {
28
+ InfrastructureFailure
29
+ } else {
30
+ DomainRejection
31
+ }
32
+
22
33
  /** The `CommandResult` a `receive` outcome answers with: the first target as
23
34
  `entityId` (omitted when nothing was produced), the fan-out as `eventCount`. */
24
35
  let receiveResultToOutcome = (
@@ -31,10 +42,12 @@ let receiveResultToOutcome = (
31
42
  | None => Accepted({msgId: requestId, eventCount: commandCount})
32
43
  }
33
44
  | Error({requestId, error, ?errorCode}) =>
45
+ let errorCode = errorCode->Option.getOr(Reventless.CommandOutcome.code(TranslationFailed))
34
46
  Rejected({
35
47
  msgId: requestId,
36
- errorCode: errorCode->Option.getOr("TranslationFailed"),
48
+ errorCode,
37
49
  errorDetail: Some(error),
50
+ cause: rejectionCauseOf(errorCode),
38
51
  })
39
52
  }
40
53
 
@@ -216,7 +229,7 @@ module Make = (
216
229
  )
217
230
  ) =>
218
231
  fail(
219
- ~errorCode="Forbidden",
232
+ ~errorCode=Reventless.CommandOutcome.code(Forbidden),
220
233
  `${Spec.name}: the caller is not authorized for every command this input translates into`,
221
234
  )
222
235
  | Ok([]) => succeed([])
@@ -225,7 +238,11 @@ module Make = (
225
238
  await publishJsons(msgs)
226
239
  succeed(pairs->Array.map(((targetId, _)) => targetId))
227
240
  } catch {
228
- | exn => fail(~errorCode="PublishFailed", messageOf(exn, "publish failed"))
241
+ | exn =>
242
+ fail(
243
+ ~errorCode=Reventless.CommandOutcome.code(PublishFailed),
244
+ messageOf(exn, "publish failed"),
245
+ )
229
246
  }
230
247
  }
231
248
  }
@@ -16,6 +16,7 @@ import * as Util_Sury$Reventless from "@reventlessdev/reventless-spec/src/util/U
16
16
  import * as OwnerScope$Reventless from "@reventlessdev/reventless-spec/src/types/OwnerScope.res.mjs";
17
17
  import * as Message$ReventlessCore from "../../Message.res.mjs";
18
18
  import * as Authorization$Reventless from "@reventlessdev/reventless-spec/src/types/Authorization.res.mjs";
19
+ import * as CommandOutcome$Reventless from "@reventlessdev/reventless-spec/src/components/CommandOutcome.res.mjs";
19
20
  import * as EffectLogger$ReventlessCore from "../../util/EffectLogger.res.mjs";
20
21
  import * as ApiNoApiHelpers$ReventlessCore from "../Api/ApiNoApiHelpers.res.mjs";
21
22
  import * as InboundTranslationSlice$ReventlessInfra from "@reventlessdev/reventless-infra/src/components/InboundTranslationSlice.res.mjs";
@@ -36,6 +37,16 @@ let auditRowSchema = Sury.$schema(s => ({
36
37
  door: s.m(Sury.$option(InboundTranslationSlice$ReventlessInfra.doorSchema))
37
38
  }));
38
39
 
40
+ function rejectionCauseOf(errorCode) {
41
+ if (errorCode === CommandOutcome$Reventless.code("Forbidden")) {
42
+ return "AccessRefusal";
43
+ } else if (errorCode === CommandOutcome$Reventless.code("PublishFailed")) {
44
+ return "InfrastructureFailure";
45
+ } else {
46
+ return "DomainRejection";
47
+ }
48
+ }
49
+
39
50
  function receiveResultToOutcome(result) {
40
51
  if (result.TAG === "Ok") {
41
52
  let match = result._0;
@@ -58,11 +69,13 @@ function receiveResultToOutcome(result) {
58
69
  }
59
70
  }
60
71
  let match$1 = result._0;
72
+ let errorCode = Stdlib_Option.getOr(match$1.errorCode, CommandOutcome$Reventless.code("TranslationFailed"));
61
73
  return {
62
74
  TAG: "Rejected",
63
75
  msgId: match$1.requestId,
64
- errorCode: Stdlib_Option.getOr(match$1.errorCode, "TranslationFailed"),
65
- errorDetail: match$1.error
76
+ errorCode: errorCode,
77
+ errorDetail: match$1.error,
78
+ cause: rejectionCauseOf(errorCode)
66
79
  };
67
80
  }
68
81
 
@@ -213,7 +226,7 @@ function Make(Spec) {
213
226
  }
214
227
  let msgs = msg$1._0;
215
228
  if (msgs.some(param => !callerAdmits(Authorization$Reventless.named(Spec.authorizationOf(Message$Reventless.variantNameOfJson(param.commandJson))), caller))) {
216
- return fail("Forbidden", Spec.name + `: the caller is not authorized for every command this input translates into`);
229
+ return fail(CommandOutcome$Reventless.code("Forbidden"), Spec.name + `: the caller is not authorized for every command this input translates into`);
217
230
  }
218
231
  if (msgs.length === 0) {
219
232
  return succeed([]);
@@ -223,7 +236,7 @@ function Make(Spec) {
223
236
  return succeed(pairs.map(param => param[0]));
224
237
  } catch (raw_exn$1) {
225
238
  let exn$1 = Primitive_exceptions.internalToException(raw_exn$1);
226
- return fail("PublishFailed", messageOf(exn$1, "publish failed"));
239
+ return fail(CommandOutcome$Reventless.code("PublishFailed"), messageOf(exn$1, "publish failed"));
227
240
  }
228
241
  };
229
242
  let refuse = (body, errorCode, error) => failWith(Uuid.v4(), body, "Webhook", errorCode, error);
@@ -241,6 +254,7 @@ function Make(Spec) {
241
254
  export {
242
255
  auditStatusSchema,
243
256
  auditRowSchema,
257
+ rejectionCauseOf,
244
258
  receiveResultToOutcome,
245
259
  requestIdOf,
246
260
  takeAuditRow,
@@ -478,10 +478,10 @@ module Make = (
478
478
  // which disagreed with the backends' casing).
479
479
  let (errorCode, errDetail) = switch err {
480
480
  | ReventlessInfra.DcbEventLog.Conflict => (
481
- "Conflict",
481
+ Reventless.CommandOutcome.code(Conflict),
482
482
  "conflict: condition check failed",
483
483
  )
484
- | StorageFailure(msg) => ("AppendFailed", msg)
484
+ | StorageFailure(msg) => (Reventless.CommandOutcome.code(AppendFailed), msg)
485
485
  }
486
486
  if retries > 0 {
487
487
  // Re-seed from the just-read snapshot so the retry reads only
@@ -504,7 +504,7 @@ module Make = (
504
504
  // A surfaced Conflict means the 3-retry loop could not absorb
505
505
  // the contention — the operator signal for "this slice is hot"
506
506
  // (consider sharding / async — Issue 10, §4 of the analysis).
507
- if errorCode == "Conflict" {
507
+ if errorCode == Reventless.CommandOutcome.code(Conflict) {
508
508
  Metrics.emitCount(~metric="AppendConflict", ~slice=Spec.name)
509
509
  }
510
510
  // Both arms here are storage, not the model: a surfaced Conflict is
@@ -17,6 +17,7 @@ import * as OwnerScope$Reventless from "@reventlessdev/reventless-spec/src/types
17
17
  import * as Message$ReventlessCore from "../../Message.res.mjs";
18
18
  import * as Metrics$ReventlessCore from "../../util/Metrics.res.mjs";
19
19
  import * as LogFormat$ReventlessCore from "../../util/LogFormat.res.mjs";
20
+ import * as CommandOutcome$Reventless from "@reventlessdev/reventless-spec/src/components/CommandOutcome.res.mjs";
20
21
  import * as EffectLogger$ReventlessCore from "../../util/EffectLogger.res.mjs";
21
22
  import * as CommandTopic_Helpers$ReventlessCore from "../CommandTopic/CommandTopic_Helpers.res.mjs";
22
23
 
@@ -311,10 +312,10 @@ function Make(Spec) {
311
312
  let err = appendResult._0;
312
313
  let match;
313
314
  match = typeof err !== "object" ? [
314
- "Conflict",
315
+ CommandOutcome$Reventless.code("Conflict"),
315
316
  "conflict: condition check failed"
316
317
  ] : [
317
- "AppendFailed",
318
+ CommandOutcome$Reventless.code("AppendFailed"),
318
319
  err._0
319
320
  ];
320
321
  let errDetail = match[1];
@@ -329,7 +330,7 @@ function Make(Spec) {
329
330
  return Effect.flatMap(EffectLogger$ReventlessCore.logWarn(comp, undefined, `append failed (retrying ` + ((3 - retries | 0) + 1 | 0).toString() + `/` + (3).toString() + `): ` + errDetail), () => attempt(retries - 1 | 0));
330
331
  } else {
331
332
  cacheInvalidate();
332
- if (errorCode === "Conflict") {
333
+ if (errorCode === CommandOutcome$Reventless.code("Conflict")) {
333
334
  Metrics$ReventlessCore.emitCount("AppendConflict", Spec.name, undefined);
334
335
  }
335
336
  CommandTopic_Helpers$ReventlessCore.reportRejected(Spec.name, "InfrastructureFailure", cmdJson.meta.msgId, {
@@ -593,6 +593,8 @@ id find the view that lists it without an `@ref`. `report` says where the type
593
593
  cannot decide: several views keyed by the identity, none, or an `@ref` naming a
594
594
  view keyed by another. `inform` takes the one case that is not a fault: an
595
595
  identity in `ownIdentities`, declared by this plugin, that no view lists yet.
596
+ Where several views are keyed by it, the one in `chapter` (the declaring
597
+ component's) is the reference, if exactly one is there.
596
598
  */
597
599
  type identityViews = {
598
600
  viewsByKey: dict<array<string>>,
@@ -600,6 +602,8 @@ type identityViews = {
600
602
  ownIdentities: array<string>,
601
603
  report: string => unit,
602
604
  inform: string => unit,
605
+ chapter?: string,
606
+ viewChapter?: string => option<string>,
603
607
  }
604
608
 
605
609
  // The reference a typed id implies, and the check on one it declares.
@@ -627,12 +631,21 @@ let identityReference = (
627
631
  )
628
632
  []
629
633
  | several =>
630
- identityViews.report(
631
- `${fieldName} is a ${key}, and ${several->Array.join(
632
- " and ",
633
- )} are all keyed by it. Say which it references with @ref.`,
634
- )
635
- []
634
+ let inChapter = switch (identityViews.chapter, identityViews.viewChapter) {
635
+ | (Some(chapter), Some(viewChapter)) =>
636
+ several->Array.filter(view => viewChapter(view) == Some(chapter))
637
+ | _ => []
638
+ }
639
+ switch inChapter {
640
+ | [view] => [(fieldName, {Reventless.Semantic.entity: view, plugin: None, identity: key})]
641
+ | _ =>
642
+ identityViews.report(
643
+ `${fieldName} is a ${key}, and ${several->Array.join(
644
+ " and ",
645
+ )} are all keyed by it, and no chapter singles one out. Say which it references with @ref.`,
646
+ )
647
+ []
648
+ }
636
649
  }
637
650
  | _ =>
638
651
  declared->Array.forEach(((_, target)) =>
@@ -1695,7 +1708,9 @@ let make = (
1695
1708
  ownIdentities: identities,
1696
1709
  report: message => once(log.warn, message),
1697
1710
  inform: message => once(log.info, message),
1711
+ viewChapter: chapterOf,
1698
1712
  }
1713
+ let identityViewsOf = component => {...identityViews, chapter: ?chapterOf(component)}
1699
1714
 
1700
1715
  let stateChangeDefs =
1701
1716
  stateChangeSlices->Array.mapWithIndex((module(SCS: ReventlessInfra.StateChangeSlice.T), i) => {
@@ -1706,7 +1721,7 @@ let make = (
1706
1721
  {
1707
1722
  Reventless.Plugin.name: SCS.Spec.name,
1708
1723
  commands: extractCommandDefs(
1709
- ~identityViews,
1724
+ ~identityViews=identityViewsOf(SCS.Spec.name),
1710
1725
  ~isAggregate=false,
1711
1726
  ~partitionKey=?partitionBySlice->Dict.get(SCS.Spec.name),
1712
1727
  ~mutationFieldFor=variantName =>
@@ -1725,7 +1740,10 @@ let make = (
1725
1740
  consumedEventTypes: consumed,
1726
1741
  linkedViews: linkedSvsFor(produced),
1727
1742
  consistencyRead: consistencyReadFor(consumed),
1728
- events: extractEventDefs(~identityViews, SCS.Spec.eventSchema->S.castToUnknown),
1743
+ events: extractEventDefs(
1744
+ ~identityViews=identityViewsOf(SCS.Spec.name),
1745
+ SCS.Spec.eventSchema->S.castToUnknown,
1746
+ ),
1729
1747
  errors: extractErrorDefs(SCS.Spec.errorSchema->S.castToUnknown),
1730
1748
  chapter: chapterOf(SCS.Spec.name),
1731
1749
  }: Reventless.Plugin.writeSideDef
@@ -1742,7 +1760,7 @@ let make = (
1742
1760
  {
1743
1761
  Reventless.Plugin.name: A.Spec.name,
1744
1762
  commands: extractCommandDefs(
1745
- ~identityViews,
1763
+ ~identityViews=identityViewsOf(A.Spec.name),
1746
1764
  ~isAggregate=true,
1747
1765
  ~mutationFieldFor=variantName =>
1748
1766
  Api_Naming.aggregateMutationField(
@@ -1759,7 +1777,10 @@ let make = (
1759
1777
  consumedEventTypes: [],
1760
1778
  linkedViews: Array.concat(linkedSvsFor(produced), linkedReadModelsFor(A.Spec.name)),
1761
1779
  consistencyRead: None,
1762
- events: extractEventDefs(~identityViews, A.Spec.eventSchema->S.castToUnknown),
1780
+ events: extractEventDefs(
1781
+ ~identityViews=identityViewsOf(A.Spec.name),
1782
+ A.Spec.eventSchema->S.castToUnknown,
1783
+ ),
1763
1784
  errors: extractErrorDefs(A.Spec.errorSchema->S.castToUnknown),
1764
1785
  chapter: chapterOf(A.Spec.name),
1765
1786
  }: Reventless.Plugin.writeSideDef
@@ -466,18 +466,34 @@ function identityReference(identityViews, fieldName, fieldSchema, declared) {
466
466
  let len = keyed.length;
467
467
  if (len !== 1) {
468
468
  if (len !== 0) {
469
- identityViews.report(fieldName + ` is a ` + key + `, and ` + keyed.join(" and ") + ` are all keyed by it. Say which it references with @ref.`);
470
- return [];
469
+ let match = identityViews.chapter;
470
+ let match$1 = identityViews.viewChapter;
471
+ let inChapter = match !== undefined ? (
472
+ match$1 !== undefined ? keyed.filter(view => Primitive_object.equal(match$1(view), match)) : []
473
+ ) : [];
474
+ if (inChapter.length !== 1) {
475
+ identityViews.report(fieldName + ` is a ` + key + `, and ` + keyed.join(" and ") + ` are all keyed by it, and no chapter singles one out. Say which it references with @ref.`);
476
+ return [];
477
+ }
478
+ let view = inChapter[0];
479
+ return [[
480
+ fieldName,
481
+ {
482
+ entity: view,
483
+ plugin: undefined,
484
+ identity: key
485
+ }
486
+ ]];
471
487
  }
472
488
  let say = identityViews.ownIdentities.includes(key) ? identityViews.inform : identityViews.report;
473
489
  say(fieldName + ` is a ` + key + `, and no view in this plugin is keyed by it, so it references nothing. List the identity in a view, or reference another plugin's with @ref("Plugin.View").`);
474
490
  return [];
475
491
  }
476
- let view = keyed[0];
492
+ let view$1 = keyed[0];
477
493
  return [[
478
494
  fieldName,
479
495
  {
480
- entity: view,
496
+ entity: view$1,
481
497
  plugin: undefined,
482
498
  identity: key
483
499
  }
@@ -816,6 +832,7 @@ function make(name, aggregatesOpt, readModelsOpt, stateViewSlicesOpt, stateChang
816
832
  let componentChapters = componentChaptersOpt !== undefined ? componentChaptersOpt : ({});
817
833
  let lifecycleModel = lifecycleModelOpt !== undefined ? lifecycleModelOpt : [];
818
834
  let identities = identitiesOpt !== undefined ? identitiesOpt : [];
835
+ let chapterOf = compName => componentChapters[compName];
819
836
  let model = declaredTransitionsOnly ? [] : lifecycleModel;
820
837
  let derivedEdgeFor = (component, command) => model.find(e => {
821
838
  if (e.component === component) {
@@ -1214,12 +1231,19 @@ function make(name, aggregatesOpt, readModelsOpt, stateViewSlicesOpt, stateChang
1214
1231
  let identityViews_viewNames = viewKeys.map(param => param[0]);
1215
1232
  let identityViews_report = message => once(log.warn, message);
1216
1233
  let identityViews_inform = message => once(log.info, message);
1234
+ let identityViews_viewChapter = chapterOf;
1217
1235
  let identityViews = {
1218
1236
  viewsByKey: viewsByKey,
1219
1237
  viewNames: identityViews_viewNames,
1220
1238
  ownIdentities: identities,
1221
1239
  report: identityViews_report,
1222
- inform: identityViews_inform
1240
+ inform: identityViews_inform,
1241
+ viewChapter: identityViews_viewChapter
1242
+ };
1243
+ let identityViewsOf = component => {
1244
+ let newrecord = {...identityViews};
1245
+ newrecord.chapter = componentChapters[component];
1246
+ return newrecord;
1223
1247
  };
1224
1248
  let stateChangeDefs = stateChangeSlices.map((SCS, i) => {
1225
1249
  let match = scsProduced[i];
@@ -1228,12 +1252,12 @@ function make(name, aggregatesOpt, readModelsOpt, stateViewSlicesOpt, stateChang
1228
1252
  let consumed = match$1[1];
1229
1253
  return {
1230
1254
  name: SCS.Spec.name,
1231
- commands: extractCommandDefs(identityViews, false, partitionBySlice[SCS.Spec.name], variantName => Api_Naming$ReventlessCore.sliceMutationFieldFor(name, SCS.Spec.name, SCS.Spec.commandSchema, variantName), name => Authorization$Reventless.named(SCS.Spec.authorizationOf(name)), SCS.Spec.commandTransition, extra => derivedEdgeFor(SCS.Spec.name, extra), SCS.Spec.commandSchema),
1255
+ commands: extractCommandDefs(identityViewsOf(SCS.Spec.name), false, partitionBySlice[SCS.Spec.name], variantName => Api_Naming$ReventlessCore.sliceMutationFieldFor(name, SCS.Spec.name, SCS.Spec.commandSchema, variantName), name => Authorization$Reventless.named(SCS.Spec.authorizationOf(name)), SCS.Spec.commandTransition, extra => derivedEdgeFor(SCS.Spec.name, extra), SCS.Spec.commandSchema),
1232
1256
  producedEventTypes: produced,
1233
1257
  consumedEventTypes: consumed,
1234
1258
  linkedViews: linkedSvsFor(produced),
1235
1259
  consistencyRead: consistencyReadFor(consumed),
1236
- events: extractEventDefs(identityViews, SCS.Spec.eventSchema),
1260
+ events: extractEventDefs(identityViewsOf(SCS.Spec.name), SCS.Spec.eventSchema),
1237
1261
  errors: extractErrorDefs(SCS.Spec.errorSchema),
1238
1262
  chapter: componentChapters[SCS.Spec.name]
1239
1263
  };
@@ -1243,12 +1267,12 @@ function make(name, aggregatesOpt, readModelsOpt, stateViewSlicesOpt, stateChang
1243
1267
  let produced = match[1];
1244
1268
  return {
1245
1269
  name: A.Spec.name,
1246
- commands: extractCommandDefs(identityViews, true, undefined, variantName => Api_Naming$ReventlessCore.aggregateMutationField(name, A.Spec.name, variantName), name => Authorization$Reventless.named(A.Spec.authorizationOf(name)), A.Spec.commandTransition, extra => derivedEdgeFor(A.Spec.name, extra), A.Spec.commandSchema),
1270
+ commands: extractCommandDefs(identityViewsOf(A.Spec.name), true, undefined, variantName => Api_Naming$ReventlessCore.aggregateMutationField(name, A.Spec.name, variantName), name => Authorization$Reventless.named(A.Spec.authorizationOf(name)), A.Spec.commandTransition, extra => derivedEdgeFor(A.Spec.name, extra), A.Spec.commandSchema),
1247
1271
  producedEventTypes: produced,
1248
1272
  consumedEventTypes: [],
1249
1273
  linkedViews: linkedSvsFor(produced).concat(linkedReadModelsFor(A.Spec.name)),
1250
1274
  consistencyRead: undefined,
1251
- events: extractEventDefs(identityViews, A.Spec.eventSchema),
1275
+ events: extractEventDefs(identityViewsOf(A.Spec.name), A.Spec.eventSchema),
1252
1276
  errors: extractErrorDefs(A.Spec.errorSchema),
1253
1277
  chapter: componentChapters[A.Spec.name]
1254
1278
  };
@@ -14,13 +14,18 @@ let _ = beforeEach(() => {
14
14
 
15
15
  // Captures whatever flows through CommandTopic_Helpers.reportRejected during a test.
16
16
  let capturedRejections: ref<array<(string, CommandTopic_Helpers.rejectedResult)>> = ref([])
17
+ let capturedCauses: ref<array<CommandTopic_Helpers.refusalCause>> = ref([])
17
18
  let capturedAccepts: ref<array<(string, CommandTopic_Helpers.acceptedResult)>> = ref([])
18
19
 
19
20
  let installChannels = () => {
20
21
  capturedRejections := []
22
+ capturedCauses := []
21
23
  capturedAccepts := []
22
24
  CommandTopic_Helpers.rejectedResultChannel.contents = Some(
23
- (ref, info) => capturedRejections := capturedRejections.contents->Array.concat([(ref, info)]),
25
+ (ref, info, cause) => {
26
+ capturedRejections := capturedRejections.contents->Array.concat([(ref, info)])
27
+ capturedCauses := capturedCauses.contents->Array.concat([cause])
28
+ },
24
29
  )
25
30
  CommandTopic_Helpers.acceptedResultChannel.contents = Some(
26
31
  (ref, info) => capturedAccepts := capturedAccepts.contents->Array.concat([(ref, info)]),
@@ -58,6 +63,8 @@ describe("Aggregate decide-rejection propagation:", () => {
58
63
  let (ref, info) = capturedRejections.contents->Array.getUnsafe(0)
59
64
  expect(ref)->toEqual("ref-1")
60
65
  expect(info.errorCode)->toEqual("AlreadyExists")
66
+ // `decide` said no: the model, not the platform.
67
+ expect(capturedCauses.contents)->toEqual([CommandTopic_Helpers.DomainRejection])
61
68
  // No event was appended.
62
69
  expect(mock.getAll()->Array.length)->toBe(1)
63
70
  },
@@ -14,18 +14,24 @@ let capturedRejections = {
14
14
  contents: []
15
15
  };
16
16
 
17
+ let capturedCauses = {
18
+ contents: []
19
+ };
20
+
17
21
  let capturedAccepts = {
18
22
  contents: []
19
23
  };
20
24
 
21
25
  function installChannels() {
22
26
  capturedRejections.contents = [];
27
+ capturedCauses.contents = [];
23
28
  capturedAccepts.contents = [];
24
- CommandTopic_Helpers$ReventlessCore.rejectedResultChannel.contents = (ref, info) => {
29
+ CommandTopic_Helpers$ReventlessCore.rejectedResultChannel.contents = (ref, info, cause) => {
25
30
  capturedRejections.contents = capturedRejections.contents.concat([[
26
31
  ref,
27
32
  info
28
33
  ]]);
34
+ capturedCauses.contents = capturedCauses.contents.concat([cause]);
29
35
  };
30
36
  CommandTopic_Helpers$ReventlessCore.acceptedResultChannel.contents = (ref, info) => {
31
37
  capturedAccepts.contents = capturedAccepts.contents.concat([[
@@ -61,6 +67,7 @@ globalThis.describe("Aggregate decide-rejection propagation:", () => {
61
67
  let match = capturedRejections.contents[0];
62
68
  globalThis.expect(match[0]).toEqual("ref-1");
63
69
  globalThis.expect(match[1].errorCode).toEqual("AlreadyExists");
70
+ globalThis.expect(capturedCauses.contents).toEqual(["DomainRejection"]);
64
71
  globalThis.expect(AggregateFixtures$ReventlessCore.mock.getAll().length).toBe(1);
65
72
  });
66
73
  });
@@ -159,6 +166,7 @@ globalThis.describe("Aggregate decide-rejection propagation:", () => {
159
166
 
160
167
  export {
161
168
  capturedRejections,
169
+ capturedCauses,
162
170
  capturedAccepts,
163
171
  installChannels,
164
172
  uninstallChannels,
@@ -50,10 +50,11 @@ describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
50
50
  let outcomes = await CommandTopic_Helpers.runInlineAndCollect([cmdJson("msg-1")], handler)
51
51
  expect(outcomes->Array.length)->toBe(1)
52
52
  switch outcomes->Array.getUnsafe(0) {
53
- | Rejected({msgId, errorCode, errorDetail}) =>
53
+ | Rejected({msgId, errorCode, errorDetail, cause}) =>
54
54
  expect(msgId)->toEqual("msg-1")
55
55
  expect(errorCode)->toEqual("AlreadyExists")
56
56
  expect(errorDetail)->toEqual(None)
57
+ expect(cause)->toEqual(CommandTopic_Helpers.DomainRejection)
57
58
  | Accepted(_) | Pending(_) => expect("expected Rejected")->toEqual("got other")
58
59
  }
59
60
  },
@@ -99,8 +100,59 @@ describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
99
100
 
100
101
  let outcomes = await CommandTopic_Helpers.runInlineAndCollect([cmdJson("msg-1")], handler)
101
102
  switch outcomes->Array.getUnsafe(0) {
102
- | Rejected({errorCode}) => expect(errorCode)->toEqual("Conflict")
103
+ | Rejected({errorCode, cause}) =>
104
+ expect(errorCode)->toEqual("Conflict")
105
+ expect(cause)->toEqual(CommandTopic_Helpers.InfrastructureFailure)
103
106
  | _ => expect("expected Rejected(Conflict)")->toEqual("got other")
104
107
  }
105
108
  })
109
+
110
+ testPromise("a reported access refusal keeps its cause", async () => {
111
+ let handler: CommandTopic_Helpers.jsonCommandsHandler = stream =>
112
+ stream
113
+ ->Stream.runCollect
114
+ ->Effect.map(
115
+ items => {
116
+ items->Array.forEach(
117
+ item =>
118
+ CommandTopic_Helpers.reportRejected(
119
+ ~component="TestService",
120
+ ~cause=AccessRefusal,
121
+ item.reference,
122
+ {errorCode: "Forbidden", errorDetail: "not the owner"},
123
+ ),
124
+ )
125
+ items->Array.map(item => Ok(item.reference))
126
+ },
127
+ )
128
+
129
+ let outcomes = await CommandTopic_Helpers.runInlineAndCollect([cmdJson("msg-1")], handler)
130
+ switch outcomes->Array.getUnsafe(0) {
131
+ | Rejected({errorCode, cause}) =>
132
+ expect(errorCode)->toEqual("Forbidden")
133
+ expect(cause)->toEqual(CommandTopic_Helpers.AccessRefusal)
134
+ | _ => expect("expected Rejected(Forbidden)")->toEqual("got other")
135
+ }
136
+ })
137
+ })
138
+
139
+ describe("CommandTopic_Helpers.commandOutcomeToJson:", () => {
140
+ let causeOf = (cause: CommandTopic_Helpers.refusalCause) =>
141
+ CommandTopic_Helpers.commandOutcomeToJson(
142
+ Rejected({msgId: "m", errorCode: "X", errorDetail: None, cause}),
143
+ )
144
+ ->JSON.Decode.object
145
+ ->Option.flatMap(o => o->Dict.get("cause"))
146
+ ->Option.flatMap(JSON.Decode.string)
147
+
148
+ testSync("a rejection carries its cause as the GraphQL enum value", () => {
149
+ expect(causeOf(DomainRejection))->toEqual(Some("DOMAIN"))
150
+ expect(causeOf(AccessRefusal))->toEqual(Some("ACCESS"))
151
+ expect(causeOf(InfrastructureFailure))->toEqual(Some("INFRASTRUCTURE"))
152
+ })
153
+
154
+ testSync("an accepted outcome carries no cause", () => {
155
+ let json = CommandTopic_Helpers.commandOutcomeToJson(Accepted({msgId: "m", eventCount: 1}))
156
+ expect(json->JSON.Decode.object->Option.flatMap(o => o->Dict.get("cause")))->toEqual(None)
157
+ })
106
158
  })
@@ -1,6 +1,8 @@
1
1
  // Generated by ReScript, PLEASE EDIT WITH CARE
2
2
 
3
3
  import * as Stream from "@reventlessdev/rescript-effect/src/Stream.res.mjs";
4
+ import * as Stdlib_JSON from "@rescript/runtime/lib/es6/Stdlib_JSON.js";
5
+ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
4
6
  import * as Effect from "effect/Effect";
5
7
  import * as CommandTopic_Helpers$ReventlessCore from "../../src/components/CommandTopic/CommandTopic_Helpers.res.mjs";
6
8
 
@@ -52,6 +54,7 @@ globalThis.describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
52
54
  globalThis.expect(match.msgId).toEqual("msg-1");
53
55
  globalThis.expect(match.errorCode).toEqual("AlreadyExists");
54
56
  globalThis.expect(match.errorDetail).toEqual(undefined);
57
+ globalThis.expect(match.cause).toEqual("DomainRejection");
55
58
  return;
56
59
  case "Accepted" :
57
60
  case "Pending" :
@@ -93,6 +96,7 @@ globalThis.describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
93
96
  switch (match.TAG) {
94
97
  case "Rejected" :
95
98
  globalThis.expect(match.errorCode).toEqual("Conflict");
99
+ globalThis.expect(match.cause).toEqual("InfrastructureFailure");
96
100
  return;
97
101
  case "Accepted" :
98
102
  case "Pending" :
@@ -100,6 +104,53 @@ globalThis.describe("CommandTopic_Helpers.runInlineAndCollect:", () => {
100
104
  return;
101
105
  }
102
106
  });
107
+ globalThis.test("a reported access refusal keeps its cause", async () => {
108
+ let handler = stream => Effect.map(Stream.runCollect(stream), items => {
109
+ items.forEach(item => CommandTopic_Helpers$ReventlessCore.reportRejected("TestService", "AccessRefusal", item.reference, {
110
+ errorCode: "Forbidden",
111
+ errorDetail: "not the owner"
112
+ }));
113
+ return items.map(item => ({
114
+ TAG: "Ok",
115
+ _0: item.reference
116
+ }));
117
+ });
118
+ let outcomes = await CommandTopic_Helpers$ReventlessCore.runInlineAndCollect([cmdJson("msg-1")], handler);
119
+ let match = outcomes[0];
120
+ switch (match.TAG) {
121
+ case "Rejected" :
122
+ globalThis.expect(match.errorCode).toEqual("Forbidden");
123
+ globalThis.expect(match.cause).toEqual("AccessRefusal");
124
+ return;
125
+ case "Accepted" :
126
+ case "Pending" :
127
+ globalThis.expect("expected Rejected(Forbidden)").toEqual("got other");
128
+ return;
129
+ }
130
+ });
131
+ });
132
+
133
+ globalThis.describe("CommandTopic_Helpers.commandOutcomeToJson:", () => {
134
+ let causeOf = cause => Stdlib_Option.flatMap(Stdlib_Option.flatMap(Stdlib_JSON.Decode.object(CommandTopic_Helpers$ReventlessCore.commandOutcomeToJson({
135
+ TAG: "Rejected",
136
+ msgId: "m",
137
+ errorCode: "X",
138
+ errorDetail: undefined,
139
+ cause: cause
140
+ })), o => o["cause"]), Stdlib_JSON.Decode.string);
141
+ globalThis.test("a rejection carries its cause as the GraphQL enum value", () => {
142
+ globalThis.expect(causeOf("DomainRejection")).toEqual("DOMAIN");
143
+ globalThis.expect(causeOf("AccessRefusal")).toEqual("ACCESS");
144
+ globalThis.expect(causeOf("InfrastructureFailure")).toEqual("INFRASTRUCTURE");
145
+ });
146
+ globalThis.test("an accepted outcome carries no cause", () => {
147
+ let json = CommandTopic_Helpers$ReventlessCore.commandOutcomeToJson({
148
+ TAG: "Accepted",
149
+ msgId: "m",
150
+ eventCount: 1
151
+ });
152
+ globalThis.expect(Stdlib_Option.flatMap(Stdlib_JSON.Decode.object(json), o => o["cause"])).toEqual(undefined);
153
+ });
103
154
  });
104
155
 
105
156
  export {
@@ -11,7 +11,14 @@ module CustomerId = Reventless.Id.Make({
11
11
  let key = "customerId"
12
12
  })
13
13
 
14
- let refsOf = (~viewsByKey, ~ownIdentities=[], ~minted=?, schema: S.t<'a>) => {
14
+ let refsOf = (
15
+ ~viewsByKey,
16
+ ~ownIdentities=[],
17
+ ~minted=?,
18
+ ~chapter=?,
19
+ ~viewChapters=[],
20
+ schema: S.t<'a>,
21
+ ) => {
15
22
  let reports = []
16
23
  let identityViews: Plugin_Structure.identityViews = {
17
24
  viewsByKey: Dict.fromArray(viewsByKey),
@@ -19,6 +26,8 @@ let refsOf = (~viewsByKey, ~ownIdentities=[], ~minted=?, schema: S.t<'a>) => {
19
26
  ownIdentities,
20
27
  report: message => reports->Array.push(message),
21
28
  inform: message => reports->Array.push(`info: ${message}`),
29
+ ?chapter,
30
+ viewChapter: view => Dict.fromArray(viewChapters)->Dict.get(view),
22
31
  }
23
32
  let properties = switch schema->S.castToUnknown {
24
33
  | Object({properties}) => properties
@@ -59,6 +68,38 @@ describe("a reference derived from the type", () => {
59
68
  expect(reports->Array.some(r => r->String.includes("Products and ProductDemand")))->toBe(true)
60
69
  })
61
70
 
71
+ // A counter keyed by the product beside the product list: each slice links to
72
+ // the view in its own chapter, so adding the counter leaves the rest untouched.
73
+ testSync("of several views keyed by it, the one in the field's chapter is the reference", () => {
74
+ let viewsByKey = [("customerId", ["Customers"]), ("productId", ["Products", "ProductDemand"])]
75
+ let viewChapters = [("Products", "Product"), ("ProductDemand", "ProductDemand")]
76
+ let (product, productReports) = refsOf(~viewsByKey, ~viewChapters, ~chapter="Product", order)
77
+ let (demand, _) = refsOf(~viewsByKey, ~viewChapters, ~chapter="ProductDemand", order)
78
+ expect((product, productReports, demand))->toEqual((
79
+ [("buyer", "Customers"), ("productIds", "Products")],
80
+ [],
81
+ [("buyer", "Customers"), ("productIds", "ProductDemand")],
82
+ ))
83
+ })
84
+
85
+ testSync("a chapter holding none of them, or several, still asks for @ref", () => {
86
+ let viewsByKey = [("customerId", ["Customers"]), ("productId", ["Products", "ProductDemand"])]
87
+ let (elsewhere, _) = refsOf(
88
+ ~viewsByKey,
89
+ ~viewChapters=[("Products", "Product"), ("ProductDemand", "ProductDemand")],
90
+ ~chapter="Order",
91
+ order,
92
+ )
93
+ let (both, reports) = refsOf(
94
+ ~viewsByKey,
95
+ ~viewChapters=[("Products", "Product"), ("ProductDemand", "Product")],
96
+ ~chapter="Product",
97
+ order,
98
+ )
99
+ expect((elsewhere, both))->toEqual(([("buyer", "Customers")], [("buyer", "Customers")]))
100
+ expect(reports->Array.some(r => r->String.includes("no chapter singles one out")))->toBe(true)
101
+ })
102
+
62
103
  testSync("no view keyed by it is reported", () => {
63
104
  let (refs, reports) = refsOf(~viewsByKey=[("productId", ["AvailableProducts"])], order)
64
105
  expect(refs)->toEqual([("productIds", "AvailableProducts")])
@@ -13,8 +13,9 @@ let CustomerId = Id$Reventless.Make({
13
13
  key: "customerId"
14
14
  });
15
15
 
16
- function refsOf(viewsByKey, ownIdentitiesOpt, minted, schema) {
16
+ function refsOf(viewsByKey, ownIdentitiesOpt, minted, chapter, viewChaptersOpt, schema) {
17
17
  let ownIdentities = ownIdentitiesOpt !== undefined ? ownIdentitiesOpt : [];
18
+ let viewChapters = viewChaptersOpt !== undefined ? viewChaptersOpt : [];
18
19
  let reports = [];
19
20
  let identityViews_viewsByKey = Object.fromEntries(viewsByKey);
20
21
  let identityViews_viewNames = viewsByKey.flatMap(param => param[1]);
@@ -24,12 +25,15 @@ function refsOf(viewsByKey, ownIdentitiesOpt, minted, schema) {
24
25
  let identityViews_inform = message => {
25
26
  reports.push(`info: ` + message);
26
27
  };
28
+ let identityViews_viewChapter = view => Object.fromEntries(viewChapters)[view];
27
29
  let identityViews = {
28
30
  viewsByKey: identityViews_viewsByKey,
29
31
  viewNames: identityViews_viewNames,
30
32
  ownIdentities: ownIdentities,
31
33
  report: identityViews_report,
32
- inform: identityViews_inform
34
+ inform: identityViews_inform,
35
+ chapter: chapter,
36
+ viewChapter: identityViews_viewChapter
33
37
  };
34
38
  let properties;
35
39
  properties = schema.type === "object" ? schema.properties : ({});
@@ -60,7 +64,7 @@ globalThis.describe("a reference derived from the type", () => {
60
64
  "productId",
61
65
  ["AvailableProducts"]
62
66
  ]
63
- ], undefined, undefined, order);
67
+ ], undefined, undefined, undefined, undefined, order);
64
68
  globalThis.expect(match[0]).toEqual([
65
69
  [
66
70
  "buyer",
@@ -86,18 +90,121 @@ globalThis.describe("a reference derived from the type", () => {
86
90
  "ProductDemand"
87
91
  ]
88
92
  ]
89
- ], undefined, undefined, order);
93
+ ], undefined, undefined, undefined, undefined, order);
90
94
  globalThis.expect(match[0]).toEqual([[
91
95
  "buyer",
92
96
  "Customers"
93
97
  ]]);
94
98
  globalThis.expect(match[1].some(r => r.includes("Products and ProductDemand"))).toBe(true);
95
99
  });
100
+ globalThis.test("of several views keyed by it, the one in the field's chapter is the reference", () => {
101
+ let viewsByKey = [
102
+ [
103
+ "customerId",
104
+ ["Customers"]
105
+ ],
106
+ [
107
+ "productId",
108
+ [
109
+ "Products",
110
+ "ProductDemand"
111
+ ]
112
+ ]
113
+ ];
114
+ let viewChapters = [
115
+ [
116
+ "Products",
117
+ "Product"
118
+ ],
119
+ [
120
+ "ProductDemand",
121
+ "ProductDemand"
122
+ ]
123
+ ];
124
+ let match = refsOf(viewsByKey, undefined, undefined, "Product", viewChapters, order);
125
+ let match$1 = refsOf(viewsByKey, undefined, undefined, "ProductDemand", viewChapters, order);
126
+ globalThis.expect([
127
+ match[0],
128
+ match[1],
129
+ match$1[0]
130
+ ]).toEqual([
131
+ [
132
+ [
133
+ "buyer",
134
+ "Customers"
135
+ ],
136
+ [
137
+ "productIds",
138
+ "Products"
139
+ ]
140
+ ],
141
+ [],
142
+ [
143
+ [
144
+ "buyer",
145
+ "Customers"
146
+ ],
147
+ [
148
+ "productIds",
149
+ "ProductDemand"
150
+ ]
151
+ ]
152
+ ]);
153
+ });
154
+ globalThis.test("a chapter holding none of them, or several, still asks for @ref", () => {
155
+ let viewsByKey = [
156
+ [
157
+ "customerId",
158
+ ["Customers"]
159
+ ],
160
+ [
161
+ "productId",
162
+ [
163
+ "Products",
164
+ "ProductDemand"
165
+ ]
166
+ ]
167
+ ];
168
+ let match = refsOf(viewsByKey, undefined, undefined, "Order", [
169
+ [
170
+ "Products",
171
+ "Product"
172
+ ],
173
+ [
174
+ "ProductDemand",
175
+ "ProductDemand"
176
+ ]
177
+ ], order);
178
+ let match$1 = refsOf(viewsByKey, undefined, undefined, "Product", [
179
+ [
180
+ "Products",
181
+ "Product"
182
+ ],
183
+ [
184
+ "ProductDemand",
185
+ "Product"
186
+ ]
187
+ ], order);
188
+ globalThis.expect([
189
+ match[0],
190
+ match$1[0]
191
+ ]).toEqual([
192
+ [[
193
+ "buyer",
194
+ "Customers"
195
+ ]],
196
+ [[
197
+ "buyer",
198
+ "Customers"
199
+ ]]
200
+ ]);
201
+ globalThis.expect(match$1[1].some(r => r.includes("no chapter singles one out"))).toBe(true);
202
+ });
96
203
  globalThis.test("no view keyed by it is reported", () => {
97
204
  let match = refsOf([[
98
205
  "productId",
99
206
  ["AvailableProducts"]
100
- ]], undefined, undefined, order);
207
+ ]], undefined, undefined, undefined, undefined, order);
101
208
  globalThis.expect(match[0]).toEqual([[
102
209
  "productIds",
103
210
  "AvailableProducts"
@@ -108,14 +215,14 @@ globalThis.describe("a reference derived from the type", () => {
108
215
  let match = refsOf([[
109
216
  "productId",
110
217
  ["AvailableProducts"]
111
- ]], ["customerId"], undefined, order);
218
+ ]], ["customerId"], undefined, undefined, undefined, order);
112
219
  globalThis.expect(match[1]).toEqual([`info: buyer is a customerId, and no view in this plugin is keyed by it, so it references nothing. List the identity in a view, or reference another plugin's with @ref("Plugin.View").`]);
113
220
  });
114
221
  globalThis.test("one it does not declare still warns", () => {
115
222
  let match = refsOf([[
116
223
  "productId",
117
224
  ["AvailableProducts"]
118
- ]], ["orderId"], undefined, order);
225
+ ]], ["orderId"], undefined, undefined, undefined, order);
119
226
  globalThis.expect(match[1].some(r => r.startsWith("buyer is a customerId"))).toBe(true);
120
227
  });
121
228
  globalThis.test("the id a creating command mints references nothing", () => {
@@ -128,7 +235,7 @@ globalThis.describe("a reference derived from the type", () => {
128
235
  "productId",
129
236
  ["AvailableProducts"]
130
237
  ]
131
- ], undefined, "buyer", order);
238
+ ], undefined, "buyer", undefined, undefined, order);
132
239
  globalThis.expect([
133
240
  match[0],
134
241
  match[1]
@@ -144,7 +251,7 @@ globalThis.describe("a reference derived from the type", () => {
144
251
  let match = refsOf([[
145
252
  "customerId",
146
253
  ["Customers"]
147
- ]], undefined, undefined, Sury.$schema(s => ({
254
+ ]], undefined, undefined, undefined, undefined, Sury.$schema(s => ({
148
255
  customerId: s.m(Sury.string)
149
256
  })));
150
257
  globalThis.expect([
@@ -171,7 +278,7 @@ globalThis.describe("a declared @ref on a typed id", () => {
171
278
  "productId",
172
279
  ["Products"]
173
280
  ]
174
- ], undefined, undefined, referenced);
281
+ ], undefined, undefined, undefined, undefined, referenced);
175
282
  globalThis.expect(match[0]).toEqual([[
176
283
  "buyer",
177
284
  "Products"
@@ -188,7 +295,7 @@ globalThis.describe("a declared @ref on a typed id", () => {
188
295
  "Customers",
189
296
  "VipCustomers"
190
297
  ]
191
- ]], undefined, undefined, chosen);
298
+ ]], undefined, undefined, undefined, undefined, chosen);
192
299
  globalThis.expect([
193
300
  match[0],
194
301
  match[1]
@@ -207,7 +314,7 @@ globalThis.describe("a declared @ref on a typed id", () => {
207
314
  let match = refsOf([[
208
315
  "customerId",
209
316
  ["Customers"]
210
- ]], undefined, "buyer", chosen);
317
+ ]], undefined, "buyer", undefined, undefined, chosen);
211
318
  globalThis.expect(match[0]).toEqual([[
212
319
  "buyer",
213
320
  "Customers"