@cratis/chronicle 6.56.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 (299) hide show
  1. package/EventStore.ts +2 -2
  2. package/WellKnownTelemetryNames.ts +2 -0
  3. package/auditing/CausationType.ts +5 -0
  4. package/dist/EventStore.js +2 -2
  5. package/dist/EventStore.js.map +1 -1
  6. package/dist/WellKnownTelemetryNames.d.ts +2 -0
  7. package/dist/WellKnownTelemetryNames.d.ts.map +1 -1
  8. package/dist/WellKnownTelemetryNames.js +2 -0
  9. package/dist/WellKnownTelemetryNames.js.map +1 -1
  10. package/dist/auditing/CausationType.d.ts +4 -0
  11. package/dist/auditing/CausationType.d.ts.map +1 -1
  12. package/dist/auditing/CausationType.js +4 -0
  13. package/dist/auditing/CausationType.js.map +1 -1
  14. package/dist/eventSequences/CompensateOptions.d.ts +7 -0
  15. package/dist/eventSequences/CompensateOptions.d.ts.map +1 -0
  16. package/dist/eventSequences/CompensateOptions.js +4 -0
  17. package/dist/eventSequences/CompensateOptions.js.map +1 -0
  18. package/dist/eventSequences/EventSequence.d.ts +3 -0
  19. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  20. package/dist/eventSequences/EventSequence.js +45 -0
  21. package/dist/eventSequences/EventSequence.js.map +1 -1
  22. package/dist/eventSequences/IEventSequence.d.ts +13 -0
  23. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  24. package/dist/eventSequences/index.d.ts +1 -0
  25. package/dist/eventSequences/index.d.ts.map +1 -1
  26. package/dist/eventSequences/index.js.map +1 -1
  27. package/dist/events/EventContext.d.ts +5 -0
  28. package/dist/events/EventContext.d.ts.map +1 -1
  29. package/dist/events/compensationForDecorator.d.ts +32 -0
  30. package/dist/events/compensationForDecorator.d.ts.map +1 -0
  31. package/dist/events/compensationForDecorator.js +44 -0
  32. package/dist/events/compensationForDecorator.js.map +1 -0
  33. package/dist/events/eventTypeDecorator.d.ts +7 -0
  34. package/dist/events/eventTypeDecorator.d.ts.map +1 -1
  35. package/dist/events/eventTypeDecorator.js +13 -4
  36. package/dist/events/eventTypeDecorator.js.map +1 -1
  37. package/dist/events/index.d.ts +2 -1
  38. package/dist/events/index.d.ts.map +1 -1
  39. package/dist/events/index.js +2 -1
  40. package/dist/events/index.js.map +1 -1
  41. package/dist/events/toClientEventContext.d.ts.map +1 -1
  42. package/dist/events/toClientEventContext.js +20 -0
  43. package/dist/events/toClientEventContext.js.map +1 -1
  44. package/dist/observation/batches/BatchContext.d.ts +43 -0
  45. package/dist/observation/batches/BatchContext.d.ts.map +1 -0
  46. package/dist/observation/batches/BatchContext.js +60 -0
  47. package/dist/observation/batches/BatchContext.js.map +1 -0
  48. package/dist/observation/batches/BatchContextObserver.d.ts +14 -0
  49. package/dist/observation/batches/BatchContextObserver.d.ts.map +1 -0
  50. package/dist/observation/batches/BatchContextObserver.js +4 -0
  51. package/dist/observation/batches/BatchContextObserver.js.map +1 -0
  52. package/dist/observation/batches/BatchContextValues.d.ts +13 -0
  53. package/dist/observation/batches/BatchContextValues.d.ts.map +1 -0
  54. package/dist/observation/batches/BatchContextValues.js +4 -0
  55. package/dist/observation/batches/BatchContextValues.js.map +1 -0
  56. package/dist/observation/batches/BatchMethod.d.ts +9 -0
  57. package/dist/observation/batches/BatchMethod.d.ts.map +1 -0
  58. package/dist/observation/batches/BatchMethod.js +4 -0
  59. package/dist/observation/batches/BatchMethod.js.map +1 -0
  60. package/dist/observation/batches/BatchMethodReturnedAValue.d.ts +12 -0
  61. package/dist/observation/batches/BatchMethodReturnedAValue.d.ts.map +1 -0
  62. package/dist/observation/batches/BatchMethodReturnedAValue.js +20 -0
  63. package/dist/observation/batches/BatchMethodReturnedAValue.js.map +1 -0
  64. package/dist/observation/batches/BatchMethods.d.ts +31 -0
  65. package/dist/observation/batches/BatchMethods.d.ts.map +1 -0
  66. package/dist/observation/batches/BatchMethods.js +81 -0
  67. package/dist/observation/batches/BatchMethods.js.map +1 -0
  68. package/dist/observation/batches/BatchOutcome.d.ts +15 -0
  69. package/dist/observation/batches/BatchOutcome.d.ts.map +1 -0
  70. package/dist/observation/batches/BatchOutcome.js +4 -0
  71. package/dist/observation/batches/BatchOutcome.js.map +1 -0
  72. package/dist/observation/batches/BatchOutcomeKind.d.ts +8 -0
  73. package/dist/observation/batches/BatchOutcomeKind.d.ts.map +1 -0
  74. package/dist/observation/batches/BatchOutcomeKind.js +11 -0
  75. package/dist/observation/batches/BatchOutcomeKind.js.map +1 -0
  76. package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts +13 -0
  77. package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts.map +1 -0
  78. package/dist/observation/batches/DeferralNotSupportedByKernel.js +19 -0
  79. package/dist/observation/batches/DeferralNotSupportedByKernel.js.map +1 -0
  80. package/dist/observation/batches/DeliveredPartition.d.ts +11 -0
  81. package/dist/observation/batches/DeliveredPartition.d.ts.map +1 -0
  82. package/dist/observation/batches/DeliveredPartition.js +4 -0
  83. package/dist/observation/batches/DeliveredPartition.js.map +1 -0
  84. package/dist/observation/batches/EventAndContext.d.ts +28 -0
  85. package/dist/observation/batches/EventAndContext.d.ts.map +1 -0
  86. package/dist/observation/batches/EventAndContext.js +35 -0
  87. package/dist/observation/batches/EventAndContext.js.map +1 -0
  88. package/dist/observation/batches/EventBatch.d.ts +52 -0
  89. package/dist/observation/batches/EventBatch.d.ts.map +1 -0
  90. package/dist/observation/batches/EventBatch.js +92 -0
  91. package/dist/observation/batches/EventBatch.js.map +1 -0
  92. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts +14 -0
  93. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts.map +1 -0
  94. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js +23 -0
  95. package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js.map +1 -0
  96. package/dist/observation/batches/InvalidBatchMethod.d.ts +13 -0
  97. package/dist/observation/batches/InvalidBatchMethod.d.ts.map +1 -0
  98. package/dist/observation/batches/InvalidBatchMethod.js +20 -0
  99. package/dist/observation/batches/InvalidBatchMethod.js.map +1 -0
  100. package/dist/observation/batches/ObservationOrigin.d.ts +21 -0
  101. package/dist/observation/batches/ObservationOrigin.d.ts.map +1 -0
  102. package/dist/observation/batches/ObservationOrigin.js +32 -0
  103. package/dist/observation/batches/ObservationOrigin.js.map +1 -0
  104. package/dist/observation/batches/ObservedEventType.d.ts +11 -0
  105. package/dist/observation/batches/ObservedEventType.d.ts.map +1 -0
  106. package/dist/observation/batches/ObservedEventType.js +4 -0
  107. package/dist/observation/batches/ObservedEventType.js.map +1 -0
  108. package/dist/observation/batches/PageMessages.d.ts +22 -0
  109. package/dist/observation/batches/PageMessages.d.ts.map +1 -0
  110. package/dist/observation/batches/PageMessages.js +32 -0
  111. package/dist/observation/batches/PageMessages.js.map +1 -0
  112. package/dist/observation/batches/PartitionFailedInBatch.d.ts +10 -0
  113. package/dist/observation/batches/PartitionFailedInBatch.d.ts.map +1 -0
  114. package/dist/observation/batches/PartitionFailedInBatch.js +16 -0
  115. package/dist/observation/batches/PartitionFailedInBatch.js.map +1 -0
  116. package/dist/observation/batches/PartitionNotInBatch.d.ts +10 -0
  117. package/dist/observation/batches/PartitionNotInBatch.d.ts.map +1 -0
  118. package/dist/observation/batches/PartitionNotInBatch.js +16 -0
  119. package/dist/observation/batches/PartitionNotInBatch.js.map +1 -0
  120. package/dist/observation/batches/PartitionOutcome.d.ts +19 -0
  121. package/dist/observation/batches/PartitionOutcome.d.ts.map +1 -0
  122. package/dist/observation/batches/PartitionOutcome.js +4 -0
  123. package/dist/observation/batches/PartitionOutcome.js.map +1 -0
  124. package/dist/observation/batches/PartitionProblem.d.ts +17 -0
  125. package/dist/observation/batches/PartitionProblem.d.ts.map +1 -0
  126. package/dist/observation/batches/PartitionProblem.js +4 -0
  127. package/dist/observation/batches/PartitionProblem.js.map +1 -0
  128. package/dist/observation/batches/PartitionSettlement.d.ts +29 -0
  129. package/dist/observation/batches/PartitionSettlement.d.ts.map +1 -0
  130. package/dist/observation/batches/PartitionSettlement.js +64 -0
  131. package/dist/observation/batches/PartitionSettlement.js.map +1 -0
  132. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts +12 -0
  133. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts.map +1 -0
  134. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js +20 -0
  135. package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js.map +1 -0
  136. package/dist/observation/batches/batchSize.d.ts +42 -0
  137. package/dist/observation/batches/batchSize.d.ts.map +1 -0
  138. package/dist/observation/batches/batchSize.js +55 -0
  139. package/dist/observation/batches/batchSize.js.map +1 -0
  140. package/dist/observation/batches/createBatchContext.d.ts +13 -0
  141. package/dist/observation/batches/createBatchContext.d.ts.map +1 -0
  142. package/dist/observation/batches/createBatchContext.js +27 -0
  143. package/dist/observation/batches/createBatchContext.js.map +1 -0
  144. package/dist/observation/batches/observes.d.ts +39 -0
  145. package/dist/observation/batches/observes.d.ts.map +1 -0
  146. package/dist/observation/batches/observes.js +63 -0
  147. package/dist/observation/batches/observes.js.map +1 -0
  148. package/dist/observation/batches/runConcurrently.d.ts +9 -0
  149. package/dist/observation/batches/runConcurrently.d.ts.map +1 -0
  150. package/dist/observation/batches/runConcurrently.js +22 -0
  151. package/dist/observation/batches/runConcurrently.js.map +1 -0
  152. package/dist/observation/createHandlerInstanceValidator.d.ts +1 -1
  153. package/dist/observation/createHandlerInstanceValidator.d.ts.map +1 -1
  154. package/dist/observation/createHandlerInstanceValidator.js +5 -7
  155. package/dist/observation/createHandlerInstanceValidator.js.map +1 -1
  156. package/dist/observation/getInstanceMethods.d.ts +3 -1
  157. package/dist/observation/getInstanceMethods.d.ts.map +1 -1
  158. package/dist/observation/getInstanceMethods.js +13 -4
  159. package/dist/observation/getInstanceMethods.js.map +1 -1
  160. package/dist/observation/index.d.ts +14 -0
  161. package/dist/observation/index.d.ts.map +1 -1
  162. package/dist/observation/index.js +13 -0
  163. package/dist/observation/index.js.map +1 -1
  164. package/dist/projections/eventContextPropertyExpression.js +1 -1
  165. package/dist/projections/eventContextPropertyExpression.js.map +1 -1
  166. package/dist/reactors/ReactorDispatcher.d.ts +15 -0
  167. package/dist/reactors/ReactorDispatcher.d.ts.map +1 -1
  168. package/dist/reactors/ReactorDispatcher.js +25 -2
  169. package/dist/reactors/ReactorDispatcher.js.map +1 -1
  170. package/dist/reactors/ReactorObservationTarget.d.ts +45 -0
  171. package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -0
  172. package/dist/reactors/ReactorObservationTarget.js +4 -0
  173. package/dist/reactors/ReactorObservationTarget.js.map +1 -0
  174. package/dist/reactors/ReactorPageDispatcher.d.ts +33 -0
  175. package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -0
  176. package/dist/reactors/ReactorPageDispatcher.js +293 -0
  177. package/dist/reactors/ReactorPageDispatcher.js.map +1 -0
  178. package/dist/reactors/Reactors.d.ts.map +1 -1
  179. package/dist/reactors/Reactors.js +21 -149
  180. package/dist/reactors/Reactors.js.map +1 -1
  181. package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts +14 -0
  182. package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts.map +1 -0
  183. package/dist/reactors/for_Reactors/given/observe_reactor_messages.js +61 -0
  184. package/dist/reactors/for_Reactors/given/observe_reactor_messages.js.map +1 -0
  185. package/dist/reactors/index.d.ts +2 -0
  186. package/dist/reactors/index.d.ts.map +1 -1
  187. package/dist/reactors/index.js +1 -0
  188. package/dist/reactors/index.js.map +1 -1
  189. package/dist/reducers/ReducerEventDispatcher.d.ts +26 -1
  190. package/dist/reducers/ReducerEventDispatcher.d.ts.map +1 -1
  191. package/dist/reducers/ReducerEventDispatcher.js +35 -3
  192. package/dist/reducers/ReducerEventDispatcher.js.map +1 -1
  193. package/dist/reducers/Reducers.d.ts +2 -0
  194. package/dist/reducers/Reducers.d.ts.map +1 -1
  195. package/dist/reducers/Reducers.js +94 -22
  196. package/dist/reducers/Reducers.js.map +1 -1
  197. package/dist/reducers/ReductionOutcome.d.ts +27 -3
  198. package/dist/reducers/ReductionOutcome.d.ts.map +1 -1
  199. package/dist/reducers/ReductionOutcome.js +51 -7
  200. package/dist/reducers/ReductionOutcome.js.map +1 -1
  201. package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts +19 -0
  202. package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts.map +1 -0
  203. package/dist/reducers/for_Reducers/given/observe_reducer_messages.js +61 -0
  204. package/dist/reducers/for_Reducers/given/observe_reducer_messages.js.map +1 -0
  205. package/dist/reducers/index.d.ts +2 -0
  206. package/dist/reducers/index.d.ts.map +1 -1
  207. package/dist/reducers/index.js +1 -0
  208. package/dist/reducers/index.js.map +1 -1
  209. package/dist/schemas/JsonSchema.d.ts +2 -0
  210. package/dist/schemas/JsonSchema.d.ts.map +1 -1
  211. package/dist/testing/InProcessEventSequence.d.ts +1 -0
  212. package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
  213. package/dist/testing/InProcessEventSequence.js +1 -0
  214. package/dist/testing/InProcessEventSequence.js.map +1 -1
  215. package/dist/testing/ReactorScenario.d.ts.map +1 -1
  216. package/dist/testing/ReactorScenario.js +4 -1
  217. package/dist/testing/ReactorScenario.js.map +1 -1
  218. package/dist/testing/ReducerReadModelProcessor.d.ts +1 -0
  219. package/dist/testing/ReducerReadModelProcessor.d.ts.map +1 -1
  220. package/dist/testing/ReducerReadModelProcessor.js +45 -0
  221. package/dist/testing/ReducerReadModelProcessor.js.map +1 -1
  222. package/dist/tsconfig.tsbuildinfo +1 -1
  223. package/eventSequences/CompensateOptions.ts +10 -0
  224. package/eventSequences/EventSequence.compensate.spec.ts +72 -0
  225. package/eventSequences/EventSequence.ts +51 -0
  226. package/eventSequences/IEventSequence.ts +14 -0
  227. package/eventSequences/index.ts +1 -0
  228. package/events/EventContext.ts +6 -0
  229. package/events/compensationFor.spec.ts +73 -0
  230. package/events/compensationForDecorator.ts +48 -0
  231. package/events/eventTypeDecorator.ts +13 -4
  232. package/events/index.ts +2 -1
  233. package/events/toClientEventContext.ts +21 -0
  234. package/observation/batches/BatchContext.ts +75 -0
  235. package/observation/batches/BatchContextObserver.ts +16 -0
  236. package/observation/batches/BatchContextValues.ts +16 -0
  237. package/observation/batches/BatchMethod.ts +13 -0
  238. package/observation/batches/BatchMethodReturnedAValue.ts +16 -0
  239. package/observation/batches/BatchMethods.ts +90 -0
  240. package/observation/batches/BatchOutcome.ts +22 -0
  241. package/observation/batches/BatchOutcomeKind.ts +11 -0
  242. package/observation/batches/DeferralNotSupportedByKernel.ts +17 -0
  243. package/observation/batches/DeliveredPartition.ts +16 -0
  244. package/observation/batches/EventAndContext.ts +37 -0
  245. package/observation/batches/EventBatch.ts +105 -0
  246. package/observation/batches/EventTypeObservedByMoreThanOneMethod.ts +17 -0
  247. package/observation/batches/InvalidBatchMethod.ts +16 -0
  248. package/observation/batches/ObservationOrigin.ts +37 -0
  249. package/observation/batches/ObservedEventType.ts +16 -0
  250. package/observation/batches/PageMessages.ts +37 -0
  251. package/observation/batches/PartitionFailedInBatch.ts +14 -0
  252. package/observation/batches/PartitionNotInBatch.ts +14 -0
  253. package/observation/batches/PartitionOutcome.ts +22 -0
  254. package/observation/batches/PartitionProblem.ts +25 -0
  255. package/observation/batches/PartitionSettlement.ts +70 -0
  256. package/observation/batches/ReducerMixesBatchAndPerEventMethods.ts +16 -0
  257. package/observation/batches/batchSize.ts +79 -0
  258. package/observation/batches/createBatchContext.ts +32 -0
  259. package/observation/batches/for_BatchMethods/when_discovering_batch_methods.spec.ts +155 -0
  260. package/observation/batches/for_EventBatch/when_reporting_outcomes.spec.ts +66 -0
  261. package/observation/batches/for_PartitionSettlement/when_settling_a_partition.spec.ts +31 -0
  262. package/observation/batches/for_batchSize/when_declaring_bounds.spec.ts +23 -0
  263. package/observation/batches/for_observes/when_decorating_methods.legacy.spec.ts +28 -0
  264. package/observation/batches/for_observes/when_decorating_methods.spec.ts +33 -0
  265. package/observation/batches/for_runConcurrently/when_running_items.spec.ts +22 -0
  266. package/observation/batches/observes.ts +68 -0
  267. package/observation/batches/runConcurrently.ts +23 -0
  268. package/observation/createHandlerInstanceValidator.ts +5 -7
  269. package/observation/getInstanceMethods.ts +13 -4
  270. package/observation/index.ts +14 -0
  271. package/package.json +2 -2
  272. package/projections/eventContextPropertyExpression.ts +2 -2
  273. package/reactors/ReactorDispatcher.ts +27 -2
  274. package/reactors/ReactorObservationTarget.ts +48 -0
  275. package/reactors/ReactorPageDispatcher.ts +321 -0
  276. package/reactors/Reactors.ts +22 -164
  277. package/reactors/for_Reactors/given/observe_reactor_messages.ts +72 -0
  278. package/reactors/for_Reactors/when_delivering_pages/as_a_legacy_single_partition.spec.ts +51 -0
  279. package/reactors/for_Reactors/when_delivering_pages/returning_a_value_from_a_batch_method.spec.ts +34 -0
  280. package/reactors/for_Reactors/when_delivering_pages/with_batch_and_per_event_methods.spec.ts +81 -0
  281. package/reactors/for_Reactors/when_delivering_pages/with_batch_outcomes.spec.ts +86 -0
  282. package/reactors/for_Reactors/when_delivering_pages/with_per_event_handlers.spec.ts +52 -0
  283. package/reactors/index.ts +2 -0
  284. package/reducers/ReducerEventDispatcher.ts +44 -3
  285. package/reducers/Reducers.ts +109 -25
  286. package/reducers/ReductionOutcome.ts +55 -8
  287. package/reducers/for_Reducers/given/observe_reducer_messages.ts +77 -0
  288. package/reducers/for_Reducers/when_delivering_pages/to_a_batch_reducer.spec.ts +111 -0
  289. package/reducers/for_Reducers/when_delivering_pages/to_a_per_event_reducer.spec.ts +53 -0
  290. package/reducers/index.ts +2 -0
  291. package/schemas/JsonSchema.ts +2 -0
  292. package/telemetry/for_ChronicleTelemetry/given/a_client.fixture.ts +1 -0
  293. package/telemetry/for_ChronicleTelemetry/given/a_span_name_registry.fixture.ts +2 -0
  294. package/telemetry/for_ChronicleTelemetry/when_naming_spans/with_convention_names.spec.ts +2 -1
  295. package/testing/InProcessEventSequence.ts +1 -0
  296. package/testing/ReactorScenario.ts +5 -1
  297. package/testing/ReducerReadModelProcessor.ts +44 -0
  298. package/testing/for_ReactorScenario/when_the_reactor_has_a_batch_method.spec.ts +26 -0
  299. package/testing/for_ReadModelScenario/when_reducing_with_a_batch_method/with_events_for_two_event_sources.spec.ts +43 -0
