@cratis/chronicle 6.57.0 → 6.58.0

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 (234) hide show
  1. package/EventStore.ts +2 -2
  2. package/dist/EventStore.js +2 -2
  3. package/dist/EventStore.js.map +1 -1
  4. package/dist/observation/batches/BatchContext.d.ts +43 -0
  5. package/dist/observation/batches/BatchContext.d.ts.map +1 -0
  6. package/dist/observation/batches/BatchContext.js +60 -0
  7. package/dist/observation/batches/BatchContext.js.map +1 -0
  8. package/dist/observation/batches/BatchContextObserver.d.ts +14 -0
  9. package/dist/observation/batches/BatchContextObserver.d.ts.map +1 -0
  10. package/dist/observation/batches/BatchContextObserver.js +4 -0
  11. package/dist/observation/batches/BatchContextObserver.js.map +1 -0
  12. package/dist/observation/batches/BatchContextValues.d.ts +13 -0
  13. package/dist/observation/batches/BatchContextValues.d.ts.map +1 -0
  14. package/dist/observation/batches/BatchContextValues.js +4 -0
  15. package/dist/observation/batches/BatchContextValues.js.map +1 -0
  16. package/dist/observation/batches/BatchMethod.d.ts +9 -0
  17. package/dist/observation/batches/BatchMethod.d.ts.map +1 -0
  18. package/dist/observation/batches/BatchMethod.js +4 -0
  19. package/dist/observation/batches/BatchMethod.js.map +1 -0
  20. package/dist/observation/batches/BatchMethodReturnedAValue.d.ts +12 -0
  21. package/dist/observation/batches/BatchMethodReturnedAValue.d.ts.map +1 -0
  22. package/dist/observation/batches/BatchMethodReturnedAValue.js +20 -0
  23. package/dist/observation/batches/BatchMethodReturnedAValue.js.map +1 -0
  24. package/dist/observation/batches/BatchMethods.d.ts +31 -0
  25. package/dist/observation/batches/BatchMethods.d.ts.map +1 -0
  26. package/dist/observation/batches/BatchMethods.js +81 -0
  27. package/dist/observation/batches/BatchMethods.js.map +1 -0
  28. package/dist/observation/batches/BatchOutcome.d.ts +15 -0
  29. package/dist/observation/batches/BatchOutcome.d.ts.map +1 -0
  30. package/dist/observation/batches/BatchOutcome.js +4 -0
  31. package/dist/observation/batches/BatchOutcome.js.map +1 -0
  32. package/dist/observation/batches/BatchOutcomeKind.d.ts +8 -0
  33. package/dist/observation/batches/BatchOutcomeKind.d.ts.map +1 -0
  34. package/dist/observation/batches/BatchOutcomeKind.js +11 -0
  35. package/dist/observation/batches/BatchOutcomeKind.js.map +1 -0
  36. package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts +13 -0
  37. package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts.map +1 -0
  38. package/dist/observation/batches/DeferralNotSupportedByKernel.js +19 -0
  39. package/dist/observation/batches/DeferralNotSupportedByKernel.js.map +1 -0
  40. package/dist/observation/batches/DeliveredPartition.d.ts +11 -0
  41. package/dist/observation/batches/DeliveredPartition.d.ts.map +1 -0
  42. package/dist/observation/batches/DeliveredPartition.js +4 -0
  43. package/dist/observation/batches/DeliveredPartition.js.map +1 -0
  44. package/dist/observation/batches/EventAndContext.d.ts +28 -0
  45. package/dist/observation/batches/EventAndContext.d.ts.map +1 -0
  46. package/dist/observation/batches/EventAndContext.js +35 -0
  47. package/dist/observation/batches/EventAndContext.js.map +1 -0
  48. package/dist/observation/batches/EventBatch.d.ts +52 -0
  49. package/dist/observation/batches/EventBatch.d.ts.map +1 -0
  50. package/dist/observation/batches/EventBatch.js +92 -0
  51. package/dist/observation/batches/EventBatch.js.map +1 -0
  52. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts +14 -0
  53. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts.map +1 -0
  54. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js +23 -0
  55. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js.map +1 -0
  56. package/dist/observation/batches/InvalidBatchMethod.d.ts +13 -0
  57. package/dist/observation/batches/InvalidBatchMethod.d.ts.map +1 -0
  58. package/dist/observation/batches/InvalidBatchMethod.js +20 -0
  59. package/dist/observation/batches/InvalidBatchMethod.js.map +1 -0
  60. package/dist/observation/batches/ObservationOrigin.d.ts +21 -0
  61. package/dist/observation/batches/ObservationOrigin.d.ts.map +1 -0
  62. package/dist/observation/batches/ObservationOrigin.js +32 -0
  63. package/dist/observation/batches/ObservationOrigin.js.map +1 -0
  64. package/dist/observation/batches/ObservedEventType.d.ts +11 -0
  65. package/dist/observation/batches/ObservedEventType.d.ts.map +1 -0
  66. package/dist/observation/batches/ObservedEventType.js +4 -0
  67. package/dist/observation/batches/ObservedEventType.js.map +1 -0
  68. package/dist/observation/batches/PageMessages.d.ts +22 -0
  69. package/dist/observation/batches/PageMessages.d.ts.map +1 -0
  70. package/dist/observation/batches/PageMessages.js +32 -0
  71. package/dist/observation/batches/PageMessages.js.map +1 -0
  72. package/dist/observation/batches/PartitionFailedInBatch.d.ts +10 -0
  73. package/dist/observation/batches/PartitionFailedInBatch.d.ts.map +1 -0
  74. package/dist/observation/batches/PartitionFailedInBatch.js +16 -0
  75. package/dist/observation/batches/PartitionFailedInBatch.js.map +1 -0
  76. package/dist/observation/batches/PartitionNotInBatch.d.ts +10 -0
  77. package/dist/observation/batches/PartitionNotInBatch.d.ts.map +1 -0
  78. package/dist/observation/batches/PartitionNotInBatch.js +16 -0
  79. package/dist/observation/batches/PartitionNotInBatch.js.map +1 -0
  80. package/dist/observation/batches/PartitionOutcome.d.ts +19 -0
  81. package/dist/observation/batches/PartitionOutcome.d.ts.map +1 -0
  82. package/dist/observation/batches/PartitionOutcome.js +4 -0
  83. package/dist/observation/batches/PartitionOutcome.js.map +1 -0
  84. package/dist/observation/batches/PartitionProblem.d.ts +17 -0
  85. package/dist/observation/batches/PartitionProblem.d.ts.map +1 -0
  86. package/dist/observation/batches/PartitionProblem.js +4 -0
  87. package/dist/observation/batches/PartitionProblem.js.map +1 -0
  88. package/dist/observation/batches/PartitionSettlement.d.ts +29 -0
  89. package/dist/observation/batches/PartitionSettlement.d.ts.map +1 -0
  90. package/dist/observation/batches/PartitionSettlement.js +64 -0
  91. package/dist/observation/batches/PartitionSettlement.js.map +1 -0
  92. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts +12 -0
  93. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts.map +1 -0
  94. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js +20 -0
  95. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js.map +1 -0
  96. package/dist/observation/batches/batchSize.d.ts +42 -0
  97. package/dist/observation/batches/batchSize.d.ts.map +1 -0
  98. package/dist/observation/batches/batchSize.js +55 -0
  99. package/dist/observation/batches/batchSize.js.map +1 -0
  100. package/dist/observation/batches/createBatchContext.d.ts +13 -0
  101. package/dist/observation/batches/createBatchContext.d.ts.map +1 -0
  102. package/dist/observation/batches/createBatchContext.js +27 -0
  103. package/dist/observation/batches/createBatchContext.js.map +1 -0
  104. package/dist/observation/batches/observes.d.ts +39 -0
  105. package/dist/observation/batches/observes.d.ts.map +1 -0
  106. package/dist/observation/batches/observes.js +63 -0
  107. package/dist/observation/batches/observes.js.map +1 -0
  108. package/dist/observation/batches/runConcurrently.d.ts +9 -0
  109. package/dist/observation/batches/runConcurrently.d.ts.map +1 -0
  110. package/dist/observation/batches/runConcurrently.js +22 -0
  111. package/dist/observation/batches/runConcurrently.js.map +1 -0
  112. package/dist/observation/createHandlerInstanceValidator.d.ts +1 -1
  113. package/dist/observation/createHandlerInstanceValidator.d.ts.map +1 -1
  114. package/dist/observation/createHandlerInstanceValidator.js +5 -7
  115. package/dist/observation/createHandlerInstanceValidator.js.map +1 -1
  116. package/dist/observation/getInstanceMethods.d.ts +3 -1
  117. package/dist/observation/getInstanceMethods.d.ts.map +1 -1
  118. package/dist/observation/getInstanceMethods.js +13 -4
  119. package/dist/observation/getInstanceMethods.js.map +1 -1
  120. package/dist/observation/index.d.ts +14 -0
  121. package/dist/observation/index.d.ts.map +1 -1
  122. package/dist/observation/index.js +13 -0
  123. package/dist/observation/index.js.map +1 -1
  124. package/dist/reactors/ReactorDispatcher.d.ts +15 -0
  125. package/dist/reactors/ReactorDispatcher.d.ts.map +1 -1
  126. package/dist/reactors/ReactorDispatcher.js +25 -2
  127. package/dist/reactors/ReactorDispatcher.js.map +1 -1
  128. package/dist/reactors/ReactorObservationTarget.d.ts +45 -0
  129. package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -0
  130. package/dist/reactors/ReactorObservationTarget.js +4 -0
  131. package/dist/reactors/ReactorObservationTarget.js.map +1 -0
  132. package/dist/reactors/ReactorPageDispatcher.d.ts +33 -0
  133. package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -0
  134. package/dist/reactors/ReactorPageDispatcher.js +293 -0
  135. package/dist/reactors/ReactorPageDispatcher.js.map +1 -0
  136. package/dist/reactors/Reactors.d.ts.map +1 -1
  137. package/dist/reactors/Reactors.js +21 -149
  138. package/dist/reactors/Reactors.js.map +1 -1
  139. package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts +14 -0
  140. package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts.map +1 -0
  141. package/dist/reactors/for_Reactors/given/observe_reactor_messages.js +61 -0
  142. package/dist/reactors/for_Reactors/given/observe_reactor_messages.js.map +1 -0
  143. package/dist/reactors/index.d.ts +2 -0
  144. package/dist/reactors/index.d.ts.map +1 -1
  145. package/dist/reactors/index.js +1 -0
  146. package/dist/reactors/index.js.map +1 -1
  147. package/dist/reducers/ReducerEventDispatcher.d.ts +26 -1
  148. package/dist/reducers/ReducerEventDispatcher.d.ts.map +1 -1
  149. package/dist/reducers/ReducerEventDispatcher.js +35 -3
  150. package/dist/reducers/ReducerEventDispatcher.js.map +1 -1
  151. package/dist/reducers/Reducers.d.ts +2 -0
  152. package/dist/reducers/Reducers.d.ts.map +1 -1
  153. package/dist/reducers/Reducers.js +94 -22
  154. package/dist/reducers/Reducers.js.map +1 -1
  155. package/dist/reducers/ReductionOutcome.d.ts +27 -3
  156. package/dist/reducers/ReductionOutcome.d.ts.map +1 -1
  157. package/dist/reducers/ReductionOutcome.js +51 -7
  158. package/dist/reducers/ReductionOutcome.js.map +1 -1
  159. package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts +19 -0
  160. package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts.map +1 -0
  161. package/dist/reducers/for_Reducers/given/observe_reducer_messages.js +61 -0
  162. package/dist/reducers/for_Reducers/given/observe_reducer_messages.js.map +1 -0
  163. package/dist/reducers/index.d.ts +2 -0
  164. package/dist/reducers/index.d.ts.map +1 -1
  165. package/dist/reducers/index.js +1 -0
  166. package/dist/reducers/index.js.map +1 -1
  167. package/dist/testing/ReactorScenario.d.ts.map +1 -1
  168. package/dist/testing/ReactorScenario.js +4 -1
  169. package/dist/testing/ReactorScenario.js.map +1 -1
  170. package/dist/testing/ReducerReadModelProcessor.d.ts +1 -0
  171. package/dist/testing/ReducerReadModelProcessor.d.ts.map +1 -1
  172. package/dist/testing/ReducerReadModelProcessor.js +45 -0
  173. package/dist/testing/ReducerReadModelProcessor.js.map +1 -1
  174. package/dist/tsconfig.tsbuildinfo +1 -1
  175. package/observation/batches/BatchContext.ts +75 -0
  176. package/observation/batches/BatchContextObserver.ts +16 -0
  177. package/observation/batches/BatchContextValues.ts +16 -0
  178. package/observation/batches/BatchMethod.ts +13 -0
  179. package/observation/batches/BatchMethodReturnedAValue.ts +16 -0
  180. package/observation/batches/BatchMethods.ts +90 -0
  181. package/observation/batches/BatchOutcome.ts +22 -0
  182. package/observation/batches/BatchOutcomeKind.ts +11 -0
  183. package/observation/batches/DeferralNotSupportedByKernel.ts +17 -0
  184. package/observation/batches/DeliveredPartition.ts +16 -0
  185. package/observation/batches/EventAndContext.ts +37 -0
  186. package/observation/batches/EventBatch.ts +105 -0
  187. package/observation/batches/EventTypeObservedByMoreThanOneMethod.ts +17 -0
  188. package/observation/batches/InvalidBatchMethod.ts +16 -0
  189. package/observation/batches/ObservationOrigin.ts +37 -0
  190. package/observation/batches/ObservedEventType.ts +16 -0
  191. package/observation/batches/PageMessages.ts +37 -0
  192. package/observation/batches/PartitionFailedInBatch.ts +14 -0
  193. package/observation/batches/PartitionNotInBatch.ts +14 -0
  194. package/observation/batches/PartitionOutcome.ts +22 -0
  195. package/observation/batches/PartitionProblem.ts +25 -0
  196. package/observation/batches/PartitionSettlement.ts +70 -0
  197. package/observation/batches/ReducerMixesBatchAndPerEventMethods.ts +16 -0
  198. package/observation/batches/batchSize.ts +79 -0
  199. package/observation/batches/createBatchContext.ts +32 -0
  200. package/observation/batches/for_BatchMethods/when_discovering_batch_methods.spec.ts +155 -0
  201. package/observation/batches/for_EventBatch/when_reporting_outcomes.spec.ts +66 -0
  202. package/observation/batches/for_PartitionSettlement/when_settling_a_partition.spec.ts +31 -0
  203. package/observation/batches/for_batchSize/when_declaring_bounds.spec.ts +23 -0
  204. package/observation/batches/for_observes/when_decorating_methods.legacy.spec.ts +28 -0
  205. package/observation/batches/for_observes/when_decorating_methods.spec.ts +33 -0
  206. package/observation/batches/for_runConcurrently/when_running_items.spec.ts +22 -0
  207. package/observation/batches/observes.ts +68 -0
  208. package/observation/batches/runConcurrently.ts +23 -0
  209. package/observation/createHandlerInstanceValidator.ts +5 -7
  210. package/observation/getInstanceMethods.ts +13 -4
  211. package/observation/index.ts +14 -0
  212. package/package.json +1 -1
  213. package/reactors/ReactorDispatcher.ts +27 -2
  214. package/reactors/ReactorObservationTarget.ts +48 -0
  215. package/reactors/ReactorPageDispatcher.ts +321 -0
  216. package/reactors/Reactors.ts +22 -164
  217. package/reactors/for_Reactors/given/observe_reactor_messages.ts +72 -0
  218. package/reactors/for_Reactors/when_delivering_pages/as_a_legacy_single_partition.spec.ts +51 -0
  219. package/reactors/for_Reactors/when_delivering_pages/returning_a_value_from_a_batch_method.spec.ts +34 -0
  220. package/reactors/for_Reactors/when_delivering_pages/with_batch_and_per_event_methods.spec.ts +81 -0
  221. package/reactors/for_Reactors/when_delivering_pages/with_batch_outcomes.spec.ts +86 -0
  222. package/reactors/for_Reactors/when_delivering_pages/with_per_event_handlers.spec.ts +52 -0
  223. package/reactors/index.ts +2 -0
  224. package/reducers/ReducerEventDispatcher.ts +44 -3
  225. package/reducers/Reducers.ts +109 -25
  226. package/reducers/ReductionOutcome.ts +55 -8
  227. package/reducers/for_Reducers/given/observe_reducer_messages.ts +77 -0
  228. package/reducers/for_Reducers/when_delivering_pages/to_a_batch_reducer.spec.ts +111 -0
  229. package/reducers/for_Reducers/when_delivering_pages/to_a_per_event_reducer.spec.ts +53 -0
  230. package/reducers/index.ts +2 -0
  231. package/testing/ReactorScenario.ts +5 -1
  232. package/testing/ReducerReadModelProcessor.ts +44 -0
  233. package/testing/for_ReactorScenario/when_the_reactor_has_a_batch_method.spec.ts +26 -0
  234. package/testing/for_ReadModelScenario/when_reducing_with_a_batch_method/with_events_for_two_event_sources.spec.ts +43 -0
