@cratis/chronicle 6.71.2 → 6.72.1

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 (131) hide show
  1. package/dist/reactors/AsyncQueue.d.ts +10 -0
  2. package/dist/reactors/AsyncQueue.d.ts.map +1 -0
  3. package/dist/reactors/AsyncQueue.js +42 -0
  4. package/dist/reactors/AsyncQueue.js.map +1 -0
  5. package/dist/reactors/IReactorBuilder.d.ts +12 -0
  6. package/dist/reactors/IReactorBuilder.d.ts.map +1 -0
  7. package/dist/reactors/IReactorBuilder.js +4 -0
  8. package/dist/reactors/IReactorBuilder.js.map +1 -0
  9. package/dist/reactors/IReactorDefinition.d.ts +14 -0
  10. package/dist/reactors/IReactorDefinition.d.ts.map +1 -0
  11. package/dist/reactors/IReactorDefinition.js +4 -0
  12. package/dist/reactors/IReactorDefinition.js.map +1 -0
  13. package/dist/reactors/IReactorDefinitionBuilder.d.ts +9 -0
  14. package/dist/reactors/IReactorDefinitionBuilder.d.ts.map +1 -0
  15. package/dist/reactors/IReactorDefinitionBuilder.js +4 -0
  16. package/dist/reactors/IReactorDefinitionBuilder.js.map +1 -0
  17. package/dist/reactors/IReactors.d.ts +21 -10
  18. package/dist/reactors/IReactors.d.ts.map +1 -1
  19. package/dist/reactors/ReactorBuilder.d.ts +32 -0
  20. package/dist/reactors/ReactorBuilder.d.ts.map +1 -0
  21. package/dist/reactors/ReactorBuilder.js +91 -0
  22. package/dist/reactors/ReactorBuilder.js.map +1 -0
  23. package/dist/reactors/ReactorCallback.d.ts +4 -0
  24. package/dist/reactors/ReactorCallback.d.ts.map +1 -0
  25. package/dist/reactors/ReactorCallback.js +4 -0
  26. package/dist/reactors/ReactorCallback.js.map +1 -0
  27. package/dist/reactors/ReactorEvent.d.ts +7 -0
  28. package/dist/reactors/ReactorEvent.d.ts.map +1 -0
  29. package/dist/reactors/ReactorEvent.js +4 -0
  30. package/dist/reactors/ReactorEvent.js.map +1 -0
  31. package/dist/reactors/ReactorObservation.d.ts +21 -0
  32. package/dist/reactors/ReactorObservation.d.ts.map +1 -0
  33. package/dist/reactors/ReactorObservation.js +43 -0
  34. package/dist/reactors/ReactorObservation.js.map +1 -0
  35. package/dist/reactors/ReactorObservationTarget.d.ts +4 -1
  36. package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -1
  37. package/dist/reactors/ReactorPageDispatcher.d.ts +6 -0
  38. package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -1
  39. package/dist/reactors/ReactorPageDispatcher.js +96 -51
  40. package/dist/reactors/ReactorPageDispatcher.js.map +1 -1
  41. package/dist/reactors/ReactorRegistration.d.ts +14 -0
  42. package/dist/reactors/ReactorRegistration.d.ts.map +1 -0
  43. package/dist/reactors/ReactorRegistration.js +4 -0
  44. package/dist/reactors/ReactorRegistration.js.map +1 -0
  45. package/dist/reactors/ReactorRegistrationKind.d.ts +7 -0
  46. package/dist/reactors/ReactorRegistrationKind.d.ts.map +1 -0
  47. package/dist/reactors/ReactorRegistrationKind.js +10 -0
  48. package/dist/reactors/ReactorRegistrationKind.js.map +1 -0
  49. package/dist/reactors/ReactorRegistrations.d.ts +17 -0
  50. package/dist/reactors/ReactorRegistrations.d.ts.map +1 -0
  51. package/dist/reactors/ReactorRegistrations.js +42 -0
  52. package/dist/reactors/ReactorRegistrations.js.map +1 -0
  53. package/dist/reactors/ReactorSubscription.d.ts +4 -0
  54. package/dist/reactors/ReactorSubscription.d.ts.map +1 -0
  55. package/dist/reactors/ReactorSubscription.js +4 -0
  56. package/dist/reactors/ReactorSubscription.js.map +1 -0
  57. package/dist/reactors/Reactors.d.ts +31 -38
  58. package/dist/reactors/Reactors.d.ts.map +1 -1
  59. package/dist/reactors/Reactors.js +143 -274
  60. package/dist/reactors/Reactors.js.map +1 -1
  61. package/dist/reactors/WaitTillSubscribedOptions.d.ts +7 -0
  62. package/dist/reactors/WaitTillSubscribedOptions.d.ts.map +1 -0
  63. package/dist/reactors/WaitTillSubscribedOptions.js +4 -0
  64. package/dist/reactors/WaitTillSubscribedOptions.js.map +1 -0
  65. package/dist/reactors/index.d.ts +5 -0
  66. package/dist/reactors/index.d.ts.map +1 -1
  67. package/dist/reactors/index.js.map +1 -1
  68. package/dist/reactors/prepareReactor.d.ts +34 -0
  69. package/dist/reactors/prepareReactor.d.ts.map +1 -0
  70. package/dist/reactors/prepareReactor.js +75 -0
  71. package/dist/reactors/prepareReactor.js.map +1 -0
  72. package/dist/reactors/waitTillSubscribed.d.ts +5 -0
  73. package/dist/reactors/waitTillSubscribed.d.ts.map +1 -0
  74. package/dist/reactors/waitTillSubscribed.js +29 -0
  75. package/dist/reactors/waitTillSubscribed.js.map +1 -0
  76. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.d.ts +145 -0
  77. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.d.ts.map +1 -0
  78. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.js +142 -0
  79. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.js.map +1 -0
  80. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.d.ts +24 -0
  81. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.d.ts.map +1 -0
  82. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.js +34 -0
  83. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.js.map +1 -0
  84. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.d.ts +7 -0
  85. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.d.ts.map +1 -0
  86. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.js +33 -0
  87. package/dist/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.js.map +1 -0
  88. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.js +1 -1
  89. package/dist/testing/projections/ProjectionArithmeticChildrenCapabilities.js.map +1 -1
  90. package/dist/tsconfig.tsbuildinfo +1 -1
  91. package/package.json +2 -2
  92. package/reactors/AsyncQueue.ts +41 -0
  93. package/reactors/IReactorBuilder.ts +15 -0
  94. package/reactors/IReactorDefinition.ts +17 -0
  95. package/reactors/IReactorDefinitionBuilder.ts +12 -0
  96. package/reactors/IReactors.ts +25 -10
  97. package/reactors/ReactorBuilder.ts +98 -0
  98. package/reactors/ReactorCallback.ts +7 -0
  99. package/reactors/ReactorEvent.ts +10 -0
  100. package/reactors/ReactorObservation.ts +45 -0
  101. package/reactors/ReactorObservationTarget.ts +4 -1
  102. package/reactors/ReactorPageDispatcher.ts +98 -54
  103. package/reactors/ReactorRegistration.ts +11 -0
  104. package/reactors/ReactorRegistrationKind.ts +9 -0
  105. package/reactors/ReactorRegistrations.ts +45 -0
  106. package/reactors/ReactorSubscription.ts +7 -0
  107. package/reactors/Reactors.ts +156 -310
  108. package/reactors/WaitTillSubscribedOptions.ts +9 -0
  109. package/reactors/for_Reactors/given/runtime_reactors.fixture.ts +50 -0
  110. package/reactors/for_Reactors/when_a_class_reactor_fails_to_restart.spec.ts +67 -0
  111. package/reactors/for_Reactors/when_a_class_reactor_fails_to_start.spec.ts +80 -0
  112. package/reactors/for_Reactors/when_class_delivery_is_unregistered.spec.ts +62 -0
  113. package/reactors/for_Reactors/when_defining_runtime_reactors.spec.ts +77 -0
  114. package/reactors/for_Reactors/when_dispatching_runtime_reactors.spec.ts +94 -0
  115. package/reactors/for_Reactors/when_registering_runtime_reactors.spec.ts +102 -0
  116. package/reactors/for_Reactors/when_stopping_runtime_reactors.spec.ts +160 -0
  117. package/reactors/for_Reactors/when_using_the_default_artifacts_provider.spec.ts +80 -0
  118. package/reactors/for_Reactors/when_waiting_till_subscribed.spec.ts +65 -0
  119. package/reactors/index.ts +5 -0
  120. package/reactors/prepareReactor.ts +79 -0
  121. package/reactors/waitTillSubscribed.ts +29 -0
  122. package/testing/for_ReadModelScenario/when_subtracting_with_children/given/compiled_projection.ts +71 -0
  123. package/testing/for_ReadModelScenario/when_subtracting_with_children/given/lifecycle.ts +38 -0
  124. package/testing/for_ReadModelScenario/when_subtracting_with_children/given/oracle_input.ts +36 -0
  125. package/testing/for_ReadModelScenario/when_subtracting_with_children/with_a_fluent_projection.spec.ts +40 -0
  126. package/testing/for_ReadModelScenario/when_subtracting_with_children/with_legacy_decorators.legacy.spec.ts +50 -0
  127. package/testing/for_ReadModelScenario/when_subtracting_with_children/with_standard_decorators.standard.spec.ts +51 -0
  128. package/testing/projections/ProjectionArithmeticChildrenCapabilities.ts +1 -1
  129. package/testing/projections/for_ProjectionCapabilities/when_validating_add_with_children.spec.ts +1 -1
  130. package/testing/projections/for_ProjectionCapabilities/when_validating_count_with_children.spec.ts +11 -9
  131. package/testing/projections/for_ProjectionCapabilities/when_validating_subtract_with_children.spec.ts +105 -0