@@ -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 'reflect-metadata';
5
+ import { Constructor } from '@cratis/fundamentals';
6
+
7
+ /** Metadata key used to store the compensated event type on a class. */
8
+ const COMPENSATION_FOR_METADATA_KEY = 'chronicle:compensationFor';
9
+
10
+ /**
11
+ * TypeScript decorator that declares an event type as a compensation for another event type.
12
+ * This is the TypeScript equivalent of the C# `[CompensationFor<TEventType>]` attribute.
13
+ *
14
+ * Chronicle registers the link with the event type's schema. A compensation event type can compensate
15
+ * for one event type, and is appended with `IEventSequence.compensate()`.
16
+ *
17
+ * Apply it together with {@link eventType}; the order of the decorators does not matter.
18
+ *
19
+ * @param compensated - The class of the event type being compensated for.
20
+ * @returns A class decorator.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * @eventType()
25
+ * class EntryPosted { constructor(readonly amount: number) {} }
26
+ *
27
+ * @eventType()
28
+ * @compensationFor(EntryPosted)
29
+ * class EntryReversed { constructor(readonly reason: string) {} }
30
+ * ```
31
+ */
32
+ export function compensationFor(compensated: Constructor): (target: object, context?: ClassDecoratorContext) => void {
33
+ return (target: object, context?: ClassDecoratorContext) => {
34
+ Reflect.defineMetadata(COMPENSATION_FOR_METADATA_KEY, compensated, target);
35
+ context?.addInitializer(function () {
36
+ Reflect.defineMetadata(COMPENSATION_FOR_METADATA_KEY, compensated, this as object);
37
+ });
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Gets the class of the event type that a class declared as a compensation with {@link compensationFor} compensates for.
43
+ * @param target - The class constructor to inspect.
44
+ * @returns The compensated event class, or undefined when the class is not a compensation.
45
+ */
46
+ export function getCompensatedTypeFor(target: Function): Constructor | undefined {
47
+ return Reflect.getMetadata(COMPENSATION_FOR_METADATA_KEY, target) as Constructor | undefined;
48
+ }
@@ -6,6 +6,7 @@ import { Constructor } from '@cratis/fundamentals';
6
6
  import { EventType } from './EventType.js';
7
7
  import { EventTypeId } from './EventTypeId.js';
8
8
  import { EventTypeGeneration } from './EventTypeGeneration.js';
9
+ import { getCompensatedTypeFor } from './compensationForDecorator.js';
9
10
  import { DecoratorType, TypeDiscoverer, TypeIntrospector } from '../types/index.js';
10
11
  import { JsonSchema, JsonSchemaGenerator } from '../schemas/index.js';
11
12
  import { ChronicleClassDecorator } from '../types/standardDecoratorMetadata.js';
@@ -162,9 +163,17 @@ export function getEventTypeMetadata(target: Function): EventTypeMetadata | unde
162
163
  */
163
164
  export function getEventTypeJsonSchemaFor(target: Function): JsonSchema {
164
165
  const metadata = getEventTypeMetadata(target);
165
- if (metadata) {
166
- return metadata.schema;
167
- }
166
+ const schema = metadata ? metadata.schema : JsonSchemaGenerator.createEmptySchema(target.name);
167
+ const compensated = getCompensatedEventTypeIdFor(target);
168
+ return compensated ? { ...schema, compensationFor: compensated.value } : schema;
169
+ }
168
170
 
169
- return JsonSchemaGenerator.createEmptySchema(target.name);
171
+ /**
172
+ * Gets the identifier of the event type that a class declared with `@compensationFor` compensates for.
173
+ * @param target - The class constructor to inspect.
174
+ * @returns The compensated event type identifier, or undefined when the class is not a compensation.
175
+ */
176
+ export function getCompensatedEventTypeIdFor(target: Function): EventTypeId | undefined {
177
+ const compensated = getCompensatedTypeFor(target);
178
+ return compensated ? getEventTypeFor(compensated as unknown as Function).id : undefined;
170
179
  }
package/events/index.ts CHANGED
@@ -7,7 +7,8 @@ export { handles } from './handles.js';
7
7
  export { EventType } from './EventType.js';
8
8
  export { EventTypeId } from './EventTypeId.js';
9
9
  export { EventTypeGeneration } from './EventTypeGeneration.js';
10
- export { eventType, getEventTypeFor, hasEventType, getEventTypeMetadata, getEventTypeJsonSchemaFor } from './eventTypeDecorator.js';
10
+ export { eventType, getEventTypeFor, hasEventType, getEventTypeMetadata, getEventTypeJsonSchemaFor, getCompensatedEventTypeIdFor } from './eventTypeDecorator.js';
11
+ export { compensationFor, getCompensatedTypeFor } from './compensationForDecorator.js';
11
12
  export type { EventTypeMetadata } from './eventTypeDecorator.js';
12
13
  export type { EventContext } from './EventContext.js';
13
14
  export type { CausationEntry } from './CausationEntry.js';
@@ -10,6 +10,9 @@ import { EventTypeId } from './EventTypeId.js';
10
10
  import { Tag } from './Tag.js';
11
11
  import { NamedTag } from './NamedTag.js';
12
12
  import type { WireEventContext } from './WireEventContext.js';
13
+ import { DecoratorType } from '../types/DecoratorType.js';
14
+ import { TypeDiscoverer } from '../types/TypeDiscoverer.js';
15
+ import { getCompensatedTypeFor } from './compensationForDecorator.js';
13
16
 
14
17
  /** Converts kernel metadata identically for reads, reactors, and reducers. */
15
18
  export function toClientEventContext(context: WireEventContext): EventContext {
@@ -38,6 +41,7 @@ export function toClientEventContext(context: WireEventContext): EventContext {
38
41
  occurred: causation.Occurred ? new Date(causation.Occurred.Value) : undefined,
39
42
  properties: { ...causation.Properties }
40
43
  })),
44
+ compensationFor: toClientCompensationFor(context),
41
45
  tags: (context.Tags ?? []).map(value => new Tag(value)),
42
46
  namedTags: (context.NamedTags ?? []).map(tag => new NamedTag(tag.Name, tag.Value))
43
47
  };
