@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.
- package/EventStore.ts +2 -2
- package/WellKnownTelemetryNames.ts +2 -0
- package/auditing/CausationType.ts +5 -0
- package/dist/EventStore.js +2 -2
- package/dist/EventStore.js.map +1 -1
- package/dist/WellKnownTelemetryNames.d.ts +2 -0
- package/dist/WellKnownTelemetryNames.d.ts.map +1 -1
- package/dist/WellKnownTelemetryNames.js +2 -0
- package/dist/WellKnownTelemetryNames.js.map +1 -1
- package/dist/auditing/CausationType.d.ts +4 -0
- package/dist/auditing/CausationType.d.ts.map +1 -1
- package/dist/auditing/CausationType.js +4 -0
- package/dist/auditing/CausationType.js.map +1 -1
- package/dist/eventSequences/CompensateOptions.d.ts +7 -0
- package/dist/eventSequences/CompensateOptions.d.ts.map +1 -0
- package/dist/eventSequences/CompensateOptions.js +4 -0
- package/dist/eventSequences/CompensateOptions.js.map +1 -0
- package/dist/eventSequences/EventSequence.d.ts +3 -0
- package/dist/eventSequences/EventSequence.d.ts.map +1 -1
- package/dist/eventSequences/EventSequence.js +45 -0
- package/dist/eventSequences/EventSequence.js.map +1 -1
- package/dist/eventSequences/IEventSequence.d.ts +13 -0
- package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
- package/dist/eventSequences/index.d.ts +1 -0
- package/dist/eventSequences/index.d.ts.map +1 -1
- package/dist/eventSequences/index.js.map +1 -1
- package/dist/events/EventContext.d.ts +5 -0
- package/dist/events/EventContext.d.ts.map +1 -1
- package/dist/events/compensationForDecorator.d.ts +32 -0
- package/dist/events/compensationForDecorator.d.ts.map +1 -0
- package/dist/events/compensationForDecorator.js +44 -0
- package/dist/events/compensationForDecorator.js.map +1 -0
- package/dist/events/eventTypeDecorator.d.ts +7 -0
- package/dist/events/eventTypeDecorator.d.ts.map +1 -1
- package/dist/events/eventTypeDecorator.js +13 -4
- package/dist/events/eventTypeDecorator.js.map +1 -1
- package/dist/events/index.d.ts +2 -1
- package/dist/events/index.d.ts.map +1 -1
- package/dist/events/index.js +2 -1
- package/dist/events/index.js.map +1 -1
- package/dist/events/toClientEventContext.d.ts.map +1 -1
- package/dist/events/toClientEventContext.js +20 -0
- package/dist/events/toClientEventContext.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/projections/eventContextPropertyExpression.js +1 -1
- package/dist/projections/eventContextPropertyExpression.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/schemas/JsonSchema.d.ts +2 -0
- package/dist/schemas/JsonSchema.d.ts.map +1 -1
- package/dist/testing/InProcessEventSequence.d.ts +1 -0
- package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
- package/dist/testing/InProcessEventSequence.js +1 -0
- package/dist/testing/InProcessEventSequence.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/eventSequences/CompensateOptions.ts +10 -0
- package/eventSequences/EventSequence.compensate.spec.ts +72 -0
- package/eventSequences/EventSequence.ts +51 -0
- package/eventSequences/IEventSequence.ts +14 -0
- package/eventSequences/index.ts +1 -0
- package/events/EventContext.ts +6 -0
- package/events/compensationFor.spec.ts +73 -0
- package/events/compensationForDecorator.ts +48 -0
- package/events/eventTypeDecorator.ts +13 -4
- package/events/index.ts +2 -1
- package/events/toClientEventContext.ts +21 -0
- 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 +2 -2
- package/projections/eventContextPropertyExpression.ts +2 -2
- 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/schemas/JsonSchema.ts +2 -0
- package/telemetry/for_ChronicleTelemetry/given/a_client.fixture.ts +1 -0
- package/telemetry/for_ChronicleTelemetry/given/a_span_name_registry.fixture.ts +2 -0
- package/telemetry/for_ChronicleTelemetry/when_naming_spans/with_convention_names.spec.ts +2 -1
- package/testing/InProcessEventSequence.ts +1 -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
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { Constructor } from '@cratis/fundamentals';
|
|
5
|
+
import { ObservationState, ReplayState, type AppendedEvent, type EventsToObserve, type ReactorResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import type { ActivatedArtifact } from '../artifacts/ActivatedArtifact.js';
|
|
7
|
+
import { ArtifactCompletionFailed } from '../artifacts/ArtifactCompletionFailed.js';
|
|
8
|
+
import { ArtifactDelivery } from '../artifacts/ArtifactDelivery.js';
|
|
9
|
+
import { ArtifactKind } from '../artifacts/ArtifactKind.js';
|
|
10
|
+
import { runActivated, withActivatedArtifact } from '../artifacts/withActivatedArtifact.js';
|
|
11
|
+
import type { EventContext } from '../events/EventContext.js';
|
|
12
|
+
import { toClientEventContext } from '../events/toClientEventContext.js';
|
|
13
|
+
import { notifyReplayLifecycle } from '../observation/notifyReplayLifecycle.js';
|
|
14
|
+
import type { BatchContext } from '../observation/batches/BatchContext.js';
|
|
15
|
+
import { createBatchContext } from '../observation/batches/createBatchContext.js';
|
|
16
|
+
import { BatchOutcomeKind } from '../observation/batches/BatchOutcomeKind.js';
|
|
17
|
+
import type { BatchMethod } from '../observation/batches/BatchMethod.js';
|
|
18
|
+
import { BatchMethodReturnedAValue } from '../observation/batches/BatchMethodReturnedAValue.js';
|
|
19
|
+
import { EventAndContext } from '../observation/batches/EventAndContext.js';
|
|
20
|
+
import { EventBatch } from '../observation/batches/EventBatch.js';
|
|
21
|
+
import { isPage, partitionsOfEvents } from '../observation/batches/PageMessages.js';
|
|
22
|
+
import type { DeliveredPartition } from '../observation/batches/DeliveredPartition.js';
|
|
23
|
+
import { PartitionFailedInBatch } from '../observation/batches/PartitionFailedInBatch.js';
|
|
24
|
+
import { failedAt, settlePartition, toPartitionResult } from '../observation/batches/PartitionSettlement.js';
|
|
25
|
+
import type { PartitionOutcome } from '../observation/batches/PartitionOutcome.js';
|
|
26
|
+
import type { PartitionProblem } from '../observation/batches/PartitionProblem.js';
|
|
27
|
+
import { dispatchReactorSideEffects } from './ReactorSideEffects.js';
|
|
28
|
+
import { invokeReactorHandler, selectReactorHandler } from './ReactorDispatcher.js';
|
|
29
|
+
import type { ReactorObservationTarget } from './ReactorObservationTarget.js';
|
|
30
|
+
import { ReactorDelivery } from './ReactorDelivery.js';
|
|
31
|
+
|
|
32
|
+
type ReactorInstance = Record<string, Function>;
|
|
33
|
+
type Artifact = ActivatedArtifact<ReactorInstance>;
|
|
34
|
+
|
|
35
|
+
/** An event of a page bound for a batch method, with the partition it was delivered in. */
|
|
36
|
+
type PageEvent = { readonly partition: string; readonly event: EventAndContext };
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Dispatches one delivery of a reactor observation, a page of partitions or a legacy single partition, to its batch and
|
|
41
|
+
* per-event methods, and settles each partition on its own.
|
|
42
|
+
*/
|
|
43
|
+
export class ReactorPageDispatcher {
|
|
44
|
+
private readonly _batchEventTypes: ReadonlyMap<string, { method: BatchMethod; type: Constructor }>;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Creates a new {@link ReactorPageDispatcher}.
|
|
48
|
+
* @param _target - The {@link ReactorObservationTarget}.
|
|
49
|
+
*/
|
|
50
|
+
constructor(private readonly _target: ReactorObservationTarget) {
|
|
51
|
+
this._batchEventTypes = new Map(_target.batchMethods.flatMap(method =>
|
|
52
|
+
[...method.eventTypes.values()].map(eventType => [eventType.id, { method, type: eventType.type }] as const)));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Dispatches a delivery and creates the result to send back to the kernel.
|
|
57
|
+
* @param message - The {@link EventsToObserve} delivered.
|
|
58
|
+
* @returns The {@link ReactorResult}.
|
|
59
|
+
*/
|
|
60
|
+
async dispatch(message: EventsToObserve): Promise<ReactorResult> {
|
|
61
|
+
const partitions = partitionsOfEvents(message);
|
|
62
|
+
this._target.logger.debug('Received events to observe', {
|
|
63
|
+
reactorId: this._target.id,
|
|
64
|
+
partitions: partitions.length,
|
|
65
|
+
count: partitions.reduce((count, partition) => count + partition.events.length, 0),
|
|
66
|
+
replayState: message.ReplayState
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const notificationFailure = await this.notifyReplayTransition(message, partitions);
|
|
70
|
+
const problems = notificationFailure ?? await this.observe(message, partitions);
|
|
71
|
+
const outcomes = partitions.map(partition => settlePartition(partition.partition,
|
|
72
|
+
partition.events.map(event => event.Context!.SequenceNumber), problems));
|
|
73
|
+
return toReactorResult(message, outcomes);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private async notifyReplayTransition(message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[] | undefined> {
|
|
77
|
+
const { id, reactorType, eventSequenceId, services, signal, artifactActivator, reactorInstance, validateInstance } = this._target;
|
|
78
|
+
try {
|
|
79
|
+
if (artifactActivator && message.ReplayState !== ReplayState.REPLAY_STATE_None) {
|
|
80
|
+
if (!services) throw new Error('Reactor activation requires the owning event store.');
|
|
81
|
+
await withActivatedArtifact(reactorType, {
|
|
82
|
+
kind: ArtifactKind.Reactor, artifactId: id, eventStore: services.eventStore,
|
|
83
|
+
readModels: services.readModels, eventSequenceId, partition: message.Partition,
|
|
84
|
+
signal, delivery: ArtifactDelivery.ReplayNotification, replayState: message.ReplayState
|
|
85
|
+
}, artifactActivator, artifact => {
|
|
86
|
+
validateInstance(artifact.instance as object);
|
|
87
|
+
return runActivated(artifact, () =>
|
|
88
|
+
notifyReplayLifecycle(artifact.instance as object, message.ReplayState, message.Partition),
|
|
89
|
+
{ delivery: ArtifactDelivery.ReplayNotification, replayState: message.ReplayState });
|
|
90
|
+
}, this._target.connectionLogger);
|
|
91
|
+
} else if (reactorInstance) {
|
|
92
|
+
await notifyReplayLifecycle(reactorInstance, message.ReplayState, message.Partition);
|
|
93
|
+
}
|
|
94
|
+
return undefined;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
this._target.logger.error('Error notifying reactor of replay lifecycle transition', { reactorId: id, error });
|
|
97
|
+
const messages = error instanceof ArtifactCompletionFailed && error.processingError !== undefined
|
|
98
|
+
? [String(error.processingError), String(error)] : [String(error)];
|
|
99
|
+
return partitions.map(partition => ({
|
|
100
|
+
...failedAt(partition.partition, firstSequenceNumberOf(partition), error),
|
|
101
|
+
exceptionMessages: messages
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private async observe(message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
|
|
107
|
+
const { id, reactorType, eventSequenceId, services, signal, artifactActivator, reactorInstance, validateInstance } = this._target;
|
|
108
|
+
const first = artifactActivator ? this.firstInvocableEvent(partitions) : undefined;
|
|
109
|
+
if (!first || !artifactActivator) {
|
|
110
|
+
return this.observeWith({ instance: reactorInstance ?? {} }, message, partitions);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const problems: PartitionProblem[] = [];
|
|
114
|
+
try {
|
|
115
|
+
if (!services) throw new Error('Reactor activation requires the owning event store.');
|
|
116
|
+
await withActivatedArtifact(reactorType as new () => ReactorInstance, {
|
|
117
|
+
kind: ArtifactKind.Reactor, artifactId: id, eventStore: services.eventStore,
|
|
118
|
+
readModels: services.readModels, eventSequenceId, partition: first.partition,
|
|
119
|
+
signal, delivery: ArtifactDelivery.Events, eventContext: toClientEventContext(first.event.Context!)
|
|
120
|
+
}, artifactActivator, async artifact => {
|
|
121
|
+
validateInstance(artifact.instance);
|
|
122
|
+
problems.push(...await this.observeWith(artifact, message, partitions));
|
|
123
|
+
}, this._target.connectionLogger);
|
|
124
|
+
return problems;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
this._target.logger.error('Error activating reactor', { reactorId: id, error });
|
|
127
|
+
return partitions.map(partition => activationFailure(partition, problems, error));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private firstInvocableEvent(partitions: readonly DeliveredPartition[]): { partition: string; event: AppendedEvent } | undefined {
|
|
132
|
+
for (const partition of partitions) {
|
|
133
|
+
for (const event of partition.events) {
|
|
134
|
+
const eventTypeId = event.Context?.EventType?.Id;
|
|
135
|
+
if (eventTypeId && this._batchEventTypes.has(eventTypeId)) return { partition: partition.partition, event };
|
|
136
|
+
const selection = this.select(this._target.reactorInstance, event);
|
|
137
|
+
if (selection?.methodName && !selection.skipReplay) return { partition: partition.partition, event };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private select(instance: ReactorInstance | undefined, event: AppendedEvent) {
|
|
144
|
+
return selectReactorHandler(this._target.entries, this._target.reactorType, instance,
|
|
145
|
+
event.Context?.EventType?.Id, event.Context?.ObservationState ?? 0);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private async observeWith(artifact: Artifact, message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
|
|
149
|
+
const problems: PartitionProblem[] = [];
|
|
150
|
+
if (this._target.batchMethods.length > 0) {
|
|
151
|
+
problems.push(...await this.observeBatches(artifact, message, partitions));
|
|
152
|
+
}
|
|
153
|
+
for (const partition of partitions) {
|
|
154
|
+
const problem = await this.observePartition(artifact, partition);
|
|
155
|
+
if (problem) problems.push(problem);
|
|
156
|
+
}
|
|
157
|
+
return problems;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
private async observeBatches(artifact: Artifact, message: EventsToObserve, partitions: readonly DeliveredPartition[]): Promise<PartitionProblem[]> {
|
|
161
|
+
const problems: PartitionProblem[] = [];
|
|
162
|
+
const events: PageEvent[] = [];
|
|
163
|
+
for (const partition of partitions) {
|
|
164
|
+
for (const event of partition.events) {
|
|
165
|
+
const batchEventType = this._batchEventTypes.get(event.Context?.EventType?.Id ?? '');
|
|
166
|
+
if (!batchEventType) continue;
|
|
167
|
+
try {
|
|
168
|
+
events.push({ partition: partition.partition, event: this.toEventAndContext(event, batchEventType.type) });
|
|
169
|
+
} catch (error) {
|
|
170
|
+
problems.push(failedAt(partition.partition, event.Context!.SequenceNumber, error));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
events.sort((left, right) => left.event.context.sequenceNumber < right.event.context.sequenceNumber ? -1
|
|
175
|
+
: left.event.context.sequenceNumber > right.event.context.sequenceNumber ? 1 : 0);
|
|
176
|
+
|
|
177
|
+
const context = this.createBatchContext(message, partitions);
|
|
178
|
+
for (const method of this._target.batchMethods) {
|
|
179
|
+
const observed = events.filter(event => method.eventTypes.has(event.event.context.eventType.id.value));
|
|
180
|
+
if (observed.length === 0) continue;
|
|
181
|
+
problems.push(...await this.invokeBatchMethod(artifact, method, observed, context));
|
|
182
|
+
}
|
|
183
|
+
return problems;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private async invokeBatchMethod(artifact: Artifact, method: BatchMethod, observed: readonly PageEvent[], context: BatchContext): Promise<PartitionProblem[]> {
|
|
187
|
+
const { id, reactorType } = this._target;
|
|
188
|
+
const batch = new EventBatch(observed.map(event => event.event), context.canDefer);
|
|
189
|
+
const partitionOf = new Map(observed.map(event => [event.event.context.eventSourceId, event.partition]));
|
|
190
|
+
try {
|
|
191
|
+
this._target.logger.info('Invoking reactor batch method', { reactorId: id, method: method.methodName, count: observed.length });
|
|
192
|
+
const result: unknown = await runActivated(artifact, () => artifact.instance[method.methodName](batch, context),
|
|
193
|
+
{ delivery: ArtifactDelivery.Events, eventContext: observed[0].event.context, methodName: method.methodName });
|
|
194
|
+
if (result !== undefined) throw new BatchMethodReturnedAValue((reactorType as Function).name, method.methodName);
|
|
195
|
+
return batch.outcomes.map(outcome => {
|
|
196
|
+
const partition = partitionOf.get(outcome.partition) ?? outcome.partition;
|
|
197
|
+
return outcome.kind === BatchOutcomeKind.Deferred
|
|
198
|
+
? { partition, at: outcome.at, state: ObservationState.Deferred, exceptionMessages: [], exceptionStackTrace: '',
|
|
199
|
+
retryAfterMilliseconds: outcome.retryAfterMilliseconds }
|
|
200
|
+
: failedAt(partition, outcome.at, outcome.error ?? new PartitionFailedInBatch(outcome.partition));
|
|
201
|
+
});
|
|
202
|
+
} catch (error) {
|
|
203
|
+
this._target.logger.error('Error handling events in reactor batch method', { reactorId: id, method: method.methodName, error });
|
|
204
|
+
const firstOfPartition = new Map<string, bigint>();
|
|
205
|
+
for (const event of observed) {
|
|
206
|
+
if (!firstOfPartition.has(event.partition)) firstOfPartition.set(event.partition, event.event.context.sequenceNumber);
|
|
207
|
+
}
|
|
208
|
+
return [...firstOfPartition].map(([partition, at]) => failedAt(partition, at, error));
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private async observePartition(artifact: Artifact, partition: DeliveredPartition): Promise<PartitionProblem | undefined> {
|
|
213
|
+
const { id, reactorType, eventStoreName, namespace, services, eventLog, resultHandler } = this._target;
|
|
214
|
+
for (const event of partition.events) {
|
|
215
|
+
const eventTypeId = event.Context?.EventType?.Id;
|
|
216
|
+
if (!eventTypeId) {
|
|
217
|
+
this._target.logger.warn('Event missing event type context', { reactorId: id });
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (this._batchEventTypes.has(eventTypeId)) continue;
|
|
221
|
+
|
|
222
|
+
const selection = this.select(artifact.instance, event);
|
|
223
|
+
if (!selection?.methodName || selection.skipReplay) {
|
|
224
|
+
if (selection?.skipReplay) {
|
|
225
|
+
this._target.logger.debug('Reactor handler skipped for replay', { reactorId: id, eventTypeId, method: selection.methodName });
|
|
226
|
+
} else {
|
|
227
|
+
this._target.logger.debug('No reactor handler found', { reactorId: id, eventTypeId, isReplay: selection?.isReplay ?? false });
|
|
228
|
+
}
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
const content = JSON.parse(event.Content) as Record<string, unknown>;
|
|
234
|
+
const context = toClientEventContext(event.Context!);
|
|
235
|
+
this._target.logger.info('Invoking reactor handler', {
|
|
236
|
+
reactorId: id, method: selection.methodName, sequenceNumber: event.Context!.SequenceNumber.toString(), eventTypeId
|
|
237
|
+
});
|
|
238
|
+
await invokeReactorHandler(artifact, selection.methodName, content, context, services, result =>
|
|
239
|
+
dispatchReactorSideEffects(eventLog, result, context, reactorType as Function, eventStoreName, namespace, resultHandler),
|
|
240
|
+
this.deliveryFor(context));
|
|
241
|
+
} catch (error) {
|
|
242
|
+
this._target.logger.error('Error handling event in reactor', { reactorId: id, error });
|
|
243
|
+
return failedAt(partition.partition, event.Context!.SequenceNumber, error);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private toEventAndContext(event: AppendedEvent, eventType: Constructor): EventAndContext {
|
|
250
|
+
const context = toClientEventContext(event.Context!);
|
|
251
|
+
return new EventAndContext(JSON.parse(event.Content) as Record<string, unknown>, context, eventType, this.deliveryFor(context));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private deliveryFor(context: EventContext): ReactorDelivery {
|
|
255
|
+
const { id, eventStoreName, namespace, eventSequenceId } = this._target;
|
|
256
|
+
return new ReactorDelivery(id, context.eventStore ?? eventStoreName, context.namespace ?? namespace, eventSequenceId,
|
|
257
|
+
context.eventSourceId, context.sequenceNumber);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
private createBatchContext(message: EventsToObserve, partitions: readonly DeliveredPartition[]): BatchContext {
|
|
261
|
+
const { id, eventStoreName, namespace, eventSequenceId, signal } = this._target;
|
|
262
|
+
return createBatchContext({ observerId: id, eventStore: eventStoreName, namespace, eventSequenceId, signal }, message, partitions);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Gets the sequence number of the first event of a partition, or zero when it has none.
|
|
268
|
+
* @param partition - The partition.
|
|
269
|
+
* @returns The sequence number.
|
|
270
|
+
*/
|
|
271
|
+
function firstSequenceNumberOf(partition: DeliveredPartition): bigint {
|
|
272
|
+
return partition.events[0]?.Context?.SequenceNumber ?? 0n;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Replaces what a partition reported with the failure of the activation that observed it, keeping the reported messages.
|
|
277
|
+
* @param partition - The partition.
|
|
278
|
+
* @param problems - The problems reported while observing, before the activation failed.
|
|
279
|
+
* @param error - The activation failure.
|
|
280
|
+
* @returns The {@link PartitionProblem} failing the partition from its first event.
|
|
281
|
+
*/
|
|
282
|
+
function activationFailure(partition: DeliveredPartition, problems: readonly PartitionProblem[], error: unknown): PartitionProblem {
|
|
283
|
+
const reported = problems.filter(problem => problem.partition === partition.partition)
|
|
284
|
+
.reduce<PartitionProblem | undefined>((first, problem) => !first || problem.at < first.at ? problem : first, undefined);
|
|
285
|
+
const stack = error instanceof Error ? (error.stack ?? '') : '';
|
|
286
|
+
return {
|
|
287
|
+
partition: partition.partition,
|
|
288
|
+
at: firstSequenceNumberOf(partition),
|
|
289
|
+
state: ObservationState.Failed,
|
|
290
|
+
exceptionMessages: [...(reported?.exceptionMessages ?? []), String(error)],
|
|
291
|
+
exceptionStackTrace: error instanceof ArtifactCompletionFailed && reported?.exceptionStackTrace ? `${reported.exceptionStackTrace}\n${stack}` : stack,
|
|
292
|
+
retryAfterMilliseconds: 0
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Creates the result of a delivery: one result per partition for a page, or the legacy single-partition fields.
|
|
298
|
+
* @param message - The delivered message.
|
|
299
|
+
* @param outcomes - The outcome of each partition, in delivery order.
|
|
300
|
+
* @returns The {@link ReactorResult}.
|
|
301
|
+
*/
|
|
302
|
+
function toReactorResult(message: EventsToObserve, outcomes: readonly PartitionOutcome[]): ReactorResult {
|
|
303
|
+
if (isPage(message)) {
|
|
304
|
+
return {
|
|
305
|
+
Partition: '', State: ObservationState.OBSERVATION_STATE_None, LastSuccessfulObservation: 0n,
|
|
306
|
+
ExceptionMessages: [], ExceptionStackTrace: '', DeliveryId: message.DeliveryId ?? 0n,
|
|
307
|
+
RetryAfterMilliseconds: 0n, Partitions: outcomes.map(toPartitionResult)
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
const [outcome] = outcomes;
|
|
311
|
+
return {
|
|
312
|
+
Partition: message.Partition,
|
|
313
|
+
State: outcome.state === ObservationState.Deferred ? ObservationState.Failed : outcome.state,
|
|
314
|
+
LastSuccessfulObservation: outcome.lastSuccessfulObservation,
|
|
315
|
+
ExceptionMessages: [...outcome.exceptionMessages],
|
|
316
|
+
ExceptionStackTrace: outcome.exceptionStackTrace,
|
|
317
|
+
DeliveryId: message.DeliveryId ?? 0n,
|
|
318
|
+
RetryAfterMilliseconds: 0n,
|
|
319
|
+
Partitions: []
|
|
320
|
+
};
|
|
321
|
+
}
|
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
|
+
}
|