@@ -0,0 +1,45 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { EventsToObserve, ReactorMessage } from '@cratis/chronicle.contracts';
5
+ import { AsyncQueue } from './AsyncQueue.js';
6
+ import type { ReactorRegistration } from './ReactorRegistration.js';
7
+ import type { ReactorPageDispatcher } from './ReactorPageDispatcher.js';
8
+
9
+ /** One stream attempt, whose identity is never reused by reconnect or same-ID replacement. */
10
+ export class ReactorObservation {
11
+ readonly queue = new AsyncQueue<ReactorMessage>();
12
+ readonly controller = new AbortController();
13
+ private _iterator?: AsyncIterator<EventsToObserve>;
14
+
15
+ constructor(readonly registration: ReactorRegistration, readonly connectionId: string) {}
16
+
17
+ /** Local teardown does not wait for a server response or an uncooperative callback. */
18
+ stop(): void {
19
+ this.controller.abort();
20
+ this.queue.complete();
21
+ void this._iterator?.return?.()?.catch(() => undefined);
22
+ }
23
+
24
+ /** Only transport failures escape through the supplied classifier. */
25
+ async observe(stream: AsyncIterable<EventsToObserve>, dispatcher: ReactorPageDispatcher, callbacks: {
26
+ delivered: () => void;
27
+ failed: (error: unknown) => import('../observation/ObservationStreamOutcome.js').ObservationStreamOutcome;
28
+ }): Promise<import('../observation/ObservationStreamOutcome.js').ObservationStreamOutcome> {
29
+ this._iterator = stream[Symbol.asyncIterator]();
30
+ while (!this.controller.signal.aborted) {
31
+ let next: IteratorResult<EventsToObserve>;
32
+ try {
33
+ next = await this._iterator.next();
34
+ } catch (error) {
35
+ return callbacks.failed(error);
36
+ }
37
+ if (next.done) return 'ended';
38
+ if (this.controller.signal.aborted) return 'stopped';
39
+ callbacks.delivered();
40
+ const result = await dispatcher.dispatch(next.value);
41
+ this.queue.send({ Content: { Value0: undefined, Value1: result } });
42
+ }
43
+ return 'stopped';
44
+ }
45
+ }
@@ -2,6 +2,7 @@
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
4
  import type { Constructor } from '@cratis/fundamentals';