@@ -46,3 +50,20 @@ export function toClientEventContext(context: WireEventContext): EventContext {
46
50
  function toClientIdentity(identity: WireEventContext['CausedBy']): Identity | undefined {
47
51
  return identity ? new Identity(identity.Subject, identity.Name, identity.UserName, toClientIdentity(identity.OnBehalfOf)) : undefined;
48
52
  }
53
+
54
+ /**
55
+ * The wire format carries an unset compensation as zero, which is also a valid sequence number. Zero is therefore
56
+ * only a compensation when the event type is a registered compensation event type.
57
+ */
58
+ function toClientCompensationFor(context: WireEventContext): bigint | undefined {
59
+ const compensationFor = context.CompensationFor;
60
+ if (compensationFor === undefined) {
61
+ return undefined;
62
+ }
63
+ if (compensationFor !== 0n) {
64
+ return compensationFor;
65
+ }
66
+ const eventTypeId = context.EventType?.Id;
67
+ const type = eventTypeId ? TypeDiscoverer.default.getTypeByDecoratorTypeAndName(DecoratorType.EventType, eventTypeId) : undefined;
68
+ return type && getCompensatedTypeFor(type) ? 0n : undefined;
69
+ }
@@ -0,0 +1,75 @@
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 } from './ObservationOrigin.js';
5
+ import type { BatchContextValues } from './BatchContextValues.js';
6
+
7
+ /**
8
+ * Describes the page of events a batch method is called for. It is read-only, and only batch methods receive it:
9
+ * per-event methods never get a {@link BatchContext}.
10
+ */
11
+ export class BatchContext {
12
+ /** The identifier of the observer (reactor or reducer). */
13
+ readonly observerId: string;
14
+
15
+ /** The event store the events come from. */
16
+ readonly eventStore: string;
17
+
18
+ /** The namespace the events come from. */
19
+ readonly namespace: string;
20
+
21
+ /** The event sequence the events come from. */
22
+ readonly eventSequenceId: string;
23
+
24
+ /** The path the page came from: live, catch-up, replay or retry. */
25
+ readonly origin: ObservationOrigin;
26
+
27
+ /** The partitions (event source identifiers) in the page, in the order the kernel delivered them. */
28
+ readonly partitions: readonly string[];
29
+
30
+ /** The number of events in the page. */
31
+ readonly eventCount: number;
32
+
33
+ /** The sequence number of the first event in the page, or undefined when the page is empty. */
34
+ readonly firstSequenceNumber: bigint | undefined;
35
+
36
+ /** The sequence number of the last event in the page, or undefined when the page is empty. */
37
+ readonly lastSequenceNumber: bigint | undefined;
38
+
39
+ /** When the kernel stops waiting for the result, or undefined when it waits without a deadline. */
40
+ readonly deadline: Date | undefined;
41
+
42
+ /** Aborted when the observation disconnects or the client is disposed. */
43
+ readonly signal: AbortSignal;
44
+
45
+ /**
46
+ * Whether the kernel accepts deferred partitions for this page. A kernel that delivers single partitions
47
+ * instead of pages cannot defer; a deferral is then reported as a failure.
48
+ */
49
+ readonly canDefer: boolean;
50
+
51
+ /**
52
+ * Creates a new {@link BatchContext}.
53
+ * @param values - The values describing the page.
54
+ */
55
+ constructor(values: BatchContextValues) {
56
+ this.observerId = values.observerId;
57
+ this.eventStore = values.eventStore;
58
+ this.namespace = values.namespace;
59
+ this.eventSequenceId = values.eventSequenceId;
60
+ this.origin = values.origin;
61
+ this.partitions = Object.freeze([...values.partitions]);
62
+ this.eventCount = values.eventCount;
63
+ this.firstSequenceNumber = values.firstSequenceNumber;
64
+ this.lastSequenceNumber = values.lastSequenceNumber;
65
+ this.deadline = values.deadline;
66
+ this.signal = values.signal;
67
+ this.canDefer = values.canDefer;
68
+ Object.freeze(this);
69
+ }
70
+
71
+ /** Whether the page is part of a replay. */
72
+ get isReplay(): boolean {
73
+ return this.origin === ObservationOrigin.Replay;
74
+ }
75
+ }
@@ -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
+ /** The observer a {@link BatchContext} is created for. */
5
+ export type BatchContextObserver = {
6
+ /** The identifier of the observer. */
7
+ readonly observerId: string;
8
+ /** The event store the observer is registered with. */
9
+ readonly eventStore: string;
10
+ /** The namespace the observer is registered in. */
11
+ readonly namespace: string;
12
+ /** The event sequence the observer observes. */
13
+ readonly eventSequenceId: string;
14
+ /** Aborted when the observation stops. */
15
+ readonly signal: AbortSignal;
16
+ };
@@ -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 { BatchContextObserver } from './BatchContextObserver.js';
5
+ import type { ObservationOrigin } from './ObservationOrigin.js';
6
+
7
+ /** The values a {@link BatchContext} is created from. See {@link BatchContext} for what each value means. */
8
+ export type BatchContextValues = BatchContextObserver & {
9
+ readonly origin: ObservationOrigin;
10
+ readonly partitions: readonly string[];
11
+ readonly eventCount: number;
12
+ readonly firstSequenceNumber: bigint | undefined;
13
+ readonly lastSequenceNumber: bigint | undefined;
14
+ readonly deadline: Date | undefined;
15
+ readonly canDefer: boolean;
16
+ };
@@ -0,0 +1,13 @@
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 { ObservedEventType } from './ObservedEventType.js';
5
+
6
+ /** A method of an observer that takes an {@link EventBatch}. */
7
+ export interface BatchMethod {
8
+ /** The name of the method. */
9
+ readonly methodName: string;
10
+
11
+ /** The event types the method observes, by event type identifier. */
12
+ readonly eventTypes: ReadonlyMap<string, ObservedEventType>;
13
+ }
@@ -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
+ /** Reported when a reactor batch method returns a value. Batch reactor methods do not return events or other side effects. */
5
+ export class BatchMethodReturnedAValue extends Error {
6
+ /**
7
+ * Creates a new {@link BatchMethodReturnedAValue}.
8
+ * @param observerType - The name of the reactor class.
9
+ * @param method - The name of the batch method.
10
+ */
11
+ constructor(readonly observerType: string, readonly method: string) {
12
+ super(`Batch method '${method}' on reactor '${observerType}' returned a value. Batch reactor methods return nothing; ` +
13
+ 'append through an event log instead of returning events.');
14
+ this.name = 'BatchMethodReturnedAValue';
15
+ }
16
+ }
@@ -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
+ }