@cratis/chronicle 6.57.0 → 6.59.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 (260) hide show
  1. package/EventStore.ts +2 -2
  2. package/README.md +1 -1
  3. package/connection/ChronicleConnection.ts +2 -2
  4. package/connection/ChronicleConnectionString.spec.ts +21 -0
  5. package/connection/ChronicleConnectionString.ts +16 -6
  6. package/connection/LeastConnectionsLoadBalancerStrategy.ts +1 -1
  7. package/connection/LoadBalancerStrategyFactory.ts +2 -2
  8. package/connection/TokenProvider.ts +2 -1
  9. package/connection/fetchOAuthAccessToken.ts +3 -3
  10. package/connection/for_ChronicleConnection/when_warning_about_tls_validation/tls_validation_warning.spec.ts +6 -1
  11. package/dist/EventStore.js +2 -2
  12. package/dist/EventStore.js.map +1 -1
  13. package/dist/connection/ChronicleConnection.js +2 -2
  14. package/dist/connection/ChronicleConnection.js.map +1 -1
  15. package/dist/connection/ChronicleConnectionString.d.ts +7 -2
  16. package/dist/connection/ChronicleConnectionString.d.ts.map +1 -1
  17. package/dist/connection/ChronicleConnectionString.js +14 -6
  18. package/dist/connection/ChronicleConnectionString.js.map +1 -1
  19. package/dist/connection/LeastConnectionsLoadBalancerStrategy.d.ts +1 -1
  20. package/dist/connection/LeastConnectionsLoadBalancerStrategy.js +1 -1
  21. package/dist/connection/LoadBalancerStrategyFactory.d.ts +2 -2
  22. package/dist/connection/LoadBalancerStrategyFactory.js +2 -2
  23. package/dist/connection/TokenProvider.d.ts +2 -1
  24. package/dist/connection/TokenProvider.d.ts.map +1 -1
  25. package/dist/connection/TokenProvider.js +2 -1
  26. package/dist/connection/TokenProvider.js.map +1 -1
  27. package/dist/connection/fetchOAuthAccessToken.d.ts +1 -1
  28. package/dist/connection/fetchOAuthAccessToken.js +3 -3
  29. package/dist/connection/fetchOAuthAccessToken.js.map +1 -1
  30. package/dist/observation/batches/BatchContext.d.ts +43 -0
  31. package/dist/observation/batches/BatchContext.d.ts.map +1 -0
  32. package/dist/observation/batches/BatchContext.js +60 -0
  33. package/dist/observation/batches/BatchContext.js.map +1 -0
  34. package/dist/observation/batches/BatchContextObserver.d.ts +14 -0
  35. package/dist/observation/batches/BatchContextObserver.d.ts.map +1 -0
  36. package/dist/observation/batches/BatchContextObserver.js +4 -0
  37. package/dist/observation/batches/BatchContextObserver.js.map +1 -0
  38. package/dist/observation/batches/BatchContextValues.d.ts +13 -0
  39. package/dist/observation/batches/BatchContextValues.d.ts.map +1 -0
  40. package/dist/observation/batches/BatchContextValues.js +4 -0
  41. package/dist/observation/batches/BatchContextValues.js.map +1 -0
  42. package/dist/observation/batches/BatchMethod.d.ts +9 -0
  43. package/dist/observation/batches/BatchMethod.d.ts.map +1 -0
  44. package/dist/observation/batches/BatchMethod.js +4 -0
  45. package/dist/observation/batches/BatchMethod.js.map +1 -0
  46. package/dist/observation/batches/BatchMethodReturnedAValue.d.ts +12 -0
  47. package/dist/observation/batches/BatchMethodReturnedAValue.d.ts.map +1 -0
  48. package/dist/observation/batches/BatchMethodReturnedAValue.js +20 -0
  49. package/dist/observation/batches/BatchMethodReturnedAValue.js.map +1 -0
  50. package/dist/observation/batches/BatchMethods.d.ts +31 -0
  51. package/dist/observation/batches/BatchMethods.d.ts.map +1 -0
  52. package/dist/observation/batches/BatchMethods.js +81 -0
  53. package/dist/observation/batches/BatchMethods.js.map +1 -0
  54. package/dist/observation/batches/BatchOutcome.d.ts +15 -0
  55. package/dist/observation/batches/BatchOutcome.d.ts.map +1 -0
  56. package/dist/observation/batches/BatchOutcome.js +4 -0
  57. package/dist/observation/batches/BatchOutcome.js.map +1 -0
  58. package/dist/observation/batches/BatchOutcomeKind.d.ts +8 -0
  59. package/dist/observation/batches/BatchOutcomeKind.d.ts.map +1 -0
  60. package/dist/observation/batches/BatchOutcomeKind.js +11 -0
  61. package/dist/observation/batches/BatchOutcomeKind.js.map +1 -0
  62. package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts +13 -0
  63. package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts.map +1 -0
  64. package/dist/observation/batches/DeferralNotSupportedByKernel.js +19 -0
  65. package/dist/observation/batches/DeferralNotSupportedByKernel.js.map +1 -0
  66. package/dist/observation/batches/DeliveredPartition.d.ts +11 -0
  67. package/dist/observation/batches/DeliveredPartition.d.ts.map +1 -0
  68. package/dist/observation/batches/DeliveredPartition.js +4 -0
  69. package/dist/observation/batches/DeliveredPartition.js.map +1 -0
  70. package/dist/observation/batches/EventAndContext.d.ts +28 -0
  71. package/dist/observation/batches/EventAndContext.d.ts.map +1 -0
  72. package/dist/observation/batches/EventAndContext.js +35 -0
  73. package/dist/observation/batches/EventAndContext.js.map +1 -0
  74. package/dist/observation/batches/EventBatch.d.ts +52 -0
  75. package/dist/observation/batches/EventBatch.d.ts.map +1 -0
  76. package/dist/observation/batches/EventBatch.js +92 -0
  77. package/dist/observation/batches/EventBatch.js.map +1 -0
  78. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts +14 -0
  79. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts.map +1 -0
  80. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js +23 -0
  81. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js.map +1 -0
  82. package/dist/observation/batches/InvalidBatchMethod.d.ts +13 -0
  83. package/dist/observation/batches/InvalidBatchMethod.d.ts.map +1 -0
  84. package/dist/observation/batches/InvalidBatchMethod.js +20 -0
  85. package/dist/observation/batches/InvalidBatchMethod.js.map +1 -0
  86. package/dist/observation/batches/ObservationOrigin.d.ts +21 -0
  87. package/dist/observation/batches/ObservationOrigin.d.ts.map +1 -0
  88. package/dist/observation/batches/ObservationOrigin.js +32 -0
  89. package/dist/observation/batches/ObservationOrigin.js.map +1 -0
  90. package/dist/observation/batches/ObservedEventType.d.ts +11 -0
  91. package/dist/observation/batches/ObservedEventType.d.ts.map +1 -0
  92. package/dist/observation/batches/ObservedEventType.js +4 -0
  93. package/dist/observation/batches/ObservedEventType.js.map +1 -0
  94. package/dist/observation/batches/PageMessages.d.ts +22 -0
  95. package/dist/observation/batches/PageMessages.d.ts.map +1 -0
  96. package/dist/observation/batches/PageMessages.js +32 -0
  97. package/dist/observation/batches/PageMessages.js.map +1 -0
  98. package/dist/observation/batches/PartitionFailedInBatch.d.ts +10 -0
  99. package/dist/observation/batches/PartitionFailedInBatch.d.ts.map +1 -0
  100. package/dist/observation/batches/PartitionFailedInBatch.js +16 -0
  101. package/dist/observation/batches/PartitionFailedInBatch.js.map +1 -0
  102. package/dist/observation/batches/PartitionNotInBatch.d.ts +10 -0
  103. package/dist/observation/batches/PartitionNotInBatch.d.ts.map +1 -0
  104. package/dist/observation/batches/PartitionNotInBatch.js +16 -0
  105. package/dist/observation/batches/PartitionNotInBatch.js.map +1 -0
  106. package/dist/observation/batches/PartitionOutcome.d.ts +19 -0
  107. package/dist/observation/batches/PartitionOutcome.d.ts.map +1 -0
  108. package/dist/observation/batches/PartitionOutcome.js +4 -0
  109. package/dist/observation/batches/PartitionOutcome.js.map +1 -0
  110. package/dist/observation/batches/PartitionProblem.d.ts +17 -0
  111. package/dist/observation/batches/PartitionProblem.d.ts.map +1 -0
  112. package/dist/observation/batches/PartitionProblem.js +4 -0
  113. package/dist/observation/batches/PartitionProblem.js.map +1 -0
  114. package/dist/observation/batches/PartitionSettlement.d.ts +29 -0
  115. package/dist/observation/batches/PartitionSettlement.d.ts.map +1 -0
  116. package/dist/observation/batches/PartitionSettlement.js +64 -0
  117. package/dist/observation/batches/PartitionSettlement.js.map +1 -0
  118. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts +12 -0
  119. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts.map +1 -0
  120. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js +20 -0
  121. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js.map +1 -0
  122. package/dist/observation/batches/batchSize.d.ts +42 -0
  123. package/dist/observation/batches/batchSize.d.ts.map +1 -0
  124. package/dist/observation/batches/batchSize.js +55 -0
  125. package/dist/observation/batches/batchSize.js.map +1 -0
  126. package/dist/observation/batches/createBatchContext.d.ts +13 -0
  127. package/dist/observation/batches/createBatchContext.d.ts.map +1 -0
  128. package/dist/observation/batches/createBatchContext.js +27 -0
  129. package/dist/observation/batches/createBatchContext.js.map +1 -0
  130. package/dist/observation/batches/observes.d.ts +39 -0
  131. package/dist/observation/batches/observes.d.ts.map +1 -0
  132. package/dist/observation/batches/observes.js +63 -0
  133. package/dist/observation/batches/observes.js.map +1 -0
  134. package/dist/observation/batches/runConcurrently.d.ts +9 -0
  135. package/dist/observation/batches/runConcurrently.d.ts.map +1 -0
  136. package/dist/observation/batches/runConcurrently.js +22 -0
  137. package/dist/observation/batches/runConcurrently.js.map +1 -0
  138. package/dist/observation/createHandlerInstanceValidator.d.ts +1 -1
  139. package/dist/observation/createHandlerInstanceValidator.d.ts.map +1 -1
  140. package/dist/observation/createHandlerInstanceValidator.js +5 -7
  141. package/dist/observation/createHandlerInstanceValidator.js.map +1 -1
  142. package/dist/observation/getInstanceMethods.d.ts +3 -1
  143. package/dist/observation/getInstanceMethods.d.ts.map +1 -1
  144. package/dist/observation/getInstanceMethods.js +13 -4
  145. package/dist/observation/getInstanceMethods.js.map +1 -1
  146. package/dist/observation/index.d.ts +14 -0
  147. package/dist/observation/index.d.ts.map +1 -1
  148. package/dist/observation/index.js +13 -0
  149. package/dist/observation/index.js.map +1 -1
  150. package/dist/reactors/ReactorDispatcher.d.ts +15 -0
  151. package/dist/reactors/ReactorDispatcher.d.ts.map +1 -1
  152. package/dist/reactors/ReactorDispatcher.js +25 -2
  153. package/dist/reactors/ReactorDispatcher.js.map +1 -1
  154. package/dist/reactors/ReactorObservationTarget.d.ts +45 -0
  155. package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -0
  156. package/dist/reactors/ReactorObservationTarget.js +4 -0
  157. package/dist/reactors/ReactorObservationTarget.js.map +1 -0
  158. package/dist/reactors/ReactorPageDispatcher.d.ts +33 -0
  159. package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -0
  160. package/dist/reactors/ReactorPageDispatcher.js +293 -0
  161. package/dist/reactors/ReactorPageDispatcher.js.map +1 -0
  162. package/dist/reactors/Reactors.d.ts.map +1 -1
  163. package/dist/reactors/Reactors.js +21 -149
  164. package/dist/reactors/Reactors.js.map +1 -1
  165. package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts +14 -0
  166. package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts.map +1 -0
  167. package/dist/reactors/for_Reactors/given/observe_reactor_messages.js +61 -0
  168. package/dist/reactors/for_Reactors/given/observe_reactor_messages.js.map +1 -0
  169. package/dist/reactors/index.d.ts +2 -0
  170. package/dist/reactors/index.d.ts.map +1 -1
  171. package/dist/reactors/index.js +1 -0
  172. package/dist/reactors/index.js.map +1 -1
  173. package/dist/reducers/ReducerEventDispatcher.d.ts +26 -1
  174. package/dist/reducers/ReducerEventDispatcher.d.ts.map +1 -1
  175. package/dist/reducers/ReducerEventDispatcher.js +35 -3
  176. package/dist/reducers/ReducerEventDispatcher.js.map +1 -1
  177. package/dist/reducers/Reducers.d.ts +2 -0
  178. package/dist/reducers/Reducers.d.ts.map +1 -1
  179. package/dist/reducers/Reducers.js +94 -22
  180. package/dist/reducers/Reducers.js.map +1 -1
  181. package/dist/reducers/ReductionOutcome.d.ts +27 -3
  182. package/dist/reducers/ReductionOutcome.d.ts.map +1 -1
  183. package/dist/reducers/ReductionOutcome.js +51 -7
  184. package/dist/reducers/ReductionOutcome.js.map +1 -1
  185. package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts +19 -0
  186. package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts.map +1 -0
  187. package/dist/reducers/for_Reducers/given/observe_reducer_messages.js +61 -0
  188. package/dist/reducers/for_Reducers/given/observe_reducer_messages.js.map +1 -0
  189. package/dist/reducers/index.d.ts +2 -0
  190. package/dist/reducers/index.d.ts.map +1 -1
  191. package/dist/reducers/index.js +1 -0
  192. package/dist/reducers/index.js.map +1 -1
  193. package/dist/testing/ReactorScenario.d.ts.map +1 -1
  194. package/dist/testing/ReactorScenario.js +4 -1
  195. package/dist/testing/ReactorScenario.js.map +1 -1
  196. package/dist/testing/ReducerReadModelProcessor.d.ts +1 -0
  197. package/dist/testing/ReducerReadModelProcessor.d.ts.map +1 -1
  198. package/dist/testing/ReducerReadModelProcessor.js +45 -0
  199. package/dist/testing/ReducerReadModelProcessor.js.map +1 -1
  200. package/dist/tsconfig.tsbuildinfo +1 -1
  201. package/observation/batches/BatchContext.ts +75 -0
  202. package/observation/batches/BatchContextObserver.ts +16 -0
  203. package/observation/batches/BatchContextValues.ts +16 -0
  204. package/observation/batches/BatchMethod.ts +13 -0
  205. package/observation/batches/BatchMethodReturnedAValue.ts +16 -0
  206. package/observation/batches/BatchMethods.ts +90 -0
  207. package/observation/batches/BatchOutcome.ts +22 -0
  208. package/observation/batches/BatchOutcomeKind.ts +11 -0
  209. package/observation/batches/DeferralNotSupportedByKernel.ts +17 -0
  210. package/observation/batches/DeliveredPartition.ts +16 -0
  211. package/observation/batches/EventAndContext.ts +37 -0
  212. package/observation/batches/EventBatch.ts +105 -0
  213. package/observation/batches/EventTypeObservedByMoreThanOneMethod.ts +17 -0
  214. package/observation/batches/InvalidBatchMethod.ts +16 -0
  215. package/observation/batches/ObservationOrigin.ts +37 -0
  216. package/observation/batches/ObservedEventType.ts +16 -0
  217. package/observation/batches/PageMessages.ts +37 -0
  218. package/observation/batches/PartitionFailedInBatch.ts +14 -0
  219. package/observation/batches/PartitionNotInBatch.ts +14 -0
  220. package/observation/batches/PartitionOutcome.ts +22 -0
  221. package/observation/batches/PartitionProblem.ts +25 -0
  222. package/observation/batches/PartitionSettlement.ts +70 -0
  223. package/observation/batches/ReducerMixesBatchAndPerEventMethods.ts +16 -0
  224. package/observation/batches/batchSize.ts +79 -0
  225. package/observation/batches/createBatchContext.ts +32 -0
  226. package/observation/batches/for_BatchMethods/when_discovering_batch_methods.spec.ts +155 -0
  227. package/observation/batches/for_EventBatch/when_reporting_outcomes.spec.ts +66 -0
  228. package/observation/batches/for_PartitionSettlement/when_settling_a_partition.spec.ts +31 -0
  229. package/observation/batches/for_batchSize/when_declaring_bounds.spec.ts +23 -0
  230. package/observation/batches/for_observes/when_decorating_methods.legacy.spec.ts +28 -0
  231. package/observation/batches/for_observes/when_decorating_methods.spec.ts +33 -0
  232. package/observation/batches/for_runConcurrently/when_running_items.spec.ts +22 -0
  233. package/observation/batches/observes.ts +68 -0
  234. package/observation/batches/runConcurrently.ts +23 -0
  235. package/observation/createHandlerInstanceValidator.ts +5 -7
  236. package/observation/getInstanceMethods.ts +13 -4
  237. package/observation/index.ts +14 -0
  238. package/package.json +1 -1
  239. package/reactors/ReactorDispatcher.ts +27 -2
  240. package/reactors/ReactorObservationTarget.ts +48 -0
  241. package/reactors/ReactorPageDispatcher.ts +321 -0
  242. package/reactors/Reactors.ts +22 -164
  243. package/reactors/for_Reactors/given/observe_reactor_messages.ts +72 -0
  244. package/reactors/for_Reactors/when_delivering_pages/as_a_legacy_single_partition.spec.ts +51 -0
  245. package/reactors/for_Reactors/when_delivering_pages/returning_a_value_from_a_batch_method.spec.ts +34 -0
  246. package/reactors/for_Reactors/when_delivering_pages/with_batch_and_per_event_methods.spec.ts +81 -0
  247. package/reactors/for_Reactors/when_delivering_pages/with_batch_outcomes.spec.ts +86 -0
  248. package/reactors/for_Reactors/when_delivering_pages/with_per_event_handlers.spec.ts +52 -0
  249. package/reactors/index.ts +2 -0
  250. package/reducers/ReducerEventDispatcher.ts +44 -3
  251. package/reducers/Reducers.ts +109 -25
  252. package/reducers/ReductionOutcome.ts +55 -8
  253. package/reducers/for_Reducers/given/observe_reducer_messages.ts +77 -0
  254. package/reducers/for_Reducers/when_delivering_pages/to_a_batch_reducer.spec.ts +111 -0
  255. package/reducers/for_Reducers/when_delivering_pages/to_a_per_event_reducer.spec.ts +53 -0
  256. package/reducers/index.ts +2 -0
  257. package/testing/ReactorScenario.ts +5 -1
  258. package/testing/ReducerReadModelProcessor.ts +44 -0
  259. package/testing/for_ReactorScenario/when_the_reactor_has_a_batch_method.spec.ts +26 -0
  260. package/testing/for_ReadModelScenario/when_reducing_with_a_batch_method/with_events_for_two_event_sources.spec.ts +43 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/chronicle",
