@cratis/chronicle 6.61.0 → 6.62.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/connection/ChronicleConnection.ts +7 -1
- package/connection/ChronicleServices.ts +2 -0
- package/dist/connection/ChronicleConnection.d.ts +1 -0
- package/dist/connection/ChronicleConnection.d.ts.map +1 -1
- package/dist/connection/ChronicleConnection.js +6 -2
- package/dist/connection/ChronicleConnection.js.map +1 -1
- package/dist/connection/ChronicleServices.d.ts +2 -1
- package/dist/connection/ChronicleServices.d.ts.map +1 -1
- package/dist/eventSequences/EventForEventSourceId.d.ts +21 -1
- package/dist/eventSequences/EventForEventSourceId.d.ts.map +1 -1
- package/dist/eventSequences/EventSequence.d.ts +9 -0
- package/dist/eventSequences/EventSequence.d.ts.map +1 -1
- package/dist/eventSequences/EventSequence.js +18 -0
- package/dist/eventSequences/EventSequence.js.map +1 -1
- package/dist/eventSequences/IEventSequence.d.ts +30 -0
- package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
- package/dist/imports/EventImport.d.ts +29 -0
- package/dist/imports/EventImport.d.ts.map +1 -0
- package/dist/imports/EventImport.js +248 -0
- package/dist/imports/EventImport.js.map +1 -0
- package/dist/imports/EventImportSettings.d.ts +32 -0
- package/dist/imports/EventImportSettings.d.ts.map +1 -0
- package/dist/imports/EventImportSettings.js +4 -0
- package/dist/imports/EventImportSettings.js.map +1 -0
- package/dist/imports/IEventImport.d.ts +50 -0
- package/dist/imports/IEventImport.d.ts.map +1 -0
- package/dist/imports/IEventImport.js +4 -0
- package/dist/imports/IEventImport.js.map +1 -0
- package/dist/imports/ImportChunkRefused.d.ts +12 -0
- package/dist/imports/ImportChunkRefused.d.ts.map +1 -0
- package/dist/imports/ImportChunkRefused.js +19 -0
- package/dist/imports/ImportChunkRefused.js.map +1 -0
- package/dist/imports/ImportCouldNotBegin.d.ts +10 -0
- package/dist/imports/ImportCouldNotBegin.d.ts.map +1 -0
- package/dist/imports/ImportCouldNotBegin.js +16 -0
- package/dist/imports/ImportCouldNotBegin.js.map +1 -0
- package/dist/imports/ImportOptions.d.ts +26 -0
- package/dist/imports/ImportOptions.d.ts.map +1 -0
- package/dist/imports/ImportOptions.js +4 -0
- package/dist/imports/ImportOptions.js.map +1 -0
- package/dist/imports/ImportProgress.d.ts +20 -0
- package/dist/imports/ImportProgress.d.ts.map +1 -0
- package/dist/imports/ImportProgress.js +4 -0
- package/dist/imports/ImportProgress.js.map +1 -0
- package/dist/imports/ImportRejection.d.ts +10 -0
- package/dist/imports/ImportRejection.d.ts.map +1 -0
- package/dist/imports/ImportRejection.js +4 -0
- package/dist/imports/ImportRejection.js.map +1 -0
- package/dist/imports/ImportResult.d.ts +30 -0
- package/dist/imports/ImportResult.d.ts.map +1 -0
- package/dist/imports/ImportResult.js +4 -0
- package/dist/imports/ImportResult.js.map +1 -0
- package/dist/imports/ImportState.d.ts +18 -0
- package/dist/imports/ImportState.d.ts.map +1 -0
- package/dist/imports/ImportState.js +21 -0
- package/dist/imports/ImportState.js.map +1 -0
- package/dist/imports/ImportTarget.d.ts +16 -0
- package/dist/imports/ImportTarget.d.ts.map +1 -0
- package/dist/imports/ImportTarget.js +4 -0
- package/dist/imports/ImportTarget.js.map +1 -0
- package/dist/imports/ImportWasAbandoned.d.ts +11 -0
- package/dist/imports/ImportWasAbandoned.d.ts.map +1 -0
- package/dist/imports/ImportWasAbandoned.js +16 -0
- package/dist/imports/ImportWasAbandoned.js.map +1 -0
- package/dist/imports/ImportsNotSupported.d.ts +5 -0
- package/dist/imports/ImportsNotSupported.d.ts.map +1 -0
- package/dist/imports/ImportsNotSupported.js +10 -0
- package/dist/imports/ImportsNotSupported.js.map +1 -0
- package/dist/imports/OnInvalidEvent.d.ts +8 -0
- package/dist/imports/OnInvalidEvent.d.ts.map +1 -0
- package/dist/imports/OnInvalidEvent.js +11 -0
- package/dist/imports/OnInvalidEvent.js.map +1 -0
- package/dist/imports/abortable.d.ts +23 -0
- package/dist/imports/abortable.d.ts.map +1 -0
- package/dist/imports/abortable.js +60 -0
- package/dist/imports/abortable.js.map +1 -0
- package/dist/imports/beginEventImport.d.ts +16 -0
- package/dist/imports/beginEventImport.d.ts.map +1 -0
- package/dist/imports/beginEventImport.js +74 -0
- package/dist/imports/beginEventImport.js.map +1 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.d.ts +144 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.d.ts.map +1 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.js +132 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.js.map +1 -0
- package/dist/imports/importEvents.d.ts +13 -0
- package/dist/imports/importEvents.d.ts.map +1 -0
- package/dist/imports/importEvents.js +35 -0
- package/dist/imports/importEvents.js.map +1 -0
- package/dist/imports/index.d.ts +12 -0
- package/dist/imports/index.d.ts.map +1 -0
- package/dist/imports/index.js +9 -0
- package/dist/imports/index.js.map +1 -0
- package/dist/imports/isTransientImportFailure.d.ts +7 -0
- package/dist/imports/isTransientImportFailure.d.ts.map +1 -0
- package/dist/imports/isTransientImportFailure.js +13 -0
- package/dist/imports/isTransientImportFailure.js.map +1 -0
- package/dist/imports/sizeOfImportEvent.d.ts +9 -0
- package/dist/imports/sizeOfImportEvent.d.ts.map +1 -0
- package/dist/imports/sizeOfImportEvent.js +25 -0
- package/dist/imports/sizeOfImportEvent.js.map +1 -0
- package/dist/imports/toImportEvent.d.ts +14 -0
- package/dist/imports/toImportEvent.d.ts.map +1 -0
- package/dist/imports/toImportEvent.js +54 -0
- package/dist/imports/toImportEvent.js.map +1 -0
- package/dist/imports/toImportProgress.d.ts +9 -0
- package/dist/imports/toImportProgress.d.ts.map +1 -0
- package/dist/imports/toImportProgress.js +20 -0
- package/dist/imports/toImportProgress.js.map +1 -0
- package/dist/imports/toImportResult.d.ts +9 -0
- package/dist/imports/toImportResult.d.ts.map +1 -0
- package/dist/imports/toImportResult.js +33 -0
- package/dist/imports/toImportResult.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/observation/index.d.ts +2 -0
- package/dist/observation/index.d.ts.map +1 -1
- package/dist/observation/index.js +1 -0
- package/dist/observation/index.js.map +1 -1
- package/dist/testing/BatchPartitionOutcome.d.ts +7 -0
- package/dist/testing/BatchPartitionOutcome.d.ts.map +1 -0
- package/dist/testing/BatchPartitionOutcome.js +4 -0
- package/dist/testing/BatchPartitionOutcome.js.map +1 -0
- package/dist/testing/InProcessEventSequence.d.ts +4 -0
- package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
- package/dist/testing/InProcessEventSequence.js +2 -0
- package/dist/testing/InProcessEventSequence.js.map +1 -1
- package/dist/testing/ReactorDeliveryResult.d.ts +2 -0
- package/dist/testing/ReactorDeliveryResult.d.ts.map +1 -1
- package/dist/testing/ReactorScenario.d.ts +46 -10
- package/dist/testing/ReactorScenario.d.ts.map +1 -1
- package/dist/testing/ReactorScenario.js +120 -29
- package/dist/testing/ReactorScenario.js.map +1 -1
- package/dist/testing/deliverToBatchMethods.d.ts +35 -0
- package/dist/testing/deliverToBatchMethods.d.ts.map +1 -0
- package/dist/testing/deliverToBatchMethods.js +55 -0
- package/dist/testing/deliverToBatchMethods.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/eventSequences/EventForEventSourceId.ts +25 -1
- package/eventSequences/EventSequence.ts +28 -0
- package/eventSequences/IEventSequence.ts +33 -0
- package/imports/EventImport.ts +263 -0
- package/imports/EventImportSettings.ts +46 -0
- package/imports/IEventImport.ts +58 -0
- package/imports/ImportChunkRefused.ts +15 -0
- package/imports/ImportCouldNotBegin.ts +14 -0
- package/imports/ImportOptions.ts +36 -0
- package/imports/ImportProgress.ts +29 -0
- package/imports/ImportRejection.ts +14 -0
- package/imports/ImportResult.ts +43 -0
- package/imports/ImportState.ts +26 -0
- package/imports/ImportTarget.ts +23 -0
- package/imports/ImportWasAbandoned.ts +16 -0
- package/imports/ImportsNotSupported.ts +10 -0
- package/imports/OnInvalidEvent.ts +11 -0
- package/imports/abortable.ts +57 -0
- package/imports/beginEventImport.ts +85 -0
- package/imports/for_EventImport/given/a_kernel_import_session.ts +160 -0
- package/imports/for_EventImport/when_a_chunk_fails.spec.ts +65 -0
- package/imports/for_EventImport/when_abandoning.spec.ts +52 -0
- package/imports/for_EventImport/when_cancelling_with_an_abort_signal.spec.ts +59 -0
- package/imports/for_EventImport/when_completing.spec.ts +71 -0
- package/imports/for_EventImport/when_cutting_events_into_chunks.spec.ts +70 -0
- package/imports/for_EventImport/when_keeping_chunks_in_flight.spec.ts +49 -0
- package/imports/for_beginEventImport/when_reattaching.spec.ts +82 -0
- package/imports/for_beginEventImport/when_the_kernel_does_not_serve_imports.spec.ts +55 -0
- package/imports/for_importEvents/when_importing_in_one_call.spec.ts +99 -0
- package/imports/for_toImportEvent/when_converting_an_event.spec.ts +74 -0
- package/imports/importEvents.ts +44 -0
- package/imports/index.ts +14 -0
- package/imports/isTransientImportFailure.ts +15 -0
- package/imports/sizeOfImportEvent.ts +25 -0
- package/imports/toImportEvent.ts +60 -0
- package/imports/toImportProgress.ts +24 -0
- package/imports/toImportResult.ts +36 -0
- package/index.ts +3 -0
- package/observation/index.ts +2 -0
- package/package.json +7 -2
- package/projections/for_childrenOrderingSupport/when_detecting_support_in_the_pinned_contracts.spec.ts +1 -1
- package/testing/BatchPartitionOutcome.ts +10 -0
- package/testing/InProcessEventSequence.ts +4 -0
- package/testing/ReactorDeliveryResult.ts +2 -0
- package/testing/ReactorScenario.ts +147 -39
- package/testing/deliverToBatchMethods.ts +90 -0
- package/testing/for_ReactorScenario/when_the_reactor_has_a_batch_method.spec.ts +143 -9
|
@@ -9,7 +9,7 @@ chai.should();
|
|
|
9
9
|
|
|
10
10
|
// The contracts version this expectation was verified against. Bumping the contracts fails the first spec on purpose:
|
|
11
11
|
// re-check children ordering support for the new version, then update both the version and the expectation together.
|
|
12
|
-
const verifiedContractsVersion = '19.
|
|
12
|
+
const verifiedContractsVersion = '19.153.0';
|
|
13
13
|
const supportedInVerifiedVersion = true;
|
|
14
14
|
|
|
15
15
|
const pinnedContractsVersion = (JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as {
|
|
@@ -0,0 +1,10 @@
|
|
|
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 { BatchOutcome } from '../observation/batches/BatchOutcome.js';
|
|
5
|
+
|
|
6
|
+
/** A partition a batch method of a scenario reactor reported as failed or deferred. */
|
|
7
|
+
export interface BatchPartitionOutcome extends BatchOutcome {
|
|
8
|
+
/** The name of the batch method that reported it. */
|
|
9
|
+
readonly methodName: string;
|
|
10
|
+
}
|
|
@@ -26,6 +26,8 @@ import { EventSequenceNumber } from '../eventSequences/EventSequenceNumber.js';
|
|
|
26
26
|
import type { IEventSequence } from '../eventSequences/IEventSequence.js';
|
|
27
27
|
import type { ITransactionalEventSequence } from '../eventSequences/ITransactionalEventSequence.js';
|
|
28
28
|
import type { CompleteStreamResult } from '../eventSequences/CompleteStreamResult.js';
|
|
29
|
+
import type { IEventImport } from '../imports/IEventImport.js';
|
|
30
|
+
import type { ImportResult } from '../imports/ImportResult.js';
|
|
29
31
|
import { prepareSingleAppend } from '../eventSequences/prepareSingleAppend.js';
|
|
30
32
|
import { toContractsGuid } from '../connection/Guid.js';
|
|
31
33
|
import { getRemovedConstraintNames } from '../events/constraints/removeConstraint.js';
|
|
@@ -398,6 +400,8 @@ export class InProcessEventSequence implements IEventSequence {
|
|
|
398
400
|
async redactForEventSource(): Promise<void> { throw this.unsupported('redactForEventSource', this.id.value, 'Redaction requires kernel storage.'); }
|
|
399
401
|
async copy(): Promise<Guid> { throw this.unsupported('copy', this.id.value, 'Copying events requires kernel jobs.'); }
|
|
400
402
|
async completeStream(): Promise<CompleteStreamResult> { throw this.unsupported('completeStream', this.id.value, 'Stream completion requires a kernel.'); }
|
|
403
|
+
async import(): Promise<ImportResult> { throw this.unsupported('import', this.id.value, 'Importing events requires kernel import sessions.'); }
|
|
404
|
+
async beginImport(): Promise<IEventImport> { throw this.unsupported('beginImport', this.id.value, 'Importing events requires kernel import sessions.'); }
|
|
401
405
|
|
|
402
406
|
private filterIds(types?: Constructor[]): string[] {
|
|
403
407
|
return (types ?? []).map(type => {
|
|
@@ -6,6 +6,8 @@ import type { EventContext } from '../events/EventContext.js';
|
|
|
6
6
|
/** Observable outcome of one ordered source-partition delivery (not a kernel checkpoint). */
|
|
7
7
|
export interface ReactorDeliveryResult {
|
|
8
8
|
readonly sourceId: string;
|
|
9
|
+
/** The partitions (event source identifiers) the delivery carried, in the order their first event appears. */
|
|
10
|
+
readonly partitions: readonly string[];
|
|
9
11
|
readonly handled: readonly EventContext[];
|
|
10
12
|
readonly skipped: readonly EventContext[];
|
|
11
13
|
readonly completed: boolean;
|
|
@@ -37,13 +37,20 @@ import type { RecordedReactorSideEffect } from './RecordedReactorSideEffect.js';
|
|
|
37
37
|
import { observeUnsupportedOperations } from './InProcessEventSequence.js';
|
|
38
38
|
import { UnsupportedEventSequenceOperation } from './UnsupportedEventSequenceOperation.js';
|
|
39
39
|
import { UnsupportedReactorOperation } from './UnsupportedReactorOperation.js';
|
|
40
|
+
import type { BatchMethod } from '../observation/batches/BatchMethod.js';
|
|
41
|
+
import { BatchOutcomeKind } from '../observation/batches/BatchOutcomeKind.js';
|
|
42
|
+
import type { BatchPartitionOutcome } from './BatchPartitionOutcome.js';
|
|
43
|
+
import { deliverToBatchMethods } from './deliverToBatchMethods.js';
|
|
40
44
|
|
|
41
45
|
/** Live, ordered reactor deliveries over the fixture-proven EventScenario event boundary. */
|
|
42
46
|
export class ReactorScenario {
|
|
43
|
-
readonly given:
|
|
44
|
-
readonly when:
|
|
47
|
+
readonly given: ReactorScenarioPhase;
|
|
48
|
+
readonly when: ReactorScenarioPhase;
|
|
45
49
|
private readonly _events: EventScenario;
|
|
46
50
|
private readonly _entries: ReturnType<typeof getReactorEventTypes>;
|
|
51
|
+
private readonly _batchMethods: readonly BatchMethod[];
|
|
52
|
+
private readonly _batchEventTypeIds: ReadonlySet<string>;
|
|
53
|
+
private readonly _partitionOutcomes: BatchPartitionOutcome[] = [];
|
|
47
54
|
private readonly _eventTypes: readonly Constructor[];
|
|
48
55
|
private readonly _instance?: Record<string, Function>;
|
|
49
56
|
private readonly _validateInstance: (instance: object) => void;
|
|
@@ -89,19 +96,20 @@ export class ReactorScenario {
|
|
|
89
96
|
eventTypeMigrations: eventTypeMigrations === undefined ? undefined : [...eventTypeMigrations]
|
|
90
97
|
} });
|
|
91
98
|
this._entries = getReactorEventTypes(_reactor, this._eventTypes);
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
this._entries.flatMap(entry => [entry.methodName, entry.replayMethodName].filter((name): name is string => !!name)));
|
|
99
|
+
this._batchMethods = getReactorBatchMethods(_reactor, this._eventTypes);
|
|
100
|
+
this._batchEventTypeIds = new Set(this._batchMethods.flatMap(method => [...method.eventTypes.keys()]));
|
|
101
|
+
this._validateInstance = createHandlerInstanceValidator(_reactor, [
|
|
102
|
+
...this._entries.flatMap(entry => [entry.methodName, entry.replayMethodName].filter((name): name is string => !!name)),
|
|
103
|
+
...this._batchMethods.map(method => method.methodName)]);
|
|
98
104
|
// Every unsupported event-sequence operation is latched at its source, whichever result or stream carries it.
|
|
99
105
|
observeUnsupportedOperations(this._events.eventSequence, error => { this.latch(error); });
|
|
100
106
|
this._instance = _options.artifactActivator ? undefined : new (_reactor as new () => Record<string, Function>)();
|
|
101
107
|
if (this._instance) this._validateInstance(this._instance);
|
|
102
108
|
this._store = _options.servicesEventStore ?? this.scenarioStore();
|
|
103
|
-
this.given = { forEventSource: (id, options) => ({ events: (...events) => this.deliver(id, events, true, options) })
|
|
104
|
-
|
|
109
|
+
this.given = { forEventSource: (id, options) => ({ events: (...events) => this.deliver(id, events, true, options) }),
|
|
110
|
+
page: (...events) => this.deliverPage(events, true) };
|
|
111
|
+
this.when = { forEventSource: (id, options) => ({ events: (...events) => this.deliver(id, events, false, options) }),
|
|
112
|
+
page: (...events) => this.deliverPage(events, false) };
|
|
105
113
|
}
|
|
106
114
|
|
|
107
115
|
private scenarioStore(): IEventStore {
|
|
@@ -120,7 +128,7 @@ export class ReactorScenario {
|
|
|
120
128
|
const rejectSubscribed = (events: readonly object[]) => {
|
|
121
129
|
if (events.some(event => {
|
|
122
130
|
const id = getEventTypeMetadata(event.constructor)?.eventType.id.value;
|
|
123
|
-
return this._entries.some(entry => entry.id === id);
|
|
131
|
+
return id !== undefined && (this._entries.some(entry => entry.id === id) || this._batchEventTypeIds.has(id));
|
|
124
132
|
})) {
|
|
125
133
|
throw this.violation('services.eventLog.append.subscribed',
|
|
126
134
|
'Delivery of a reactor\'s own appended events is not supported.');
|
|
@@ -161,18 +169,39 @@ export class ReactorScenario {
|
|
|
161
169
|
get produced(): readonly unknown[] { return Object.freeze(this._effects.map(effect => effect.value)); }
|
|
162
170
|
get sideEffects(): readonly RecordedReactorSideEffect[] { return Object.freeze([...this._effects]); }
|
|
163
171
|
get results(): readonly ReactorDeliveryResult[] { return Object.freeze([...this._results]); }
|
|
172
|
+
/**
|
|
173
|
+
* The partitions the reactor's batch methods reported as failed or deferred, in the order they were reported. A batch
|
|
174
|
+
* method that throws fails every partition in its batch instead, and the scenario rejects the call that delivered it.
|
|
175
|
+
*/
|
|
176
|
+
get partitionOutcomes(): readonly BatchPartitionOutcome[] { return Object.freeze([...this._partitionOutcomes]); }
|
|
164
177
|
/** Committed input and explicit service appends; recorded returned effects are not part of this history. */
|
|
165
178
|
get appendedEvents(): readonly AppendedEvent[] { return this._events.appendedEvents; }
|
|
166
179
|
/** Assertion view, deliberately not a callable Promise-like `then`. */
|
|
167
180
|
get then(): { readonly produced: readonly unknown[]; readonly sideEffects: readonly RecordedReactorSideEffect[];
|
|
168
|
-
readonly results: readonly ReactorDeliveryResult[] } {
|
|
169
|
-
return { produced: this.produced, sideEffects: this.sideEffects, results: this.results };
|
|
181
|
+
readonly results: readonly ReactorDeliveryResult[]; readonly partitionOutcomes: readonly BatchPartitionOutcome[] } {
|
|
182
|
+
return { produced: this.produced, sideEffects: this.sideEffects, results: this.results, partitionOutcomes: this.partitionOutcomes };
|
|
170
183
|
}
|
|
171
184
|
shouldHaveProduced<T>(type: new (...args: never[]) => T, predicate: (value: T) => boolean = () => true): void {
|
|
172
185
|
if (!this.produced.some(value => value instanceof type && predicate(value))) {
|
|
173
186
|
throw new Error(`Expected reactor '${this._reactor.name}' to produce a matching '${type.name}'.`);
|
|
174
187
|
}
|
|
175
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Asserts that a batch method failed a partition.
|
|
191
|
+
* @param partition - The event source identifier of the partition.
|
|
192
|
+
*/
|
|
193
|
+
shouldHaveFailed(partition: string): void { this.assertOutcome(partition, BatchOutcomeKind.Failed); }
|
|
194
|
+
/**
|
|
195
|
+
* Asserts that a batch method deferred a partition.
|
|
196
|
+
* @param partition - The event source identifier of the partition.
|
|
197
|
+
*/
|
|
198
|
+
shouldHaveDeferred(partition: string): void { this.assertOutcome(partition, BatchOutcomeKind.Deferred); }
|
|
199
|
+
private assertOutcome(partition: string, kind: BatchOutcomeKind): void {
|
|
200
|
+
if (this._partitionOutcomes.some(outcome => outcome.partition === partition && outcome.kind === kind)) return;
|
|
201
|
+
const reported = this._partitionOutcomes.length > 0
|
|
202
|
+
? this._partitionOutcomes.map(outcome => `${outcome.kind} '${outcome.partition}'`).join(', ') : 'nothing';
|
|
203
|
+
throw new Error(`Expected a batch method of reactor '${this._reactor.name}' to report partition '${partition}' as ${kind}, but it reported: ${reported}.`);
|
|
204
|
+
}
|
|
176
205
|
shouldNotHaveProduced(type: Function): void {
|
|
177
206
|
if (this.produced.some(value => value instanceof type)) {
|
|
178
207
|
throw new Error(`Expected reactor '${this._reactor.name}' to produce no '${type.name}'.`);
|
|
@@ -188,11 +217,7 @@ export class ReactorScenario {
|
|
|
188
217
|
}
|
|
189
218
|
|
|
190
219
|
private async deliver(sourceId: string, input: object[], setup: boolean, options?: AppendOptions): Promise<void> {
|
|
191
|
-
|
|
192
|
-
'A previous delivery failed; failed-partition retries are not supported.');
|
|
193
|
-
if (this._busy) throw new UnsupportedReactorOperation('delivery.overlap', this._reactor.name, 'Concurrent deliveries have unproven ordering.');
|
|
194
|
-
this._busy = true;
|
|
195
|
-
try {
|
|
220
|
+
await this.exclusively(async () => {
|
|
196
221
|
if (!setup && !input.length) {
|
|
197
222
|
throw new UnsupportedReactorOperation('when.events', this._reactor.name, 'Empty action batches are not fixture-backed.');
|
|
198
223
|
}
|
|
@@ -200,13 +225,38 @@ export class ReactorScenario {
|
|
|
200
225
|
if (setup) {
|
|
201
226
|
await this._events.given.forEventSource(sourceId, options).events(...input);
|
|
202
227
|
} else {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
228
|
+
throwIfAppendFailed(await this._events.when.forEventSource(sourceId, options).events(...input));
|
|
229
|
+
}
|
|
230
|
+
const events = this._events.appendedEvents.slice(before);
|
|
231
|
+
if (events.length) await this.process(events);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private async deliverPage(entries: EventForEventSourceId[], setup: boolean): Promise<void> {
|
|
236
|
+
await this.exclusively(async () => {
|
|
237
|
+
if (!entries.length) {
|
|
238
|
+
throw new UnsupportedReactorOperation(setup ? 'given.page' : 'when.page', this._reactor.name, 'Empty pages are not fixture-backed.');
|
|
239
|
+
}
|
|
240
|
+
const before = this._events.appendedEvents.length;
|
|
241
|
+
if (setup) {
|
|
242
|
+
for (const entry of entries) {
|
|
243
|
+
await this._events.given.forEventSource(entry.eventSourceId, appendOptionsOf(entry)).events(entry.event);
|
|
244
|
+
}
|
|
245
|
+
} else {
|
|
246
|
+
throwIfAppendFailed(await this._events.appendMany(entries));
|
|
207
247
|
}
|
|
208
248
|
const events = this._events.appendedEvents.slice(before);
|
|
209
|
-
if (events.length) await this.process(
|
|
249
|
+
if (events.length) await this.process(events);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private async exclusively(deliver: () => Promise<void>): Promise<void> {
|
|
254
|
+
if (this._failed) throw new UnsupportedReactorOperation('delivery.afterFailure', this._reactor.name,
|
|
255
|
+
'A previous delivery failed; failed-partition retries are not supported.');
|
|
256
|
+
if (this._busy) throw new UnsupportedReactorOperation('delivery.overlap', this._reactor.name, 'Concurrent deliveries have unproven ordering.');
|
|
257
|
+
this._busy = true;
|
|
258
|
+
try {
|
|
259
|
+
await deliver();
|
|
210
260
|
} finally {
|
|
211
261
|
this._busy = false;
|
|
212
262
|
}
|
|
@@ -230,35 +280,37 @@ export class ReactorScenario {
|
|
|
230
280
|
if (delivery.violation) throw delivery.violation;
|
|
231
281
|
}
|
|
232
282
|
|
|
233
|
-
private async process(
|
|
283
|
+
private async process(events: readonly AppendedEvent[]): Promise<void> {
|
|
234
284
|
const delivery: { violation?: Error } = {};
|
|
235
285
|
this._delivery = delivery;
|
|
236
286
|
const deliveryIndex = this._deliveryIndex++;
|
|
237
287
|
const handled: EventContext[] = [];
|
|
238
288
|
const skipped: EventContext[] = [];
|
|
239
|
-
const
|
|
240
|
-
|
|
289
|
+
const sourceId = events[0].context.eventSourceId;
|
|
290
|
+
const partitions = [...new Set(events.map(event => event.context.eventSourceId))];
|
|
291
|
+
const outcome: { sourceId: string; partitions: readonly string[]; handled: EventContext[]; skipped: EventContext[];
|
|
292
|
+
completed: boolean; error?: unknown } = { sourceId, partitions, handled, skipped, completed: false };
|
|
241
293
|
const services: ReactorServices = { eventStore: this._store, readModels: this._store.readModels, signal: this._controller.signal };
|
|
242
|
-
const first = events.find(event =>
|
|
243
|
-
event.eventType.id.value, event.context.observationState ?? 0)?.methodName);
|
|
294
|
+
const first = events.find(event => this._batchEventTypeIds.has(event.eventType.id.value) ||
|
|
295
|
+
!!selectReactorHandler(this._entries, this._reactor, this._instance, event.eventType.id.value, event.context.observationState ?? 0)?.methodName);
|
|
244
296
|
const process = async (artifact: ActivatedArtifact<Record<string, Function>>) => {
|
|
297
|
+
// EventScenario's serialized history is the committed boundary, not the original input instance.
|
|
298
|
+
if (events.some(event => event.context.observationState !== 1)) {
|
|
299
|
+
throw new UnsupportedReactorOperation('delivery.observationState', this._reactor.name,
|
|
300
|
+
'Only initial live delivery is fixture-backed.');
|
|
301
|
+
}
|
|
302
|
+
if (this._batchMethods.length > 0) await this.processBatches(artifact, events, handled, delivery);
|
|
245
303
|
for (const event of events) {
|
|
246
|
-
//
|
|
247
|
-
if (event.
|
|
248
|
-
throw new UnsupportedReactorOperation('delivery.observationState', this._reactor.name,
|
|
249
|
-
'Only initial live delivery is fixture-backed.');
|
|
250
|
-
}
|
|
304
|
+
// The batch methods had these events, as one page.
|
|
305
|
+
if (this._batchEventTypeIds.has(event.eventType.id.value)) continue;
|
|
251
306
|
const selection = selectReactorHandler(this._entries, this._reactor, artifact.instance,
|
|
252
|
-
event.eventType.id.value, event.context.observationState);
|
|
307
|
+
event.eventType.id.value, event.context.observationState ?? 0);
|
|
253
308
|
if (!selection?.methodName || selection.skipReplay) { skipped.push(event.context); continue; }
|
|
254
309
|
await invokeReactorHandler(artifact, selection.methodName, event.content, event.context, services, result => {
|
|
255
310
|
// A swallowed unsupported call fails this event like a throwing handler: nothing is recorded.
|
|
256
311
|
this.throwIfViolated(delivery);
|
|
257
312
|
return this.record(result, event.context, selection.methodName!, deliveryIndex);
|
|
258
|
-
},
|
|
259
|
-
event.context.eventStore ?? this._options.eventStore ?? 'test-event-store',
|
|
260
|
-
event.context.namespace ?? this._options.namespace ?? 'default', 'event-log',
|
|
261
|
-
event.context.eventSourceId, event.context.sequenceNumber));
|
|
313
|
+
}, this.deliveryFor(event.context));
|
|
262
314
|
this.throwIfViolated(delivery);
|
|
263
315
|
handled.push(event.context);
|
|
264
316
|
}
|
|
@@ -287,10 +339,33 @@ export class ReactorScenario {
|
|
|
287
339
|
throw error;
|
|
288
340
|
} finally {
|
|
289
341
|
if (this._delivery === delivery) this._delivery = undefined;
|
|
290
|
-
this._results.push(Object.freeze({ ...outcome, handled: Object.freeze([...handled]), skipped: Object.freeze([...skipped]) }));
|
|
342
|
+
this._results.push(Object.freeze({ ...outcome, partitions: Object.freeze([...partitions]), handled: Object.freeze([...handled]), skipped: Object.freeze([...skipped]) }));
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
private async processBatches(artifact: ActivatedArtifact<Record<string, Function>>, events: readonly AppendedEvent[],
|
|
347
|
+
handled: EventContext[], delivery: { violation?: Error }): Promise<void> {
|
|
348
|
+
const outcomes = await deliverToBatchMethods(artifact, this._batchMethods, {
|
|
349
|
+
observerId: getReactorMetadata(this._reactor)!.id.value, observerName: this._reactor.name,
|
|
350
|
+
eventStore: this._options.eventStore ?? 'test-event-store', namespace: this._options.namespace ?? 'default',
|
|
351
|
+
events, signal: this._controller.signal, deliveryFor: context => this.deliveryFor(context)
|
|
352
|
+
});
|
|
353
|
+
this.throwIfViolated(delivery);
|
|
354
|
+
this._partitionOutcomes.push(...outcomes);
|
|
355
|
+
// An event is handled unless its partition was failed or deferred at or before it.
|
|
356
|
+
for (const event of events.filter(event => this._batchEventTypeIds.has(event.eventType.id.value))) {
|
|
357
|
+
if (!outcomes.some(reported => reported.partition === event.context.eventSourceId && reported.at <= event.context.sequenceNumber)) {
|
|
358
|
+
handled.push(event.context);
|
|
359
|
+
}
|
|
291
360
|
}
|
|
292
361
|
}
|
|
293
362
|
|
|
363
|
+
private deliveryFor(context: EventContext): ReactorDelivery {
|
|
364
|
+
return new ReactorDelivery(getReactorMetadata(this._reactor)!.id.value,
|
|
365
|
+
context.eventStore ?? this._options.eventStore ?? 'test-event-store',
|
|
366
|
+
context.namespace ?? this._options.namespace ?? 'default', 'event-log', context.eventSourceId, context.sequenceNumber);
|
|
367
|
+
}
|
|
368
|
+
|
|
294
369
|
private async record(result: unknown, context: EventContext, handler: string, deliveryIndex: number): Promise<void> {
|
|
295
370
|
if (await this._options.resultHandler?.(result, context, this._reactor,
|
|
296
371
|
this._options.eventStore ?? 'test-event-store', this._options.namespace ?? 'default')) return;
|
|
@@ -313,3 +388,36 @@ export class ReactorScenario {
|
|
|
313
388
|
}
|
|
314
389
|
}
|
|
315
390
|
}
|
|
391
|
+
|
|
392
|
+
/** The reactor scenario phase that delivers events for one event source, or a page of several. */
|
|
393
|
+
export interface ReactorScenarioPhase {
|
|
394
|
+
/**
|
|
395
|
+
* Selects the event source to deliver events for.
|
|
396
|
+
* @param id - The event source identifier.
|
|
397
|
+
* @param options - Optional append options.
|
|
398
|
+
* @returns The builder whose `events(...)` delivers its events as one page.
|
|
399
|
+
*/
|
|
400
|
+
forEventSource(id: string, options?: AppendOptions): { events(...events: object[]): Promise<void> };
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Delivers events of several event sources as one live page, as the kernel delivers a page to batch methods.
|
|
404
|
+
* @param events - The events and the event sources they are for, in the order they are appended.
|
|
405
|
+
* @returns A promise that resolves when every method has handled its events.
|
|
406
|
+
*/
|
|
407
|
+
page(...events: EventForEventSourceId[]): Promise<void>;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function throwIfAppendFailed(results: readonly { isSuccess: boolean }[]): void {
|
|
411
|
+
const failures = results.filter(result => !result.isSuccess);
|
|
412
|
+
if (failures.length) throw new Error(`ReactorScenario action append failed: ${JSON.stringify(failures, (_, value) =>
|
|
413
|
+
typeof value === 'bigint' ? value.toString() : value)}`);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function appendOptionsOf(entry: EventForEventSourceId): AppendOptions | undefined {
|
|
417
|
+
// Only what the entry sets: the seeding path refuses options it cannot honor rather than dropping them.
|
|
418
|
+
const options = Object.fromEntries(Object.entries({
|
|
419
|
+
sourceType: entry.eventSourceType, streamType: entry.eventStreamType, streamId: entry.eventStreamId, subject: entry.subject,
|
|
420
|
+
occurred: entry.occurred, tags: entry.tags, namedTags: entry.namedTags, eventSource: entry.eventSource, eventStream: entry.eventStream
|
|
421
|
+
}).filter(([, value]) => value !== undefined)) as AppendOptions;
|
|
422
|
+
return Object.keys(options).length > 0 ? options : undefined;
|
|
423
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { Constructor } from '@cratis/fundamentals';
|
|
5
|
+
import type { ActivatedArtifact } from '../artifacts/ActivatedArtifact.js';
|
|
6
|
+
import { ArtifactDelivery } from '../artifacts/ArtifactDelivery.js';
|
|
7
|
+
import { runActivated } from '../artifacts/withActivatedArtifact.js';
|
|
8
|
+
import type { AppendedEvent } from '../events/AppendedEvent.js';
|
|
9
|
+
import type { EventContext } from '../events/EventContext.js';
|
|
10
|
+
import { BatchContext } from '../observation/batches/BatchContext.js';
|
|
11
|
+
import type { BatchMethod } from '../observation/batches/BatchMethod.js';
|
|
12
|
+
import { BatchMethodReturnedAValue } from '../observation/batches/BatchMethodReturnedAValue.js';
|
|
13
|
+
import { EventAndContext } from '../observation/batches/EventAndContext.js';
|
|
14
|
+
import { EventBatch } from '../observation/batches/EventBatch.js';
|
|
15
|
+
import { ObservationOrigin } from '../observation/batches/ObservationOrigin.js';
|
|
16
|
+
import type { ReactorDelivery } from '../reactors/ReactorDelivery.js';
|
|
17
|
+
import type { BatchPartitionOutcome } from './BatchPartitionOutcome.js';
|
|
18
|
+
|
|
19
|
+
/** The page a scenario delivers to the batch methods of a reactor. */
|
|
20
|
+
export interface ScenarioPage {
|
|
21
|
+
/** The identifier of the reactor. */
|
|
22
|
+
readonly observerId: string;
|
|
23
|
+
|
|
24
|
+
/** The name of the reactor type, for errors. */
|
|
25
|
+
readonly observerName: string;
|
|
26
|
+
|
|
27
|
+
/** The event store the events come from. */
|
|
28
|
+
readonly eventStore: string;
|
|
29
|
+
|
|
30
|
+
/** The namespace the events come from. */
|
|
31
|
+
readonly namespace: string;
|
|
32
|
+
|
|
33
|
+
/** The events of the page, in sequence order. */
|
|
34
|
+
readonly events: readonly AppendedEvent[];
|
|
35
|
+
|
|
36
|
+
/** Aborted when the scenario is disposed. */
|
|
37
|
+
readonly signal: AbortSignal;
|
|
38
|
+
|
|
39
|
+
/** Creates the delivery identity of an event. */
|
|
40
|
+
readonly deliveryFor: (context: EventContext) => ReactorDelivery;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Delivers a page of events to the batch methods of a reactor as one live page, the way the kernel delivers a page: each
|
|
45
|
+
* batch method gets the events of the types it observes, in sequence order, as one {@link EventBatch}.
|
|
46
|
+
* @param artifact - The reactor instance, activated for the delivery.
|
|
47
|
+
* @param methods - The batch methods of the reactor.
|
|
48
|
+
* @param page - The {@link ScenarioPage}.
|
|
49
|
+
* @returns The partitions the batch methods reported as failed or deferred, in the order they were reported.
|
|
50
|
+
* @throws What a batch method throws, which fails every partition in its batch.
|
|
51
|
+
* @throws {@link BatchMethodReturnedAValue} when a batch method returns a value.
|
|
52
|
+
*/
|
|
53
|
+
export async function deliverToBatchMethods(artifact: ActivatedArtifact<Record<string, Function>>, methods: readonly BatchMethod[],
|
|
54
|
+
page: ScenarioPage): Promise<BatchPartitionOutcome[]> {
|
|
55
|
+
const outcomes: BatchPartitionOutcome[] = [];
|
|
56
|
+
const sequenceNumbers = page.events.map(event => event.context.sequenceNumber);
|
|
57
|
+
const context = new BatchContext({
|
|
58
|
+
observerId: page.observerId,
|
|
59
|
+
eventStore: page.eventStore,
|
|
60
|
+
namespace: page.namespace,
|
|
61
|
+
eventSequenceId: 'event-log',
|
|
62
|
+
origin: ObservationOrigin.Live,
|
|
63
|
+
partitions: [...new Set(page.events.map(event => event.context.eventSourceId))],
|
|
64
|
+
eventCount: page.events.length,
|
|
65
|
+
firstSequenceNumber: sequenceNumbers[0],
|
|
66
|
+
lastSequenceNumber: sequenceNumbers[sequenceNumbers.length - 1],
|
|
67
|
+
deadline: undefined,
|
|
68
|
+
signal: page.signal,
|
|
69
|
+
canDefer: true
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
for (const method of methods) {
|
|
73
|
+
const observed = page.events.flatMap(event => {
|
|
74
|
+
const eventType = method.eventTypes.get(event.eventType.id.value);
|
|
75
|
+
return eventType ? [toEventAndContext(event, eventType.type, page)] : [];
|
|
76
|
+
});
|
|
77
|
+
if (observed.length === 0) continue;
|
|
78
|
+
|
|
79
|
+
const batch = new EventBatch(observed, context.canDefer);
|
|
80
|
+
const result: unknown = await runActivated(artifact, () => artifact.instance[method.methodName](batch, context),
|
|
81
|
+
{ delivery: ArtifactDelivery.Events, eventContext: observed[0].context, methodName: method.methodName });
|
|
82
|
+
if (result !== undefined) throw new BatchMethodReturnedAValue(page.observerName, method.methodName);
|
|
83
|
+
outcomes.push(...batch.outcomes.map(outcome => ({ ...outcome, methodName: method.methodName })));
|
|
84
|
+
}
|
|
85
|
+
return outcomes;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function toEventAndContext(event: AppendedEvent, eventType: Constructor, page: ScenarioPage): EventAndContext {
|
|
89
|
+
return new EventAndContext(event.content, event.context, eventType, page.deliveryFor(event.context));
|
|
90
|
+
}
|
|
@@ -2,25 +2,159 @@
|
|
|
2
2
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
3
|
|
|
4
4
|
import { field } from '@cratis/fundamentals';
|
|
5
|
-
import { chai, describe, it } from 'vitest';
|
|
6
|
-
import { eventType, observes, reactor } from '../../index.js';
|
|
7
|
-
import { ReactorScenario
|
|
5
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
6
|
+
import { BatchContext, BatchMethodReturnedAValue, BatchOutcomeKind, EventBatch, eventType, ObservationOrigin, observes, reactor } from '../../index.js';
|
|
7
|
+
import { ReactorScenario } from '../index.js';
|
|
8
8
|
|
|
9
9
|
chai.should();
|
|
10
10
|
|
|
11
11
|
@eventType('scenario-batch-shipment-sent')
|
|
12
12
|
class ShipmentSent {
|
|
13
|
-
@field(String) trackingNumber
|
|
13
|
+
@field(String) trackingNumber: string;
|
|
14
|
+
constructor(trackingNumber = '') { this.trackingNumber = trackingNumber; }
|
|
14
15
|
}
|
|
15
16
|
|
|
17
|
+
@eventType('scenario-batch-shipment-lost')
|
|
18
|
+
class ShipmentLost {
|
|
19
|
+
@field(String) reason: string;
|
|
20
|
+
constructor(reason = '') { this.reason = reason; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
@eventType('scenario-batch-shipment-delivered')
|
|
24
|
+
class ShipmentDelivered {
|
|
25
|
+
@field(String) signedBy: string;
|
|
26
|
+
constructor(signedBy = '') { this.signedBy = signedBy; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let batches: { batch: EventBatch; context: BatchContext }[] = [];
|
|
30
|
+
let delivered: string[] = [];
|
|
31
|
+
let failing = '';
|
|
32
|
+
let deferring = '';
|
|
33
|
+
let throwing = false;
|
|
34
|
+
|
|
16
35
|
@reactor('scenario-batch-shipments')
|
|
17
36
|
class Shipments {
|
|
18
37
|
@observes(ShipmentSent)
|
|
19
|
-
|
|
38
|
+
@observes(ShipmentLost)
|
|
39
|
+
track(batch: EventBatch, context: BatchContext) {
|
|
40
|
+
batches.push({ batch, context });
|
|
41
|
+
if (throwing) throw new Error('tracking service is down');
|
|
42
|
+
if (failing) batch.fail(failing, new Error('unknown carrier'));
|
|
43
|
+
if (deferring) batch.defer(deferring, 1000);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
shipmentDelivered(event: ShipmentDelivered) {
|
|
47
|
+
delivered.push(event.signedBy);
|
|
48
|
+
}
|
|
20
49
|
}
|
|
21
50
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
51
|
+
const options = { artifacts: { eventTypes: [ShipmentSent, ShipmentLost, ShipmentDelivered] }, constraints: 'disabled' as const };
|
|
52
|
+
|
|
53
|
+
function reset() {
|
|
54
|
+
batches = [];
|
|
55
|
+
delivered = [];
|
|
56
|
+
failing = '';
|
|
57
|
+
deferring = '';
|
|
58
|
+
throwing = false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
describe('when the events of one events call reach a batch method', () => {
|
|
62
|
+
let scenario: ReactorScenario;
|
|
63
|
+
beforeEach(async () => {
|
|
64
|
+
reset();
|
|
65
|
+
scenario = new ReactorScenario(Shipments, options);
|
|
66
|
+
await scenario.when.forEventSource('order-1').events(new ShipmentSent('T-1'), new ShipmentDelivered('Jane'), new ShipmentLost('weather'));
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('should call the batch method once', () => batches.length.should.equal(1));
|
|
70
|
+
it('should give it the events it observes, in sequence order', () =>
|
|
71
|
+
batches[0].batch.events.map(event => event.eventType).should.deep.equal([ShipmentSent, ShipmentLost]));
|
|
72
|
+
it('should give it the content of the events', () =>
|
|
73
|
+
(batches[0].batch.ofType(ShipmentSent)[0].event as unknown as ShipmentSent).trackingNumber.should.equal('T-1'));
|
|
74
|
+
it('should describe the page as live', () => batches[0].context.origin.should.equal(ObservationOrigin.Live));
|
|
75
|
+
it('should describe every event of the page', () => batches[0].context.eventCount.should.equal(3));
|
|
76
|
+
it('should allow deferring', () => batches[0].context.canDefer.should.be.true);
|
|
77
|
+
it('should give each event its delivery identity', () => batches[0].batch.events.every(event => event.delivery !== undefined).should.be.true);
|
|
78
|
+
it('should still call the per-event method for the other events', () => delivered.should.deep.equal(['Jane']));
|
|
79
|
+
it('should report every event as handled', () => scenario.results[0].handled.length.should.equal(3));
|
|
80
|
+
it('should report no partition outcomes', () => scenario.partitionOutcomes.should.be.empty);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe('when a page of several event sources reaches a batch method', () => {
|
|
84
|
+
let scenario: ReactorScenario;
|
|
85
|
+
beforeEach(async () => {
|
|
86
|
+
reset();
|
|
87
|
+
scenario = new ReactorScenario(Shipments, options);
|
|
88
|
+
await scenario.given.page(
|
|
89
|
+
{ eventSourceId: 'order-1', event: new ShipmentSent('T-1') },
|
|
90
|
+
{ eventSourceId: 'order-2', event: new ShipmentSent('T-2') });
|
|
91
|
+
await scenario.when.page(
|
|
92
|
+
{ eventSourceId: 'order-3', event: new ShipmentSent('T-3') },
|
|
93
|
+
{ eventSourceId: 'order-4', event: new ShipmentLost('customs') },
|
|
94
|
+
{ eventSourceId: 'order-3', event: new ShipmentLost('weather') });
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('should call the batch method once per page', () => batches.length.should.equal(2));
|
|
98
|
+
it('should give the given page as one batch', () => batches[0].batch.partitions.should.deep.equal(['order-1', 'order-2']));
|
|
99
|
+
it('should give the action page as one batch', () => batches[1].batch.length.should.equal(3));
|
|
100
|
+
it('should list the partitions of the page in order', () => batches[1].context.partitions.should.deep.equal(['order-3', 'order-4']));
|
|
101
|
+
it('should report the partitions of the delivery', () => scenario.results[1].partitions.should.deep.equal(['order-3', 'order-4']));
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
describe('when a batch method fails and defers partitions', () => {
|
|
105
|
+
let scenario: ReactorScenario;
|
|
106
|
+
beforeEach(async () => {
|
|
107
|
+
reset();
|
|
108
|
+
failing = 'order-1';
|
|
109
|
+
deferring = 'order-2';
|
|
110
|
+
scenario = new ReactorScenario(Shipments, options);
|
|
111
|
+
await scenario.when.page(
|
|
112
|
+
{ eventSourceId: 'order-1', event: new ShipmentSent('T-1') },
|
|
113
|
+
{ eventSourceId: 'order-2', event: new ShipmentSent('T-2') },
|
|
114
|
+
{ eventSourceId: 'order-3', event: new ShipmentSent('T-3') });
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('should assert the failed partition', () => scenario.shouldHaveFailed('order-1'));
|
|
118
|
+
it('should assert the deferred partition', () => scenario.shouldHaveDeferred('order-2'));
|
|
119
|
+
it('should refuse to assert a partition that succeeded as failed', () =>
|
|
120
|
+
(() => scenario.shouldHaveFailed('order-3')).should.throw(/order-3.*failed 'order-1', deferred 'order-2'/));
|
|
121
|
+
it('should refuse to assert a failed partition as deferred', () => (() => scenario.shouldHaveDeferred('order-1')).should.throw());
|
|
122
|
+
it('should keep the outcomes in the order they were reported', () =>
|
|
123
|
+
scenario.partitionOutcomes.map(outcome => [outcome.partition, outcome.kind, outcome.methodName]).should.deep.equal([
|
|
124
|
+
['order-1', BatchOutcomeKind.Failed, 'track'], ['order-2', BatchOutcomeKind.Deferred, 'track']]));
|
|
125
|
+
it('should keep the delay of the deferral', () => scenario.partitionOutcomes[1].retryAfterMilliseconds.should.equal(1000));
|
|
126
|
+
it('should keep the error of the failure', () => (scenario.partitionOutcomes[0].error as Error).message.should.equal('unknown carrier'));
|
|
127
|
+
it('should report only the other partition as handled', () =>
|
|
128
|
+
scenario.results[0].handled.map(context => context.eventSourceId).should.deep.equal(['order-3']));
|
|
129
|
+
it('should complete the delivery', () => scenario.results[0].completed.should.be.true);
|
|
130
|
+
it('should offer the outcomes on the assertion view', () => scenario.then.partitionOutcomes.length.should.equal(2));
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
describe('when a batch method throws', () => {
|
|
134
|
+
let scenario: ReactorScenario;
|
|
135
|
+
let error: unknown;
|
|
136
|
+
beforeEach(async () => {
|
|
137
|
+
reset();
|
|
138
|
+
throwing = true;
|
|
139
|
+
scenario = new ReactorScenario(Shipments, options);
|
|
140
|
+
error = await scenario.when.forEventSource('order-1').events(new ShipmentSent('T-1')).catch(caught => caught);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('should reject the call that delivered the events', () => (error as Error).message.should.equal('tracking service is down'));
|
|
144
|
+
it('should report the delivery as not completed', () => scenario.results[0].completed.should.be.false);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
describe('when a batch method returns a value', () => {
|
|
148
|
+
let error: unknown;
|
|
149
|
+
beforeEach(async () => {
|
|
150
|
+
@reactor('scenario-batch-returning')
|
|
151
|
+
class Returning {
|
|
152
|
+
@observes(ShipmentSent)
|
|
153
|
+
track() { return 'done'; }
|
|
154
|
+
}
|
|
155
|
+
const scenario = new ReactorScenario(Returning, options);
|
|
156
|
+
error = await scenario.when.forEventSource('order-1').events(new ShipmentSent('T-1')).catch(caught => caught);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('should reject the delivery', () => error!.should.be.instanceOf(BatchMethodReturnedAValue));
|
|
26
160
|
});
|