@reventlessdev/reventless-core 3.0.0-alpha.341 → 3.0.0-alpha.343

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 (62) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +7 -7
  3. package/src/Projection.res +32 -4
  4. package/src/Projection.res.mjs +51 -4
  5. package/src/ViewChange.res +1 -9
  6. package/src/ViewChange.res.mjs +2 -13
  7. package/src/admin/Platform_ComponentDefinitionsApi.res +29 -1
  8. package/src/admin/Platform_ComponentDefinitionsApi.res.mjs +47 -1
  9. package/src/admin/Platform_PluginStructuresApi.res +4 -3
  10. package/src/admin/Platform_PluginStructuresApi.res.mjs +5 -1
  11. package/src/components/Api/SuryToJsonSchema.res +7 -0
  12. package/src/components/Api/SuryToJsonSchema.res.mjs +18 -0
  13. package/src/components/Dcb/Dcb_Builder.res +59 -0
  14. package/src/components/Dcb/Dcb_Builder.res.mjs +48 -3
  15. package/src/components/DcbEventLog/DcbEventLog.res +2 -0
  16. package/src/components/DcbEventLog/DcbEventLog_Adapter.res +7 -0
  17. package/src/components/DcbEventLog/DcbEventLog_Builder.res +12 -3
  18. package/src/components/DcbEventLog/DcbEventLog_Builder.res.mjs +5 -3
  19. package/src/components/DcbEventLog/DcbEventLog_Operations.res +3 -0
  20. package/src/components/DcbEventLog/DcbEventLog_Operations.res.mjs +3 -1
  21. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Builder.res.mjs +2 -2
  22. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Callback.res +156 -107
  23. package/src/components/OutboundTranslationSlice/OutboundTranslationSlice_Callback.res.mjs +174 -154
  24. package/src/components/StateChangeSlice/StateChangeSlice.res +3 -0
  25. package/src/components/StateChangeSlice/StateChangeSlice_Builder.res +6 -0
  26. package/src/components/StateChangeSlice/StateChangeSlice_Builder.res.mjs +5 -4
  27. package/src/components/StateChangeSlice/StateChangeSlice_Callback.res +369 -279
  28. package/src/components/StateChangeSlice/StateChangeSlice_Callback.res.mjs +210 -166
  29. package/src/plugin/component/Plugin_Structure.res +45 -0
  30. package/src/plugin/component/Plugin_Structure.res.mjs +42 -1
  31. package/src/util/Logger.res +5 -5
  32. package/src/util/Logger.res.mjs +3 -3
  33. package/tests/admin/AdminApiSchemaDriftTest.res +23 -0
  34. package/tests/admin/AdminApiSchemaDriftTest.res.mjs +21 -1
  35. package/tests/admin/Platform_ComponentDefinitionsApiTest.res +1 -0
  36. package/tests/admin/Platform_ComponentDefinitionsApiTest.res.mjs +1 -0
  37. package/tests/admin/Platform_PluginStructuresApiTest.res +1 -0
  38. package/tests/admin/Platform_PluginStructuresApiTest.res.mjs +1 -0
  39. package/tests/api/QuantitySemanticTest.res +68 -0
  40. package/tests/api/QuantitySemanticTest.res.mjs +68 -0
  41. package/tests/commandgenerator/OwnerActingTest.res.mjs +1 -1
  42. package/tests/commandtopic/CommandOutcomeHookTest.res.mjs +1 -1
  43. package/tests/dcb/DcbFenceCountReadTest.res +213 -0
  44. package/tests/dcb/DcbFenceCountReadTest.res.mjs +358 -0
  45. package/tests/dcb/DcbPiiSliceTest.res.mjs +1 -1
  46. package/tests/dcb/DcbReadsNothingTest.res.mjs +1 -1
  47. package/tests/dcb/DcbScopeInferenceTest.res +143 -2
  48. package/tests/dcb/DcbScopeInferenceTest.res.mjs +192 -2
  49. package/tests/dcb/DcbStateChangeSliceTest.res.mjs +22 -22
  50. package/tests/dcb/DcbTagTest.res +68 -0
  51. package/tests/dcb/DcbTagTest.res.mjs +86 -10
  52. package/tests/dcb/DcbValidationTest.res.mjs +1 -1
  53. package/tests/logger/LoggerLazyTest.res.mjs +3 -3
  54. package/tests/plugin/PluginStructureAccessTest.res +1 -0
  55. package/tests/plugin/PluginStructureAccessTest.res.mjs +1 -1
  56. package/tests/plugin/PluginStructureTest.res +61 -0
  57. package/tests/plugin/PluginStructureTest.res.mjs +78 -32
  58. package/tests/plugin/StateChange/PsRateSession.res +37 -0
  59. package/tests/plugin/StateChange/PsRateSession.res.mjs +80 -0
  60. package/tests/plugin/pluginDefinitionRequiredScalars.txt +10 -0
  61. package/tests/projection/ViewChangeTest.res +32 -0
  62. package/tests/projection/ViewChangeTest.res.mjs +57 -0