3
- "version": "6.57.0",
3
+ "version": "6.59.0",
4
4
  "description": "Event sourcing for TypeScript and Node.js — the idiomatic client for Cratis Chronicle, the open-source event-sourcing database",
5
5
  "author": "Cratis",
6
6
  "license": "MIT",
@@ -11,6 +11,8 @@ import { getEventTypeMetadata } from '../events/eventTypeDecorator.js';
11
11
  import { getHandledEventType } from '../events/handles.js';
12
12
  import { getEventHandlers } from '../observation/getEventHandlers.js';
13
13
  import { getInstanceMethods } from '../observation/getInstanceMethods.js';
14
+ import { assertEachEventTypeReachesOneMethod, getBatchMethods, withoutBatchMethods } from '../observation/batches/BatchMethods.js';
15
+ import type { BatchMethod } from '../observation/batches/BatchMethod.js';
14
16
  import { isOnceOnly } from './onceOnly.js';
15
17
  import { getReplayEventType } from './replay.js';
16
18
  import type { ReactorServices } from './ReactorServices.js';
@@ -24,8 +26,27 @@ export interface ReactorEventTypeEntry {
24
26
  readonly replayMethodName?: string;
25
27
  }
26
28
 
29
+ /**
30
+ * Discovers the batch methods of a reactor, the methods decorated with \`@observes\`.
31
+ * @param reactorType - The reactor class.
32
+ * @param registeredTypes - The event types registered with the event store.
33
+ * @returns The batch methods.
34
+ */
35
+ export function getReactorBatchMethods(reactorType: Constructor, registeredTypes: readonly Constructor[]): BatchMethod[] {
36
+ return getBatchMethods(reactorType, registeredTypes);
37
+ }
38
+
39
+ /**
40
+ * Discovers the per-event handlers of a reactor and checks that each event type reaches exactly one method,
41
+ * a batch method or a per-event method.
42
+ * @param reactorType - The reactor class.
43
+ * @param registeredTypes - The event types registered with the event store.
44
+ * @returns The per-event handler entries.
45
+ */
27
46
  export function getReactorEventTypes(reactorType: Constructor, registeredTypes: readonly Constructor[]): ReactorEventTypeEntry[] {
28
- const methods = getInstanceMethods(reactorType);
47
+ const allMethods = getInstanceMethods(reactorType);
48
+ const batchMethods = getBatchMethods(reactorType, registeredTypes, allMethods);
49
+ const methods = withoutBatchMethods(allMethods, batchMethods);
29
50
  const replayHandlers = new Map<string, string>();
30
51
  const eventTypes = new Map<string, { eventTypeClass: Function; id: string; generation: number }>();
31
52
 
@@ -67,7 +88,11 @@ export function getReactorEventTypes(reactorType: Constructor, registeredTypes:
67
88
  entries.set(eventType.id, { id: eventType.id, generation: eventType.generation, ...entries.get(eventType.id), replayMethodName });
68
89
  }
69
90
  }
