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