@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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Copyright (c) Cratis. All rights reserved.
|
|
2
2
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
3
|
|
|
4
|
-
import { ObservationState, ReducerMessage } from '@cratis/chronicle.contracts';
|
|
4
|
+
import { ObservationState, type PartitionResult, type ReducerMessage } from '@cratis/chronicle.contracts';
|
|
5
5
|
import { ArtifactCompletionFailed } from '../artifacts/ArtifactCompletionFailed.js';
|
|
6
6
|
|
|
7
7
|
/** Sentinel sequence number sent back when no event was successfully processed. */
|
|
@@ -18,6 +18,7 @@ export class ReductionOutcome {
|
|
|
18
18
|
lastSuccessfullyObservedEvent = SEQUENCE_NUMBER_UNAVAILABLE;
|
|
19
19
|
readonly exceptionMessages: string[] = [];
|
|
20
20
|
exceptionStackTrace = '';
|
|
21
|
+
retryAfterMilliseconds = 0;
|
|
21
22
|
currentState: unknown;
|
|
22
23
|
|
|
23
24
|
/** Gets whether the reduction has failed. */
|
|
@@ -32,6 +33,27 @@ export class ReductionOutcome {
|
|
|
32
33
|
this.state = ObservationState.Failed;
|
|
33
34
|
}
|
|
34
35
|
|
|
36
|
+
/**
|
|
37
|
+
* Records that a batch method deferred the reduction: nothing is written, and the event source is delivered again later.
|
|
38
|
+
* @param retryAfterMilliseconds - How long to wait before delivering again.
|
|
39
|
+
*/
|
|
40
|
+
recordDeferral(retryAfterMilliseconds: number): void {
|
|
41
|
+
this.state = ObservationState.Deferred;
|
|
42
|
+
this.lastSuccessfullyObservedEvent = SEQUENCE_NUMBER_UNAVAILABLE;
|
|
43
|
+
this.retryAfterMilliseconds = retryAfterMilliseconds;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Copies the result of another outcome, such as a failed replay notification shared by every event source of a page.
|
|
48
|
+
* @param other - The outcome to copy.
|
|
49
|
+
*/
|
|
50
|
+
copyFrom(other: ReductionOutcome): void {
|
|
51
|
+
this.state = other.state;
|
|
52
|
+
this.lastSuccessfullyObservedEvent = other.lastSuccessfullyObservedEvent;
|
|
53
|
+
this.exceptionMessages.push(...other.exceptionMessages);
|
|
54
|
+
this.exceptionStackTrace = other.exceptionStackTrace;
|
|
55
|
+
}
|
|
56
|
+
|
|
35
57
|
/** Records a failure to notify of a replay lifecycle transition. */
|
|
36
58
|
recordReplayNotificationFailure(error: unknown): void {
|
|
37
59
|
if (error instanceof ArtifactCompletionFailed && error.processingError !== undefined) {
|
|
@@ -52,23 +74,48 @@ export class ReductionOutcome {
|
|
|
52
74
|
}
|
|
53
75
|
}
|
|
54
76
|
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
77
|
+
/** The read model state as JSON, or an empty string when there is nothing to write. */
|
|
78
|
+
get readModelState(): string {
|
|
79
|
+
return this.state === ObservationState.Success && this.currentState !== undefined
|
|
58
80
|
? JSON.stringify(this.currentState)
|
|
59
|
-
:
|
|
81
|
+
: '';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Creates the result for one event source of a page.
|
|
86
|
+
* @param partition - The partition (event source).
|
|
87
|
+
* @returns The {@link PartitionResult}.
|
|
88
|
+
*/
|
|
89
|
+
toPartitionResult(partition: string): PartitionResult {
|
|
90
|
+
return {
|
|
91
|
+
Partition: partition,
|
|
92
|
+
State: this.state,
|
|
93
|
+
LastSuccessfulObservation: this.lastSuccessfullyObservedEvent,
|
|
94
|
+
ExceptionMessages: this.exceptionMessages,
|
|
95
|
+
ExceptionStackTrace: this.exceptionStackTrace,
|
|
96
|
+
RetryAfterMilliseconds: BigInt(Math.max(0, Math.round(this.retryAfterMilliseconds))),
|
|
97
|
+
ReadModelState: this.readModelState
|
|
98
|
+
};
|
|
99
|
+
}
|
|
60
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Creates the legacy single-partition result message reported back to a kernel that does not deliver pages.
|
|
103
|
+
* @param partition - The partition (event source).
|
|
104
|
+
* @param deliveryId - The delivery identifier to echo.
|
|
105
|
+
* @returns The {@link ReducerMessage}.
|
|
106
|
+
*/
|
|
107
|
+
toMessage(partition: string, deliveryId: bigint = 0n): ReducerMessage {
|
|
61
108
|
return {
|
|
62
109
|
Content: {
|
|
63
110
|
Value0: undefined,
|
|
64
111
|
Value1: {
|
|
65
112
|
Partition: partition,
|
|
66
|
-
State: this.state,
|
|
113
|
+
State: this.state === ObservationState.Deferred ? ObservationState.Failed : this.state,
|
|
67
114
|
LastSuccessfulObservation: this.lastSuccessfullyObservedEvent,
|
|
68
115
|
ExceptionMessages: this.exceptionMessages,
|
|
69
116
|
ExceptionStackTrace: this.exceptionStackTrace,
|
|
70
|
-
ReadModelState: readModelState
|
|
71
|
-
DeliveryId:
|
|
117
|
+
ReadModelState: this.readModelState,
|
|
118
|
+
DeliveryId: deliveryId,
|
|
72
119
|
RetryAfterMilliseconds: 0n,
|
|
73
120
|
Partitions: []
|
|
74
121
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
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, ObservationOrigin, ReduceOperationMessage, ReplayState,
|
|
7
|
+
type RegisterReducer, type ReducerMessage, type ReducerResult
|
|
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 { IEventStore } from '../../../IEventStore.js';
|
|
13
|
+
import { Reducers } from '../../Reducers.js';
|
|
14
|
+
|
|
15
|
+
/** Creates a delivered event of a type for an event source. */
|
|
16
|
+
export function appended(eventTypeId: string, eventSourceId: string, sequenceNumber: bigint, content: object = {}): AppendedEvent {
|
|
17
|
+
return AppendedEvent.fromPartial({
|
|
18
|
+
Content: JSON.stringify(content),
|
|
19
|
+
Context: { EventType: { Id: eventTypeId, Generation: 1 }, EventSourceId: eventSourceId, SequenceNumber: sequenceNumber }
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The events and stored state of one event source in a page. */
|
|
24
|
+
export interface ReducerPartitionInput {
|
|
25
|
+
readonly initialState?: object;
|
|
26
|
+
readonly events: AppendedEvent[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Creates a page of event sources, as a kernel that delivers pages sends it. */
|
|
30
|
+
export function page(deliveryId: bigint, partitions: Record<string, ReducerPartitionInput>, origin = ObservationOrigin.Live): ReduceOperationMessage {
|
|
31
|
+
return ReduceOperationMessage.fromPartial({
|
|
32
|
+
DeliveryId: deliveryId, Origin: origin, ReplayState: ReplayState.REPLAY_STATE_None,
|
|
33
|
+
Partitions: Object.entries(partitions).map(([partition, input]) => ({
|
|
34
|
+
Partition: partition, Events: input.events, InitialState: input.initialState ? JSON.stringify(input.initialState) : ''
|
|
35
|
+
}))
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Creates a legacy single-partition operation, as a kernel that does not deliver pages sends it. */
|
|
40
|
+
export function single(partition: string, events: AppendedEvent[], initialState?: object): ReduceOperationMessage {
|
|
41
|
+
return ReduceOperationMessage.fromPartial({
|
|
42
|
+
Partition: partition, Events: events, InitialState: initialState ? JSON.stringify(initialState) : '', ReplayState: ReplayState.REPLAY_STATE_None
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Observes a reducer through the production observation stream, without a kernel. */
|
|
47
|
+
export async function observeReducerMessages(reducerType: Constructor, eventTypes: Constructor[], messages: ReduceOperationMessage[]):
|
|
48
|
+
Promise<{ registration: RegisterReducer; results: ReducerResult[] }> {
|
|
49
|
+
const lifecycle = new ConnectionLifecycle();
|
|
50
|
+
const results: ReducerResult[] = [];
|
|
51
|
+
let registration!: RegisterReducer;
|
|
52
|
+
let finish!: () => void;
|
|
53
|
+
const finished = new Promise<void>(resolve => { finish = resolve; });
|
|
54
|
+
async function* stream(queue: AsyncIterable<ReducerMessage>) {
|
|
55
|
+
const outgoing = queue[Symbol.asyncIterator]();
|
|
56
|
+
try {
|
|
57
|
+
registration = (await outgoing.next()).value!.Content!.Value0!;
|
|
58
|
+
for (const message of messages) {
|
|
59
|
+
yield message;
|
|
60
|
+
results.push((await outgoing.next()).value!.Content!.Value1!);
|
|
61
|
+
}
|
|
62
|
+
} finally {
|
|
63
|
+
await lifecycle.disconnected(error => { throw error; });
|
|
64
|
+
finish();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const connection = { reducers: { observe: stream }, readModels: { registerMany: async () => ({}) } } as unknown as ChronicleConnection;
|
|
68
|
+
const artifacts = { reducers: [reducerType], eventTypes, readModels: [] } as unknown as IClientArtifactsProvider;
|
|
69
|
+
const reducers = new Reducers(artifacts, connection, 'store', 'default', lifecycle, 'sink', { readModels: {} } as IEventStore);
|
|
70
|
+
try {
|
|
71
|
+
await reducers.register();
|
|
72
|
+
await finished;
|
|
73
|
+
return { registration, results };
|
|
74
|
+
} finally {
|
|
75
|
+
reducers.dispose();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
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 RegisterReducer, type ReducerResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
7
|
+
import { BatchContext, EventBatch, ObservationOrigin, batchSize, observes } from '../../../observation/index.js';
|
|
8
|
+
import { reducer } from '../../reducer.js';
|
|
9
|
+
import { appended, observeReducerMessages, page } from '../given/observe_reducer_messages.js';
|
|
10
|
+
|
|
11
|
+
chai.should();
|
|
12
|
+
|
|
13
|
+
@eventType('batch-reducer-money-deposited')
|
|
14
|
+
class MoneyDeposited {
|
|
15
|
+
constructor(readonly amount: number = 0) {}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
@eventType('batch-reducer-money-withdrawn')
|
|
19
|
+
class MoneyWithdrawn {
|
|
20
|
+
constructor(readonly amount: number = 0) {}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Balance {
|
|
24
|
+
readonly balance: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe('when delivering a page to a reducer with a batch method', () => {
|
|
28
|
+
let calls: { partitions: readonly string[]; current: Balance | undefined; count: number }[];
|
|
29
|
+
let contexts: BatchContext[];
|
|
30
|
+
let registration: RegisterReducer;
|
|
31
|
+
let results: ReducerResult[];
|
|
32
|
+
|
|
33
|
+
beforeEach(async () => {
|
|
34
|
+
calls = [];
|
|
35
|
+
contexts = [];
|
|
36
|
+
|
|
37
|
+
@reducer('batch-balances')
|
|
38
|
+
@batchSize({ maxConcurrency: 1, maxEvents: 250 })
|
|
39
|
+
class Balances {
|
|
40
|
+
@observes(MoneyDeposited)
|
|
41
|
+
@observes(MoneyWithdrawn)
|
|
42
|
+
reduce(events: EventBatch, current: Balance | undefined, context: BatchContext): Balance | undefined {
|
|
43
|
+
calls.push({ partitions: events.partitions, current, count: events.length });
|
|
44
|
+
contexts.push(context);
|
|
45
|
+
if (events.partitions[0] === 'throttled') {
|
|
46
|
+
events.defer('throttled', 750);
|
|
47
|
+
return current;
|
|
48
|
+
}
|
|
49
|
+
if (events.partitions[0] === 'rejected') {
|
|
50
|
+
events.fail(events.events[1].context, new Error('overdrawn'));
|
|
51
|
+
return current;
|
|
52
|
+
}
|
|
53
|
+
return events.events.reduce((balance, entry) => ({
|
|
54
|
+
balance: balance.balance + (entry.is(MoneyDeposited) ? entry.event.amount : entry.is(MoneyWithdrawn) ? -entry.event.amount : 0)
|
|
55
|
+
}), current ?? { balance: 0 });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
({ registration, results } = await observeReducerMessages(Balances, [MoneyDeposited, MoneyWithdrawn], [page(9n, {
|
|
60
|
+
existing: { initialState: { balance: 100 }, events: [
|
|
61
|
+
appended('batch-reducer-money-deposited', 'existing', 1n, { amount: 50 }),
|
|
62
|
+
appended('batch-reducer-money-withdrawn', 'existing', 3n, { amount: 30 })
|
|
63
|
+
] },
|
|
64
|
+
fresh: { events: [appended('batch-reducer-money-deposited', 'fresh', 2n, { amount: 10 })] },
|
|
65
|
+
throttled: { events: [appended('batch-reducer-money-deposited', 'throttled', 4n, { amount: 1 })] },
|
|
66
|
+
rejected: { initialState: { balance: 5 }, events: [
|
|
67
|
+
appended('batch-reducer-money-deposited', 'rejected', 5n, { amount: 1 }),
|
|
68
|
+
appended('batch-reducer-money-withdrawn', 'rejected', 6n, { amount: 100 })
|
|
69
|
+
] }
|
|
70
|
+
}, ContractObservationOrigin.Replaying)]));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const resultFor = (partition: string) => results[0].Partitions.find(result => result.Partition === partition)!;
|
|
74
|
+
|
|
75
|
+
it('should register the observed event types and the declared bounds', () => {
|
|
76
|
+
registration.Reducer!.EventTypes.map(eventType => eventType.EventType!.Id).sort()
|
|
77
|
+
.should.deep.equal(['batch-reducer-money-deposited', 'batch-reducer-money-withdrawn']);
|
|
78
|
+
registration.PageDelivery!.should.deep.equal({ Enabled: true, MaxEventsPerPage: 250, MaxBytesPerPage: 0, MaxDelayMilliseconds: 0 });
|
|
79
|
+
});
|
|
80
|
+
it('should call the batch method once per event source with its events and stored state', () =>
|
|
81
|
+
calls.should.deep.equal([
|
|
82
|
+
{ partitions: ['existing'], current: { balance: 100 }, count: 2 },
|
|
83
|
+
{ partitions: ['fresh'], current: undefined, count: 1 },
|
|
84
|
+
{ partitions: ['throttled'], current: undefined, count: 1 },
|
|
85
|
+
{ partitions: ['rejected'], current: { balance: 5 }, count: 2 }
|
|
86
|
+
]));
|
|
87
|
+
it('should describe the whole page in the batch context', () => {
|
|
88
|
+
contexts[0].origin.should.equal(ObservationOrigin.Replay);
|
|
89
|
+
contexts[0].isReplay.should.be.true;
|
|
90
|
+
contexts[0].partitions.should.deep.equal(['existing', 'fresh', 'throttled', 'rejected']);
|
|
91
|
+
contexts[0].eventCount.should.equal(6);
|
|
92
|
+
});
|
|
93
|
+
it('should echo the delivery identifier', () => results[0].DeliveryId.should.equal(9n));
|
|
94
|
+
it('should write the next state of each event source', () => {
|
|
95
|
+
resultFor('existing').State.should.equal(ObservationState.Success);
|
|
96
|
+
JSON.parse(resultFor('existing').ReadModelState).should.deep.equal({ balance: 120 });
|
|
97
|
+
resultFor('existing').LastSuccessfulObservation.should.equal(3n);
|
|
98
|
+
JSON.parse(resultFor('fresh').ReadModelState).should.deep.equal({ balance: 10 });
|
|
99
|
+
});
|
|
100
|
+
it('should defer an event source without writing its state', () => {
|
|
101
|
+
resultFor('throttled').State.should.equal(ObservationState.Deferred);
|
|
102
|
+
resultFor('throttled').RetryAfterMilliseconds.should.equal(750n);
|
|
103
|
+
resultFor('throttled').ReadModelState.should.equal('');
|
|
104
|
+
});
|
|
105
|
+
it('should fail an event source without writing its state', () => {
|
|
106
|
+
resultFor('rejected').State.should.equal(ObservationState.Failed);
|
|
107
|
+
resultFor('rejected').ExceptionMessages.should.deep.equal(['Error: overdrawn']);
|
|
108
|
+
resultFor('rejected').ReadModelState.should.equal('');
|
|
109
|
+
resultFor('rejected').LastSuccessfulObservation.should.equal(4294967295n);
|
|
110
|
+
});
|
|
111
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
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 RegisterReducer, type ReducerResult } from '@cratis/chronicle.contracts';
|
|
6
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
7
|
+
import { reducer } from '../../reducer.js';
|
|
8
|
+
import { appended, observeReducerMessages, page, single } from '../given/observe_reducer_messages.js';
|
|
9
|
+
|
|
10
|
+
chai.should();
|
|
11
|
+
|
|
12
|
+
@eventType('per-event-reducer-item-counted')
|
|
13
|
+
class ItemCounted {}
|
|
14
|
+
|
|
15
|
+
interface Count {
|
|
16
|
+
readonly count: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
describe('when delivering pages and single partitions to a reducer with per-event methods', () => {
|
|
20
|
+
let registration: RegisterReducer;
|
|
21
|
+
let results: ReducerResult[];
|
|
22
|
+
|
|
23
|
+
beforeEach(async () => {
|
|
24
|
+
@reducer('per-event-counts')
|
|
25
|
+
class Counts {
|
|
26
|
+
itemCounted(_event: ItemCounted, current: Count | undefined): Count {
|
|
27
|
+
if (current?.count === 1) throw new Error('count is stuck');
|
|
28
|
+
return { count: (current?.count ?? 0) + 1 };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
({ registration, results } = await observeReducerMessages(Counts, [ItemCounted], [
|
|
33
|
+
page(3n, {
|
|
34
|
+
first: { events: [appended('per-event-reducer-item-counted', 'first', 1n)] },
|
|
35
|
+
stuck: { initialState: { count: 1 }, events: [appended('per-event-reducer-item-counted', 'stuck', 2n)] }
|
|
36
|
+
}),
|
|
37
|
+
single('legacy', [appended('per-event-reducer-item-counted', 'legacy', 4n)], { count: 5 })
|
|
38
|
+
]));
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('should opt in to page delivery', () => registration.PageDelivery!.Enabled.should.be.true);
|
|
42
|
+
it('should fold each event source of a page on its own', () => {
|
|
43
|
+
results[0].Partitions.map(result => result.State).should.deep.equal([ObservationState.Success, ObservationState.Failed]);
|
|
44
|
+
JSON.parse(results[0].Partitions[0].ReadModelState).should.deep.equal({ count: 1 });
|
|
45
|
+
results[0].Partitions[1].ExceptionMessages.should.deep.equal(['Error: count is stuck']);
|
|
46
|
+
});
|
|
47
|
+
it('should reply to a legacy single partition in the legacy fields', () => {
|
|
48
|
+
results[1].Partition.should.equal('legacy');
|
|
49
|
+
results[1].Partitions.should.be.empty;
|
|
50
|
+
results[1].State.should.equal(ObservationState.Success);
|
|
51
|
+
JSON.parse(results[1].ReadModelState).should.deep.equal({ count: 6 });
|
|
52
|
+
});
|
|
53
|
+
});
|
package/reducers/index.ts
CHANGED
|
@@ -7,3 +7,5 @@ export { reducer, getReducerMetadata, isReducer } from './reducer.js';
|
|
|
7
7
|
export type { ReducerMetadata } from './reducer.js';
|
|
8
8
|
export type { IReducers } from './IReducers.js';
|
|
9
9
|
export { Reducers } from './Reducers.js';
|
|
10
|
+
export { observes, batchSize, EventBatch, EventAndContext, BatchContext, ObservationOrigin } from '../observation/index.js';
|
|
11
|
+
export type { BatchSizeOptions } from '../observation/index.js';
|
package/schemas/JsonSchema.ts
CHANGED
|
@@ -51,4 +51,6 @@ export type JsonSchema = {
|
|
|
51
51
|
enum?: Array<string | number | boolean | null>;
|
|
52
52
|
compliance?: ComplianceSchemaMetadata[];
|
|
53
53
|
security?: SecuritySchemaMetadata[];
|
|
54
|
+
/** The identifier of the event type this event type compensates for, when it is a compensation. */
|
|
55
|
+
compensationFor?: string;
|
|
54
56
|
};
|
|
@@ -26,6 +26,7 @@ vi.mock('../../../connection/ChronicleConnection.js', () => ({
|
|
|
26
26
|
hasEventsForEventSourceId: async (request: { EventSourceId: string }) => ({ IsAuthorized: true, Data: { HasEvents: request.EventSourceId !== 'empty' } }),
|
|
27
27
|
forEventSourceIdAndEventTypes: async () => ({ IsAuthorized: true, Data: [] }),
|
|
28
28
|
fromSequenceNumber: async () => ({ IsAuthorized: true, Data: [] }),
|
|
29
|
+
compensate: async () => ({ Response: { SequenceNumber: 43n, ConstraintViolations: [], Errors: [] } }),
|
|
29
30
|
redact: async () => ({}),
|
|
30
31
|
redactForEventSource: async () => ({}),
|
|
31
32
|
copyEventsForEventSource: async () => ({ Response: { lo: 1n, hi: 2n } }),
|
|
@@ -9,6 +9,7 @@ export const legacySpans = {
|
|
|
9
9
|
hasEventsFor: 'chronicle.event_sequences.has_events_for',
|
|
10
10
|
getForEventSourceIdAndEventTypes: 'chronicle.event_sequences.get_for_event_source_id_and_event_types',
|
|
11
11
|
getFromSequenceNumber: 'chronicle.event_sequences.get_from_sequence_number',
|
|
12
|
+
compensate: 'chronicle.event_sequences.compensate',
|
|
12
13
|
redact: 'chronicle.event_sequences.redact',
|
|
13
14
|
redactForEventSource: 'chronicle.event_sequences.redact_for_event_source',
|
|
14
15
|
copyForEventSource: 'chronicle.event_sequences.copy_for_event_source',
|
|
@@ -25,6 +26,7 @@ export const conventionSpans = {
|
|
|
25
26
|
hasEventsFor: 'cratis.chronicle.client.event_sequence.has_events_for',
|
|
26
27
|
getForEventSourceIdAndEventTypes: 'cratis.chronicle.client.event_sequence.get_for_event_source_id_and_event_types',
|
|
27
28
|
getFromSequenceNumber: 'cratis.chronicle.client.event_sequence.get_from_sequence_number',
|
|
29
|
+
compensate: 'cratis.chronicle.client.event_sequence.compensate',
|
|
28
30
|
redact: 'cratis.chronicle.client.event_sequence.redact',
|
|
29
31
|
redactForEventSource: 'cratis.chronicle.client.event_sequence.redact_for_event_source',
|
|
30
32
|
copyForEventSource: 'cratis.chronicle.client.event_sequence.copy_for_event_source',
|
|
@@ -25,6 +25,7 @@ const operations = {
|
|
|
25
25
|
hasEventsFor: (sequence: IEventSequence) => sequence.hasEventsFor('source'),
|
|
26
26
|
getForEventSourceIdAndEventTypes: (sequence: IEventSequence) => sequence.getForEventSourceIdAndEventTypes('source', [Recorded]),
|
|
27
27
|
getFromSequenceNumber: (sequence: IEventSequence) => sequence.getFromSequenceNumber(sequenceNumber),
|
|
28
|
+
compensate: (sequence: IEventSequence) => sequence.compensate(sequenceNumber, new Recorded()),
|
|
28
29
|
redact: (sequence: IEventSequence) => sequence.redact(sequenceNumber, 'reason'),
|
|
29
30
|
redactForEventSource: (sequence: IEventSequence) => sequence.redactForEventSource('source', 'reason'),
|
|
30
31
|
copyForEventSource: (sequence: IEventSequence) => sequence.copy('source', 'target'),
|
|
@@ -61,7 +62,7 @@ for (const spanNames of [undefined, 'legacy', 'convention'] as const) {
|
|
|
61
62
|
'cratis.event_store.name': 'store', 'cratis.event_store.namespace': 'namespace',
|
|
62
63
|
'cratis.event_sequence.id': sequenceId.value
|
|
63
64
|
});
|
|
64
|
-
const hasSequenceNumber = ['append', 'getTailSequenceNumber', 'getFromSequenceNumber', 'redact'].includes(operation);
|
|
65
|
+
const hasSequenceNumber = ['append', 'getTailSequenceNumber', 'getFromSequenceNumber', 'redact', 'compensate'].includes(operation);
|
|
65
66
|
Object.keys(span.attributes).filter(key => key.startsWith('chronicle.')).should.deep.equal(
|
|
66
67
|
hasSequenceNumber ? ['chronicle.sequence_number'] : []);
|
|
67
68
|
if (hasSequenceNumber) span.attributes.should.have.property('chronicle.sequence_number', '42');
|
|
@@ -393,6 +393,7 @@ export class InProcessEventSequence implements IEventSequence {
|
|
|
393
393
|
(!ids.length || ids.includes(event.eventType.id.value))).map(event => this.snapshot(event));
|
|
394
394
|
}
|
|
395
395
|
|
|
396
|
+
async compensate(): Promise<AppendResult> { throw this.unsupported('compensate', this.id.value, 'Compensation requires kernel storage.'); }
|
|
396
397
|
async redact(): Promise<void> { throw this.unsupported('redact', this.id.value, 'Redaction requires kernel storage.'); }
|
|
397
398
|
async redactForEventSource(): Promise<void> { throw this.unsupported('redactForEventSource', this.id.value, 'Redaction requires kernel storage.'); }
|
|
398
399
|
async copy(): Promise<Guid> { throw this.unsupported('copy', this.id.value, 'Copying events requires kernel jobs.'); }
|
|
@@ -24,7 +24,7 @@ import { EventStoreName } from '../EventStoreName.js';
|
|
|
24
24
|
import { EventStoreNamespaceName } from '../EventStoreNamespaceName.js';
|
|
25
25
|
import type { IEventStore } from '../IEventStore.js';
|
|
26
26
|
import type { IReadModels } from '../readModels/IReadModels.js';
|
|
27
|
-
import { getReactorEventTypes, invokeReactorHandler, selectReactorHandler } from '../reactors/ReactorDispatcher.js';
|
|
27
|
+
import { getReactorBatchMethods, getReactorEventTypes, invokeReactorHandler, selectReactorHandler } from '../reactors/ReactorDispatcher.js';
|
|
28
28
|
import { createHandlerInstanceValidator } from '../observation/createHandlerInstanceValidator.js';
|
|
29
29
|
import { getReactorMetadata } from '../reactors/reactor.js';
|
|
30
30
|
import { normalizeReactorSideEffects } from '../reactors/ReactorSideEffects.js';
|
|
@@ -89,6 +89,10 @@ export class ReactorScenario {
|
|
|
89
89
|
eventTypeMigrations: eventTypeMigrations === undefined ? undefined : [...eventTypeMigrations]
|
|
90
90
|
} });
|
|
91
91
|
this._entries = getReactorEventTypes(_reactor, this._eventTypes);
|
|
92
|
+
if (getReactorBatchMethods(_reactor, this._eventTypes).length > 0) {
|
|
93
|
+
throw new UnsupportedReactorOperation('reactor.batchMethod', _reactor.name,
|
|
94
|
+
'Batch methods (@observes) are not fixture-backed yet.');
|
|
95
|
+
}
|
|
92
96
|
this._validateInstance = createHandlerInstanceValidator(_reactor,
|
|
93
97
|
this._entries.flatMap(entry => [entry.methodName, entry.replayMethodName].filter((name): name is string => !!name)));
|
|
94
98
|
// Every unsupported event-sequence operation is latched at its source, whichever result or stream carries it.
|
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
|
|
4
4
|
import type { Constructor } from '@cratis/fundamentals';
|
|
5
5
|
import { ReducerEventDispatcher } from '../reducers/ReducerEventDispatcher.js';
|
|
6
|
+
import { BatchContext } from '../observation/batches/BatchContext.js';
|
|
7
|
+
import { EventAndContext } from '../observation/batches/EventAndContext.js';
|
|
8
|
+
import { EventBatch } from '../observation/batches/EventBatch.js';
|
|
9
|
+
import { ObservationOrigin } from '../observation/batches/ObservationOrigin.js';
|
|
10
|
+
import { PartitionFailedInBatch } from '../observation/batches/PartitionFailedInBatch.js';
|
|
6
11
|
import { getEventSourceTypeFor } from '../events/eventSourceTypeDecorator.js';
|
|
7
12
|
import { getEventStreamTypeFor } from '../events/eventStreamTypeDecorator.js';
|
|
8
13
|
import { getFilterTagsFor } from '../events/filterEventsByTagDecorator.js';
|
|
@@ -32,6 +37,10 @@ export class ReducerReadModelProcessor<TReadModel extends object> implements IRe
|
|
|
32
37
|
const results = new Map<string, ReadModelState<TReadModel>>();
|
|
33
38
|
const reducer = new (this._reducerType as new () => Record<string, Function>)();
|
|
34
39
|
this._dispatcher.validateInstance(reducer);
|
|
40
|
+
if (this._dispatcher.batchMethod) {
|
|
41
|
+
await this.processBatches(reducer, events, results);
|
|
42
|
+
return results;
|
|
43
|
+
}
|
|
35
44
|
for (const event of events) {
|
|
36
45
|
const handler = this._dispatcher.handlerFor(event.context.eventType.id.value);
|
|
37
46
|
if (!handler) continue;
|
|
@@ -50,4 +59,39 @@ export class ReducerReadModelProcessor<TReadModel extends object> implements IRe
|
|
|
50
59
|
}
|
|
51
60
|
return results;
|
|
52
61
|
}
|
|
62
|
+
|
|
63
|
+
private async processBatches(reducer: Record<string, Function>, events: readonly ScenarioEvent[],
|
|
64
|
+
results: Map<string, ReadModelState<TReadModel>>): Promise<void> {
|
|
65
|
+
const method = this._dispatcher.batchMethod!;
|
|
66
|
+
const bySource = new Map<string, EventAndContext[]>();
|
|
67
|
+
for (const event of events) {
|
|
68
|
+
const observed = method.eventTypes.get(event.context.eventType.id.value);
|
|
69
|
+
if (!observed) continue;
|
|
70
|
+
const sourceEvents = bySource.get(event.sourceId) ?? [];
|
|
71
|
+
sourceEvents.push(new EventAndContext(event.content, event.context, observed.type));
|
|
72
|
+
bySource.set(event.sourceId, sourceEvents);
|
|
73
|
+
}
|
|
74
|
+
const signal = new AbortController().signal;
|
|
75
|
+
for (const [sourceId, sourceEvents] of bySource) {
|
|
76
|
+
const batch = new EventBatch(sourceEvents, false);
|
|
77
|
+
const sequenceNumbers = sourceEvents.map(event => event.context.sequenceNumber);
|
|
78
|
+
const context = new BatchContext({
|
|
79
|
+
observerId: this._reducerType.name, eventStore: sourceEvents[0].context.eventStore ?? '', namespace: sourceEvents[0].context.namespace ?? '',
|
|
80
|
+
eventSequenceId: 'event-log', origin: ObservationOrigin.Unknown, partitions: [sourceId], eventCount: sourceEvents.length,
|
|
81
|
+
firstSequenceNumber: sequenceNumbers[0], lastSequenceNumber: sequenceNumbers.at(-1), deadline: undefined, signal, canDefer: false
|
|
82
|
+
});
|
|
83
|
+
let next: unknown;
|
|
84
|
+
try {
|
|
85
|
+
next = await this._dispatcher.invokeBatch(reducer, batch, undefined, context);
|
|
86
|
+
const [reported] = batch.outcomes;
|
|
87
|
+
if (reported) throw reported.error ?? new PartitionFailedInBatch(sourceId);
|
|
88
|
+
} catch (cause) {
|
|
89
|
+
throw new Error(`Reducer '${this._reducerType.name}' for read model '${this._readModelType.name}' failed`, { cause });
|
|
90
|
+
}
|
|
91
|
+
results.set(sourceId, {
|
|
92
|
+
instance: next === undefined ? null : next as TReadModel | null,
|
|
93
|
+
deleted: next === undefined
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
53
97
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
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 { field } from '@cratis/fundamentals';
|
|
5
|
+
import { chai, describe, it } from 'vitest';
|
|
6
|
+
import { eventType, observes, reactor } from '../../index.js';
|
|
7
|
+
import { ReactorScenario, UnsupportedReactorOperation } from '../index.js';
|
|
8
|
+
|
|
9
|
+
chai.should();
|
|
10
|
+
|
|
11
|
+
@eventType('scenario-batch-shipment-sent')
|
|
12
|
+
class ShipmentSent {
|
|
13
|
+
@field(String) trackingNumber = '';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
@reactor('scenario-batch-shipments')
|
|
17
|
+
class Shipments {
|
|
18
|
+
@observes(ShipmentSent)
|
|
19
|
+
track() {}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe('when creating a reactor scenario for a reactor with a batch method', () => {
|
|
23
|
+
it('should refuse it instead of skipping its events', () =>
|
|
24
|
+
(() => new ReactorScenario(Shipments, { artifacts: { eventTypes: [ShipmentSent] }, constraints: 'disabled' }))
|
|
25
|
+
.should.throw(UnsupportedReactorOperation, 'reactor.batchMethod'));
|
|
26
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
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 { chai, describe, it } from 'vitest';
|
|
5
|
+
import { field } from '@cratis/fundamentals';
|
|
6
|
+
import { eventType } from '../../../events/eventTypeDecorator.js';
|
|
7
|
+
import { EventBatch, observes } from '../../../observation/index.js';
|
|
8
|
+
import { reducer } from '../../../reducers/reducer.js';
|
|
9
|
+
import { ReadModelScenario } from '../../index.js';
|
|
10
|
+
|
|
11
|
+
chai.should();
|
|
12
|
+
|
|
13
|
+
@eventType('scenario-batch-points-earned')
|
|
14
|
+
class PointsEarned {
|
|
15
|
+
constructor(readonly points: number = 0) {}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
class Score {
|
|
19
|
+
@field(Number) points = 0;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let calls = 0;
|
|
23
|
+
|
|
24
|
+
@reducer('scenario-batch-scores', undefined, Score)
|
|
25
|
+
class Scores {
|
|
26
|
+
@observes(PointsEarned)
|
|
27
|
+
reduce(events: EventBatch, current: Score | undefined): Score {
|
|
28
|
+
calls++;
|
|
29
|
+
return { points: events.ofType(PointsEarned).reduce((total, entry) => total + entry.event.points, current?.points ?? 0) };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('when reducing with a batch method in a read model scenario', () => {
|
|
34
|
+
it('should call the batch method once per event source and keep each state', async () => {
|
|
35
|
+
calls = 0;
|
|
36
|
+
const scenario = new ReadModelScenario(Score, { eventTypes: [PointsEarned], reducers: [Scores] });
|
|
37
|
+
scenario.given.forEventSource('player-1').events(new PointsEarned(3), new PointsEarned(4));
|
|
38
|
+
scenario.given.forEventSource('player-2').events(new PointsEarned(10));
|
|
39
|
+
(await scenario.instanceForEventSourceId('player-1'))!.should.deep.equal({ points: 7 });
|
|
40
|
+
(await scenario.instanceForEventSourceId('player-2'))!.should.deep.equal({ points: 10 });
|
|
41
|
+
calls.should.be.greaterThan(0);
|
|
42
|
+
});
|
|
43
|
+
});
|