@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
@@ -4,18 +4,47 @@
4
4
  import type { Constructor } from '@cratis/fundamentals';
5
5
  import { createHandlerInstanceValidator } from '../observation/createHandlerInstanceValidator.js';
6
6
  import { getEventHandlers } from '../observation/getEventHandlers.js';
7
+ import { getInstanceMethods } from '../observation/getInstanceMethods.js';
8
+ import type { BatchContext } from '../observation/batches/BatchContext.js';
9
+ import type { BatchMethod } from '../observation/batches/BatchMethod.js';
10
+ import { getBatchMethods, withoutBatchMethods } from '../observation/batches/BatchMethods.js';
11
+ import type { EventBatch } from '../observation/batches/EventBatch.js';
12
+ import { ReducerMixesBatchAndPerEventMethods } from '../observation/batches/ReducerMixesBatchAndPerEventMethods.js';
7
13
  import type { EventContext } from '../events/EventContext.js';
8
14
  import type { ReducerEventHandler } from './ReducerEventHandler.js';
9
15
 
10
16
  /** Selects and invokes the same reducer handlers for kernel deliveries and in-process scenarios. */
11
17
  export class ReducerEventDispatcher {
18
+ /** The per-event handlers; empty when the reducer has a batch method. */
12
19
  readonly handlers: ReducerEventHandler[];
20
+
21
+ /** The batch method, when the reducer has one instead of per-event handlers. */
22
+ readonly batchMethod: BatchMethod | undefined;
23
+
13
24
  readonly validateInstance: (instance: object) => void;
14
25
 
15
- /** Discovers event methods from the artifact event types. */
26
+ /**
27
+ * Discovers event methods from the artifact event types. A reducer has either per-event methods or one batch method.
28
+ * @param reducerType - The reducer class.
29
+ * @param eventTypes - The event types registered with the event store.
30
+ * @throws {@link ReducerMixesBatchAndPerEventMethods} when the reducer mixes batch and per-event methods, or has two batch methods.
31
+ */
16
32
  constructor(reducerType: Constructor, eventTypes: readonly Constructor[]) {
17
- this.handlers = getEventHandlers(reducerType, eventTypes);
18
- this.validateInstance = createHandlerInstanceValidator(reducerType, this.handlers.map(handler => handler.methodName));
33
+ const methods = getInstanceMethods(reducerType);
34
+ const batchMethods = getBatchMethods(reducerType, eventTypes, methods);
35
+ this.handlers = getEventHandlers(reducerType, eventTypes, withoutBatchMethods(methods, batchMethods));
36
+ if (batchMethods.length > 1 || (batchMethods.length === 1 && this.handlers.length > 0)) {
37
+ throw new ReducerMixesBatchAndPerEventMethods((reducerType as Function).name,
38
+ [...batchMethods.map(method => method.methodName), ...this.handlers.map(handler => handler.methodName)]);
39
+ }
40
+ this.batchMethod = batchMethods[0];
41
+ this.validateInstance = createHandlerInstanceValidator(reducerType,
42
+ [...this.handlers.map(handler => handler.methodName), ...batchMethods.map(method => method.methodName)], methods);
43
+ }
44
+
45
+ /** The event types the reducer registers: the batch method's observed types, or the per-event handlers' types. */
46
+ get eventTypes(): readonly { readonly id: string; readonly generation: number }[] {
47
+ return this.batchMethod ? [...this.batchMethod.eventTypes.values()] : this.handlers;
19
48
  }
20
49
 
21
50
  /** Resolves a registered event type, or returns undefined for an unsubscribed event. */
@@ -33,4 +62,16 @@ export class ReducerEventDispatcher {
33
62
  ): Promise<unknown> {
34
63
  return await instance[handler.methodName](event, currentState, context) as unknown;
35
64
  }
65
+
66
+ /**
67
+ * Calls the batch method with the events of one event source, its current state and the page's context.
68
+ * @param instance - The reducer instance.
69
+ * @param batch - The {@link EventBatch} of the event source.
70
+ * @param currentState - The stored state of the event source, or undefined.
71
+ * @param context - The {@link BatchContext} of the page.
72
+ * @returns The next state; undefined or null removes the read model.
73
+ */
74
+ async invokeBatch(instance: Record<string, Function>, batch: EventBatch, currentState: unknown, context: BatchContext): Promise<unknown> {
75
+ return await instance[this.batchMethod!.methodName](batch, currentState, context) as unknown;
76
+ }
36
77
  }
@@ -5,7 +5,7 @@ import 'reflect-metadata';
5
5
  import { createLogger } from '../logging/createLogger.js';
