@cratis/chronicle 6.57.0 → 6.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/EventStore.ts +2 -2
- package/dist/EventStore.js +2 -2
- package/dist/EventStore.js.map +1 -1
- package/dist/observation/batches/BatchContext.d.ts +43 -0
- package/dist/observation/batches/BatchContext.d.ts.map +1 -0
- package/dist/observation/batches/BatchContext.js +60 -0
- package/dist/observation/batches/BatchContext.js.map +1 -0
- package/dist/observation/batches/BatchContextObserver.d.ts +14 -0
- package/dist/observation/batches/BatchContextObserver.d.ts.map +1 -0
- package/dist/observation/batches/BatchContextObserver.js +4 -0
- package/dist/observation/batches/BatchContextObserver.js.map +1 -0
- package/dist/observation/batches/BatchContextValues.d.ts +13 -0
- package/dist/observation/batches/BatchContextValues.d.ts.map +1 -0
- package/dist/observation/batches/BatchContextValues.js +4 -0
- package/dist/observation/batches/BatchContextValues.js.map +1 -0
- package/dist/observation/batches/BatchMethod.d.ts +9 -0
- package/dist/observation/batches/BatchMethod.d.ts.map +1 -0
- package/dist/observation/batches/BatchMethod.js +4 -0
- package/dist/observation/batches/BatchMethod.js.map +1 -0
- package/dist/observation/batches/BatchMethodReturnedAValue.d.ts +12 -0
- package/dist/observation/batches/BatchMethodReturnedAValue.d.ts.map +1 -0
- package/dist/observation/batches/BatchMethodReturnedAValue.js +20 -0
- package/dist/observation/batches/BatchMethodReturnedAValue.js.map +1 -0
- package/dist/observation/batches/BatchMethods.d.ts +31 -0
- package/dist/observation/batches/BatchMethods.d.ts.map +1 -0
- package/dist/observation/batches/BatchMethods.js +81 -0
- package/dist/observation/batches/BatchMethods.js.map +1 -0
- package/dist/observation/batches/BatchOutcome.d.ts +15 -0
- package/dist/observation/batches/BatchOutcome.d.ts.map +1 -0
- package/dist/observation/batches/BatchOutcome.js +4 -0
- package/dist/observation/batches/BatchOutcome.js.map +1 -0
- package/dist/observation/batches/BatchOutcomeKind.d.ts +8 -0
- package/dist/observation/batches/BatchOutcomeKind.d.ts.map +1 -0
- package/dist/observation/batches/BatchOutcomeKind.js +11 -0
- package/dist/observation/batches/BatchOutcomeKind.js.map +1 -0
- package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts +13 -0
- package/dist/observation/batches/DeferralNotSupportedByKernel.d.ts.map +1 -0
- package/dist/observation/batches/DeferralNotSupportedByKernel.js +19 -0
- package/dist/observation/batches/DeferralNotSupportedByKernel.js.map +1 -0
- package/dist/observation/batches/DeliveredPartition.d.ts +11 -0
- package/dist/observation/batches/DeliveredPartition.d.ts.map +1 -0
- package/dist/observation/batches/DeliveredPartition.js +4 -0
- package/dist/observation/batches/DeliveredPartition.js.map +1 -0
- package/dist/observation/batches/EventAndContext.d.ts +28 -0
- package/dist/observation/batches/EventAndContext.d.ts.map +1 -0
- package/dist/observation/batches/EventAndContext.js +35 -0
- package/dist/observation/batches/EventAndContext.js.map +1 -0
- package/dist/observation/batches/EventBatch.d.ts +52 -0
- package/dist/observation/batches/EventBatch.d.ts.map +1 -0
- package/dist/observation/batches/EventBatch.js +92 -0
- package/dist/observation/batches/EventBatch.js.map +1 -0
- package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts +14 -0
- package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.d.ts.map +1 -0
- package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js +23 -0
- package/dist/observation/batches/EventTypeObservedByMoreThanOneMethod.js.map +1 -0
- package/dist/observation/batches/InvalidBatchMethod.d.ts +13 -0
- package/dist/observation/batches/InvalidBatchMethod.d.ts.map +1 -0
- package/dist/observation/batches/InvalidBatchMethod.js +20 -0
- package/dist/observation/batches/InvalidBatchMethod.js.map +1 -0
- package/dist/observation/batches/ObservationOrigin.d.ts +21 -0
- package/dist/observation/batches/ObservationOrigin.d.ts.map +1 -0
- package/dist/observation/batches/ObservationOrigin.js +32 -0
- package/dist/observation/batches/ObservationOrigin.js.map +1 -0
- package/dist/observation/batches/ObservedEventType.d.ts +11 -0
- package/dist/observation/batches/ObservedEventType.d.ts.map +1 -0
- package/dist/observation/batches/ObservedEventType.js +4 -0
- package/dist/observation/batches/ObservedEventType.js.map +1 -0
- package/dist/observation/batches/PageMessages.d.ts +22 -0
- package/dist/observation/batches/PageMessages.d.ts.map +1 -0
- package/dist/observation/batches/PageMessages.js +32 -0
- package/dist/observation/batches/PageMessages.js.map +1 -0
- package/dist/observation/batches/PartitionFailedInBatch.d.ts +10 -0
- package/dist/observation/batches/PartitionFailedInBatch.d.ts.map +1 -0
- package/dist/observation/batches/PartitionFailedInBatch.js +16 -0
- package/dist/observation/batches/PartitionFailedInBatch.js.map +1 -0
- package/dist/observation/batches/PartitionNotInBatch.d.ts +10 -0
- package/dist/observation/batches/PartitionNotInBatch.d.ts.map +1 -0
- package/dist/observation/batches/PartitionNotInBatch.js +16 -0
- package/dist/observation/batches/PartitionNotInBatch.js.map +1 -0
- package/dist/observation/batches/PartitionOutcome.d.ts +19 -0
- package/dist/observation/batches/PartitionOutcome.d.ts.map +1 -0
- package/dist/observation/batches/PartitionOutcome.js +4 -0
- package/dist/observation/batches/PartitionOutcome.js.map +1 -0
- package/dist/observation/batches/PartitionProblem.d.ts +17 -0
- package/dist/observation/batches/PartitionProblem.d.ts.map +1 -0
- package/dist/observation/batches/PartitionProblem.js +4 -0
- package/dist/observation/batches/PartitionProblem.js.map +1 -0
- package/dist/observation/batches/PartitionSettlement.d.ts +29 -0
- package/dist/observation/batches/PartitionSettlement.d.ts.map +1 -0
- package/dist/observation/batches/PartitionSettlement.js +64 -0
- package/dist/observation/batches/PartitionSettlement.js.map +1 -0
- package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts +12 -0
- package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.d.ts.map +1 -0
- package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js +20 -0
- package/dist/observation/batches/ReducerMixesBatchAndPerEventMethods.js.map +1 -0
- package/dist/observation/batches/batchSize.d.ts +42 -0
- package/dist/observation/batches/batchSize.d.ts.map +1 -0
- package/dist/observation/batches/batchSize.js +55 -0
- package/dist/observation/batches/batchSize.js.map +1 -0
- package/dist/observation/batches/createBatchContext.d.ts +13 -0
- package/dist/observation/batches/createBatchContext.d.ts.map +1 -0
- package/dist/observation/batches/createBatchContext.js +27 -0
- package/dist/observation/batches/createBatchContext.js.map +1 -0
- package/dist/observation/batches/observes.d.ts +39 -0
- package/dist/observation/batches/observes.d.ts.map +1 -0
- package/dist/observation/batches/observes.js +63 -0
- package/dist/observation/batches/observes.js.map +1 -0
- package/dist/observation/batches/runConcurrently.d.ts +9 -0
- package/dist/observation/batches/runConcurrently.d.ts.map +1 -0
- package/dist/observation/batches/runConcurrently.js +22 -0
- package/dist/observation/batches/runConcurrently.js.map +1 -0
- package/dist/observation/createHandlerInstanceValidator.d.ts +1 -1
- package/dist/observation/createHandlerInstanceValidator.d.ts.map +1 -1
- package/dist/observation/createHandlerInstanceValidator.js +5 -7
- package/dist/observation/createHandlerInstanceValidator.js.map +1 -1
- package/dist/observation/getInstanceMethods.d.ts +3 -1
- package/dist/observation/getInstanceMethods.d.ts.map +1 -1
- package/dist/observation/getInstanceMethods.js +13 -4
- package/dist/observation/getInstanceMethods.js.map +1 -1
- package/dist/observation/index.d.ts +14 -0
- package/dist/observation/index.d.ts.map +1 -1
- package/dist/observation/index.js +13 -0
- package/dist/observation/index.js.map +1 -1
- package/dist/reactors/ReactorDispatcher.d.ts +15 -0
- package/dist/reactors/ReactorDispatcher.d.ts.map +1 -1
- package/dist/reactors/ReactorDispatcher.js +25 -2
- package/dist/reactors/ReactorDispatcher.js.map +1 -1
- package/dist/reactors/ReactorObservationTarget.d.ts +45 -0
- package/dist/reactors/ReactorObservationTarget.d.ts.map +1 -0
- package/dist/reactors/ReactorObservationTarget.js +4 -0
- package/dist/reactors/ReactorObservationTarget.js.map +1 -0
- package/dist/reactors/ReactorPageDispatcher.d.ts +33 -0
- package/dist/reactors/ReactorPageDispatcher.d.ts.map +1 -0
- package/dist/reactors/ReactorPageDispatcher.js +293 -0
- package/dist/reactors/ReactorPageDispatcher.js.map +1 -0
- package/dist/reactors/Reactors.d.ts.map +1 -1
- package/dist/reactors/Reactors.js +21 -149
- package/dist/reactors/Reactors.js.map +1 -1
- package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts +14 -0
- package/dist/reactors/for_Reactors/given/observe_reactor_messages.d.ts.map +1 -0
- package/dist/reactors/for_Reactors/given/observe_reactor_messages.js +61 -0
- package/dist/reactors/for_Reactors/given/observe_reactor_messages.js.map +1 -0
- package/dist/reactors/index.d.ts +2 -0
- package/dist/reactors/index.d.ts.map +1 -1
- package/dist/reactors/index.js +1 -0
- package/dist/reactors/index.js.map +1 -1
- package/dist/reducers/ReducerEventDispatcher.d.ts +26 -1
- package/dist/reducers/ReducerEventDispatcher.d.ts.map +1 -1
- package/dist/reducers/ReducerEventDispatcher.js +35 -3
- package/dist/reducers/ReducerEventDispatcher.js.map +1 -1
- package/dist/reducers/Reducers.d.ts +2 -0
- package/dist/reducers/Reducers.d.ts.map +1 -1
- package/dist/reducers/Reducers.js +94 -22
- package/dist/reducers/Reducers.js.map +1 -1
- package/dist/reducers/ReductionOutcome.d.ts +27 -3
- package/dist/reducers/ReductionOutcome.d.ts.map +1 -1
- package/dist/reducers/ReductionOutcome.js +51 -7
- package/dist/reducers/ReductionOutcome.js.map +1 -1
- package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts +19 -0
- package/dist/reducers/for_Reducers/given/observe_reducer_messages.d.ts.map +1 -0
- package/dist/reducers/for_Reducers/given/observe_reducer_messages.js +61 -0
- package/dist/reducers/for_Reducers/given/observe_reducer_messages.js.map +1 -0
- package/dist/reducers/index.d.ts +2 -0
- package/dist/reducers/index.d.ts.map +1 -1
- package/dist/reducers/index.js +1 -0
- package/dist/reducers/index.js.map +1 -1
- package/dist/testing/ReactorScenario.d.ts.map +1 -1
- package/dist/testing/ReactorScenario.js +4 -1
- package/dist/testing/ReactorScenario.js.map +1 -1
- package/dist/testing/ReducerReadModelProcessor.d.ts +1 -0
- package/dist/testing/ReducerReadModelProcessor.d.ts.map +1 -1
- package/dist/testing/ReducerReadModelProcessor.js +45 -0
- package/dist/testing/ReducerReadModelProcessor.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/observation/batches/BatchContext.ts +75 -0
- package/observation/batches/BatchContextObserver.ts +16 -0
- package/observation/batches/BatchContextValues.ts +16 -0
- package/observation/batches/BatchMethod.ts +13 -0
- package/observation/batches/BatchMethodReturnedAValue.ts +16 -0
- package/observation/batches/BatchMethods.ts +90 -0
- package/observation/batches/BatchOutcome.ts +22 -0
- package/observation/batches/BatchOutcomeKind.ts +11 -0
- package/observation/batches/DeferralNotSupportedByKernel.ts +17 -0
- package/observation/batches/DeliveredPartition.ts +16 -0
- package/observation/batches/EventAndContext.ts +37 -0
- package/observation/batches/EventBatch.ts +105 -0
- package/observation/batches/EventTypeObservedByMoreThanOneMethod.ts +17 -0
- package/observation/batches/InvalidBatchMethod.ts +16 -0
- package/observation/batches/ObservationOrigin.ts +37 -0
- package/observation/batches/ObservedEventType.ts +16 -0
- package/observation/batches/PageMessages.ts +37 -0
- package/observation/batches/PartitionFailedInBatch.ts +14 -0
- package/observation/batches/PartitionNotInBatch.ts +14 -0
- package/observation/batches/PartitionOutcome.ts +22 -0
- package/observation/batches/PartitionProblem.ts +25 -0
- package/observation/batches/PartitionSettlement.ts +70 -0
- package/observation/batches/ReducerMixesBatchAndPerEventMethods.ts +16 -0
- package/observation/batches/batchSize.ts +79 -0
- package/observation/batches/createBatchContext.ts +32 -0
- package/observation/batches/for_BatchMethods/when_discovering_batch_methods.spec.ts +155 -0
- package/observation/batches/for_EventBatch/when_reporting_outcomes.spec.ts +66 -0
- package/observation/batches/for_PartitionSettlement/when_settling_a_partition.spec.ts +31 -0
- package/observation/batches/for_batchSize/when_declaring_bounds.spec.ts +23 -0
- package/observation/batches/for_observes/when_decorating_methods.legacy.spec.ts +28 -0
- package/observation/batches/for_observes/when_decorating_methods.spec.ts +33 -0
- package/observation/batches/for_runConcurrently/when_running_items.spec.ts +22 -0
- package/observation/batches/observes.ts +68 -0
- package/observation/batches/runConcurrently.ts +23 -0
- package/observation/createHandlerInstanceValidator.ts +5 -7
- package/observation/getInstanceMethods.ts +13 -4
- package/observation/index.ts +14 -0
- package/package.json +1 -1
- package/reactors/ReactorDispatcher.ts +27 -2
- package/reactors/ReactorObservationTarget.ts +48 -0
- package/reactors/ReactorPageDispatcher.ts +321 -0
- package/reactors/Reactors.ts +22 -164
- package/reactors/for_Reactors/given/observe_reactor_messages.ts +72 -0
- package/reactors/for_Reactors/when_delivering_pages/as_a_legacy_single_partition.spec.ts +51 -0
- package/reactors/for_Reactors/when_delivering_pages/returning_a_value_from_a_batch_method.spec.ts +34 -0
- package/reactors/for_Reactors/when_delivering_pages/with_batch_and_per_event_methods.spec.ts +81 -0
- package/reactors/for_Reactors/when_delivering_pages/with_batch_outcomes.spec.ts +86 -0
- package/reactors/for_Reactors/when_delivering_pages/with_per_event_handlers.spec.ts +52 -0
- package/reactors/index.ts +2 -0
- package/reducers/ReducerEventDispatcher.ts +44 -3
- package/reducers/Reducers.ts +109 -25
- package/reducers/ReductionOutcome.ts +55 -8
- package/reducers/for_Reducers/given/observe_reducer_messages.ts +77 -0
- package/reducers/for_Reducers/when_delivering_pages/to_a_batch_reducer.spec.ts +111 -0
- package/reducers/for_Reducers/when_delivering_pages/to_a_per_event_reducer.spec.ts +53 -0
- package/reducers/index.ts +2 -0
- package/testing/ReactorScenario.ts +5 -1
- package/testing/ReducerReadModelProcessor.ts +44 -0
- package/testing/for_ReactorScenario/when_the_reactor_has_a_batch_method.spec.ts +26 -0
- package/testing/for_ReadModelScenario/when_reducing_with_a_batch_method/with_events_for_two_event_sources.spec.ts +43 -0
package/reactors/Reactors.ts
CHANGED
|
@@ -5,11 +5,10 @@ import 'reflect-metadata';
|
|
|
5
5
|
import { createLogger } from '../logging/createLogger.js';
|
|
6
6
|
import { runInBackgroundContext } from '../telemetry/runInBackgroundContext.js';
|
|
7
7
|
import { Constructor } from '@cratis/fundamentals';
|
|
8
|
-
import { EventGenerationDelivery,
|
|
8
|
+
import { EventGenerationDelivery, ReactorMessage } from '@cratis/chronicle.contracts';
|
|
9
9
|
import { IClientArtifactsProvider } from '../artifacts/index.js';
|
|
10
10
|
import { ChronicleConnection } from '../connection/index.js';
|
|
11
11
|
import { ConnectionLifecycle } from '../connection/ConnectionLifecycle.js';
|
|
12
|
-
import { toClientEventContext } from '../events/toClientEventContext.js';
|
|
13
12
|
import { getTagsFor } from '../events/tagDecorator.js';
|
|
14
13
|
import { getFilterTagsFor } from '../events/filterEventsByTagDecorator.js';
|
|
15
14
|
import { getEventSourceTypeFor } from '../events/eventSourceTypeDecorator.js';
|
|
@@ -17,32 +16,23 @@ import { getEventStreamTypeFor } from '../events/eventStreamTypeDecorator.js';
|
|
|
17
16
|
import { EventSequenceId } from '../eventSequences/EventSequenceId.js';
|
|
18
17
|
import type { IEventLog } from '../eventSequences/IEventLog.js';
|
|
19
18
|
import { createHandlerInstanceValidator } from '../observation/createHandlerInstanceValidator.js';
|
|
20
|
-
import { notifyReplayLifecycle } from '../observation/notifyReplayLifecycle.js';
|
|
21
19
|
import { IReactors } from './IReactors.js';
|
|
22
|
-
import { dispatchReactorSideEffects } from './ReactorSideEffects.js';
|
|
23
20
|
import { getReactorMetadata } from './reactor.js';
|
|
24
21
|
import { isOnceOnly } from './onceOnly.js';
|
|
25
22
|
import { isStartAtTail } from './startAtTail.js';
|
|
26
|
-
import {
|
|
23
|
+
import { getReactorBatchMethods, getReactorEventTypes } from './ReactorDispatcher.js';
|
|
24
|
+
import { ReactorPageDispatcher } from './ReactorPageDispatcher.js';
|
|
25
|
+
import { toPageDelivery } from '../observation/batches/batchSize.js';
|
|
27
26
|
import type { ReactorEventTypeEntry } from './ReactorDispatcher.js';
|
|
28
27
|
import type { ReactorResultHandler } from './ReactorResultHandler.js';
|
|
29
28
|
import type { ReactorServices } from './ReactorServices.js';
|
|
30
|
-
import { ReactorDelivery } from './ReactorDelivery.js';
|
|
31
29
|
import type { IEventStore } from '../IEventStore.js';
|
|
32
30
|
import type { ClientArtifactsActivator } from '../artifacts/ClientArtifactsActivator.js';
|
|
33
|
-
import type { ActivatedArtifact } from '../artifacts/ActivatedArtifact.js';
|
|
34
|
-
import { ArtifactKind } from '../artifacts/ArtifactKind.js';
|
|
35
|
-
import { ArtifactDelivery } from '../artifacts/ArtifactDelivery.js';
|
|
36
|
-
import { withActivatedArtifact, runActivated } from '../artifacts/withActivatedArtifact.js';
|
|
37
|
-
import { ArtifactCompletionFailed } from '../artifacts/ArtifactCompletionFailed.js';
|
|
38
31
|
import { refuseClientHostedObservers } from '../artifacts/refuseClientHostedObservers.js';
|
|
39
32
|
|
|
40
33
|
/** Expression used to partition reactor observations by event source ID. */
|
|
41
34
|
const EVENT_SOURCE_ID_KEY = '$eventSourceId';
|
|
42
35
|
|
|
43
|
-
/** Sentinel sequence number sent back when no event was successfully processed. */
|
|
44
|
-
const SEQUENCE_NUMBER_UNAVAILABLE = 4294967295n;
|
|
45
|
-
|
|
46
36
|
/**
|
|
47
37
|
* A push-based async queue that implements {@link AsyncIterable} for use with nice-grpc
|
|
48
38
|
* bidirectional streaming. Values pushed via {@link send} are yielded in order to
|
|
@@ -181,9 +171,12 @@ export class Reactors implements IReactors {
|
|
|
181
171
|
|
|
182
172
|
if (this._disposed) return;
|
|
183
173
|
const registrations = [...this._reactors].map(([id, type]) => ({
|
|
184
|
-
id, type, eventTypes: getReactorEventTypes(type, this._clientArtifacts.eventTypes)
|
|
185
|
-
|
|
186
|
-
|
|
174
|
+
id, type, eventTypes: getReactorEventTypes(type, this._clientArtifacts.eventTypes),
|
|
175
|
+
batchMethods: getReactorBatchMethods(type, this._clientArtifacts.eventTypes)
|
|
176
|
+
})).map(registration => ({ ...registration, validateInstance: createHandlerInstanceValidator(registration.type, [
|
|
177
|
+
...registration.eventTypes.flatMap(entry => [entry.methodName, entry.replayMethodName].filter((name): name is string => !!name)),
|
|
178
|
+
...registration.batchMethods.map(method => method.methodName)
|
|
179
|
+
]) }));
|
|
187
180
|
this._logger.info('Registering reactors', { count: this._reactors.size });
|
|
188
181
|
for (const { id, type, eventTypes, validateInstance } of registrations) {
|
|
189
182
|
this.startObservation(id, type, eventTypes, validateInstance);
|
|
@@ -261,6 +254,7 @@ export class Reactors implements IReactors {
|
|
|
261
254
|
eventTypes: ReactorEventTypeEntry[],
|
|
262
255
|
validateInstance: (instance: object) => void
|
|
263
256
|
): Promise<void> {
|
|
257
|
+
const batchMethods = getReactorBatchMethods(reactorType, this._clientArtifacts.eventTypes);
|
|
264
258
|
const queue = new AsyncQueue<ReactorMessage>();
|
|
265
259
|
const controller = new AbortController();
|
|
266
260
|
this._queues.set(id, queue);
|
|
@@ -275,7 +269,7 @@ export class Reactors implements IReactors {
|
|
|
275
269
|
Reactor: {
|
|
276
270
|
ReactorId: id,
|
|
277
271
|
EventSequenceId: eventSequenceId,
|
|
278
|
-
EventTypes: eventTypes.map(et => ({
|
|
272
|
+
EventTypes: [...eventTypes, ...batchMethods.flatMap(method => [...method.eventTypes.values()])].map(et => ({
|
|
279
273
|
EventType: { Id: et.id, Generation: et.generation, Tombstone: false },
|
|
280
274
|
Key: EVENT_SOURCE_ID_KEY
|
|
281
275
|
})),
|
|
@@ -290,7 +284,7 @@ export class Reactors implements IReactors {
|
|
|
290
284
|
EventStreamType: getEventStreamTypeFor(reactorType)
|
|
291
285
|
}
|
|
292
286
|
},
|
|
293
|
-
PageDelivery:
|
|
287
|
+
PageDelivery: toPageDelivery(reactorType)
|
|
294
288
|
},
|
|
295
289
|
Value1: undefined
|
|
296
290
|
}
|
|
@@ -303,152 +297,16 @@ export class Reactors implements IReactors {
|
|
|
303
297
|
eventStore: this._eventStore, readModels: this._eventStore.readModels, signal: controller.signal
|
|
304
298
|
};
|
|
305
299
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
this._logger.debug('Received events to observe', {
|
|
313
|
-
reactorId: id,
|
|
314
|
-
count: eventsToObserve.Events.length,
|
|
315
|
-
replayState: eventsToObserve.ReplayState
|
|
316
|
-
});
|
|
317
|
-
|
|
318
|
-
try {
|
|
319
|
-
if (this._artifactActivator && eventsToObserve.ReplayState !== ReplayState.REPLAY_STATE_None) {
|
|
320
|
-
if (!services) throw new Error('Reactor activation requires the owning event store.');
|
|
321
|
-
await withActivatedArtifact(reactorType, {
|
|
322
|
-
kind: ArtifactKind.Reactor, artifactId: id, eventStore: services.eventStore,
|
|
323
|
-
readModels: services.readModels, eventSequenceId, partition: eventsToObserve.Partition,
|
|
324
|
-
signal: controller.signal, delivery: ArtifactDelivery.ReplayNotification,
|
|
325
|
-
replayState: eventsToObserve.ReplayState
|
|
326
|
-
}, this._artifactActivator, artifact => {
|
|
327
|
-
validateInstance(artifact.instance);
|
|
328
|
-
return runActivated(artifact, () =>
|
|
329
|
-
notifyReplayLifecycle(artifact.instance, eventsToObserve.ReplayState, eventsToObserve.Partition),
|
|
330
|
-
{ delivery: ArtifactDelivery.ReplayNotification, replayState: eventsToObserve.ReplayState });
|
|
331
|
-
}, this._connection.logger);
|
|
332
|
-
} else if (reactorInstance) {
|
|
333
|
-
await notifyReplayLifecycle(reactorInstance, eventsToObserve.ReplayState, eventsToObserve.Partition);
|
|
334
|
-
}
|
|
335
|
-
} catch (err) {
|
|
336
|
-
this._logger.error('Error notifying reactor of replay lifecycle transition', { reactorId: id, error: err });
|
|
337
|
-
if (err instanceof ArtifactCompletionFailed && err.processingError !== undefined) {
|
|
338
|
-
exceptionMessages.push(String(err.processingError));
|
|
339
|
-
}
|
|
340
|
-
exceptionMessages.push(String(err));
|
|
341
|
-
exceptionStackTrace = err instanceof Error ? (err.stack ?? '') : '';
|
|
342
|
-
state = ObservationState.Failed;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
const selectHandler = (event: typeof eventsToObserve.Events[number]) => {
|
|
346
|
-
return selectReactorHandler(eventTypes, reactorType, reactorInstance,
|
|
347
|
-
event.Context?.EventType?.Id, event.Context?.ObservationState ?? 0);
|
|
348
|
-
};
|
|
349
|
-
|
|
350
|
-
const processEvents = async (artifact: ActivatedArtifact<Record<string, Function>>) => {
|
|
351
|
-
for (const event of state === ObservationState.Failed ? [] : eventsToObserve.Events) {
|
|
352
|
-
try {
|
|
353
|
-
const eventTypeId = event.Context?.EventType?.Id;
|
|
354
|
-
if (!eventTypeId) {
|
|
355
|
-
this._logger.warn('Event missing event type context', { reactorId: id });
|
|
356
|
-
continue;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
const selection = selectHandler(event);
|
|
360
|
-
if (!selection) {
|
|
361
|
-
this._logger.debug('No reactor handler found', { reactorId: id, eventTypeId });
|
|
362
|
-
lastSuccessfullyObservedEvent = event.Context!.SequenceNumber;
|
|
363
|
-
continue;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
const { methodName, isReplay, skipReplay } = selection;
|
|
367
|
-
if (!methodName || skipReplay) {
|
|
368
|
-
if (skipReplay) {
|
|
369
|
-
this._logger.debug('Reactor handler skipped for replay', { reactorId: id, eventTypeId, method: methodName });
|
|
370
|
-
} else {
|
|
371
|
-
this._logger.debug('No reactor handler found', { reactorId: id, eventTypeId, isReplay });
|
|
372
|
-
}
|
|
373
|
-
lastSuccessfullyObservedEvent = event.Context!.SequenceNumber;
|
|
374
|
-
continue;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
const content = JSON.parse(event.Content) as Record<string, unknown>;
|
|
378
|
-
const context = toClientEventContext(event.Context!);
|
|
379
|
-
|
|
380
|
-
this._logger.info('Invoking reactor handler', {
|
|
381
|
-
reactorId: id,
|
|
382
|
-
method: methodName,
|
|
383
|
-
sequenceNumber: event.Context!.SequenceNumber.toString(),
|
|
384
|
-
eventTypeId
|
|
385
|
-
});
|
|
386
|
-
|
|
387
|
-
await invokeReactorHandler(artifact, methodName, content, context, services, result =>
|
|
388
|
-
dispatchReactorSideEffects(this._eventLog, result, context, reactorType as Function,
|
|
389
|
-
this._eventStoreName, this._namespace, this._resultHandler),
|
|
390
|
-
new ReactorDelivery(id, context.eventStore ?? this._eventStoreName,
|
|
391
|
-
context.namespace ?? this._namespace, eventSequenceId,
|
|
392
|
-
context.eventSourceId, context.sequenceNumber));
|
|
393
|
-
|
|
394
|
-
lastSuccessfullyObservedEvent = event.Context!.SequenceNumber;
|
|
395
|
-
} catch (err) {
|
|
396
|
-
this._logger.error('Error handling event in reactor', { reactorId: id, error: err });
|
|
397
|
-
exceptionMessages.push(String(err));
|
|
398
|
-
exceptionStackTrace = err instanceof Error ? (err.stack ?? '') : '';
|
|
399
|
-
state = ObservationState.Failed;
|
|
400
|
-
break;
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
};
|
|
404
|
-
|
|
405
|
-
const firstInvocableEvent = this._artifactActivator && state === ObservationState.Success
|
|
406
|
-
? eventsToObserve.Events.find(event => {
|
|
407
|
-
const selection = selectHandler(event);
|
|
408
|
-
return !!selection?.methodName && !selection.skipReplay;
|
|
409
|
-
}) : undefined;
|
|
410
|
-
if (firstInvocableEvent && this._artifactActivator) {
|
|
411
|
-
try {
|
|
412
|
-
if (!services) throw new Error('Reactor activation requires the owning event store.');
|
|
413
|
-
await withActivatedArtifact(reactorType as new () => Record<string, Function>, {
|
|
414
|
-
kind: ArtifactKind.Reactor, artifactId: id, eventStore: services.eventStore,
|
|
415
|
-
readModels: services.readModels, eventSequenceId, partition: eventsToObserve.Partition,
|
|
416
|
-
signal: controller.signal, delivery: ArtifactDelivery.Events,
|
|
417
|
-
eventContext: toClientEventContext(firstInvocableEvent.Context!)
|
|
418
|
-
}, this._artifactActivator, artifact => {
|
|
419
|
-
validateInstance(artifact.instance);
|
|
420
|
-
return processEvents(artifact);
|
|
421
|
-
}, this._connection.logger);
|
|
422
|
-
} catch (err) {
|
|
423
|
-
this._logger.error('Error activating reactor', { reactorId: id, error: err });
|
|
424
|
-
exceptionMessages.push(String(err));
|
|
425
|
-
const completionStack = err instanceof Error ? (err.stack ?? '') : '';
|
|
426
|
-
exceptionStackTrace = err instanceof ArtifactCompletionFailed && exceptionStackTrace
|
|
427
|
-
? `${exceptionStackTrace}\n${completionStack}` : completionStack;
|
|
428
|
-
state = ObservationState.Failed;
|
|
429
|
-
if (err instanceof ArtifactCompletionFailed) {
|
|
430
|
-
lastSuccessfullyObservedEvent = SEQUENCE_NUMBER_UNAVAILABLE;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
} else {
|
|
434
|
-
await processEvents({ instance: reactorInstance ?? {} });
|
|
435
|
-
}
|
|
300
|
+
const dispatcher = new ReactorPageDispatcher({
|
|
301
|
+
id, reactorType, eventSequenceId, eventStoreName: this._eventStoreName, namespace: this._namespace,
|
|
302
|
+
entries: eventTypes, batchMethods, validateInstance, reactorInstance, services, signal: controller.signal,
|
|
303
|
+
eventLog: this._eventLog, resultHandler: this._resultHandler, artifactActivator: this._artifactActivator,
|
|
304
|
+
logger: this._logger, connectionLogger: this._connection.logger
|
|
305
|
+
});
|
|
436
306
|
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
Value1: {
|
|
441
|
-
Partition: eventsToObserve.Partition,
|
|
442
|
-
State: state,
|
|
443
|
-
LastSuccessfulObservation: lastSuccessfullyObservedEvent,
|
|
444
|
-
ExceptionMessages: exceptionMessages,
|
|
445
|
-
ExceptionStackTrace: exceptionStackTrace,
|
|
446
|
-
DeliveryId: 0n,
|
|
447
|
-
RetryAfterMilliseconds: 0n,
|
|
448
|
-
Partitions: []
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
});
|
|
307
|
+
for await (const eventsToObserve of this._connection.reactors.observe(queue, { signal: controller.signal })) {
|
|
308
|
+
const result = await dispatcher.dispatch(eventsToObserve);
|
|
309
|
+
queue.send({ Content: { Value0: undefined, Value1: result } });
|
|
452
310
|
}
|
|
453
311
|
} catch (err) {
|
|
454
312
|
if (!this._queues.has(id)) {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { Constructor } from '@cratis/fundamentals';
|
|
5
|
+
import {
|
|
6
|
+
AppendedEvent, EventsToObserve, ObservationOrigin, ReplayState,
|
|
7
|
+
type RegisterReactor, type ReactorMessage, type ReactorResult
|
|
8
|
+
} from '@cratis/chronicle.contracts';
|
|
9
|
+
import type { IClientArtifactsProvider } from '../../../artifacts/index.js';
|
|
10
|
+
import type { ChronicleConnection } from '../../../connection/index.js';
|
|
11
|
+
import { ConnectionLifecycle } from '../../../connection/ConnectionLifecycle.js';
|
|
12
|
+
import type { IEventLog } from '../../../eventSequences/IEventLog.js';
|
|
13
|
+
import type { IEventStore } from '../../../IEventStore.js';
|
|
14
|
+
import { Reactors } from '../../index.js';
|
|
15
|
+
|
|
16
|
+
/** Creates a delivered event of a type for an event source. */
|
|
17
|
+
export function appended(eventTypeId: string, eventSourceId: string, sequenceNumber: bigint, content: object = {}): AppendedEvent {
|
|
18
|
+
return AppendedEvent.fromPartial({
|
|
19
|
+
Content: JSON.stringify(content),
|
|
20
|
+
Context: { EventType: { Id: eventTypeId, Generation: 1 }, EventSourceId: eventSourceId, SequenceNumber: sequenceNumber }
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Creates a page of partitions, as a kernel that delivers pages sends it. */
|
|
25
|
+
export function page(deliveryId: bigint, partitions: Record<string, AppendedEvent[]>, origin = ObservationOrigin.Live): EventsToObserve {
|
|
26
|
+
return EventsToObserve.fromPartial({
|
|
27
|
+
DeliveryId: deliveryId, Origin: origin, ReplayState: ReplayState.REPLAY_STATE_None,
|
|
28
|
+
Partitions: Object.entries(partitions).map(([partition, events]) => ({ Partition: partition, Events: events }))
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Creates a legacy single-partition delivery, as a kernel that does not deliver pages sends it. */
|
|
33
|
+
export function single(partition: string, events: AppendedEvent[], deliveryId = 0n): EventsToObserve {
|
|
34
|
+
return EventsToObserve.fromPartial({ DeliveryId: deliveryId, Partition: partition, Events: events, ReplayState: ReplayState.REPLAY_STATE_None });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Observes a reactor through the production observation stream, without a kernel. */
|
|
38
|
+
export async function observeReactorMessages(reactorType: Constructor, eventTypes: Constructor[], messages: EventsToObserve[]):
|
|
39
|
+
Promise<{ registration: RegisterReactor; results: ReactorResult[] }> {
|
|
40
|
+
const lifecycle = new ConnectionLifecycle();
|
|
41
|
+
const results: ReactorResult[] = [];
|
|
42
|
+
let registration!: RegisterReactor;
|
|
43
|
+
let failure: unknown;
|
|
44
|
+
let finish!: () => void;
|
|
45
|
+
const finished = new Promise<void>(resolve => { finish = resolve; });
|
|
46
|
+
async function* stream(queue: AsyncIterable<ReactorMessage>) {
|
|
47
|
+
const outgoing = queue[Symbol.asyncIterator]();
|
|
48
|
+
try {
|
|
49
|
+
registration = (await outgoing.next()).value!.Content!.Value0!;
|
|
50
|
+
for (const message of messages) {
|
|
51
|
+
yield message;
|
|
52
|
+
results.push((await outgoing.next()).value!.Content!.Value1!);
|
|
53
|
+
}
|
|
54
|
+
} catch (error) {
|
|
55
|
+
failure = error;
|
|
56
|
+
} finally {
|
|
57
|
+
await lifecycle.disconnected(error => { throw error; });
|
|
58
|
+
finish();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const reactors = new Reactors({ reactors: [reactorType], eventTypes } as unknown as IClientArtifactsProvider,
|
|
62
|
+
{ reactors: { observe: stream } } as unknown as ChronicleConnection,
|
|
63
|
+
'store', 'default', lifecycle, {} as IEventLog, undefined, { readModels: {} } as IEventStore);
|
|
64
|
+
try {
|
|
65
|
+
await reactors.register();
|
|
66
|
+
await finished;
|
|
67
|
+
if (failure) throw failure;
|
|
68
|
+
return { registration, results };
|
|
69
|
+
} finally {
|
|
70
|
+
reactors.dispose();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationState, type ReactorResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
7
|
+
import { BatchContext, EventBatch, observes } from '../../../observation/index.js';
|
|
8
|
+
import { reactor } from '../../reactor.js';
|
|
9
|
+
import { appended, observeReactorMessages, single } from '../given/observe_reactor_messages.js';
|
|
10
|
+
|
|
11
|
+
chai.should();
|
|
12
|
+
|
|
13
|
+
@eventType('legacy-order-placed')
|
|
14
|
+
class OrderPlaced {}
|
|
15
|
+
|
|
16
|
+
describe('when a kernel without page delivery sends a single partition to a batch reactor', () => {
|
|
17
|
+
let canDefer: boolean[];
|
|
18
|
+
let results: ReactorResult[];
|
|
19
|
+
|
|
20
|
+
beforeEach(async () => {
|
|
21
|
+
canDefer = [];
|
|
22
|
+
|
|
23
|
+
@reactor('legacy-orders')
|
|
24
|
+
class Orders {
|
|
25
|
+
@observes(OrderPlaced)
|
|
26
|
+
place(batch: EventBatch, context: BatchContext): void {
|
|
27
|
+
canDefer.push(context.canDefer);
|
|
28
|
+
if (batch.events.some(entry => entry.context.sequenceNumber === 3n)) batch.defer('order-1', 1000);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
({ results } = await observeReactorMessages(Orders, [OrderPlaced], [
|
|
33
|
+
single('order-1', [appended('legacy-order-placed', 'order-1', 1n), appended('legacy-order-placed', 'order-1', 2n)], 11n),
|
|
34
|
+
single('order-1', [appended('legacy-order-placed', 'order-1', 3n)], 12n)
|
|
35
|
+
]));
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('should tell the batch method that it cannot defer', () => canDefer.should.deep.equal([false, false]));
|
|
39
|
+
it('should reply in the legacy fields without per-partition results', () => {
|
|
40
|
+
results[0].Partition.should.equal('order-1');
|
|
41
|
+
results[0].State.should.equal(ObservationState.Success);
|
|
42
|
+
results[0].LastSuccessfulObservation.should.equal(2n);
|
|
43
|
+
results[0].Partitions.should.be.empty;
|
|
44
|
+
results[0].DeliveryId.should.equal(11n);
|
|
45
|
+
});
|
|
46
|
+
it('should fail a deferral the kernel cannot take, and say why', () => {
|
|
47
|
+
results[1].State.should.equal(ObservationState.Failed);
|
|
48
|
+
results[1].LastSuccessfulObservation.should.equal(4294967295n);
|
|
49
|
+
results[1].ExceptionMessages[0].should.contain('DeferralNotSupportedByKernel');
|
|
50
|
+
});
|
|
51
|
+
});
|
package/reactors/for_Reactors/when_delivering_pages/returning_a_value_from_a_batch_method.spec.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationState, type ReactorResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
7
|
+
import { observes } from '../../../observation/index.js';
|
|
8
|
+
import { reactor } from '../../reactor.js';
|
|
9
|
+
import { appended, observeReactorMessages, page } from '../given/observe_reactor_messages.js';
|
|
10
|
+
|
|
11
|
+
chai.should();
|
|
12
|
+
|
|
13
|
+
@eventType('returning-invoice-sent')
|
|
14
|
+
class InvoiceSent {}
|
|
15
|
+
|
|
16
|
+
describe('when a reactor batch method returns a value', () => {
|
|
17
|
+
let results: ReactorResult[];
|
|
18
|
+
|
|
19
|
+
beforeEach(async () => {
|
|
20
|
+
@reactor('returning-invoices')
|
|
21
|
+
class Invoices {
|
|
22
|
+
@observes(InvoiceSent)
|
|
23
|
+
send() {
|
|
24
|
+
return new InvoiceSent();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
({ results } = await observeReactorMessages(Invoices, [InvoiceSent], [page(1n, { 'invoice-1': [appended('returning-invoice-sent', 'invoice-1', 1n)] })]));
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('should fail the partition', () => results[0].Partitions[0].State.should.equal(ObservationState.Failed));
|
|
32
|
+
it('should say that batch methods do not return events', () =>
|
|
33
|
+
results[0].Partitions[0].ExceptionMessages[0].should.contain('BatchMethodReturnedAValue'));
|
|
34
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationOrigin as ContractObservationOrigin, ObservationState, type RegisterReactor, type ReactorResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import type { EventContext } from '../../../events/EventContext.js';
|
|
7
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
8
|
+
import { BatchContext, EventBatch, ObservationOrigin, observes } from '../../../observation/index.js';
|
|
9
|
+
import { reactor } from '../../reactor.js';
|
|
10
|
+
import { appended, observeReactorMessages, page } from '../given/observe_reactor_messages.js';
|
|
11
|
+
|
|
12
|
+
chai.should();
|
|
13
|
+
|
|
14
|
+
@eventType('batch-user-registered')
|
|
15
|
+
class UserRegistered {
|
|
16
|
+
constructor(readonly name: string = '') {}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
@eventType('batch-user-renamed')
|
|
20
|
+
class UserRenamed {
|
|
21
|
+
constructor(readonly newName: string = '') {}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
@eventType('batch-user-email-changed')
|
|
25
|
+
class UserEmailChanged {}
|
|
26
|
+
|
|
27
|
+
describe('when delivering a page to a reactor with a batch method and a per-event method', () => {
|
|
28
|
+
let batches: { names: string[]; partitions: readonly string[] }[];
|
|
29
|
+
let contexts: BatchContext[];
|
|
30
|
+
let perEvent: string[];
|
|
31
|
+
let registration: RegisterReactor;
|
|
32
|
+
let results: ReactorResult[];
|
|
33
|
+
|
|
34
|
+
beforeEach(async () => {
|
|
35
|
+
batches = [];
|
|
36
|
+
contexts = [];
|
|
37
|
+
perEvent = [];
|
|
38
|
+
|
|
39
|
+
@reactor('batch-users')
|
|
40
|
+
class Users {
|
|
41
|
+
@observes(UserRegistered)
|
|
42
|
+
@observes(UserRenamed)
|
|
43
|
+
index(batch: EventBatch, context: BatchContext): void {
|
|
44
|
+
contexts.push(context);
|
|
45
|
+
batches.push({
|
|
46
|
+
names: batch.events.map(entry => entry.is(UserRegistered) ? entry.event.name : entry.is(UserRenamed) ? entry.event.newName : '?'),
|
|
47
|
+
partitions: batch.partitions
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
userEmailChanged(_event: UserEmailChanged, context: EventContext) {
|
|
52
|
+
perEvent.push(`${context.eventSourceId}:${context.sequenceNumber}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
({ registration, results } = await observeReactorMessages(Users, [UserRegistered, UserRenamed, UserEmailChanged], [page(7n, {
|
|
57
|
+
alice: [appended('batch-user-registered', 'alice', 1n, { name: 'Alice' }), appended('batch-user-email-changed', 'alice', 3n),
|
|
58
|
+
appended('batch-user-renamed', 'alice', 4n, { newName: 'Alicia' })],
|
|
59
|
+
bob: [appended('batch-user-registered', 'bob', 2n, { name: 'Bob' })]
|
|
60
|
+
}, ContractObservationOrigin.CatchingUp)]));
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('should register the event types of both methods', () =>
|
|
64
|
+
registration.Reactor!.EventTypes.map(eventType => eventType.EventType!.Id).sort()
|
|
65
|
+
.should.deep.equal(['batch-user-email-changed', 'batch-user-registered', 'batch-user-renamed']));
|
|
66
|
+
it('should call the batch method once with its event types across partitions in sequence order', () =>
|
|
67
|
+
batches.should.deep.equal([{ names: ['Alice', 'Bob', 'Alicia'], partitions: ['alice', 'bob'] }]));
|
|
68
|
+
it('should call the per-event method only for its own event type', () => perEvent.should.deep.equal(['alice:3']));
|
|
69
|
+
it('should describe the page in the batch context', () => {
|
|
70
|
+
contexts[0].origin.should.equal(ObservationOrigin.CatchUp);
|
|
71
|
+
contexts[0].observerId.should.equal('batch-users');
|
|
72
|
+
contexts[0].partitions.should.deep.equal(['alice', 'bob']);
|
|
73
|
+
contexts[0].eventCount.should.equal(4);
|
|
74
|
+
contexts[0].firstSequenceNumber!.should.equal(1n);
|
|
75
|
+
contexts[0].lastSequenceNumber!.should.equal(4n);
|
|
76
|
+
contexts[0].canDefer.should.be.true;
|
|
77
|
+
});
|
|
78
|
+
it('should settle every partition at its last event', () =>
|
|
79
|
+
results[0].Partitions.map(result => [result.Partition, result.State, result.LastSuccessfulObservation])
|
|
80
|
+
.should.deep.equal([['alice', ObservationState.Success, 4n], ['bob', ObservationState.Success, 2n]]));
|
|
81
|
+
});
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationState, type ReactorResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import type { EventContext } from '../../../events/EventContext.js';
|
|
7
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
8
|
+
import { EventBatch, observes } from '../../../observation/index.js';
|
|
9
|
+
import { reactor } from '../../reactor.js';
|
|
10
|
+
import { appended, observeReactorMessages, page } from '../given/observe_reactor_messages.js';
|
|
11
|
+
|
|
12
|
+
chai.should();
|
|
13
|
+
|
|
14
|
+
@eventType('outcome-document-indexed')
|
|
15
|
+
class DocumentIndexed {}
|
|
16
|
+
|
|
17
|
+
@eventType('outcome-document-archived')
|
|
18
|
+
class DocumentArchived {}
|
|
19
|
+
|
|
20
|
+
@eventType('outcome-document-shared')
|
|
21
|
+
class DocumentShared {}
|
|
22
|
+
|
|
23
|
+
describe('when batch methods report outcomes for partitions of a page', () => {
|
|
24
|
+
let results: ReactorResult[];
|
|
25
|
+
let failingMethodCalls: number;
|
|
26
|
+
|
|
27
|
+
beforeEach(async () => {
|
|
28
|
+
failingMethodCalls = 0;
|
|
29
|
+
|
|
30
|
+
@reactor('outcome-documents')
|
|
31
|
+
class Documents {
|
|
32
|
+
@observes(DocumentIndexed)
|
|
33
|
+
index(batch: EventBatch): void {
|
|
34
|
+
const second = batch.events.find(entry => entry.context.sequenceNumber === 5n)!;
|
|
35
|
+
batch.fail(second.context, new Error('index rejected the document'));
|
|
36
|
+
batch.defer('throttled', 1500);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
@observes(DocumentArchived)
|
|
40
|
+
archive(): void {
|
|
41
|
+
failingMethodCalls++;
|
|
42
|
+
throw new Error('archive unavailable');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
documentShared(_event: DocumentShared, context: EventContext) {
|
|
46
|
+
if (context.eventSourceId === 'failed-late') throw new Error('share failed');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
({ results } = await observeReactorMessages(Documents, [DocumentIndexed, DocumentArchived, DocumentShared], [page(1n, {
|
|
51
|
+
healthy: [appended('outcome-document-indexed', 'healthy', 1n)],
|
|
52
|
+
'failed-at-event': [appended('outcome-document-indexed', 'failed-at-event', 2n), appended('outcome-document-indexed', 'failed-at-event', 5n)],
|
|
53
|
+
throttled: [appended('outcome-document-indexed', 'throttled', 3n), appended('outcome-document-indexed', 'throttled', 6n)],
|
|
54
|
+
archived: [appended('outcome-document-indexed', 'archived', 4n), appended('outcome-document-archived', 'archived', 7n)],
|
|
55
|
+
'failed-late': [appended('outcome-document-archived', 'failed-late', 8n), appended('outcome-document-shared', 'failed-late', 9n)]
|
|
56
|
+
})]));
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const resultFor = (partition: string) => results[0].Partitions.find(result => result.Partition === partition)!;
|
|
60
|
+
|
|
61
|
+
it('should call each batch method once for the page', () => failingMethodCalls.should.equal(1));
|
|
62
|
+
it('should succeed a partition nothing was reported for', () => {
|
|
63
|
+
resultFor('healthy').State.should.equal(ObservationState.Success);
|
|
64
|
+
resultFor('healthy').LastSuccessfulObservation.should.equal(1n);
|
|
65
|
+
});
|
|
66
|
+
it('should fail a partition from the event it was failed at, keeping the earlier events', () => {
|
|
67
|
+
resultFor('failed-at-event').State.should.equal(ObservationState.Failed);
|
|
68
|
+
resultFor('failed-at-event').LastSuccessfulObservation.should.equal(2n);
|
|
69
|
+
resultFor('failed-at-event').ExceptionMessages.should.deep.equal(['Error: index rejected the document']);
|
|
70
|
+
});
|
|
71
|
+
it('should defer a partition from its first event in the batch, with the delay', () => {
|
|
72
|
+
resultFor('throttled').State.should.equal(ObservationState.Deferred);
|
|
73
|
+
resultFor('throttled').LastSuccessfulObservation.should.equal(4294967295n);
|
|
74
|
+
resultFor('throttled').RetryAfterMilliseconds.should.equal(1500n);
|
|
75
|
+
});
|
|
76
|
+
it('should fail every partition of a throwing batch method at its first event in that batch', () => {
|
|
77
|
+
resultFor('archived').State.should.equal(ObservationState.Failed);
|
|
78
|
+
resultFor('archived').LastSuccessfulObservation.should.equal(4n);
|
|
79
|
+
resultFor('archived').ExceptionMessages.should.deep.equal(['Error: archive unavailable']);
|
|
80
|
+
});
|
|
81
|
+
it('should settle a partition at the earliest problem any method reported', () => {
|
|
82
|
+
resultFor('failed-late').State.should.equal(ObservationState.Failed);
|
|
83
|
+
resultFor('failed-late').LastSuccessfulObservation.should.equal(4294967295n);
|
|
84
|
+
resultFor('failed-late').ExceptionMessages.should.deep.equal(['Error: archive unavailable']);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationState, type RegisterReactor, type ReactorResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import type { EventContext } from '../../../events/EventContext.js';
|
|
7
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
8
|
+
import { reactor } from '../../reactor.js';
|
|
9
|
+
import { appended, observeReactorMessages, page } from '../given/observe_reactor_messages.js';
|
|
10
|
+
|
|
11
|
+
chai.should();
|
|
12
|
+
|
|
13
|
+
@eventType('paged-item-added')
|
|
14
|
+
class ItemAdded {}
|
|
15
|
+
|
|
16
|
+
describe('when delivering a page to a reactor with per-event handlers', () => {
|
|
17
|
+
let calls: string[];
|
|
18
|
+
let registration: RegisterReactor;
|
|
19
|
+
let results: ReactorResult[];
|
|
20
|
+
|
|
21
|
+
beforeEach(async () => {
|
|
22
|
+
calls = [];
|
|
23
|
+
|
|
24
|
+
@reactor('paged-per-event')
|
|
25
|
+
class Items {
|
|
26
|
+
itemAdded(_event: ItemAdded, context: EventContext) {
|
|
27
|
+
calls.push(`${context.eventSourceId}:${context.sequenceNumber}`);
|
|
28
|
+
if (context.sequenceNumber === 3n) throw new Error('second item of b failed');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
({ registration, results } = await observeReactorMessages(Items, [ItemAdded], [page(42n, {
|
|
33
|
+
a: [appended('paged-item-added', 'a', 1n), appended('paged-item-added', 'a', 4n)],
|
|
34
|
+
b: [appended('paged-item-added', 'b', 2n), appended('paged-item-added', 'b', 3n), appended('paged-item-added', 'b', 5n)]
|
|
35
|
+
})]));
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('should opt in to page delivery at registration', () => registration.PageDelivery!.Enabled.should.be.true);
|
|
39
|
+
it('should call the handler for each event of each partition in order, and stop a partition at its failure', () =>
|
|
40
|
+
calls.should.deep.equal(['a:1', 'a:4', 'b:2', 'b:3']));
|
|
41
|
+
it('should echo the delivery identifier', () => results[0].DeliveryId.should.equal(42n));
|
|
42
|
+
it('should reply with one result per partition', () => results[0].Partitions.map(result => result.Partition).should.deep.equal(['a', 'b']));
|
|
43
|
+
it('should settle the healthy partition at its last event', () => {
|
|
44
|
+
results[0].Partitions[0].State.should.equal(ObservationState.Success);
|
|
45
|
+
results[0].Partitions[0].LastSuccessfulObservation.should.equal(4n);
|
|
46
|
+
});
|
|
47
|
+
it('should settle the failed partition at the event before its failure', () => {
|
|
48
|
+
results[0].Partitions[1].State.should.equal(ObservationState.Failed);
|
|
49
|
+
results[0].Partitions[1].LastSuccessfulObservation.should.equal(2n);
|
|
50
|
+
results[0].Partitions[1].ExceptionMessages.should.deep.equal(['Error: second item of b failed']);
|
|
51
|
+
});
|
|
52
|
+
});
|
package/reactors/index.ts
CHANGED
|
@@ -13,3 +13,5 @@ export type { IReactors } from './IReactors.js';
|
|
|
13
13
|
export { Reactors } from './Reactors.js';
|
|
14
14
|
export type { ReactorResultHandler } from './ReactorResultHandler.js';
|
|
15
15
|
export type { ReactorServices } from './ReactorServices.js';
|
|
16
|
+
export { observes, batchSize, EventBatch, EventAndContext, BatchContext, ObservationOrigin } from '../observation/index.js';
|
|
17
|
+
export type { BatchSizeOptions } from '../observation/index.js';
|