70
- return [...entries.values()];
91
+ const handlers = [...entries.values()];
92
+ assertEachEventTypeReachesOneMethod(reactorType, batchMethods, handlers.map(handler => ({
93
+ id: handler.id, methodNames: [handler.methodName, handler.replayMethodName].filter((name): name is string => !!name)
94
+ })));
95
+ return handlers;
71
96
  }
72
97
 
73
98
  export function selectReactorHandler(entries: readonly ReactorEventTypeEntry[], reactorType: Constructor,
@@ -0,0 +1,48 @@
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 { ClientArtifactsActivator } from '../artifacts/ClientArtifactsActivator.js';
6
+ import type { IEventLog } from '../eventSequences/IEventLog.js';
7
+ import type { createLogger } from '../logging/createLogger.js';
8
+ import type { IChronicleLogger } from '../logging/IChronicleLogger.js';
9
+ import type { BatchMethod } from '../observation/batches/BatchMethod.js';
10
+ import type { ReactorEventTypeEntry } from './ReactorDispatcher.js';
11
+ import type { ReactorResultHandler } from './ReactorResultHandler.js';
12
+ import type { ReactorServices } from './ReactorServices.js';
13
+
14
+ /** Everything a {@link ReactorPageDispatcher} needs to know about one reactor observation. */
15
+ export interface ReactorObservationTarget {
16
+ /** The reactor identifier. */
17
+ readonly id: string;
18
+ /** The reactor class. */
19
+ readonly reactorType: Constructor;
20
+ /** The event sequence the reactor observes. */
21
+ readonly eventSequenceId: string;
22
+ /** The event store the reactor is registered with. */
23
+ readonly eventStoreName: string;
24
+ /** The namespace the reactor is registered in. */
25
+ readonly namespace: string;
26
+ /** The per-event handlers. */
27
+ readonly entries: readonly ReactorEventTypeEntry[];
28
+ /** The batch methods. */
29
+ readonly batchMethods: readonly BatchMethod[];
30
+ /** Rejects instances whose fields hide decorated methods. */
31
+ readonly validateInstance: (instance: object) => void;
32
+ /** The long-lived reactor instance, or undefined when instances are activated per delivery. */
33
+ readonly reactorInstance: Record<string, Function> | undefined;
34
+ /** The services handed to per-event handlers. */
35
+ readonly services: ReactorServices | undefined;
36
+ /** Aborted when the observation stops. */
37
+ readonly signal: AbortSignal;
38
+ /** The event log side effects returned by per-event handlers are appended to. */
39
+ readonly eventLog: IEventLog;
40
+ /** Optional handler of side-effect results. */
41
+ readonly resultHandler?: ReactorResultHandler;
42
+ /** Optional per-delivery activator. */
43
+ readonly artifactActivator?: ClientArtifactsActivator;
44
+ /** The reactor logger. */
45
+ readonly logger: ReturnType<typeof createLogger>;
46
+ /** The connection logger, for activation diagnostics. */
47
+ readonly connectionLogger?: IChronicleLogger;
48
+ }
@@ -0,0 +1,321 @@
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 { ObservationState, ReplayState, type AppendedEvent, type EventsToObserve, type ReactorResult } from '@cratis/chronicle.contracts';
6
+ import type { ActivatedArtifact } from '../artifacts/ActivatedArtifact.js';
7
+ import { ArtifactCompletionFailed } from '../artifacts/ArtifactCompletionFailed.js';
8
+ import { ArtifactDelivery } from '../artifacts/ArtifactDelivery.js';
9
+ import { ArtifactKind } from '../artifacts/ArtifactKind.js';
10
+ import { runActivated, withActivatedArtifact } from '../artifacts/withActivatedArtifact.js';
11
+ import type { EventContext } from '../events/EventContext.js';
12
+ import { toClientEventContext } from '../events/toClientEventContext.js';
13
+ import { notifyReplayLifecycle } from '../observation/notifyReplayLifecycle.js';
14
+ import type { BatchContext } from '../observation/batches/BatchContext.js';
15
+ import { createBatchContext } from '../observation/batches/createBatchContext.js';
16
+ import { BatchOutcomeKind } from '../observation/batches/BatchOutcomeKind.js';
17
+ import type { BatchMethod } from '../observation/batches/BatchMethod.js';
18
+ import { BatchMethodReturnedAValue } from '../observation/batches/BatchMethodReturnedAValue.js';
19
+ import { EventAndContext } from '../observation/batches/EventAndContext.js';
20
+ import { EventBatch } from '../observation/batches/EventBatch.js';
21
+ import { isPage, partitionsOfEvents } from '../observation/batches/PageMessages.js';
22
+ import type { DeliveredPartition } from '../observation/batches/DeliveredPartition.js';
23
+ import { PartitionFailedInBatch } from '../observation/batches/PartitionFailedInBatch.js';
24
+ import { failedAt, settlePartition, toPartitionResult } from '../observation/batches/PartitionSettlement.js';
25
+ import type { PartitionOutcome } from '../observation/batches/PartitionOutcome.js';
26
+ import type { PartitionProblem } from '../observation/batches/PartitionProblem.js';
27
+ import { dispatchReactorSideEffects } from './ReactorSideEffects.js';
28
+ import { invokeReactorHandler, selectReactorHandler } from './ReactorDispatcher.js';
29
+ import type { ReactorObservationTarget } from './ReactorObservationTarget.js';
30
+ import { ReactorDelivery } from './ReactorDelivery.js';
31
+
32
+ type ReactorInstance = Record<string, Function>;
33
+ type Artifact = ActivatedArtifact<ReactorInstance>;
34
+
35
+ /** An event of a page bound for a batch method, with the partition it was delivered in. */
36
+ type PageEvent = { readonly partition: string; readonly event: EventAndContext };
37
+
38
+
39
+ /**
40
+ * Dispatches one delivery of a reactor observation, a page of partitions or a legacy single partition, to its batch and
41
+ * per-event methods, and settles each partition on its own.
42
+ */
43
+ export class ReactorPageDispatcher {
44
+ private readonly _batchEventTypes: ReadonlyMap<string, { method: BatchMethod; type: Constructor }>;
45
+
46
+ /**
47
+ * Creates a new {@link ReactorPageDispatcher}.
48
+ * @param _target - The {@link ReactorObservationTarget}.
49
+ */
50
+ constructor(private readonly _target: ReactorObservationTarget) {
51
+ this._batchEventTypes = new Map(_target.batchMethods.flatMap(method =>
52
+ [...method.eventTypes.values()].map(eventType => [eventType.id, { method, type: eventType.type }] as const)));
53
+ }
54
+
55
+ /**
56
+ * Dispatches a delivery and creates the result to send back to the kernel.
57
+ * @param message - The {@link EventsToObserve} delivered.
58
+ * @returns The {@link ReactorResult}.
59
+ */
60
+ async dispatch(message: EventsToObserve): Promise<ReactorResult> {
61
+ const partitions = partitionsOfEvents(message);
62
+ this._target.logger.debug('Received events to observe', {
63
+ reactorId: this._target.id,
64
+ partitions: partitions.length,
65
+ count: partitions.reduce((count, partition) => count + partition.events.length, 0),
66
+ replayState: message.ReplayState
67
+ });
68
+
69
+ const notificationFailure = await this.notifyReplayTransition(message, partitions);
70
+ const problems = notificationFailure ?? await this.observe(message, partitions);
71
+ const outcomes = partitions.map(partition => settlePartition(partition.partition,
72
+ partition.events.map(event => event.Context!.SequenceNumber), problems));
73
+ return toReactorResult(message, outcomes);
74
+ }
75
+
76
+ private async notifyReplayTransition(message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[] | undefined> {
77
+ const { id, reactorType, eventSequenceId, services, signal, artifactActivator, reactorInstance, validateInstance } = this._target;
78
+ try {
79
+ if (artifactActivator && message.ReplayState !== ReplayState.REPLAY_STATE_None) {
80
+ if (!services) throw new Error('Reactor activation requires the owning event store.');
81
+ await withActivatedArtifact(reactorType, {
82
+ kind: ArtifactKind.Reactor, artifactId: id, eventStore: services.eventStore,
83
+ readModels: services.readModels, eventSequenceId, partition: message.Partition,
84
+ signal, delivery: ArtifactDelivery.ReplayNotification, replayState: message.ReplayState
85
+ }, artifactActivator, artifact => {
86
+ validateInstance(artifact.instance as object);
87
+ return runActivated(artifact, () =>
88
+ notifyReplayLifecycle(artifact.instance as object, message.ReplayState, message.Partition),
89
+ { delivery: ArtifactDelivery.ReplayNotification, replayState: message.ReplayState });
90
+ }, this._target.connectionLogger);
91
+ } else if (reactorInstance) {
92
+ await notifyReplayLifecycle(reactorInstance, message.ReplayState, message.Partition);
93
+ }
94
+ return undefined;
95
+ } catch (error) {
96
+ this._target.logger.error('Error notifying reactor of replay lifecycle transition', { reactorId: id, error });
97
+ const messages = error instanceof ArtifactCompletionFailed && error.processingError !== undefined
98
+ ? [String(error.processingError), String(error)] : [String(error)];
99
+ return partitions.map(partition => ({
100
+ ...failedAt(partition.partition, firstSequenceNumberOf(partition), error),
101
+ exceptionMessages: messages
102
+ }));
103
+ }
104
+ }
105
+
106
+ private async observe(message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
107
+ const { id, reactorType, eventSequenceId, services, signal, artifactActivator, reactorInstance, validateInstance } = this._target;
108
+ const first = artifactActivator ? this.firstInvocableEvent(partitions) : undefined;
109
+ if (!first || !artifactActivator) {
110
+ return this.observeWith({ instance: reactorInstance ?? {} }, message, partitions);
111
+ }
112
+
113
+ const problems: PartitionProblem[] = [];
114
+ try {
115
+ if (!services) throw new Error('Reactor activation requires the owning event store.');
116
+ await withActivatedArtifact(reactorType as new () => ReactorInstance, {
117
+ kind: ArtifactKind.Reactor, artifactId: id, eventStore: services.eventStore,
118
+ readModels: services.readModels, eventSequenceId, partition: first.partition,
119
+ signal, delivery: ArtifactDelivery.Events, eventContext: toClientEventContext(first.event.Context!)
120
+ }, artifactActivator, async artifact => {
121
+ validateInstance(artifact.instance);
122
+ problems.push(...await this.observeWith(artifact, message, partitions));
123
+ }, this._target.connectionLogger);
124
+ return problems;
125
+ } catch (error) {
126
+ this._target.logger.error('Error activating reactor', { reactorId: id, error });
127
+ return partitions.map(partition => activationFailure(partition, problems, error));
128
+ }
129
+ }
130
+
131
+ private firstInvocableEvent(partitions: readonly DeliveredPartition[]): { partition: string; event: AppendedEvent } | undefined {
132
+ for (const partition of partitions) {
133
+ for (const event of partition.events) {
134
+ const eventTypeId = event.Context?.EventType?.Id;
135
+ if (eventTypeId && this._batchEventTypes.has(eventTypeId)) return { partition: partition.partition, event };
136
+ const selection = this.select(this._target.reactorInstance, event);
137
+ if (selection?.methodName && !selection.skipReplay) return { partition: partition.partition, event };
138
+ }
139
+ }
140
+ return undefined;
141
+ }
142
+
143
+ private select(instance: ReactorInstance | undefined, event: AppendedEvent) {
144
+ return selectReactorHandler(this._target.entries, this._target.reactorType, instance,
145
+ event.Context?.EventType?.Id, event.Context?.ObservationState ?? 0);
146
+ }
147
+
148
+ private async observeWith(artifact: Artifact, message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
149
+ const problems: PartitionProblem[] = [];
150
+ if (this._target.batchMethods.length > 0) {
151
+ problems.push(...await this.observeBatches(artifact, message, partitions));
152
+ }
153
+ for (const partition of partitions) {
154
+ const problem = await this.observePartition(artifact, partition);
155
+ if (problem) problems.push(problem);
156
+ }
157
+ return problems;
158
+ }
159
+
160
+ private async observeBatches(artifact: Artifact, message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
161
+ const problems: PartitionProblem[] = [];
162
+ const events: PageEvent[] = [];
163
+ for (const partition of partitions) {
164
+ for (const event of partition.events) {
165
+ const batchEventType = this._batchEventTypes.get(event.Context?.EventType?.Id ?? '');
166
+ if (!batchEventType) continue;
167
+ try {
168
+ events.push({ partition: partition.partition, event: this.toEventAndContext(event, batchEventType.type) });
169
+ } catch (error) {
170
+ problems.push(failedAt(partition.partition, event.Context!.SequenceNumber, error));
171
+ }
172
+ }
173
+ }
174
+ events.sort((left, right) => left.event.context.sequenceNumber < right.event.context.sequenceNumber ? -1
175
+ : left.event.context.sequenceNumber > right.event.context.sequenceNumber ? 1 : 0);
176
+
177
+ const context = this.createBatchContext(message, partitions);
178
+ for (const method of this._target.batchMethods) {
179
+ const observed = events.filter(event => method.eventTypes.has(event.event.context.eventType.id.value));
180
+ if (observed.length === 0) continue;
181
+ problems.push(...await this.invokeBatchMethod(artifact, method, observed, context));
182
+ }
183
+ return problems;
184
+ }
185
+
186
+ private async invokeBatchMethod(artifact: Artifact, method: BatchMethod, observed: readonly PageEvent[], context: BatchContext): Promise<PartitionProblem[]> {
187
+ const { id, reactorType } = this._target;
188
+ const batch = new EventBatch(observed.map(event => event.event), context.canDefer);
189
+ const partitionOf = new Map(observed.map(event => [event.event.context.eventSourceId, event.partition]));
190
+ try {
191
+ this._target.logger.info('Invoking reactor batch method', { reactorId: id, method: method.methodName, count: observed.length });
192
+ const result: unknown = await runActivated(artifact, () => artifact.instance[method.methodName](batch, context),
193
+ { delivery: ArtifactDelivery.Events, eventContext: observed[0].event.context, methodName: method.methodName });
194
+ if (result !== undefined) throw new BatchMethodReturnedAValue((reactorType as Function).name, method.methodName);
195
+ return batch.outcomes.map(outcome => {
196
+ const partition = partitionOf.get(outcome.partition) ?? outcome.partition;
197
+ return outcome.kind === BatchOutcomeKind.Deferred
198
+ ? { partition, at: outcome.at, state: ObservationState.Deferred, exceptionMessages: [], exceptionStackTrace: '',
199
+ retryAfterMilliseconds: outcome.retryAfterMilliseconds }
200
+ : failedAt(partition, outcome.at, outcome.error ?? new PartitionFailedInBatch(outcome.partition));
201
+ });
202
+ } catch (error) {
203
+ this._target.logger.error('Error handling events in reactor batch method', { reactorId: id, method: method.methodName, error });
204
+ const firstOfPartition = new Map<string, bigint>();
205
+ for (const event of observed) {
206
+ if (!firstOfPartition.has(event.partition)) firstOfPartition.set(event.partition, event.event.context.sequenceNumber);
207
+ }
208
+ return [...firstOfPartition].map(([partition, at]) => failedAt(partition, at, error));
209
+ }
210
+ }
211
+
212
+ private async observePartition(artifact: Artifact, partition: DeliveredPartition): Promise<PartitionProblem | undefined> {
213
+ const { id, reactorType, eventStoreName, namespace, services, eventLog, resultHandler } = this._target;
214
+ for (const event of partition.events) {
215
+ const eventTypeId = event.Context?.EventType?.Id;
216
+ if (!eventTypeId) {
217
+ this._target.logger.warn('Event missing event type context', { reactorId: id });
218
+ continue;
219
+ }
220
+ if (this._batchEventTypes.has(eventTypeId)) continue;
221
+
222
+ const selection = this.select(artifact.instance, event);
223
+ if (!selection?.methodName || selection.skipReplay) {
224
+ if (selection?.skipReplay) {
225
+ this._target.logger.debug('Reactor handler skipped for replay', { reactorId: id, eventTypeId, method: selection.methodName });
226
+ } else {
227
+ this._target.logger.debug('No reactor handler found', { reactorId: id, eventTypeId, isReplay: selection?.isReplay ?? false });
228
+ }
229
+ continue;
230
+ }
231
+
232
+ try {
233
+ const content = JSON.parse(event.Content) as Record<string, unknown>;
234
+ const context = toClientEventContext(event.Context!);
235
+ this._target.logger.info('Invoking reactor handler', {
236
+ reactorId: id, method: selection.methodName, sequenceNumber: event.Context!.SequenceNumber.toString(), eventTypeId
237
+ });
238
+ await invokeReactorHandler(artifact, selection.methodName, content, context, services, result =>
239
+ dispatchReactorSideEffects(eventLog, result, context, reactorType as Function, eventStoreName, namespace, resultHandler),
240
+ this.deliveryFor(context));
241
+ } catch (error) {
242
+ this._target.logger.error('Error handling event in reactor', { reactorId: id, error });
243
+ return failedAt(partition.partition, event.Context!.SequenceNumber, error);
244
+ }
245
+ }
246
+ return undefined;
247
+ }
248
+
249
+ private toEventAndContext(event: AppendedEvent, eventType: Constructor): EventAndContext {
250
+ const context = toClientEventContext(event.Context!);
251
+ return new EventAndContext(JSON.parse(event.Content) as Record<string, unknown>, context, eventType, this.deliveryFor(context));
252
+ }
253
+
254
+ private deliveryFor(context: EventContext): ReactorDelivery {
255
+ const { id, eventStoreName, namespace, eventSequenceId } = this._target;
256
+ return new ReactorDelivery(id, context.eventStore ?? eventStoreName, context.namespace ?? namespace, eventSequenceId,
257
+ context.eventSourceId, context.sequenceNumber);
258
+ }
259
+
260
+ private createBatchContext(message: EventsToObserve, partitions: readonly DeliveredPartition[]): BatchContext {
261
+ const { id, eventStoreName, namespace, eventSequenceId, signal } = this._target;
262
+ return createBatchContext({ observerId: id, eventStore: eventStoreName, namespace, eventSequenceId, signal }, message, partitions);
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Gets the sequence number of the first event of a partition, or zero when it has none.
268
+ * @param partition - The partition.
269
+ * @returns The sequence number.
270
+ */
271
+ function firstSequenceNumberOf(partition: DeliveredPartition): bigint {
272
+ return partition.events[0]?.Context?.SequenceNumber ?? 0n;
273
+ }
274
+
275
+ /**
276
+ * Replaces what a partition reported with the failure of the activation that observed it, keeping the reported messages.
277
+ * @param partition - The partition.
278
+ * @param problems - The problems reported while observing, before the activation failed.
279
+ * @param error - The activation failure.
280
+ * @returns The {@link PartitionProblem} failing the partition from its first event.
281
+ */
282
+ function activationFailure(partition: DeliveredPartition, problems: readonly PartitionProblem[], error: unknown): PartitionProblem {
283
+ const reported = problems.filter(problem => problem.partition === partition.partition)
284
+ .reduce<PartitionProblem | undefined>((first, problem) => !first || problem.at < first.at ? problem : first, undefined);
285
+ const stack = error instanceof Error ? (error.stack ?? '') : '';
286
+ return {
287
+ partition: partition.partition,
288
+ at: firstSequenceNumberOf(partition),
289
+ state: ObservationState.Failed,
290
+ exceptionMessages: [...(reported?.exceptionMessages ?? []), String(error)],
291
+ exceptionStackTrace: error instanceof ArtifactCompletionFailed && reported?.exceptionStackTrace ? `${reported.exceptionStackTrace}\n${stack}` : stack,
292
+ retryAfterMilliseconds: 0
293
+ };
294
+ }
295
+
296
+ /**
297
+ * Creates the result of a delivery: one result per partition for a page, or the legacy single-partition fields.
298
+ * @param message - The delivered message.
299
+ * @param outcomes - The outcome of each partition, in delivery order.
300
+ * @returns The {@link ReactorResult}.
301
+ */
302
+ function toReactorResult(message: EventsToObserve, outcomes: readonly PartitionOutcome[]): ReactorResult {
303
+ if (isPage(message)) {
304
+ return {
305
+ Partition: '', State: ObservationState.OBSERVATION_STATE_None, LastSuccessfulObservation: 0n,
306
+ ExceptionMessages: [], ExceptionStackTrace: '', DeliveryId: message.DeliveryId ?? 0n,
307
+ RetryAfterMilliseconds: 0n, Partitions: outcomes.map(toPartitionResult)
308
+ };
309
+ }
310
+ const [outcome] = outcomes;
311
+ return {
312
+ Partition: message.Partition,
313
+ State: outcome.state === ObservationState.Deferred ? ObservationState.Failed : outcome.state,
314
+ LastSuccessfulObservation: outcome.lastSuccessfulObservation,
315
+ ExceptionMessages: [...outcome.exceptionMessages],
316
+ ExceptionStackTrace: outcome.exceptionStackTrace,
317
+ DeliveryId: message.DeliveryId ?? 0n,
318
+ RetryAfterMilliseconds: 0n,
319
+ Partitions: []
320
+ };
321
+ }