6
6
  import { runInBackgroundContext } from '../telemetry/runInBackgroundContext.js';
7
7
  import { Constructor } from '@cratis/fundamentals';
8
- import { AppendedEvent, EventGenerationDelivery, ReadModelObserverType, ReduceOperationMessage, ReducerMessage, ReplayState } from '@cratis/chronicle.contracts';
8
+ import { AppendedEvent, EventGenerationDelivery, ObservationState, ReadModelObserverType, ReduceOperationMessage, ReducerMessage, ReplayState } from '@cratis/chronicle.contracts';
9
9
  import { IClientArtifactsProvider } from '../artifacts/index.js';
10
10
  import { ChronicleConnection } from '../connection/index.js';
11
11
  import { ConnectionLifecycle } from '../connection/ConnectionLifecycle.js';
@@ -35,6 +35,16 @@ import { ArtifactKind } from '../artifacts/ArtifactKind.js';
35
35
  import { ArtifactDelivery } from '../artifacts/ArtifactDelivery.js';
36
36
  import { refuseClientHostedObservers } from '../artifacts/refuseClientHostedObservers.js';
37
37
  import { withActivatedArtifact, runActivated } from '../artifacts/withActivatedArtifact.js';
38
+ import type { BatchContext } from '../observation/batches/BatchContext.js';
39
+ import { BatchOutcomeKind } from '../observation/batches/BatchOutcomeKind.js';
40
+ import { getMaxConcurrency, toPageDelivery } from '../observation/batches/batchSize.js';
41
+ import { createBatchContext } from '../observation/batches/createBatchContext.js';
42
+ import type { DeliveredPartition } from '../observation/batches/DeliveredPartition.js';
43
+ import { EventAndContext } from '../observation/batches/EventAndContext.js';
44
+ import { EventBatch } from '../observation/batches/EventBatch.js';
45
+ import { isPage, partitionsOfOperation } from '../observation/batches/PageMessages.js';
46
+ import { PartitionFailedInBatch } from '../observation/batches/PartitionFailedInBatch.js';
47
+ import { runConcurrently } from '../observation/batches/runConcurrently.js';
38
48
 
39
49
  /** Expression used to partition reducer observations by event source ID. */
40
50
  const EVENT_SOURCE_ID_KEY = '$eventSourceId';