@@ -195,6 +195,7 @@ let structure: pluginStructure = {
195
195
  requiredCapabilities: [capabilityDecl],
196
196
  admission: [admissionDef],
197
197
  admissionDoors: [admissionDoor],
198
+ quantities: [Reventless.Quantity.energy],
198
199
  }
199
200
 
200
201
  let panel: panelManifestEntry = {
@@ -401,6 +402,28 @@ let guards: array<guard> = [
401
402
  wireOnly: [],
402
403
  recordOnly: [],
403
404
  },
405
+ {
406
+ gqlType: "Platform_QuantityDef",
407
+ sdlTypes: componentSdl,
408
+ recordFields: schemaKeys(Reventless.Quantity.defSchema),
409
+ wireFields: jsonKeys(
410
+ Platform_ComponentDefinitionsApi.encodeQuantityDef(Reventless.Quantity.energy),
411
+ ),
412
+ wireOnly: [],
413
+ recordOnly: [],
414
+ },
415
+ {
416
+ gqlType: "Platform_QuantityUnitDef",
417
+ sdlTypes: componentSdl,
418
+ recordFields: schemaKeys(Reventless.Quantity.unitDefSchema),
419
+ wireFields: jsonKeys(
420
+ Platform_ComponentDefinitionsApi.encodeQuantityDef(Reventless.Quantity.energy)->firstOf(
421
+ "units",
422
+ ),
423
+ ),
424
+ wireOnly: [],
425
+ recordOnly: [],
426
+ },
404
427
  {
405
428
  gqlType: "Platform_RequiredCapabilityDeclaration",
406
429
  sdlTypes: structuresSdl,
@@ -3,6 +3,7 @@
3
3
  import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.js";
4
4
  import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
5
5
  import * as Plugin$Reventless from "@reventlessdev/reventless-spec/src/components/Plugin.res.mjs";
6
+ import * as Quantity$Reventless from "@reventlessdev/reventless-spec/src/semantic/Quantity.res.mjs";
6
7
  import * as Admission$Reventless from "@reventlessdev/reventless-spec/src/types/Admission.res.mjs";
7
8
  import * as SchemaType$ReventlessCore from "../../src/components/Api/SchemaType.res.mjs";
8
9
  import * as UiFragments$ReventlessCore from "../../src/admin/UiFragmentRegistry/StateView/UiFragments.res.mjs";
@@ -334,6 +335,8 @@ let structure_admission = [admissionDef];
334
335
 
335
336
  let structure_admissionDoors = [admissionDoor];
336
337
 
338
+ let structure_quantities = [Quantity$Reventless.energy];
339
+
337
340
  let structure = {
338
341
  readModels: structure_readModels,
339
342
  stateViewSlices: structure_stateViewSlices,
@@ -348,7 +351,8 @@ let structure = {
348
351
  requiredStoreDeclarations: structure_requiredStoreDeclarations,
349
352
  requiredCapabilities: structure_requiredCapabilities,
350
353
  admission: structure_admission,
351
- admissionDoors: structure_admissionDoors
354
+ admissionDoors: structure_admissionDoors,
355
+ quantities: structure_quantities
352
356
  };
353
357
 
354
358
  let panel_positions = ["platform-summary"];
@@ -528,6 +532,22 @@ let guards = [
528
532
  wireOnly: [],
529
533
  recordOnly: []
530
534
  },
535
+ {
536
+ gqlType: "Platform_QuantityDef",
537
+ sdlTypes: Platform_ComponentDefinitionsApi$ReventlessCore.sdlTypes,
538
+ recordFields: schemaKeys(Quantity$Reventless.defSchema),
539
+ wireFields: jsonKeys(Platform_ComponentDefinitionsApi$ReventlessCore.encodeQuantityDef(Quantity$Reventless.energy)),
540
+ wireOnly: [],
541
+ recordOnly: []
542
+ },
543
+ {
544
+ gqlType: "Platform_QuantityUnitDef",
545
+ sdlTypes: Platform_ComponentDefinitionsApi$ReventlessCore.sdlTypes,
546
+ recordFields: schemaKeys(Quantity$Reventless.unitDefSchema),
547
+ wireFields: jsonKeys(firstOf(Platform_ComponentDefinitionsApi$ReventlessCore.encodeQuantityDef(Quantity$Reventless.energy), "units")),
548
+ wireOnly: [],
549
+ recordOnly: []
550
+ },
531
551
  {
532
552
  gqlType: "Platform_RequiredCapabilityDeclaration",
533
553
  sdlTypes: Platform_PluginStructuresApi$ReventlessCore.sdlTypes,
@@ -95,6 +95,7 @@ describe("encodePluginStructureEntry", () => {
95
95
  "internalQueryables",
96
96
  "outboundTranslationSlices",
97
97
  "pluginId",
98
+ "quantities",
98
99
  "readModels",
99
100
  "stateChangeSlices",
100
101
  "stateViewSlices",
@@ -150,6 +150,7 @@ globalThis.describe("encodePluginStructureEntry", () => {
150
150
  "internalQueryables",
151
151
  "outboundTranslationSlices",
152
152
  "pluginId",
153
+ "quantities",
153
154
  "readModels",
154
155
  "stateChangeSlices",
155
156
  "stateViewSlices"
@@ -100,6 +100,7 @@ describe("Platform_PluginStructures entry", () => {
100
100
  "inboundTranslationSlices",
101
101
  "outboundTranslationSlices",
102
102
  "pluginId",
103
+ "quantities",
103
104
  "readModels",
104
105
  "requiredCapabilities",
105
106
  "requiredStoreDeclarations",
@@ -151,6 +151,7 @@ globalThis.describe("Platform_PluginStructures entry", () => {
151
151
  "inboundTranslationSlices",
152
152
  "outboundTranslationSlices",
153
153
  "pluginId",
154
+ "quantities",
154
155
  "readModels",
155
156
  "requiredCapabilities",
156
157
  "requiredStoreDeclarations",
@@ -0,0 +1,68 @@
1
+ open JestGlobals
2
+
3
+ // A field holding a quantity, or money per a quantity's unit, says which in its
4
+ // JSON schema: the semantic, and the quantity and unit in their own key.
5
+
6
+ let getProperty = (schema: JSON.t, key: string): option<JSON.t> =>
7
+ schema->JSON.Decode.object->Option.flatMap(o => o->Dict.get(key))
8
+
9
+ let fieldOf = (json, name) =>
10
+ getProperty(json, "properties")->Option.flatMap(p => getProperty(p, name))
11
+
12
+ let unitTarget = (~quantity, ~unit) => Some(
13
+ JSON.Encode.object(
14
+ Dict.fromArray([
15
+ ("quantity", JSON.Encode.string(quantity)),
16
+ ("unit", JSON.Encode.string(unit)),
17
+ ]),
18
+ ),
19
+ )
20
+
21
+ let schema = S.schema(s =>
22
+ {
23
+ "sessionId": s.matches(S.string),
24
+ "delivered": s.matches(Reventless.Energy.kilowattHour),
25
+ "price": s.matches(Reventless.PricePer.unit(Reventless.Energy.kilowattHour)),
26
+ "maxPower": s.matches(S.option(Reventless.Power.kilowatt)),
27
+ }
28
+ )->S.castToUnknown
29
+
30
+ let json = SuryToJsonSchema.deriveObjectSchema(schema)
31
+
32
+ describe("a quantity in a view's JSON schema", () => {
33
+ testSync("a quantity field carries the semantic and its unit", () => {
34
+ let field = fieldOf(json, "delivered")
35
+ expect(field->Option.flatMap(getProperty(_, "x-reventless-semantic")))->toEqual(
36
+ Some(JSON.Encode.string("quantity")),
37
+ )
38
+ expect(field->Option.flatMap(getProperty(_, "x-reventless-semantic-unit")))->toEqual(
39
+ unitTarget(~quantity="energy", ~unit="kWh"),
40
+ )
41
+ // Still a number: typing a field changes nothing stored.
42
+ expect(field->Option.flatMap(getProperty(_, "type")))->toEqual(
43
+ Some(JSON.Encode.string("number")),
44
+ )
45
+ })
46
+
47
+ testSync("a price per unit carries its semantic and the unit it is per", () => {
48
+ let field = fieldOf(json, "price")
49
+ expect(field->Option.flatMap(getProperty(_, "x-reventless-semantic")))->toEqual(
50
+ Some(JSON.Encode.string("pricePerUnit")),
51
+ )
52
+ expect(field->Option.flatMap(getProperty(_, "x-reventless-semantic-unit")))->toEqual(
53
+ unitTarget(~quantity="energy", ~unit="kWh"),
54
+ )
55
+ })
56
+
57
+ testSync("an optional quantity keeps its unit", () =>
58
+ expect(
59
+ fieldOf(json, "maxPower")->Option.flatMap(getProperty(_, "x-reventless-semantic-unit")),
60
+ )->toEqual(unitTarget(~quantity="power", ~unit="kW"))
61
+ )
62
+
63
+ testSync("a field with no quantity has no unit key", () =>
64
+ expect(
65
+ fieldOf(json, "sessionId")->Option.flatMap(getProperty(_, "x-reventless-semantic-unit")),
66
+ )->toEqual(None)
67
+ )
68
+ })
@@ -0,0 +1,68 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Sury from "sury";
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";
6
+ import * as Power$Reventless from "@reventlessdev/reventless-spec/src/semantic/Power.res.mjs";
7
+ import * as Energy$Reventless from "@reventlessdev/reventless-spec/src/semantic/Energy.res.mjs";
8
+ import * as PricePer$Reventless from "@reventlessdev/reventless-spec/src/semantic/PricePer.res.mjs";
9
+ import * as SuryToJsonSchema$ReventlessCore from "../../src/components/Api/SuryToJsonSchema.res.mjs";
10
+
11
+ function getProperty(schema, key) {
12
+ return Stdlib_Option.flatMap(Stdlib_JSON.Decode.object(schema), o => o[key]);
13
+ }
14
+
15
+ function fieldOf(json, name) {
16
+ return Stdlib_Option.flatMap(getProperty(json, "properties"), p => getProperty(p, name));
17
+ }
18
+
19
+ function unitTarget(quantity, unit) {
20
+ return Object.fromEntries([
21
+ [
22
+ "quantity",
23
+ quantity
24
+ ],
25
+ [
26
+ "unit",
27
+ unit
28
+ ]
29
+ ]);
30
+ }
31
+
32
+ let schema = Sury.$schema(s => ({
33
+ sessionId: s.m(Sury.string),
34
+ delivered: s.m(Energy$Reventless.kilowattHour),
35
+ price: s.m(PricePer$Reventless.unit(Energy$Reventless.kilowattHour)),
36
+ maxPower: s.m(Sury.$option(Power$Reventless.kilowatt))
37
+ }));
38
+
39
+ let json = SuryToJsonSchema$ReventlessCore.deriveObjectSchema(undefined, undefined, schema);
40
+
41
+ globalThis.describe("a quantity in a view's JSON schema", () => {
42
+ globalThis.test("a quantity field carries the semantic and its unit", () => {
43
+ let field = fieldOf(json, "delivered");
44
+ globalThis.expect(Stdlib_Option.flatMap(field, __x => getProperty(__x, "x-reventless-semantic"))).toEqual("quantity");
45
+ globalThis.expect(Stdlib_Option.flatMap(field, __x => getProperty(__x, "x-reventless-semantic-unit"))).toEqual(unitTarget("energy", "kWh"));
46
+ globalThis.expect(Stdlib_Option.flatMap(field, __x => getProperty(__x, "type"))).toEqual("number");
47
+ });
48
+ globalThis.test("a price per unit carries its semantic and the unit it is per", () => {
49
+ let field = fieldOf(json, "price");
50
+ globalThis.expect(Stdlib_Option.flatMap(field, __x => getProperty(__x, "x-reventless-semantic"))).toEqual("pricePerUnit");
51
+ globalThis.expect(Stdlib_Option.flatMap(field, __x => getProperty(__x, "x-reventless-semantic-unit"))).toEqual(unitTarget("energy", "kWh"));
52
+ });
53
+ globalThis.test("an optional quantity keeps its unit", () => {
54
+ globalThis.expect(Stdlib_Option.flatMap(fieldOf(json, "maxPower"), __x => getProperty(__x, "x-reventless-semantic-unit"))).toEqual(unitTarget("power", "kW"));
55
+ });
56
+ globalThis.test("a field with no quantity has no unit key", () => {
57
+ globalThis.expect(Stdlib_Option.flatMap(fieldOf(json, "sessionId"), __x => getProperty(__x, "x-reventless-semantic-unit"))).toEqual(undefined);
58
+ });
59
+ });
60
+
61
+ export {
62
+ getProperty,
63
+ fieldOf,
64
+ unitTarget,
65
+ schema,
66
+ json,
67
+ }
68
+ /* schema Not a pure module */
@@ -597,7 +597,7 @@ async function deliverDcb(crossPartitionTagKeysOpt, partitionTagOpt, hop, cmd) {
597
597
  let crossPartitionTagKeys = crossPartitionTagKeysOpt !== undefined ? crossPartitionTagKeysOpt : [];
598
598
  let partitionTag = partitionTagOpt !== undefined ? partitionTagOpt : orderPartition;
599
599
  let command$p = Message$ReventlessCore.decodeCommand$p(cross(hop, cmd), Id$Reventless.$$String.schema, commandSchema);
600
- await Effect.runPromise(OrderHandler.handleCommands(undefined, crossPartitionTagKeys, partitionTag, dcbEventLog, Stream.fromIterable([{
600
+ await Effect.runPromise(OrderHandler.handleCommands(undefined, crossPartitionTagKeys, undefined, partitionTag, dcbEventLog, Stream.fromIterable([{
601
601
  command: command$p,
602
602
  reference: cmd.meta.msgId
603
603
  }])));
@@ -82,7 +82,7 @@ function sliceItem(reference, command) {
82
82
  }
83
83
 
84
84
  function runSlice(reference, command) {
85
- return Effect.runPromise(SliceHandler.handleCommands(undefined, undefined, undefined, dcbEventLog, Stream.fromIterable([sliceItem(reference, command)])));
85
+ return Effect.runPromise(SliceHandler.handleCommands(undefined, undefined, undefined, undefined, dcbEventLog, Stream.fromIterable([sliceItem(reference, command)])));
86
86
  }
87
87
 
88
88
  function runAgg(aggIdOpt, reference, command) {
@@ -0,0 +1,213 @@
1
+ // A slice that reads a key across partitions reads it through an eventually
2
+ // consistent index. Before it decides, it checks that it read every event the
3
+ // key's fence counted, and reads again while the index is behind.
4
+
5
+ open JestGlobals
6
+
7
+ let mock = DcbFixtures.makeMockStorage()
8
+
9
+ module LogOps = DcbEventLog_Operations.Make({
10
+ let name = "FenceCountLog"
11
+ let serviceName = "FenceCountLog"
12
+ let storage = mock.operations
13
+ let publishJson = mock.mockPublishJson
14
+ })
15
+
16
+ // An index that misses every stored event for its first `staleReads` reads.
17
+ let staleReads = ref(0)
18
+ let reads = ref(0)
19
+ let appends = ref(0)
20
+ let conditions: ref<array<option<Reventless.DcbTag.appendCondition>>> = ref([])
21
+ let queries: ref<array<Reventless.DcbTag.query>> = ref([])
22
+ let counted = ref(true)
23
+ let student: Reventless.DcbTag.tag = {key: "studentId", value: "S1"}
24
+
25
+ let eventLog: DcbEventLog.operations = {
26
+ read: LogOps.read,
27
+ readStream: (~query, ~after=?, ~strongConsistency=?) => {
28
+ reads := reads.contents + 1
29
+ queries := queries.contents->Array.concat([query])
30
+ let stale = reads.contents <= staleReads.contents
31
+ LogOps.readStream(~query, ~after?, ~strongConsistency?)->Stream.filter(_ => !stale)
32
+ },
33
+ append: (events, ~condition=?) => {
34
+ appends := appends.contents + 1
35
+ conditions := conditions.contents->Array.concat([condition])
36
+ LogOps.append(events, ~condition?)
37
+ },
38
+ appendStream: LogOps.appendStream,
39
+ readFences: async tags =>
40
+ tags->Array.map((tag): Reventless.DcbFenceCount.fence => {
41
+ tag,
42
+ counted: counted.contents,
43
+ counts: Dict.fromArray([
44
+ (
45
+ "StudentSubscribed",
46
+ mock.getEvents()
47
+ ->Array.filter(e => e.tags->Array.some(t => t.key == tag.key && t.value == tag.value))
48
+ ->Array.length,
49
+ ),
50
+ ]),
51
+ }),
52
+ }
53
+
54
+ module SubscribeSpec = {
55
+ let name = "Subscribe"
56
+ module Id = Reventless.Id.String
57
+ let moduleUrl: string = %raw(`import.meta.url`)
58
+
59
+ @schema
60
+ type event =
61
+ | StudentSubscribed({
62
+ courseId: @s.matches(Reventless.DcbTag.string) string,
63
+ studentId: @s.matches(Reventless.DcbTag.string) string,
64
+ })
65
+
66
+ @schema
67
+ type consumedEvent =
68
+ | StudentSubscribed({
69
+ courseId: @s.matches(Reventless.DcbTag.string) string,
70
+ studentId: @s.matches(Reventless.DcbTag.string) string,
71
+ })
72
+
73
+ @schema
74
+ type command =
75
+ | Subscribe({
76
+ courseId: @s.matches(Reventless.DcbTag.string) string,
77
+ studentId: @s.matches(Reventless.DcbTag.string) string,
78
+ })
79
+
80
+ @schema
81
+ type error = AlreadySubscribedElsewhere
82
+ }
83
+
84
+ // A student takes one course at a time.
85
+ module SubscribeDecision = {
86
+ type state = bool
87
+ let initialState = false
88
+ let moduleUrl = SubscribeSpec.moduleUrl
89
+ let evolve = (_state, _event: SubscribeSpec.consumedEvent) => true
90
+ let decide = (subscribed, command: SubscribeSpec.command): result<
91
+ array<SubscribeSpec.event>,
92
+ SubscribeSpec.error,
93
+ > =>
94
+ switch command {
95
+ | Subscribe(_) if subscribed => Error(AlreadySubscribedElsewhere)
96
+ | Subscribe({courseId, studentId}) => Ok([StudentSubscribed({courseId, studentId})])
97
+ }
98
+ }
99
+
100
+ module SubscribeHandler = StateChangeSlice_Callback.Make(SubscribeSpec, SubscribeDecision)
101
+
102
+ let subscribe = (reference, courseId) =>
103
+ SubscribeHandler.handleCommands(
104
+ ~crossPartitionTagKeys=["studentId"],
105
+ ~partitionTag=Reventless.DcbTag.Simple({key: "courseId"}),
106
+ eventLog,
107
+ Stream.fromIterable([
108
+ {
109
+ ReventlessInfra.CommandTopic.command: {
110
+ Message.id: Reventless.Id.String.makeFromString("cmd-" ++ reference),
111
+ meta: DcbFixtures.testMeta,
112
+ command: SubscribeSpec.Subscribe({courseId, studentId: student.value}),
113
+ },
114
+ reference,
115
+ },
116
+ ]),
117
+ )->Effect.runPromise
118
+
119
+ // The student is already in course C1; the index has not shown it yet.
120
+ let givenSubscribedThenStale = async n => {
121
+ let _ = await subscribe("first", "C1")
122
+ SubscribeHandler.resetCache()
123
+ reads := 0
124
+ appends := 0
125
+ staleReads := n
126
+ }
127
+
128
+ let _ = beforeEach(() => {
129
+ mock.reset()
130
+ SubscribeHandler.resetCache()
131
+ reads := 0
132
+ appends := 0
133
+ conditions := []
134
+ queries := []
135
+ staleReads := 0
136
+ counted := true
137
+ })
138
+
139
+ describe("a read of a counted cross-partition fence", () => {
140
+ testPromise("reads again until the index shows what was counted", async () => {
141
+ await givenSubscribedThenStale(1)
142
+ let result = await subscribe("second", "C2")
143
+ // The second read saw the first subscription, so nothing was appended.
144
+ expect((result, mock.getEvents()->Array.length, reads.contents, appends.contents))->toEqual((
145
+ [Ok("second")],
146
+ 1,
147
+ 2,
148
+ 0,
149
+ ))
150
+ })
151
+
152
+ testPromise("answers a conflict when the index stays behind", async () => {
153
+ await givenSubscribedThenStale(10)
154
+ let result = await subscribe("second", "C2")
155
+ expect((result, mock.getEvents()->Array.length, reads.contents, appends.contents))->toEqual((
156
+ [Error("second")],
157
+ 1,
158
+ 4,
159
+ 0,
160
+ ))
161
+ })
162
+
163
+ testPromise("a fence not yet counted is not checked", async () => {
164
+ counted := false
165
+ await givenSubscribedThenStale(1)
166
+ let _ = await subscribe("second", "C2")
167
+ // Decided on the stale read, as before counting existed: only the append's
168
+ // condition catches it, and the retry reads again.
169
+ expect((mock.getEvents()->Array.length, reads.contents, appends.contents))->toEqual((1, 2, 1))
170
+ })
171
+
172
+ testPromise("the append carries the count it read", async () => {
173
+ let _ = await subscribe("first", "C1")
174
+ expect(conditions.contents->Array.map(c => c->Option.flatMap(c => c.fenceCounts)))->toEqual([
175
+ Some([{Reventless.DcbTag.tag: student, eventType: "StudentSubscribed", count: 0}]),
176
+ ])
177
+ })
178
+ })
179
+
180
+ describe("a slice that reads a pair", () => {
181
+ testPromise("reads the pair's types by its key from the index", async () => {
182
+ let _ = await SubscribeHandler.handleCommands(
183
+ ~crossPartitionPairs=[
184
+ {reader: "Subscribe", eventType: "StudentSubscribed", key: "courseId", writers: ["Enrol"]},
185
+ {reader: "Other", eventType: "StudentSubscribed", key: "studentId", writers: ["Enrol"]},
186
+ ],
187
+ ~partitionTag=Reventless.DcbTag.Simple({key: "courseId"}),
188
+ eventLog,
189
+ Stream.fromIterable([
190
+ {
191
+ ReventlessInfra.CommandTopic.command: {
192
+ Message.id: Reventless.Id.String.makeFromString("cmd-pair"),
193
+ meta: DcbFixtures.testMeta,
194
+ command: SubscribeSpec.Subscribe({courseId: "C9", studentId: student.value}),
195
+ },
196
+ reference: "pair",
197
+ },
198
+ ]),
199
+ )->Effect.runPromise
200
+ let across =
201
+ queries.contents
202
+ ->Array.flat
203
+ ->Array.filter(qi => qi.crossPartition == Some(true))
204
+ ->Array.map(qi => (qi.tags, qi.eventTypes))
205
+ expect(across->Array.length > 0)->toBe(true)
206
+ expect(
207
+ across->Array.every(
208
+ ((tags, types)) =>
209
+ tags == Some([{key: "courseId", value: "C9"}]) && types == Some(["StudentSubscribed"]),
210
+ ),
211
+ )->toBe(true)
212
+ })
213
+ })