@@ -0,0 +1,90 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { Constructor } from '@cratis/fundamentals';
5
+ import { getEventTypeMetadata } from '../../events/eventTypeDecorator.js';
6
+ import { getHandledEventType } from '../../events/handles.js';
7
+ import { isOnceOnly } from '../../reactors/onceOnly.js';
8
+ import { getReplayEventType } from '../../reactors/replay.js';
9
+ import { getInstanceMethods } from '../getInstanceMethods.js';
10
+ import { EventTypeObservedByMoreThanOneMethod } from './EventTypeObservedByMoreThanOneMethod.js';
11
+ import { InvalidBatchMethod } from './InvalidBatchMethod.js';
12
+ import { getObservedEventTypes } from './observes.js';
13
+ import type { BatchMethod } from './BatchMethod.js';
14
+ import type { ObservedEventType } from './ObservedEventType.js';
15
+
16
+ /**
17
+ * Discovers the batch methods of an observer: the methods decorated with `@observes`.
18
+ * @param observerType - The observer class.
19
+ * @param registeredTypes - The event types registered with the event store.
20
+ * @param methods - The instance methods of the observer.
21
+ * @returns The {@link BatchMethod} instances.
22
+ * @throws {@link InvalidBatchMethod} when a batch method also declares a per-event decorator or observes an unregistered type.
23
+ * @throws {@link EventTypeObservedByMoreThanOneMethod} when two batch methods observe the same event type.
24
+ */
25
+ export function getBatchMethods(observerType: Constructor, registeredTypes: readonly Constructor[],
26
+ methods: ReadonlyMap<string, Function> = getInstanceMethods(observerType)): BatchMethod[] {
27
+ const typeName = (observerType as Function).name;
28
+ const observedBy = new Map<string, string>();
29
+ const batchMethods: BatchMethod[] = [];
30
+ for (const [name, method] of methods) {
31
+ const observed = getObservedEventTypes(method);
32
+ if (observed.length === 0) continue;
33
+ if (getHandledEventType(method) !== undefined) {
34
+ throw new InvalidBatchMethod(typeName, name, 'it cannot also declare @handles. A batch method declares its event types with @observes only.');
35
+ }
36
+ if (getReplayEventType(method) !== undefined) {
37
+ throw new InvalidBatchMethod(typeName, name, 'it cannot also declare @replay. Batch methods receive replayed pages; check BatchContext.isReplay.');
38
+ }
39
+ if (isOnceOnly(method)) {
40
+ throw new InvalidBatchMethod(typeName, name, 'it cannot be @onceOnly. Mark the whole reactor @onceOnly, or check BatchContext.isReplay.');
41
+ }
42
+
43
+ const eventTypes = new Map<string, ObservedEventType>();
44
+ for (const eventType of observed) {
45
+ const metadata = registeredTypes.includes(eventType) ? getEventTypeMetadata(eventType) : undefined;
46
+ if (!metadata) {
47
+ throw new InvalidBatchMethod(typeName, name, `it observes '${(eventType as Function).name}', which has no registered event type. Register that event constructor with the event store.`);
48
+ }
49
+ const id = metadata.eventType.id.value;
50
+ const previous = observedBy.get(id);
51
+ if (previous !== undefined) {
52
+ throw new EventTypeObservedByMoreThanOneMethod(typeName, (eventType as Function).name, [previous, name]);
53
+ }
54
+ observedBy.set(id, name);
55
+ eventTypes.set(id, { type: eventType, id, generation: metadata.eventType.generation.value });
56
+ }
57
+ batchMethods.push({ methodName: name, eventTypes });
58
+ }
59
+ return batchMethods;
60
+ }
61
+
62
+ /**
63
+ * Gets the instance methods of an observer that are not batch methods, for per-event discovery.
64
+ * @param methods - The instance methods.
65
+ * @param batchMethods - The batch methods.
66
+ * @returns The methods without the batch methods.
67
+ */
68
+ export function withoutBatchMethods(methods: ReadonlyMap<string, Function>, batchMethods: readonly BatchMethod[]): Map<string, Function> {
69
+ const names = new Set(batchMethods.map(method => method.methodName));
70
+ return new Map([...methods].filter(([name]) => !names.has(name)));
71
+ }
72
+
73
+ /**
74
+ * Throws when an event type observed by a batch method is also handled by a per-event method.
75
+ * @param observerType - The observer class.
76
+ * @param batchMethods - The batch methods.
77
+ * @param handlers - The per-event handlers, each with the event type identifier and the methods it reaches.
78
+ * @throws {@link EventTypeObservedByMoreThanOneMethod} when an event type reaches both.
79
+ */
80
+ export function assertEachEventTypeReachesOneMethod(observerType: Constructor, batchMethods: readonly BatchMethod[],
81
+ handlers: readonly { readonly id: string; readonly methodNames: readonly string[] }[]): void {
82
+ for (const handler of handlers) {
83
+ const batchMethod = batchMethods.find(method => method.eventTypes.has(handler.id));
84
+ if (batchMethod) {
85
+ const observed = batchMethod.eventTypes.get(handler.id)!;
86
+ throw new EventTypeObservedByMoreThanOneMethod((observerType as Function).name, (observed.type as Function).name,
87
+ [batchMethod.methodName, ...handler.methodNames]);
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,22 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { BatchOutcomeKind } from './BatchOutcomeKind.js';
5
+
6
+ /** A partition a batch method reported it could not handle. */
7
+ export interface BatchOutcome {
8
+ /** The partition. */
9
+ readonly partition: string;
10
+
11
+ /** The sequence number of the first event not handled. */
12
+ readonly at: bigint;
13
+
14
+ /** Whether the partition failed or was deferred. */
15
+ readonly kind: BatchOutcomeKind;
16
+
17
+ /** The error describing a failure. */
18
+ readonly error?: unknown;
19
+
20
+ /** How long to wait before delivering the partition again, for a deferral. */
21
+ readonly retryAfterMilliseconds: number;
22
+ }
@@ -0,0 +1,11 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** What a batch method reported for a partition. */
5
+ export enum BatchOutcomeKind {
6
+ /** The partition failed. */
7
+ Failed = 'failed',
8
+
9
+ /** The partition is delivered again later, without failing. */
10
+ Deferred = 'deferred'
11
+ }
@@ -0,0 +1,17 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /**
5
+ * Reported when a batch method defers a partition but the kernel does not accept deferred partitions,
6
+ * so the partition is failed instead.
7
+ */
8
+ export class DeferralNotSupportedByKernel extends Error {
9
+ /**
10
+ * Creates a new {@link DeferralNotSupportedByKernel}.
11
+ * @param partition - The partition that was deferred.
12
+ */
13
+ constructor(readonly partition: string) {
14
+ super(`Partition '${partition}' was deferred, but the kernel does not accept deferred partitions. The partition is failed instead.`);
15
+ this.name = 'DeferralNotSupportedByKernel';
16
+ }
17
+ }
@@ -0,0 +1,16 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { AppendedEvent } from '@cratis/chronicle.contracts';
5
+
6
+ /** The events of one partition in a delivery. */
7
+ export interface DeliveredPartition {
8
+ /** The partition. */
9
+ readonly partition: string;
10
+
11
+ /** The events of the partition, in sequence order. */
12
+ readonly events: readonly AppendedEvent[];
13
+
14
+ /** The stored read model state as JSON, for reducers. */
15
+ readonly initialState: string;
16
+ }
@@ -0,0 +1,37 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { Constructor } from '@cratis/fundamentals';
5
+ import type { EventContext } from '../../events/EventContext.js';
6
+ import type { ReactorDelivery } from '../../reactors/ReactorDelivery.js';
7
+
8
+ /**
9
+ * One event in an {@link EventBatch}: its content, its context and the event type it was registered as.
10
+ * The content is the deserialized JSON of the event, as per-event handlers receive it.
11
+ */
12
+ export class EventAndContext<TEvent = unknown> {
13
+ /**
14
+ * Creates a new {@link EventAndContext}.
15
+ * @param event - The content of the event.
16
+ * @param context - The {@link EventContext} of the event.
17
+ * @param eventType - The registered event constructor the event was appended as.
18
+ * @param delivery - The {@link ReactorDelivery} identifying the event's delivery, for reactors.
19
+ */
20
+ constructor(
21
+ readonly event: TEvent,
22
+ readonly context: EventContext,
23
+ readonly eventType: Constructor,
24
+ readonly delivery?: ReactorDelivery
25
+ ) {
26
+ Object.freeze(this);
27
+ }
28
+
29
+ /**
30
+ * Checks whether the event is of a given event type, narrowing {@link event} to it.
31
+ * @param eventType - The event constructor to check for.
32
+ * @returns True when the event was appended as that event type.
33
+ */
34
+ is<T>(eventType: Constructor<T>): this is EventAndContext<T> {
35
+ return this.eventType === eventType;
36
+ }
37
+ }
@@ -0,0 +1,105 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { Constructor } from '@cratis/fundamentals';
5
+ import type { EventContext } from '../../events/EventContext.js';
6
+ import type { EventAndContext } from './EventAndContext.js';
7
+ import type { BatchOutcome } from './BatchOutcome.js';
8
+ import { BatchOutcomeKind } from './BatchOutcomeKind.js';
9
+ import { DeferralNotSupportedByKernel } from './DeferralNotSupportedByKernel.js';
10
+ import { PartitionNotInBatch } from './PartitionNotInBatch.js';
11
+
12
+ /**
13
+ * The events a batch method is called with, in sequence order, and the way it reports partitions it could not handle.
14
+ *
15
+ * Returning normally means every partition in the batch succeeded. Throwing fails every partition in the batch at its
16
+ * first event in the batch. {@link EventBatch.fail} and {@link EventBatch.defer} report a single partition, so the rest
17
+ * of the batch can still succeed.
18
+ */
19
+ export class EventBatch implements Iterable<EventAndContext> {
20
+ readonly #events: readonly EventAndContext[];
21
+ readonly #canDefer: boolean;
22
+ readonly #outcomes: BatchOutcome[] = [];
23
+
24
+ /**
25
+ * Creates a new {@link EventBatch}.
26
+ * @param events - The events, in sequence order.
27
+ * @param canDefer - Whether the kernel accepts deferred partitions.
28
+ */
29
+ constructor(events: readonly EventAndContext[], canDefer: boolean = true) {
30
+ this.#events = Object.freeze([...events]);
31
+ this.#canDefer = canDefer;
32
+ }
33
+
34
+ /** The events in the batch, in sequence order. */
35
+ get events(): readonly EventAndContext[] {
36
+ return this.#events;
37
+ }
38
+
39
+ /** The number of events in the batch. */
40
+ get length(): number {
41
+ return this.#events.length;
42
+ }
43
+
44
+ /** The partitions (event source identifiers) the batch holds events for, in the order their first event appears. */
45
+ get partitions(): readonly string[] {
46
+ return [...new Set(this.#events.map(event => event.context.eventSourceId))];
47
+ }
48
+
49
+ /** The outcomes reported for single partitions, in the order they were reported. */
50
+ get outcomes(): readonly BatchOutcome[] {
51
+ return this.#outcomes;
52
+ }
53
+
54
+ /**
55
+ * Gets the events of one event type, narrowed to it.
56
+ * @param eventType - The event constructor.
57
+ * @returns The events of that type, in sequence order.
58
+ */
59
+ ofType<T>(eventType: Constructor<T>): EventAndContext<T>[] {
60
+ return this.#events.filter((event): event is EventAndContext<T> => event.is(eventType));
61
+ }
62
+
63
+ /**
64
+ * Fails a partition. Given a partition, it fails from its first event in the batch; given the context of an event,
65
+ * it fails from that event, and the partition's earlier events count as handled.
66
+ * @param partitionOrEvent - The partition (event source identifier), or the {@link EventContext} of the event it fails at.
67
+ * @param error - What went wrong. Defaults to a {@link PartitionFailedInBatch} error.
68
+ */
69
+ fail(partitionOrEvent: string | EventContext, error?: unknown): void {
70
+ const [partition, at] = this.#locate(partitionOrEvent);
71
+ this.#outcomes.push({ partition, at, kind: BatchOutcomeKind.Failed, error, retryAfterMilliseconds: 0 });
72
+ }
73
+
74
+ /**
75
+ * Defers a partition: it is not failed, does not count towards quarantine, and is delivered again after a delay.
76
+ * Given a partition, it is delivered again from its first event in the batch; given the context of an event, from that event.
77
+ * When the kernel does not accept deferrals, the partition is failed with {@link DeferralNotSupportedByKernel} instead.
78
+ * @param partitionOrEvent - The partition (event source identifier), or the {@link EventContext} of the event to deliver again from.
79
+ * @param retryAfterMilliseconds - How long to wait, in milliseconds, before the partition is delivered again.
80
+ */
81
+ defer(partitionOrEvent: string | EventContext, retryAfterMilliseconds: number): void {
82
+ const [partition, at] = this.#locate(partitionOrEvent);
83
+ if (!this.#canDefer) {
84
+ this.#outcomes.push({ partition, at, kind: BatchOutcomeKind.Failed, error: new DeferralNotSupportedByKernel(partition), retryAfterMilliseconds: 0 });
85
+ return;
86
+ }
87
+ this.#outcomes.push({ partition, at, kind: BatchOutcomeKind.Deferred, retryAfterMilliseconds: Math.max(0, Math.round(retryAfterMilliseconds)) });
88
+ }
89
+
90
+ /** @inheritdoc */
91
+ [Symbol.iterator](): Iterator<EventAndContext> {
92
+ return this.#events[Symbol.iterator]();
93
+ }
94
+
95
+ #locate(partitionOrEvent: string | EventContext): [string, bigint] {
96
+ if (typeof partitionOrEvent === 'string') {
97
+ const first = this.#events.find(event => event.context.eventSourceId === partitionOrEvent);
98
+ if (!first) throw new PartitionNotInBatch(partitionOrEvent);
99
+ return [partitionOrEvent, first.context.sequenceNumber];
100
+ }
101
+ const partition = partitionOrEvent.eventSourceId;
102
+ if (!this.#events.some(event => event.context.eventSourceId === partition)) throw new PartitionNotInBatch(partition);
103
+ return [partition, partitionOrEvent.sequenceNumber];
104
+ }
105
+ }
@@ -0,0 +1,17 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** Thrown at registration when an event type would reach more than one method of an observer. */
5
+ export class EventTypeObservedByMoreThanOneMethod extends Error {
6
+ /**
7
+ * Creates a new {@link EventTypeObservedByMoreThanOneMethod}.
8
+ * @param observerType - The name of the observer class.
9
+ * @param eventType - The name of the event type.
10
+ * @param methods - The methods the event type would reach.
11
+ */
12
+ constructor(readonly observerType: string, readonly eventType: string, readonly methods: readonly string[]) {
13
+ super(`Event type '${eventType}' reaches more than one method of '${observerType}' (${methods.map(method => `'${method}'`).join(', ')}). ` +
14
+ 'Each event type must reach exactly one method: a batch method or a per-event method, never both.');
15
+ this.name = 'EventTypeObservedByMoreThanOneMethod';
16
+ }
17
+ }
@@ -0,0 +1,16 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** Thrown at registration when a method decorated with `@observes` cannot be used as a batch method. */
5
+ export class InvalidBatchMethod extends Error {
6
+ /**
7
+ * Creates a new {@link InvalidBatchMethod}.
8
+ * @param observerType - The name of the observer class.
9
+ * @param method - The name of the method.
10
+ * @param reason - Why the method cannot be a batch method.
11
+ */
12
+ constructor(readonly observerType: string, readonly method: string, reason: string) {
13
+ super(`Batch method '${method}' on '${observerType}' is not valid: ${reason}`);
14
+ this.name = 'InvalidBatchMethod';
15
+ }
16
+ }
@@ -0,0 +1,37 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { ObservationOrigin as ContractObservationOrigin } from '@cratis/chronicle.contracts';
5
+
6
+ /** The path a delivery of events to an observer came from. */
7
+ export enum ObservationOrigin {
8
+ /** The origin is not known, for example because the kernel does not report it. */
9
+ Unknown = 0,
10
+
11
+ /** The events were appended now and delivered to an observer that is up to date. */
12
+ Live = 1,
13
+
14
+ /** The events were read from storage for an observer that is behind. */
15
+ CatchUp = 2,
16
+
17
+ /** The events were read from storage for an observer that was rewound. */
18
+ Replay = 3,
19
+
20
+ /** The events were read from storage to recover a failed or deferred partition. */
21
+ Retry = 4
22
+ }
23
+
24
+ /**
25
+ * Converts the origin the kernel reports to the client {@link ObservationOrigin}.
26
+ * @param origin - The origin on the wire, or undefined when the kernel does not report one.
27
+ * @returns The client {@link ObservationOrigin}.
28
+ */
29
+ export function toObservationOrigin(origin: ContractObservationOrigin | undefined): ObservationOrigin {
30
+ switch (origin) {
31
+ case ContractObservationOrigin.Live: return ObservationOrigin.Live;
32
+ case ContractObservationOrigin.CatchingUp: return ObservationOrigin.CatchUp;
33
+ case ContractObservationOrigin.Replaying: return ObservationOrigin.Replay;
34
+ case ContractObservationOrigin.Retrying: return ObservationOrigin.Retry;
35
+ default: return ObservationOrigin.Unknown;
36
+ }
37
+ }
@@ -0,0 +1,16 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { Constructor } from '@cratis/fundamentals';
5
+
6
+ /** An event type a batch method observes. */
7
+ export interface ObservedEventType {
8
+ /** The event constructor. */
9
+ readonly type: Constructor;
10
+
11
+ /** The event type identifier. */
12
+ readonly id: string;
13
+
14
+ /** The event type generation. */
15
+ readonly generation: number;
16
+ }
@@ -0,0 +1,37 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { EventsToObserve, ReduceOperationMessage } from '@cratis/chronicle.contracts';
5
+ import type { DeliveredPartition } from './DeliveredPartition.js';
6
+
7
+ /**
8
+ * Gets whether the kernel delivered a page of partitions. A kernel that does not know page delivery sends one partition
9
+ * in the legacy fields, and cannot take deferrals or per-partition results.
10
+ * @param message - The delivered message.
11
+ * @returns True when the message is a page.
12
+ */
13
+ export function isPage(message: EventsToObserve | ReduceOperationMessage): boolean {
14
+ return (message.Partitions?.length ?? 0) > 0;
15
+ }
16
+
17
+ /**
18
+ * Gets the partitions of a reactor delivery, treating a single-partition delivery as a page of one.
19
+ * @param message - The {@link EventsToObserve} delivered.
20
+ * @returns The {@link DeliveredPartition} instances.
21
+ */
22
+ export function partitionsOfEvents(message: EventsToObserve): DeliveredPartition[] {
23
+ return isPage(message)
24
+ ? message.Partitions.map(partition => ({ partition: partition.Partition, events: partition.Events, initialState: '' }))
25
+ : [{ partition: message.Partition, events: message.Events ?? [], initialState: '' }];
26
+ }
27
+
28
+ /**
29
+ * Gets the partitions of a reducer delivery, treating a single-partition delivery as a page of one.
30
+ * @param message - The {@link ReduceOperationMessage} delivered.
31
+ * @returns The {@link DeliveredPartition} instances.
32
+ */
33
+ export function partitionsOfOperation(message: ReduceOperationMessage): DeliveredPartition[] {
34
+ return isPage(message)
35
+ ? message.Partitions.map(partition => ({ partition: partition.Partition, events: partition.Events, initialState: partition.InitialState }))
36
+ : [{ partition: message.Partition, events: message.Events ?? [], initialState: message.InitialState }];
37
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** Reported when a batch method fails a partition without giving a reason. */
5
+ export class PartitionFailedInBatch extends Error {
6
+ /**
7
+ * Creates a new {@link PartitionFailedInBatch}.
8
+ * @param partition - The partition that was failed.
9
+ */
10
+ constructor(readonly partition: string) {
11
+ super(`Partition '${partition}' was failed by a batch method.`);
12
+ this.name = 'PartitionFailedInBatch';
13
+ }
14
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** Thrown when a batch method reports an outcome for a partition the batch holds no events for. */
5
+ export class PartitionNotInBatch extends Error {
6
+ /**
7
+ * Creates a new {@link PartitionNotInBatch}.
8
+ * @param partition - The partition the outcome was reported for.
9
+ */
10
+ constructor(readonly partition: string) {
11
+ super(`The batch holds no events for partition '${partition}', so no outcome can be reported for it.`);
12
+ this.name = 'PartitionNotInBatch';
13
+ }
14
+ }
@@ -0,0 +1,22 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { ObservationState } from '@cratis/chronicle.contracts';
5
+
6
+ /** The outcome of observing the events of one partition of a delivery. */
7
+ export interface PartitionOutcome {
8
+ /** The partition. */
9
+ readonly partition: string;
10
+ /** The settled state of the partition. */
11
+ readonly state: ObservationState;
12
+ /** The last event of the partition that was observed successfully. */
13
+ readonly lastSuccessfulObservation: bigint;
14
+ /** The messages describing a failure. */
15
+ readonly exceptionMessages: readonly string[];
16
+ /** The stack trace of a failure. */
17
+ readonly exceptionStackTrace: string;
18
+ /** How long to wait before delivering again, for a deferral. */
19
+ readonly retryAfterMilliseconds: number;
20
+ /** The reduced read model state as JSON, for reducers. */
21
+ readonly readModelState?: string;
22
+ }
@@ -0,0 +1,25 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { ObservationState } from '@cratis/chronicle.contracts';
5
+
6
+ /** The first event of a partition that one method of an observer did not handle. */
7
+ export interface PartitionProblem {
8
+ /** The partition. */
9
+ readonly partition: string;
10
+
11
+ /** The sequence number of the event. */
12
+ readonly at: bigint;
13
+
14
+ /** Whether the partition failed or was deferred. */
15
+ readonly state: ObservationState.Failed | ObservationState.Deferred;
16
+
17
+ /** The messages describing a failure. */
18
+ readonly exceptionMessages: readonly string[];
19
+
20
+ /** The stack trace of a failure. */
21
+ readonly exceptionStackTrace: string;
22
+
23
+ /** How long to wait before delivering again, for a deferral. */
24
+ readonly retryAfterMilliseconds: number;
25
+ }
@@ -0,0 +1,70 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { ObservationState, type PartitionResult } from '@cratis/chronicle.contracts';
5
+ import type { PartitionOutcome } from './PartitionOutcome.js';
6
+ import type { PartitionProblem } from './PartitionProblem.js';
7
+
8
+ /** Sequence number reported when no event of a partition was observed successfully. */
9
+ export const SEQUENCE_NUMBER_UNAVAILABLE = 4294967295n;
10
+
11
+ /**
12
+ * Creates a {@link PartitionProblem} for a failure.
13
+ * @param partition - The partition.
14
+ * @param at - The sequence number of the event it failed at.
15
+ * @param error - What went wrong.
16
+ * @returns The {@link PartitionProblem}.
17
+ */
18
+ export function failedAt(partition: string, at: bigint, error: unknown): PartitionProblem {
19
+ return {
20
+ partition, at, state: ObservationState.Failed,
21
+ exceptionMessages: [String(error)],
22
+ exceptionStackTrace: error instanceof Error ? (error.stack ?? '') : '',
23
+ retryAfterMilliseconds: 0
24
+ };
25
+ }
26
+
27
+ /**
28
+ * Settles a partition: it succeeds when no method reported a problem for it, and otherwise settles at its earliest problem.
29
+ * Events before that problem count as observed.
30
+ * @param partition - The partition.
31
+ * @param sequenceNumbers - The sequence numbers of the partition's events, in order.
32
+ * @param problems - The problems reported by any method, for any partition.
33
+ * @returns The {@link PartitionOutcome}.
34
+ */
35
+ export function settlePartition(partition: string, sequenceNumbers: readonly bigint[], problems: readonly PartitionProblem[]): PartitionOutcome {
36
+ const earliest = problems
37
+ .filter(problem => problem.partition === partition)
38
+ .reduce<PartitionProblem | undefined>((first, problem) => !first || problem.at < first.at ? problem : first, undefined);
39
+ if (!earliest) {
40
+ return {
41
+ partition, state: ObservationState.Success,
42
+ lastSuccessfulObservation: sequenceNumbers.at(-1) ?? SEQUENCE_NUMBER_UNAVAILABLE,
43
+ exceptionMessages: [], exceptionStackTrace: '', retryAfterMilliseconds: 0
44
+ };
45
+ }
46
+ const handled = sequenceNumbers.filter(sequenceNumber => sequenceNumber < earliest.at);
47
+ return {
48
+ partition, state: earliest.state,
49
+ lastSuccessfulObservation: handled.at(-1) ?? SEQUENCE_NUMBER_UNAVAILABLE,
50
+ exceptionMessages: earliest.exceptionMessages, exceptionStackTrace: earliest.exceptionStackTrace,
51
+ retryAfterMilliseconds: earliest.retryAfterMilliseconds
52
+ };
53
+ }
54
+
55
+ /**
56
+ * Converts a {@link PartitionOutcome} to the {@link PartitionResult} sent to the kernel.
57
+ * @param outcome - The outcome.
58
+ * @returns The {@link PartitionResult}.
59
+ */
60
+ export function toPartitionResult(outcome: PartitionOutcome): PartitionResult {
61
+ return {
62
+ Partition: outcome.partition,
63
+ State: outcome.state,
64
+ LastSuccessfulObservation: outcome.lastSuccessfulObservation,
65
+ ExceptionMessages: [...outcome.exceptionMessages],
66
+ ExceptionStackTrace: outcome.exceptionStackTrace,
67
+ RetryAfterMilliseconds: BigInt(Math.max(0, Math.round(outcome.retryAfterMilliseconds))),
68
+ ReadModelState: outcome.readModelState ?? ''
69
+ };
70
+ }
@@ -0,0 +1,16 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** Thrown at registration when a reducer declares a batch method and per-event methods, or more than one batch method. */
5
+ export class ReducerMixesBatchAndPerEventMethods extends Error {
6
+ /**
7
+ * Creates a new {@link ReducerMixesBatchAndPerEventMethods}.
8
+ * @param reducerType - The name of the reducer class.
9
+ * @param methods - The methods that conflict.
10
+ */
11
+ constructor(readonly reducerType: string, readonly methods: readonly string[]) {
12
+ super(`Reducer '${reducerType}' declares ${methods.map(method => `'${method}'`).join(', ')}. ` +
13
+ 'A reducer has either per-event methods or exactly one batch method, never both, because it is a single fold over one event source.');
14
+ this.name = 'ReducerMixesBatchAndPerEventMethods';
15
+ }
16
+ }