5
+ import type { IReactorDefinition } from './IReactorDefinition.js';
5
6
  import type { ClientArtifactsActivator } from '../artifacts/ClientArtifactsActivator.js';
6
7
  import type { IEventLog } from '../eventSequences/IEventLog.js';
7
8
  import type { createLogger } from '../logging/createLogger.js';
@@ -16,7 +17,9 @@ export interface ReactorObservationTarget {
16
17
  /** The reactor identifier. */
17
18
  readonly id: string;
18
19
  /** The reactor class. */
19
- readonly reactorType: Constructor;
20
+ readonly reactorType: Constructor | undefined;
21
+ /** The runtime callback, absent for discovered class reactors. */
22
+ readonly runtime?: IReactorDefinition;
20
23
  /** The event sequence the reactor observes. */
21
24
  readonly eventSequenceId: string;
22
25
  /** The event store the reactor is registered with. */
@@ -78,7 +78,7 @@ export class ReactorPageDispatcher {
78
78
  try {
79
79
  if (artifactActivator && message.ReplayState !== ReplayState.REPLAY_STATE_None) {
80
80
  if (!services) throw new Error('Reactor activation requires the owning event store.');
81
- await withActivatedArtifact(reactorType, {
81
+ await withActivatedArtifact(reactorType!, {
82
82
  kind: ArtifactKind.Reactor, artifactId: id, eventStore: services.eventStore,
83
83
  readModels: services.readModels, eventSequenceId, partition: message.Partition,
84
84
  signal, delivery: ArtifactDelivery.ReplayNotification, replayState: message.ReplayState
@@ -94,15 +94,18 @@ export class ReactorPageDispatcher {
94
94
  return undefined;
95
95
  } catch (error) {
96
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
- }));
97
+ return this.replayFailures(partitions, error);
103
98
  }
104
99
  }
105
100
 
101
+ private replayFailures(partitions: readonly DeliveredPartition[], error: unknown): PartitionProblem[] {
102
+ const messages = error instanceof ArtifactCompletionFailed && error.processingError !== undefined
103
+ ? [String(error.processingError), String(error)] : [String(error)];
104
+ return partitions.map(partition => ({
105
+ ...failedAt(partition.partition, firstSequenceNumberOf(partition), error), exceptionMessages: messages
106
+ }));
107
+ }
108
+
106
109
  private async observe(message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
107
110
  const { id, reactorType, eventSequenceId, services, signal, artifactActivator, reactorInstance, validateInstance } = this._target;
108
111
  const first = artifactActivator ? this.firstInvocableEvent(partitions) : undefined;
@@ -131,17 +134,21 @@ export class ReactorPageDispatcher {
131
134
  private firstInvocableEvent(partitions: readonly DeliveredPartition[]): { partition: string; event: AppendedEvent } | undefined {
132
135
  for (const partition of partitions) {
133
136
  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 };
137
+ if (this.isInvocable(event)) return { partition: partition.partition, event };
138
138
  }
139
139
  }
140
140
  return undefined;
141
141
  }
142
142
 
143
+ private isInvocable(event: AppendedEvent): boolean {
144
+ const eventTypeId = event.Context?.EventType?.Id;
145
+ if (eventTypeId && this._batchEventTypes.has(eventTypeId)) return true;
146
+ const selection = this.select(this._target.reactorInstance, event);
147
+ return !!selection?.methodName && !selection.skipReplay;
148
+ }
149
+
143
150
  private select(instance: ReactorInstance | undefined, event: AppendedEvent) {
144
- return selectReactorHandler(this._target.entries, this._target.reactorType, instance,
151
+ return selectReactorHandler(this._target.entries, this._target.reactorType!, instance,
145
152
  event.Context?.EventType?.Id, event.Context?.ObservationState ?? 0);
146
153
  }
147
154
 
@@ -160,22 +167,12 @@ export class ReactorPageDispatcher {
160
167
  private async observeBatches(artifact: Artifact, message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
161
168
  const problems: PartitionProblem[] = [];
162
169
  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);
170
+ for (const partition of partitions) this.collectBatchEvents(partition, events, problems);
171
+ events.sort(comparePageEvents);
176
172
 
177
173
  const context = this.createBatchContext(message, partitions);
178
174
  for (const method of this._target.batchMethods) {
175
+ if (this._target.signal.aborted) break;
179
176
  const observed = events.filter(event => method.eventTypes.has(event.event.context.eventType.id.value));
180
177
  if (observed.length === 0) continue;
181
178
  problems.push(...await this.invokeBatchMethod(artifact, method, observed, context));
@@ -183,6 +180,18 @@ export class ReactorPageDispatcher {
183
180
  return problems;
184
181
  }
185
182
 
183
+ private collectBatchEvents(partition: DeliveredPartition, events: PageEvent[], problems: PartitionProblem[]): void {
184
+ for (const event of partition.events) {
185
+ const batchEventType = this._batchEventTypes.get(event.Context?.EventType?.Id ?? '');
186
+ if (!batchEventType) continue;
187
+ try {
188
+ events.push({ partition: partition.partition, event: this.toEventAndContext(event, batchEventType.type) });
189
+ } catch (error) {
190
+ problems.push(failedAt(partition.partition, event.Context!.SequenceNumber, error));
191
+ }
192
+ }
193
+ }
194
+
186
195
  private async invokeBatchMethod(artifact: Artifact, method: BatchMethod, observed: readonly PageEvent[], context: BatchContext): Promise<PartitionProblem[]> {
187
196
  const { id, reactorType } = this._target;
188
197
  const batch = new EventBatch(observed.map(event => event.event), context.canDefer);
@@ -209,43 +218,72 @@ export class ReactorPageDispatcher {
209
218
  }
210
219
  }
211
220
 
212
- private async observePartition(artifact: Artifact, partition: DeliveredPartition): Promise<PartitionProblem | undefined> {
213
- const { id, reactorType, eventStoreName, namespace, services, eventLog, resultHandler } = this._target;
221
+ private async observeRuntimePartition(partition: DeliveredPartition): Promise<PartitionProblem | undefined> {
214
222
  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
-
223
+ if (this._target.signal.aborted) break;
224
+ if (!event.Context?.EventType) continue;
232
225
  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));
226
+ await this._target.runtime!.handle({
227
+ content: JSON.parse(event.Content), context: toClientEventContext(event.Context)
228
+ }, this._target.signal);
241
229
  } catch (error) {
242
- this._target.logger.error('Error handling event in reactor', { reactorId: id, error });
243
- return failedAt(partition.partition, event.Context!.SequenceNumber, error);
230
+ this._target.logger.error('Error handling event in reactor', { reactorId: this._target.id, error });
231
+ return failedAt(partition.partition, event.Context.SequenceNumber, error);
244
232
  }
245
233
  }
246
234
  return undefined;
247
235
  }
248
236
 
237
+ private async observePartition(artifact: Artifact, partition: DeliveredPartition): Promise<PartitionProblem | undefined> {
238
+ if (this._target.runtime) return this.observeRuntimePartition(partition);
239
+ for (const event of partition.events) {
240
+ if (this._target.signal.aborted) break;
241
+ const problem = await this.observeClassEvent(artifact, partition.partition, event);
242
+ if (problem) return problem;
243
+ }
244
+ return undefined;
245
+ }
246
+
247
+ private async observeClassEvent(artifact: Artifact, partition: string, event: AppendedEvent): Promise<PartitionProblem | undefined> {
248
+ const { id, reactorType, eventStoreName, namespace, services, eventLog, resultHandler } = this._target;
249
+ const eventTypeId = event.Context?.EventType?.Id;
250
+ if (!eventTypeId) {
251
+ this._target.logger.warn('Event missing event type context', { reactorId: id });
252
+ return undefined;
253
+ }
254
+ if (this._batchEventTypes.has(eventTypeId)) return undefined;
255
+
256
+ const selection = this.select(artifact.instance, event);
257
+ if (!selection?.methodName || selection.skipReplay) {
258
+ this.logSkippedHandler(eventTypeId, selection);
259
+ return undefined;
260
+ }
261
+
262
+ try {
263
+ const content = JSON.parse(event.Content) as Record<string, unknown>;
264
+ const context = toClientEventContext(event.Context!);
265
+ this._target.logger.info('Invoking reactor handler', {
266
+ reactorId: id, method: selection.methodName, sequenceNumber: event.Context!.SequenceNumber.toString(), eventTypeId
267
+ });
268
+ await invokeReactorHandler(artifact, selection.methodName, content, context, services, result =>
269
+ dispatchReactorSideEffects(eventLog, result, context, reactorType as Function, eventStoreName, namespace, resultHandler),
270
+ this.deliveryFor(context));
271
+ } catch (error) {
272
+ this._target.logger.error('Error handling event in reactor', { reactorId: id, error });
273
+ return failedAt(partition, event.Context!.SequenceNumber, error);
274
+ }
275
+ return undefined;
276
+ }
277
+
278
+ private logSkippedHandler(eventTypeId: string, selection: ReturnType<ReactorPageDispatcher['select']>): void {
279
+ const { id } = this._target;
280
+ if (selection?.skipReplay) {
281
+ this._target.logger.debug('Reactor handler skipped for replay', { reactorId: id, eventTypeId, method: selection.methodName });
282
+ } else {
283
+ this._target.logger.debug('No reactor handler found', { reactorId: id, eventTypeId, isReplay: selection?.isReplay ?? false });
284
+ }
285
+ }
286
+
249
287
  private toEventAndContext(event: AppendedEvent, eventType: Constructor): EventAndContext {
250
288
  const context = toClientEventContext(event.Context!);
251
289
  return new EventAndContext(JSON.parse(event.Content) as Record<string, unknown>, context, eventType, this.deliveryFor(context));
@@ -263,6 +301,12 @@ export class ReactorPageDispatcher {
263
301
  }
264
302
  }
265
303
 
304
+ function comparePageEvents(left: PageEvent, right: PageEvent): number {
305
+ const first = left.event.context.sequenceNumber;
306
+ const second = right.event.context.sequenceNumber;
307
+ return first < second ? -1 : first > second ? 1 : 0;
308
+ }
309
+
266
310
  /**
267
311
  * Gets the sequence number of the first event of a partition, or zero when it has none.
268
312
  * @param partition - The partition.
@@ -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
+ import type { Constructor } from '@cratis/fundamentals';
5
+ import type { IReactorDefinition } from './IReactorDefinition.js';
6
+ import { ReactorRegistrationKind } from './ReactorRegistrationKind.js';
7
+
8
+ /** The identity retained independently of any particular observation attempt. */
9
+ export type ReactorRegistration =
10
+ { readonly id: string; readonly kind: ReactorRegistrationKind.Discovered; readonly type: Constructor } |
11
+ { readonly id: string; readonly kind: ReactorRegistrationKind.Fluent | ReactorRegistrationKind.Delegate; readonly definition: IReactorDefinition };
@@ -0,0 +1,9 @@
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
+ /** Describes how a local registration was authored. */
5
+ export enum ReactorRegistrationKind {
6
+ Discovered = 'discovered',
7
+ Fluent = 'fluent',
8
+ Delegate = 'delegate'
9
+ }
@@ -0,0 +1,45 @@
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 { getReactorMetadata } from './reactor.js';
6
+ import type { ReactorRegistration } from './ReactorRegistration.js';
7
+ import { ReactorRegistrationKind } from './ReactorRegistrationKind.js';
8
+
9
+ /** Coordinates discovery and runtime identities before any observation is opened. */
10
+ export class ReactorRegistrations {
11
+ private readonly _entries = new Map<string, ReactorRegistration>();
12
+ private readonly _removed = new Set<string>();
13
+
14
+ get all(): readonly ReactorRegistration[] { return [...this._entries.values()]; }
15
+
16
+ /** Validates the entire discovery batch before committing it. */
17
+ discover(types: readonly Constructor[]): void {
18
+ const discovered = new Map<string, ReactorRegistration>();
19
+ for (const type of types) {
20
+ const id = getReactorMetadata(type)?.id.value;
21
+ if (id === undefined || this._removed.has(id)) continue;
22
+ if (discovered.has(id)) this.duplicate(id);
23
+ const existing = this._entries.get(id);
24
+ if (existing && !(existing.kind === ReactorRegistrationKind.Discovered && existing.type === type)) this.duplicate(id);
25
+ discovered.set(id, existing ?? { id, kind: ReactorRegistrationKind.Discovered, type });
26
+ }
27
+ for (const [id, entry] of discovered) this._entries.set(id, entry);
28
+ }
29
+
30
+ /** Reserves synchronously: local-start registration has no asynchronous acknowledgment window. */
31
+ add(entry: ReactorRegistration): void {
32
+ if (this._entries.has(entry.id)) this.duplicate(entry.id);
33
+ this._entries.set(entry.id, entry);
34
+ }
35
+
36
+ /** Removes restoration eligibility and suppresses automatic rediscovery. */
37
+ remove(id: string): void {
38
+ if (this._entries.get(id)?.kind === ReactorRegistrationKind.Discovered) this._removed.add(id);
39
+ this._entries.delete(id);
40
+ }
41
+
42
+ isCurrent(entry: ReactorRegistration): boolean { return this._entries.get(entry.id) === entry; }
43
+
44
+ private duplicate(id: string): never { throw new Error(`Reactor id '${id}' is already registered.`); }
45
+ }
@@ -0,0 +1,7 @@
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 { prepareReactor } from './prepareReactor.js';
5
+
6
+ /** A locally validated subscription, shared by subsequent observation attempts. */
7
+ export type ReactorSubscription = ReturnType<typeof prepareReactor>;