// Copyright (c) Cratis. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. import 'reflect-metadata'; import { createLogger } from '../logging/createLogger.js'; import { runInBackgroundContext } from '../telemetry/runInBackgroundContext.js'; import { Constructor } from '@cratis/fundamentals'; import { AppendedEvent, EventGenerationDelivery, ObservationState, ReadModelObserverType, ReduceOperationMessage, ReducerMessage, ReplayState } from '@cratis/chronicle.contracts'; import { IClientArtifactsProvider } from '../artifacts/index.js'; import { ChronicleConnection } from '../connection/index.js'; import { ConnectionLifecycle } from '../connection/ConnectionLifecycle.js'; import { toClientEventContext } from '../events/toClientEventContext.js'; import { getTagsFor } from '../events/tagDecorator.js'; import { getFilterTagsFor } from '../events/filterEventsByTagDecorator.js'; import { getEventSourceTypeFor } from '../events/eventSourceTypeDecorator.js'; import { getEventStreamTypeFor } from '../events/eventStreamTypeDecorator.js'; import { EventSequenceId } from '../eventSequences/EventSequenceId.js'; import { notifyReplayLifecycle } from '../observation/notifyReplayLifecycle.js'; import { IReducers } from './IReducers.js'; import { getReducerMetadata } from './reducer.js'; import { ReducerEventDispatcher } from './ReducerEventDispatcher.js'; import { ReducerObservation } from './ReducerObservation.js'; import { ReducerObservationSession } from './ReducerObservationSession.js'; import { ReductionOutcome } from './ReductionOutcome.js'; import { getReadModelMetadata } from '../readModels/index.js'; import { getReadModelId } from '../readModels/readModel.js'; import { buildReadModelDefinition } from '../readModels/buildReadModelDefinition.js'; import type { ReadModelNamingPolicy } from '../readModels/ReadModelNamingPolicy.js'; import { assertUniqueReadModelIds } from '../readModels/assertUniqueReadModelIds.js'; import { JsonSchemaGenerator } from '../schemas/index.js'; import type { IEventStore } from '../IEventStore.js'; import type { ClientArtifactsActivator } from '../artifacts/ClientArtifactsActivator.js'; import type { ActivatedArtifact } from '../artifacts/ActivatedArtifact.js'; import { ArtifactKind } from '../artifacts/ArtifactKind.js'; import { ArtifactDelivery } from '../artifacts/ArtifactDelivery.js'; import { refuseClientHostedObservers } from '../artifacts/refuseClientHostedObservers.js'; import { withActivatedArtifact, runActivated } from '../artifacts/withActivatedArtifact.js'; import type { BatchContext } from '../observation/batches/BatchContext.js'; import { BatchOutcomeKind } from '../observation/batches/BatchOutcomeKind.js'; import { getMaxConcurrency, toPageDelivery } from '../observation/batches/batchSize.js'; import { createBatchContext } from '../observation/batches/createBatchContext.js'; import type { DeliveredPartition } from '../observation/batches/DeliveredPartition.js'; import { EventAndContext } from '../observation/batches/EventAndContext.js'; import { EventBatch } from '../observation/batches/EventBatch.js'; import { isPage, partitionsOfOperation } from '../observation/batches/PageMessages.js'; import { PartitionFailedInBatch } from '../observation/batches/PartitionFailedInBatch.js'; import { runConcurrently } from '../observation/batches/runConcurrently.js'; import { ObservationReconnectBackoff, type ObservationReconnectBackoffOptions } from '../observation/ObservationReconnectBackoff.js'; import { classifyStreamError, StreamErrorKind } from '../observation/classifyStreamError.js'; import type { ObservationStreamOutcome } from '../observation/ObservationStreamOutcome.js'; /** Expression used to partition reducer observations by event source ID. */ const EVENT_SOURCE_ID_KEY = '$eventSourceId'; /** * A push-based async queue that implements {@link AsyncIterable} for use with nice-grpc * bidirectional streaming. Values pushed via {@link send} are yielded in order to * any consumer that iterates the queue. */ class AsyncQueue { private readonly _queue: T[] = []; private _resolve: ((result: IteratorResult) => void) | undefined = undefined; private _done = false; /** Pushes a value into the queue. No-op if the queue has been completed. */ send(value: T): void { if (this._done) return; if (this._resolve) { const resolve = this._resolve; this._resolve = undefined; resolve({ value, done: false }); } else { this._queue.push(value); } } /** Signals that no more values will be pushed, causing consumers to finish iteration. */ complete(): void { this._done = true; if (this._resolve) { this._resolve({ value: undefined, done: true }); this._resolve = undefined; } } [Symbol.asyncIterator](): AsyncIterator { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; return { next(): Promise> { if (self._queue.length > 0) { return Promise.resolve({ value: self._queue.shift()!, done: false }); } if (self._done) { return Promise.resolve({ value: undefined, done: true }); } return new Promise(resolve => { self._resolve = resolve as (result: IteratorResult) => void; }); }, return(): Promise> { self._done = true; if (self._resolve) { self._resolve({ value: undefined, done: true }); self._resolve = undefined; } return Promise.resolve({ value: undefined, done: true }); } }; } } /** * Implements {@link IReducers}, managing discovery and registration of reducers * with the Chronicle Kernel via bidirectional gRPC streaming. */ export class Reducers implements IReducers { private readonly _logger: ReturnType; private readonly _lifecycle: ConnectionLifecycle; private readonly _unsubscribeDisconnected: () => void; private readonly _reducers = new Map(); private readonly _queues = new Map>(); private readonly _observations = new Map(); private readonly _reconnectBackoffs = new Map(); private readonly _reobserveTimers = new Map>(); private _registered = false; private _disposed = false; /** * Creates a new {@link Reducers} instance. * @param _clientArtifacts - Provider for discovered client artifact types. * @param _connection - The Chronicle gRPC connection. * @param _eventStoreName - The name of the event store. * @param _namespace - The namespace within the event store. * @param lifecycle - The connection lifecycle used to react to disconnect events. * @param _defaultSinkTypeId - The default sink type identifier used when registering read models. * @param _eventStore - The event store handed to reducers that request it. * @param _artifactActivator - Optional per-delivery activator. * @param _readModelNamingPolicy - Optional policy naming the container of each read model. * @param _skipKeepAlive - Whether the client runs without a keep-alive, which refuses client-hosted reducers. * @param _reconnectBackoff - How a reducer waits before opening its observation stream again after it ended. */ constructor( private readonly _clientArtifacts: IClientArtifactsProvider, private readonly _connection: ChronicleConnection, private readonly _eventStoreName: string, private readonly _namespace: string, lifecycle: ConnectionLifecycle, private readonly _defaultSinkTypeId: string, private readonly _eventStore?: IEventStore, private readonly _artifactActivator?: ClientArtifactsActivator, private readonly _readModelNamingPolicy?: ReadModelNamingPolicy, private readonly _skipKeepAlive: boolean = false, private readonly _reconnectBackoff: ObservationReconnectBackoffOptions = {} ) { this._logger = createLogger('@cratis/chronicle/reducers', _connection.logger); this._lifecycle = lifecycle; this._unsubscribeDisconnected = lifecycle.onDisconnected(async () => { this._logger.info('Disconnected — stopping all reducer observations'); this._registered = false; this.disconnectAll(); }); } /** Stops observations permanently when the owning client is disposed. */ dispose(): void { this._unsubscribeDisconnected(); this._disposed = true; this._registered = false; this.disconnectAll(); this._reconnectBackoffs.clear(); } /** @inheritdoc */ async discover(): Promise { this._reducers.clear(); for (const type of this._clientArtifacts.reducers) { const metadata = getReducerMetadata(type); if (metadata) { this._reducers.set(metadata.id.value, type); this._logger.debug('Discovered reducer', { reducerId: metadata.id.value, type: (type as Function).name }); } } } /** @inheritdoc */ async register(): Promise { if (this._skipKeepAlive) refuseClientHostedObservers({ reactors: [], reducers: this._clientArtifacts.reducers }); if (this._registered || this._disposed) { return; } if (this._reducers.size === 0) { await this.discover(); } const registrations = [...this._reducers].map(([id, type]) => ({ id, type, dispatcher: new ReducerEventDispatcher(type, this._clientArtifacts.eventTypes) })); assertUniqueReadModelIds(this._clientArtifacts.readModels); await this.registerReadModels(); if (this._disposed) return; this._logger.info('Registering reducers', { count: this._reducers.size }); for (const { id, type, dispatcher } of registrations) { this.startObservation(id, type, dispatcher); } this._registered = true; } private async registerReadModels(): Promise { if (this._reducers.size === 0) { return; } const readModels = Array.from(this._reducers.entries()).map(([id, reducerType]) => { const readModelName = this.getReducerReadModelIdentifier(reducerType); return buildReadModelDefinition({ identifier: readModelName, type: getReducerMetadata(reducerType)?.readModel, schema: this.getReducerSchema(reducerType, readModelName), sinkTypeId: this._defaultSinkTypeId, observerType: ReadModelObserverType.Reducer, observerIdentifier: id, namingPolicy: this._readModelNamingPolicy }); }); const identifiers = new Set(); for (const definition of readModels) { const identifier = definition.Type.Identifier; if (identifiers.has(identifier)) throw new Error(`Read model id '${identifier}' has multiple reducers.`); identifiers.add(identifier); } this._logger.info('Registering read models for reducers', { count: readModels.length }); await this._connection.readModels.registerMany({ EventStore: this._eventStoreName, Owner: 1, ReadModels: readModels, Source: 1 }); } private getReducerSchema(reducerType: Constructor, readModelName: string): string { const metadata = getReducerMetadata(reducerType); if (metadata?.readModel) { const readModelMeta = getReadModelMetadata(metadata.readModel); if (readModelMeta?.schema) { return JSON.stringify(readModelMeta.schema); } // Generate the schema directly from the inferred model type. return JSON.stringify(JsonSchemaGenerator.generate(metadata.readModel)); } // No read model type declared — generate from a minimal schema const minimalSchema = { ...JsonSchemaGenerator.createEmptySchema(readModelName), additionalProperties: true }; return JSON.stringify(minimalSchema); } private startObservation(id: string, reducerType: Constructor, dispatcher: ReducerEventDispatcher): void { runInBackgroundContext(() => { if (this._disposed) return; const metadata = getReducerMetadata(reducerType)!; const eventSequenceId = metadata.eventSequenceId ?? EventSequenceId.eventLog.value; const readModelName = this.getReducerReadModelIdentifier(reducerType); this._logger.info('Starting reducer observation', { reducerId: id, eventSequenceId, readModel: readModelName, handlerCount: dispatcher.handlers.length, handlers: dispatcher.handlers.map(e => e.methodName) }); void this.runObservation({ id, reducerType, eventSequenceId, readModelName, dispatcher }); }); } private async runObservation(observation: ReducerObservation): Promise { let outcome: ObservationStreamOutcome = 'ended'; try { outcome = await this.observeReducer(observation); } catch (error) { this._logger.error('Reducer observation loop exited with error', { reducerId: observation.id, error }); } if (outcome === 'ended') this.scheduleReobserve(observation.id, observation.reducerType, observation.dispatcher); } private reconnectBackoffFor(id: string): ObservationReconnectBackoff { let backoff = this._reconnectBackoffs.get(id); if (!backoff) { backoff = new ObservationReconnectBackoff(this._reconnectBackoff); this._reconnectBackoffs.set(id, backoff); } return backoff; } /** * Re-establishes an observation whose stream ended. * * The stream ending without an error is not proof that all is well — the kernel * closes a cross-store (inbox) observation's stream rather than tailing it * forever, so a reducer that does not re-subscribe there silently stops * observing until the whole client reconnects. Both endings are therefore * retried. The delay keeps a stream that keeps ending from becoming a hot loop, * and grows with jitter while it does (see {@link ObservationReconnectBackoff}). */ private scheduleReobserve(id: string, reducerType: Constructor, dispatcher: ReducerEventDispatcher): void { // A disconnect clears the registration; the reconnect re-registers every // reducer from scratch, so retrying here as well would double up. if (!this._registered || this._disposed) { return; } clearTimeout(this._reobserveTimers.get(id)); const delayMs = this.reconnectBackoffFor(id).nextDelayMs(); this._logger.debug('Waiting before re-establishing reducer observation', { reducerId: id, delayMs }); const handle = runInBackgroundContext(() => setTimeout(() => { this._reobserveTimers.delete(id); // A reconnect in the meantime has already opened a new stream; opening another would leave one untracked. if (!this._registered || this._disposed || this._observations.has(id)) { return; } this._logger.info('Re-establishing reducer observation', { reducerId: id }); this.startObservation(id, reducerType, dispatcher); }, delayMs)); handle.unref?.(); this._reobserveTimers.set(id, handle); } private getReducerReadModelIdentifier(reducerType: Constructor): string { const metadata = getReducerMetadata(reducerType); if (metadata?.readModel) { return getReadModelId(metadata.readModel); } return (reducerType as Function).name; } private async observeReducer(observation: ReducerObservation): Promise { const { id, reducerType } = observation; const queue = new AsyncQueue(); const controller = new AbortController(); this._queues.set(id, queue); this._observations.set(id, controller); const connectionId = this._lifecycle.connectionId; const backoff = this.reconnectBackoffFor(id); backoff.streamOpened(); queue.send(this.createRegistrationMessage(observation, connectionId)); let iterator: AsyncIterator | undefined; let streamFinished = false; try { const reducerInstance = this._artifactActivator ? undefined : new (reducerType as new () => Record)(); if (reducerInstance) observation.dispatcher.validateInstance(reducerInstance); const session: ReducerObservationSession = { ...observation, signal: controller.signal, reducerInstance }; // Pull each message by hand so only a failure of the stream itself is classified: an error from a // reducer is the reducer's failure, and must never make the whole client reconnect. iterator = this._connection.reducers.observe(queue, { signal: controller.signal })[Symbol.asyncIterator](); for (;;) { let next: IteratorResult; try { next = await iterator.next(); } catch (streamError) { streamFinished = true; return this.streamFailed(id, queue, controller.signal, connectionId, streamError); } if (next.done) { streamFinished = true; break; } const operation = next.value; backoff.streamDelivered(); const partitions = partitionsOfOperation(operation); const notification = this.beginReduction(session, operation, partitions); await this.notifyReplayTransition(session, operation, notification); const context = createBatchContext({ observerId: id, eventStore: this._eventStoreName, namespace: this._namespace, eventSequenceId: session.eventSequenceId, signal: controller.signal }, operation, partitions); const outcomes = await runConcurrently(partitions, getMaxConcurrency(reducerType), partition => this.reducePartition(session, partition, notification, context)); queue.send(toResultMessage(operation, partitions, outcomes)); } if (this._queues.get(id) !== queue) { this._logger.debug('Reducer observation stream closed cleanly', { reducerId: id }); return 'superseded'; } return 'ended'; } catch (handlerError) { if (this._queues.get(id) !== queue) return 'superseded'; this._logger.error('Reducer observation failed while handling a delivery', { reducerId: id, error: handlerError }); return 'ended'; } finally { if (!streamFinished) { controller.abort(); void iterator?.return?.()?.catch(() => undefined); } // Only retire our own queue: a reconnect can already have replaced it, // and deleting the new one would leave that observation untracked and // leak a duplicate stream on every reconnect. if (this._queues.get(id) === queue) { this._queues.delete(id); this._observations.delete(id); } queue.complete(); } } private streamFailed(id: string, queue: AsyncQueue, signal: AbortSignal, connectionId: string, error: unknown): ObservationStreamOutcome { // A late error from a stream that a disconnect, a dispose or a newer stream replaced says nothing about now. if (this._queues.get(id) !== queue) { this._logger.debug('Reducer observation stream closed cleanly', { reducerId: id }); return 'superseded'; } const kind = classifyStreamError(error); if (kind === StreamErrorKind.Cancelled && signal.aborted) return 'stopped'; if (kind === StreamErrorKind.SessionLost) { // The kernel lost this client's registration. Opening the same stream with the same connection id // can never work, so reconnect the whole client, which re-registers every reducer. this._logger.warn('Reducer observation stream lost its session; reconnecting the client', { reducerId: id, error }); this._lifecycle.requestReconnect(connectionId, 'reducer-session-lost', error, handlerError => this._logger.error('Reconnect request handler failed', { reducerId: id, error: handlerError })); return 'sessionLost'; } this._logger.error('Reducer observation stream ended unexpectedly', { reducerId: id, error }); return 'ended'; } private createRegistrationMessage({ id, reducerType, eventSequenceId, readModelName, dispatcher }: ReducerObservation, connectionId: string): ReducerMessage { return { Content: { Value0: { ConnectionId: connectionId, EventStore: this._eventStoreName, Namespace: this._namespace, Reducer: { ReducerId: id, EventSequenceId: eventSequenceId, EventTypes: dispatcher.eventTypes.map(et => ({ EventType: { Id: et.id, Generation: et.generation, Tombstone: false }, Key: EVENT_SOURCE_ID_KEY })), ReadModel: readModelName, Hash: '', IsActive: getReducerMetadata(reducerType)?.isActive ?? true, GenerationDelivery: EventGenerationDelivery.Compatibility, Tags: getTagsFor(reducerType).map(t => t.value), Filters: { FilterTags: getFilterTagsFor(reducerType).map(t => t.value), EventSourceType: getEventSourceTypeFor(reducerType), EventStreamType: getEventStreamTypeFor(reducerType) } }, PageDelivery: toPageDelivery(reducerType), StateCaching: undefined }, Value1: undefined } }; } private beginReduction(session: ReducerObservationSession, operation: ReduceOperationMessage, partitions: readonly DeliveredPartition[]): ReductionOutcome { this._logger.debug('Received reduce operation', { reducerId: session.id, partitions: partitions.length, count: partitions.reduce((count, partition) => count + partition.events.length, 0), replayState: operation.ReplayState }); return new ReductionOutcome(); } private async reducePartition(session: ReducerObservationSession, partition: DeliveredPartition, notification: ReductionOutcome, context: BatchContext): Promise { const outcome = new ReductionOutcome(); if (notification.failed) { outcome.copyFrom(notification); return outcome; } outcome.currentState = partition.initialState ? JSON.parse(partition.initialState) as unknown : undefined; await this.reduceEvents(session, partition, outcome, context); return outcome; } private async notifyReplayTransition( session: ReducerObservationSession, operation: ReduceOperationMessage, outcome: ReductionOutcome ): Promise { try { if (this._artifactActivator && operation.ReplayState !== ReplayState.REPLAY_STATE_None) { await this.notifyActivatedReplayTransition(session, operation, this._artifactActivator); } else if (session.reducerInstance) { await notifyReplayLifecycle(session.reducerInstance, operation.ReplayState, operation.Partition); } } catch (err) { this._logger.error('Error notifying reducer of replay lifecycle transition', { reducerId: session.id, error: err }); outcome.recordReplayNotificationFailure(err); } } private async notifyActivatedReplayTransition( { id, reducerType, eventSequenceId, dispatcher, signal }: ReducerObservationSession, operation: ReduceOperationMessage, activator: ClientArtifactsActivator ): Promise { const eventStore = this.requireEventStore(); await withActivatedArtifact(reducerType, { kind: ArtifactKind.Reducer, artifactId: id, eventStore, readModels: eventStore.readModels, eventSequenceId, partition: operation.Partition, signal, delivery: ArtifactDelivery.ReplayNotification, replayState: operation.ReplayState }, activator, artifact => { dispatcher.validateInstance(artifact.instance); return runActivated(artifact, () => notifyReplayLifecycle(artifact.instance, operation.ReplayState, operation.Partition), { delivery: ArtifactDelivery.ReplayNotification, replayState: operation.ReplayState }); }, this._connection.logger); } private requireEventStore(): IEventStore { if (!this._eventStore) throw new Error('Reducer activation requires the owning event store.'); return this._eventStore; } private async reduceEvents( session: ReducerObservationSession, partition: DeliveredPartition, outcome: ReductionOutcome, context: BatchContext ): Promise { const { id, reducerType, eventSequenceId, dispatcher, signal, reducerInstance } = session; const firstInvocableEvent = this._artifactActivator && !outcome.failed ? partition.events.find(event => !!event.Context?.EventType?.Id && (dispatcher.batchMethod ? dispatcher.batchMethod.eventTypes.has(event.Context.EventType.Id) : !!dispatcher.handlerFor(event.Context.EventType.Id))) : undefined; if (!firstInvocableEvent || !this._artifactActivator) { await this.processEvents(session, partition, outcome, { instance: reducerInstance ?? {} }, context); return; } try { const eventStore = this.requireEventStore(); await withActivatedArtifact(reducerType as new () => Record, { kind: ArtifactKind.Reducer, artifactId: id, eventStore, readModels: eventStore.readModels, eventSequenceId, partition: partition.partition, signal, delivery: ArtifactDelivery.Events, eventContext: toClientEventContext(firstInvocableEvent.Context!) }, this._artifactActivator, artifact => { dispatcher.validateInstance(artifact.instance); return this.processEvents(session, partition, outcome, artifact, context); }, this._connection.logger); } catch (err) { this._logger.error('Error activating reducer', { reducerId: id, error: err }); outcome.recordActivationFailure(err); } } private async processEvents( session: ReducerObservationSession, partition: DeliveredPartition, outcome: ReductionOutcome, artifact: ActivatedArtifact>, context: BatchContext ): Promise { if (outcome.failed) return; if (session.dispatcher.batchMethod) { await this.processBatch(session, partition, outcome, artifact, context); return; } for (const event of partition.events) { try { // Skipped events stay synchronous; only an actual handler invocation is awaited. const pending = this.processEvent(session, event, outcome, artifact); if (pending) await pending; } catch (err) { this._logger.error('Error handling event in reducer', { reducerId: session.id, error: err }); outcome.recordFailure(err); break; } } } private async processBatch( { id, dispatcher }: ReducerObservationSession, partition: DeliveredPartition, outcome: ReductionOutcome, artifact: ActivatedArtifact>, context: BatchContext ): Promise { const method = dispatcher.batchMethod!; const events = partition.events.filter(event => method.eventTypes.has(event.Context?.EventType?.Id ?? '')); if (events.length === 0) return; try { const batch = new EventBatch(events.map(event => new EventAndContext(JSON.parse(event.Content) as Record, toClientEventContext(event.Context!), method.eventTypes.get(event.Context!.EventType!.Id)!.type)), context.canDefer); this._logger.info('Invoking reducer batch method', { reducerId: id, method: method.methodName, count: events.length }); const next = await runActivated(artifact, () => dispatcher.invokeBatch(artifact.instance, batch, outcome.currentState, context), { delivery: ArtifactDelivery.Events, eventContext: batch.events[0].context, methodName: method.methodName }); const [reported] = batch.outcomes; if (reported?.kind === BatchOutcomeKind.Deferred) { outcome.recordDeferral(reported.retryAfterMilliseconds); } else if (reported) { outcome.recordFailure(reported.error ?? new PartitionFailedInBatch(partition.partition)); } else { outcome.currentState = next; outcome.lastSuccessfullyObservedEvent = events.at(-1)!.Context!.SequenceNumber; } } catch (err) { this._logger.error('Error handling events in reducer batch method', { reducerId: id, error: err }); outcome.recordFailure(err); } } private processEvent( { id, dispatcher }: ReducerObservationSession, event: AppendedEvent, outcome: ReductionOutcome, artifact: ActivatedArtifact> ): Promise | undefined { const eventTypeId = event.Context?.EventType?.Id; if (!eventTypeId) { this._logger.warn('Event missing event type context', { reducerId: id }); return; } const entry = dispatcher.handlerFor(eventTypeId); if (!entry) { this._logger.debug('No handler registered for event type — skipping', { reducerId: id, eventTypeId }); outcome.lastSuccessfullyObservedEvent = event.Context!.SequenceNumber; return; } const content = JSON.parse(event.Content) as Record; const context = toClientEventContext(event.Context!); this._logger.info('Invoking reducer handler', { reducerId: id, method: entry.methodName, sequenceNumber: event.Context!.SequenceNumber.toString(), eventTypeId, hasState: outcome.currentState !== undefined }); return this.invokeHandler( () => runActivated(artifact, () => dispatcher.invoke(artifact.instance, entry, content, outcome.currentState, context), { delivery: ArtifactDelivery.Events, eventContext: context, methodName: entry.methodName }), outcome, event.Context!.SequenceNumber); } private async invokeHandler(invoke: () => Promise, outcome: ReductionOutcome, sequenceNumber: bigint): Promise { outcome.currentState = await invoke(); outcome.lastSuccessfullyObservedEvent = sequenceNumber; } private disconnectAll(): void { for (const timer of this._reobserveTimers.values()) clearTimeout(timer); this._reobserveTimers.clear(); for (const controller of this._observations.values()) controller.abort(); for (const queue of this._queues.values()) queue.complete(); this._observations.clear(); this._queues.clear(); } } /** * Creates the result of a reduce operation: one result per event source for a page, or the legacy single-partition fields. * @param operation - The delivered operation. * @param partitions - The partitions of the operation. * @param outcomes - The outcome of each partition, in the same order. * @returns The {@link ReducerMessage}. */ function toResultMessage(operation: ReduceOperationMessage, partitions: readonly DeliveredPartition[], outcomes: readonly ReductionOutcome[]): ReducerMessage { if (!isPage(operation)) return outcomes[0].toMessage(operation.Partition, operation.DeliveryId ?? 0n); return { Content: { Value0: undefined, Value1: { Partition: '', State: ObservationState.OBSERVATION_STATE_None, LastSuccessfulObservation: 0n, ExceptionMessages: [], ExceptionStackTrace: '', ReadModelState: '', DeliveryId: operation.DeliveryId ?? 0n, RetryAfterMilliseconds: 0n, Partitions: outcomes.map((outcome, index) => outcome.toPartitionResult(partitions[index].partition)) } } }; }