@@ -328,15 +338,14 @@ export class Reducers implements IReducers {
328
338
  const session: ReducerObservationSession = { ...observation, signal: controller.signal, reducerInstance };
329
339
 
330
340
  for await (const operation of this._connection.reducers.observe(queue, { signal: controller.signal })) {
331
- // Delivery steps are awaited here, not inside a wrapper async function, so that
332
- // async-context updates made by handlers reach this loop as they did originally.
333
- const outcome = this.beginReduction(session, operation);
334
- await this.notifyReplayTransition(session, operation, outcome);
335
- outcome.currentState = operation.InitialState
336
- ? JSON.parse(operation.InitialState) as unknown
337
- : undefined;
338
- await this.reduceEvents(session, operation, outcome);
339
- queue.send(outcome.toMessage(operation.Partition));
341
+ const partitions = partitionsOfOperation(operation);
342
+ const notification = this.beginReduction(session, operation, partitions);
343
+ await this.notifyReplayTransition(session, operation, notification);
344
+ const context = createBatchContext({ observerId: id, eventStore: this._eventStoreName, namespace: this._namespace,
345
+ eventSequenceId: session.eventSequenceId, signal: controller.signal }, operation, partitions);
346
+ const outcomes = await runConcurrently(partitions, getMaxConcurrency(reducerType),
347
+ partition => this.reducePartition(session, partition, notification, context));
348
+ queue.send(toResultMessage(operation, partitions, outcomes));
340
349
  }
341
350
  } catch (err) {
342
351
  if (!this._queues.has(id)) {
@@ -366,7 +375,7 @@ export class Reducers implements IReducers {
366
375
  Reducer: {
367
376
  ReducerId: id,
368
377
  EventSequenceId: eventSequenceId,
369
- EventTypes: dispatcher.handlers.map(et => ({
378
+ EventTypes: dispatcher.eventTypes.map(et => ({
370
379
  EventType: { Id: et.id, Generation: et.generation, Tombstone: false },
371
380
  Key: EVENT_SOURCE_ID_KEY
372
381
  })),
@@ -381,24 +390,37 @@ export class Reducers implements IReducers {
381
390
  EventStreamType: getEventStreamTypeFor(reducerType)
382
391
  }
383
392
  },
384
- PageDelivery: undefined
393
+ PageDelivery: toPageDelivery(reducerType)
385
394
  },
386
395
  Value1: undefined
387
396
  }
388
397
  };
389
398
  }
390
399
 
391
- private beginReduction(session: ReducerObservationSession, operation: ReduceOperationMessage): ReductionOutcome {
400
+ private beginReduction(session: ReducerObservationSession, operation: ReduceOperationMessage,
401
+ partitions: readonly DeliveredPartition[]): ReductionOutcome {
392
402
  this._logger.debug('Received reduce operation', {
393
403
  reducerId: session.id,
394
- count: operation.Events.length,
395
- hasInitialState: operation.InitialState !== '',
404
+ partitions: partitions.length,
405
+ count: partitions.reduce((count, partition) => count + partition.events.length, 0),
396
406
  replayState: operation.ReplayState
397
407
  });
398
408
 
399
409
  return new ReductionOutcome();
400
410
  }
401
411
 
412
+ private async reducePartition(session: ReducerObservationSession, partition: DeliveredPartition,
413
+ notification: ReductionOutcome, context: BatchContext): Promise<ReductionOutcome> {
414
+ const outcome = new ReductionOutcome();
415
+ if (notification.failed) {
416
+ outcome.copyFrom(notification);
417
+ return outcome;
418
+ }
419
+ outcome.currentState = partition.initialState ? JSON.parse(partition.initialState) as unknown : undefined;
420
+ await this.reduceEvents(session, partition, outcome, context);
421
+ return outcome;
422
+ }
423
+
402
424
  private async notifyReplayTransition(
403
425
  session: ReducerObservationSession,
404
426
  operation: ReduceOperationMessage,
@@ -442,16 +464,18 @@ export class Reducers implements IReducers {
442
464
 
443
465
  private async reduceEvents(
444
466
  session: ReducerObservationSession,
445
- operation: ReduceOperationMessage,
446
- outcome: ReductionOutcome
467
+ partition: DeliveredPartition,
468
+ outcome: ReductionOutcome,
469
+ context: BatchContext
447
470
  ): Promise<void> {
448
471
  const { id, reducerType, eventSequenceId, dispatcher, signal, reducerInstance } = session;
449
472
  const firstInvocableEvent = this._artifactActivator && !outcome.failed
450
- ? operation.Events.find(event =>
451
- !!event.Context?.EventType?.Id && !!dispatcher.handlerFor(event.Context.EventType.Id))
473
+ ? partition.events.find(event => !!event.Context?.EventType?.Id && (dispatcher.batchMethod
474
+ ? dispatcher.batchMethod.eventTypes.has(event.Context.EventType.Id)
475
+ : !!dispatcher.handlerFor(event.Context.EventType.Id)))
452
476
  : undefined;
453
477
  if (!firstInvocableEvent || !this._artifactActivator) {
454
- await this.processEvents(session, operation, outcome, { instance: reducerInstance ?? {} });
478
+ await this.processEvents(session, partition, outcome, { instance: reducerInstance ?? {} }, context);
455
479
  return;
456
480
  }
457
481
 
@@ -459,12 +483,12 @@ export class Reducers implements IReducers {
459
483
  const eventStore = this.requireEventStore();
460
484
  await withActivatedArtifact(reducerType as new () => Record<string, Function>, {
461
485
  kind: ArtifactKind.Reducer, artifactId: id, eventStore,
462
- readModels: eventStore.readModels, eventSequenceId, partition: operation.Partition,
486
+ readModels: eventStore.readModels, eventSequenceId, partition: partition.partition,
463
487
  signal, delivery: ArtifactDelivery.Events,
464
488
  eventContext: toClientEventContext(firstInvocableEvent.Context!)
465
489
  }, this._artifactActivator, artifact => {
466
490
  dispatcher.validateInstance(artifact.instance);
467
- return this.processEvents(session, operation, outcome, artifact);
491
+ return this.processEvents(session, partition, outcome, artifact, context);
468
492
  }, this._connection.logger);
469
493
  } catch (err) {
470
494
  this._logger.error('Error activating reducer', { reducerId: id, error: err });
@@ -474,11 +498,17 @@ export class Reducers implements IReducers {
474
498
 
475
499
  private async processEvents(
476
500
  session: ReducerObservationSession,
477
- operation: ReduceOperationMessage,
501
+ partition: DeliveredPartition,
478
502
  outcome: ReductionOutcome,
479
- artifact: ActivatedArtifact<Record<string, Function>>
503
+ artifact: ActivatedArtifact<Record<string, Function>>,
504
+ context: BatchContext
480
505
  ): Promise<void> {
481
- for (const event of outcome.failed ? [] : operation.Events) {
506
+ if (outcome.failed) return;
507
+ if (session.dispatcher.batchMethod) {
508
+ await this.processBatch(session, partition, outcome, artifact, context);
509
+ return;
510
+ }
511
+ for (const event of partition.events) {
482
512
  try {
483
513
  // Skipped events stay synchronous; only an actual handler invocation is awaited.
484
514
  const pending = this.processEvent(session, event, outcome, artifact);
@@ -491,6 +521,37 @@ export class Reducers implements IReducers {
491
521
  }
492
522
  }
493
523
 
524
+ private async processBatch(
525
+ { id, dispatcher }: ReducerObservationSession,
526
+ partition: DeliveredPartition,
527
+ outcome: ReductionOutcome,
528
+ artifact: ActivatedArtifact<Record<string, Function>>,
529
+ context: BatchContext
530
+ ): Promise<void> {
531
+ const method = dispatcher.batchMethod!;
532
+ const events = partition.events.filter(event => method.eventTypes.has(event.Context?.EventType?.Id ?? ''));
533
+ if (events.length === 0) return;
534
+ try {
535
+ const batch = new EventBatch(events.map(event => new EventAndContext(JSON.parse(event.Content) as Record<string, unknown>,
536
+ toClientEventContext(event.Context!), method.eventTypes.get(event.Context!.EventType!.Id)!.type)), context.canDefer);
537
+ this._logger.info('Invoking reducer batch method', { reducerId: id, method: method.methodName, count: events.length });
538
+ const next = await runActivated(artifact, () => dispatcher.invokeBatch(artifact.instance, batch, outcome.currentState, context),
539
+ { delivery: ArtifactDelivery.Events, eventContext: batch.events[0].context, methodName: method.methodName });
540
+ const [reported] = batch.outcomes;
541
+ if (reported?.kind === BatchOutcomeKind.Deferred) {
542
+ outcome.recordDeferral(reported.retryAfterMilliseconds);
543
+ } else if (reported) {
544
+ outcome.recordFailure(reported.error ?? new PartitionFailedInBatch(partition.partition));
545
+ } else {
546
+ outcome.currentState = next;
547
+ outcome.lastSuccessfullyObservedEvent = events.at(-1)!.Context!.SequenceNumber;
548
+ }
549
+ } catch (err) {
550
+ this._logger.error('Error handling events in reducer batch method', { reducerId: id, error: err });
551
+ outcome.recordFailure(err);
552
+ }
553
+ }
554
+
494
555
  private processEvent(
495
556
  { id, dispatcher }: ReducerObservationSession,
496
557
  event: AppendedEvent,
@@ -540,3 +601,26 @@ export class Reducers implements IReducers {
540
601
  this._queues.clear();
541
602
  }
542
603
  }
604
+
605
+ /**
606
+ * Creates the result of a reduce operation: one result per event source for a page, or the legacy single-partition fields.
607
+ * @param operation - The delivered operation.
608
+ * @param partitions - The partitions of the operation.
609
+ * @param outcomes - The outcome of each partition, in the same order.
610
+ * @returns The {@link ReducerMessage}.
611
+ */
612
+ function toResultMessage(operation: ReduceOperationMessage, partitions: readonly DeliveredPartition[],
613
+ outcomes: readonly ReductionOutcome[]): ReducerMessage {
614
+ if (!isPage(operation)) return outcomes[0].toMessage(operation.Partition, operation.DeliveryId ?? 0n);
615
+ return {
616
+ Content: {
617
+ Value0: undefined,
618
+ Value1: {
619
+ Partition: '', State: ObservationState.OBSERVATION_STATE_None, LastSuccessfulObservation: 0n,
620
+ ExceptionMessages: [], ExceptionStackTrace: '', ReadModelState: '',
621
+ DeliveryId: operation.DeliveryId ?? 0n, RetryAfterMilliseconds: 0n,
622
+ Partitions: outcomes.map((outcome, index) => outcome.toPartitionResult(partitions[index].partition))
623
+ }
624
+ }
625
+ };
626
+ }
@@ -1,7 +1,7 @@
1
1
  // Copyright (c) Cratis. All rights reserved.
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
- import { ObservationState, ReducerMessage } from '@cratis/chronicle.contracts';
4
+ import { ObservationState, type PartitionResult, type ReducerMessage } from '@cratis/chronicle.contracts';
5
5
  import { ArtifactCompletionFailed } from '../artifacts/ArtifactCompletionFailed.js';
6
6
 
7
7
  /** Sentinel sequence number sent back when no event was successfully processed. */
@@ -18,6 +18,7 @@ export class ReductionOutcome {
18
18
  lastSuccessfullyObservedEvent = SEQUENCE_NUMBER_UNAVAILABLE;
19
19
  readonly exceptionMessages: string[] = [];
20
20
  exceptionStackTrace = '';
21
+ retryAfterMilliseconds = 0;
21
22
  currentState: unknown;
22
23
 
23
24
  /** Gets whether the reduction has failed. */
@@ -32,6 +33,27 @@ export class ReductionOutcome {
32
33
  this.state = ObservationState.Failed;
33
34
  }
34
35
 
36
+ /**
37
+ * Records that a batch method deferred the reduction: nothing is written, and the event source is delivered again later.
38
+ * @param retryAfterMilliseconds - How long to wait before delivering again.
39
+ */
40
+ recordDeferral(retryAfterMilliseconds: number): void {
41
+ this.state = ObservationState.Deferred;
42
+ this.lastSuccessfullyObservedEvent = SEQUENCE_NUMBER_UNAVAILABLE;
43
+ this.retryAfterMilliseconds = retryAfterMilliseconds;
44
+ }
45
+
46
+ /**
47
+ * Copies the result of another outcome, such as a failed replay notification shared by every event source of a page.
48
+ * @param other - The outcome to copy.
49
+ */
50
+ copyFrom(other: ReductionOutcome): void {
51
+ this.state = other.state;
52
+ this.lastSuccessfullyObservedEvent = other.lastSuccessfullyObservedEvent;
53
+ this.exceptionMessages.push(...other.exceptionMessages);
54
+ this.exceptionStackTrace = other.exceptionStackTrace;
55
+ }
56
+
35
57
  /** Records a failure to notify of a replay lifecycle transition. */
36
58
  recordReplayNotificationFailure(error: unknown): void {
37
59
  if (error instanceof ArtifactCompletionFailed && error.processingError !== undefined) {
@@ -52,23 +74,48 @@ export class ReductionOutcome {
52
74
  }
53
75
  }
54
76
 
55
- /** Creates the result message reported back to the kernel. */
56
- toMessage(partition: string): ReducerMessage {
57
- const readModelState = this.state === ObservationState.Success && this.currentState !== undefined
77
+ /** The read model state as JSON, or an empty string when there is nothing to write. */
78
+ get readModelState(): string {
79
+ return this.state === ObservationState.Success && this.currentState !== undefined
58
80
  ? JSON.stringify(this.currentState)
59
- : undefined;
81
+ : '';
82
+ }
83
+
84
+ /**
85
+ * Creates the result for one event source of a page.
86
+ * @param partition - The partition (event source).
87
+ * @returns The {@link PartitionResult}.
88
+ */
89
+ toPartitionResult(partition: string): PartitionResult {
90
+ return {
91
+ Partition: partition,
92
+ State: this.state,
93
+ LastSuccessfulObservation: this.lastSuccessfullyObservedEvent,
94
+ ExceptionMessages: this.exceptionMessages,
95
+ ExceptionStackTrace: this.exceptionStackTrace,
96
+ RetryAfterMilliseconds: BigInt(Math.max(0, Math.round(this.retryAfterMilliseconds))),
97
+ ReadModelState: this.readModelState
98
+ };
99
+ }
60
100
 
101
+ /**
102
+ * Creates the legacy single-partition result message reported back to a kernel that does not deliver pages.
103
+ * @param partition - The partition (event source).
104
+ * @param deliveryId - The delivery identifier to echo.
105
+ * @returns The {@link ReducerMessage}.
106
+ */
107
+ toMessage(partition: string, deliveryId: bigint = 0n): ReducerMessage {
61
108
  return {
62
109
  Content: {
63
110
  Value0: undefined,
64
111
  Value1: {
65
112
  Partition: partition,
66
- State: this.state,
113
+ State: this.state === ObservationState.Deferred ? ObservationState.Failed : this.state,
67
114
  LastSuccessfulObservation: this.lastSuccessfullyObservedEvent,
68
115
  ExceptionMessages: this.exceptionMessages,
69
116
  ExceptionStackTrace: this.exceptionStackTrace,
70
- ReadModelState: readModelState ?? '',
71
- DeliveryId: 0n,
117
+ ReadModelState: this.readModelState,
118
+ DeliveryId: deliveryId,
72
119
  RetryAfterMilliseconds: 0n,
73
120
  Partitions: []
74
121
  }
@@ -0,0 +1,77 @@
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 {
6
+ AppendedEvent, ObservationOrigin, ReduceOperationMessage, ReplayState,
7
+ type RegisterReducer, type ReducerMessage, type ReducerResult
8
+ } from '@cratis/chronicle.contracts';
9
+ import type { IClientArtifactsProvider } from '../../../artifacts/index.js';
10
+ import type { ChronicleConnection } from '../../../connection/index.js';
11
+ import { ConnectionLifecycle } from '../../../connection/ConnectionLifecycle.js';
12
+ import type { IEventStore } from '../../../IEventStore.js';
13
+ import { Reducers } from '../../Reducers.js';
14
+
15
+ /** Creates a delivered event of a type for an event source. */
16
+ export function appended(eventTypeId: string, eventSourceId: string, sequenceNumber: bigint, content: object = {}): AppendedEvent {
17
+ return AppendedEvent.fromPartial({
18
+ Content: JSON.stringify(content),
19
+ Context: { EventType: { Id: eventTypeId, Generation: 1 }, EventSourceId: eventSourceId, SequenceNumber: sequenceNumber }
20
+ });
21
+ }
22
+
23
+ /** The events and stored state of one event source in a page. */
24
+ export interface ReducerPartitionInput {
25
+ readonly initialState?: object;
26
+ readonly events: AppendedEvent[];
27
+ }
28
+
29
+ /** Creates a page of event sources, as a kernel that delivers pages sends it. */
30
+ export function page(deliveryId: bigint, partitions: Record<string, ReducerPartitionInput>, origin = ObservationOrigin.Live): ReduceOperationMessage {
31
+ return ReduceOperationMessage.fromPartial({
32
+ DeliveryId: deliveryId, Origin: origin, ReplayState: ReplayState.REPLAY_STATE_None,
33
+ Partitions: Object.entries(partitions).map(([partition, input]) => ({
34
+ Partition: partition, Events: input.events, InitialState: input.initialState ? JSON.stringify(input.initialState) : ''
35
+ }))
36
+ });
37
+ }
38
+
39
+ /** Creates a legacy single-partition operation, as a kernel that does not deliver pages sends it. */
40
+ export function single(partition: string, events: AppendedEvent[], initialState?: object): ReduceOperationMessage {
41
+ return ReduceOperationMessage.fromPartial({
42
+ Partition: partition, Events: events, InitialState: initialState ? JSON.stringify(initialState) : '', ReplayState: ReplayState.REPLAY_STATE_None
43
+ });
44
+ }
45
+
46
+ /** Observes a reducer through the production observation stream, without a kernel. */
47
+ export async function observeReducerMessages(reducerType: Constructor, eventTypes: Constructor[], messages: ReduceOperationMessage[]):
48
+ Promise<{ registration: RegisterReducer; results: ReducerResult[] }> {
49
+ const lifecycle = new ConnectionLifecycle();
50
+ const results: ReducerResult[] = [];
51
+ let registration!: RegisterReducer;
52
+ let finish!: () => void;
53
+ const finished = new Promise<void>(resolve => { finish = resolve; });
54
+ async function* stream(queue: AsyncIterable<ReducerMessage>) {
55
+ const outgoing = queue[Symbol.asyncIterator]();
56
+ try {
57
+ registration = (await outgoing.next()).value!.Content!.Value0!;
58
+ for (const message of messages) {
59
+ yield message;
60
+ results.push((await outgoing.next()).value!.Content!.Value1!);
61
+ }
62
+ } finally {
63
+ await lifecycle.disconnected(error => { throw error; });
64
+ finish();
65
+ }
66
+ }
67
+ const connection = { reducers: { observe: stream }, readModels: { registerMany: async () => ({}) } } as unknown as ChronicleConnection;
68
+ const artifacts = { reducers: [reducerType], eventTypes, readModels: [] } as unknown as IClientArtifactsProvider;
69
+ const reducers = new Reducers(artifacts, connection, 'store', 'default', lifecycle, 'sink', { readModels: {} } as IEventStore);
70
+ try {
71
+ await reducers.register();
72
+ await finished;
73
+ return { registration, results };
74
+ } finally {
75
+ reducers.dispose();
76
+ }
77
+ }
@@ -0,0 +1,111 @@
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 { beforeEach, chai, describe, it } from 'vitest';
5
+ import { ObservationOrigin as ContractObservationOrigin, ObservationState, type RegisterReducer, type ReducerResult } from '@cratis/chronicle.contracts';
6
+ import { eventType } from '../../../events/eventTypeDecorator.js';
7
+ import { BatchContext, EventBatch, ObservationOrigin, batchSize, observes } from '../../../observation/index.js';
8
+ import { reducer } from '../../reducer.js';
9
+ import { appended, observeReducerMessages, page } from '../given/observe_reducer_messages.js';
10
+
11
+ chai.should();
12
+
13
+ @eventType('batch-reducer-money-deposited')
14
+ class MoneyDeposited {
15
+ constructor(readonly amount: number = 0) {}
16
+ }
17
+
18
+ @eventType('batch-reducer-money-withdrawn')
19
+ class MoneyWithdrawn {
20
+ constructor(readonly amount: number = 0) {}
21
+ }
22
+
23
+ interface Balance {
24
+ readonly balance: number;
25
+ }
26
+
27
+ describe('when delivering a page to a reducer with a batch method', () => {
28
+ let calls: { partitions: readonly string[]; current: Balance | undefined; count: number }[];
29
+ let contexts: BatchContext[];
30
+ let registration: RegisterReducer;
31
+ let results: ReducerResult[];
32
+
33
+ beforeEach(async () => {
34
+ calls = [];
35
+ contexts = [];
36
+
37
+ @reducer('batch-balances')
38
+ @batchSize({ maxConcurrency: 1, maxEvents: 250 })
39
+ class Balances {
40
+ @observes(MoneyDeposited)
41
+ @observes(MoneyWithdrawn)
42
+ reduce(events: EventBatch, current: Balance | undefined, context: BatchContext): Balance | undefined {
43
+ calls.push({ partitions: events.partitions, current, count: events.length });
44
+ contexts.push(context);
45
+ if (events.partitions[0] === 'throttled') {
46
+ events.defer('throttled', 750);
47
+ return current;
48
+ }
49
+ if (events.partitions[0] === 'rejected') {
50
+ events.fail(events.events[1].context, new Error('overdrawn'));
51
+ return current;
52
+ }
53
+ return events.events.reduce((balance, entry) => ({
54
+ balance: balance.balance + (entry.is(MoneyDeposited) ? entry.event.amount : entry.is(MoneyWithdrawn) ? -entry.event.amount : 0)
55
+ }), current ?? { balance: 0 });
56
+ }
57
+ }
58
+
59
+ ({ registration, results } = await observeReducerMessages(Balances, [MoneyDeposited, MoneyWithdrawn], [page(9n, {
60
+ existing: { initialState: { balance: 100 }, events: [
61
+ appended('batch-reducer-money-deposited', 'existing', 1n, { amount: 50 }),
62
+ appended('batch-reducer-money-withdrawn', 'existing', 3n, { amount: 30 })
63
+ ] },
64
+ fresh: { events: [appended('batch-reducer-money-deposited', 'fresh', 2n, { amount: 10 })] },
65
+ throttled: { events: [appended('batch-reducer-money-deposited', 'throttled', 4n, { amount: 1 })] },
66
+ rejected: { initialState: { balance: 5 }, events: [
67
+ appended('batch-reducer-money-deposited', 'rejected', 5n, { amount: 1 }),
68
+ appended('batch-reducer-money-withdrawn', 'rejected', 6n, { amount: 100 })
69
+ ] }
70
+ }, ContractObservationOrigin.Replaying)]));
71
+ });
72
+
73
+ const resultFor = (partition: string) => results[0].Partitions.find(result => result.Partition === partition)!;
74
+
75
+ it('should register the observed event types and the declared bounds', () => {
76
+ registration.Reducer!.EventTypes.map(eventType => eventType.EventType!.Id).sort()
77
+ .should.deep.equal(['batch-reducer-money-deposited', 'batch-reducer-money-withdrawn']);
78
+ registration.PageDelivery!.should.deep.equal({ Enabled: true, MaxEventsPerPage: 250, MaxBytesPerPage: 0, MaxDelayMilliseconds: 0 });
79
+ });
80
+ it('should call the batch method once per event source with its events and stored state', () =>
81
+ calls.should.deep.equal([
82
+ { partitions: ['existing'], current: { balance: 100 }, count: 2 },
83
+ { partitions: ['fresh'], current: undefined, count: 1 },
84
+ { partitions: ['throttled'], current: undefined, count: 1 },
85
+ { partitions: ['rejected'], current: { balance: 5 }, count: 2 }
86
+ ]));
87
+ it('should describe the whole page in the batch context', () => {
88
+ contexts[0].origin.should.equal(ObservationOrigin.Replay);
89
+ contexts[0].isReplay.should.be.true;
90
+ contexts[0].partitions.should.deep.equal(['existing', 'fresh', 'throttled', 'rejected']);
91
+ contexts[0].eventCount.should.equal(6);
92
+ });
93
+ it('should echo the delivery identifier', () => results[0].DeliveryId.should.equal(9n));
94
+ it('should write the next state of each event source', () => {
95
+ resultFor('existing').State.should.equal(ObservationState.Success);
96
+ JSON.parse(resultFor('existing').ReadModelState).should.deep.equal({ balance: 120 });
97
+ resultFor('existing').LastSuccessfulObservation.should.equal(3n);
98
+ JSON.parse(resultFor('fresh').ReadModelState).should.deep.equal({ balance: 10 });
99
+ });
100
+ it('should defer an event source without writing its state', () => {
101
+ resultFor('throttled').State.should.equal(ObservationState.Deferred);
102
+ resultFor('throttled').RetryAfterMilliseconds.should.equal(750n);
103
+ resultFor('throttled').ReadModelState.should.equal('');
104
+ });
105
+ it('should fail an event source without writing its state', () => {
106
+ resultFor('rejected').State.should.equal(ObservationState.Failed);
107
+ resultFor('rejected').ExceptionMessages.should.deep.equal(['Error: overdrawn']);
108
+ resultFor('rejected').ReadModelState.should.equal('');
109
+ resultFor('rejected').LastSuccessfulObservation.should.equal(4294967295n);
110
+ });
111
+ });
@@ -0,0 +1,53 @@
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 { beforeEach, chai, describe, it } from 'vitest';
5
+ import { ObservationState, type RegisterReducer, type ReducerResult } from '@cratis/chronicle.contracts';
6
+ import { eventType } from '../../../events/eventTypeDecorator.js';
7
+ import { reducer } from '../../reducer.js';
8
+ import { appended, observeReducerMessages, page, single } from '../given/observe_reducer_messages.js';
9
+
10
+ chai.should();
11
+
12
+ @eventType('per-event-reducer-item-counted')
13
+ class ItemCounted {}
14
+
15
+ interface Count {
16
+ readonly count: number;
17
+ }
18
+
19
+ describe('when delivering pages and single partitions to a reducer with per-event methods', () => {
20
+ let registration: RegisterReducer;
21
+ let results: ReducerResult[];
22
+
23
+ beforeEach(async () => {
24
+ @reducer('per-event-counts')
25
+ class Counts {
26
+ itemCounted(_event: ItemCounted, current: Count | undefined): Count {
27
+ if (current?.count === 1) throw new Error('count is stuck');
28
+ return { count: (current?.count ?? 0) + 1 };
29
+ }
30
+ }
31
+
32
+ ({ registration, results } = await observeReducerMessages(Counts, [ItemCounted], [
33
+ page(3n, {
34
+ first: { events: [appended('per-event-reducer-item-counted', 'first', 1n)] },
35
+ stuck: { initialState: { count: 1 }, events: [appended('per-event-reducer-item-counted', 'stuck', 2n)] }
36
+ }),
37
+ single('legacy', [appended('per-event-reducer-item-counted', 'legacy', 4n)], { count: 5 })
38
+ ]));
39
+ });
40
+
41
+ it('should opt in to page delivery', () => registration.PageDelivery!.Enabled.should.be.true);
42
+ it('should fold each event source of a page on its own', () => {
43
+ results[0].Partitions.map(result => result.State).should.deep.equal([ObservationState.Success, ObservationState.Failed]);
44
+ JSON.parse(results[0].Partitions[0].ReadModelState).should.deep.equal({ count: 1 });
45
+ results[0].Partitions[1].ExceptionMessages.should.deep.equal(['Error: count is stuck']);
46
+ });
47
+ it('should reply to a legacy single partition in the legacy fields', () => {
48
+ results[1].Partition.should.equal('legacy');
49
+ results[1].Partitions.should.be.empty;
50
+ results[1].State.should.equal(ObservationState.Success);
51
+ JSON.parse(results[1].ReadModelState).should.deep.equal({ count: 6 });
52
+ });
53
+ });
package/reducers/index.ts CHANGED
@@ -7,3 +7,5 @@ export { reducer, getReducerMetadata, isReducer } from './reducer.js';
7
7
  export type { ReducerMetadata } from './reducer.js';
8
8
  export type { IReducers } from './IReducers.js';
9
9
  export { Reducers } from './Reducers.js';
10
+ export { observes, batchSize, EventBatch, EventAndContext, BatchContext, ObservationOrigin } from '../observation/index.js';
11
+ export type { BatchSizeOptions } from '../observation/index.js';