Fix event processing: decouple listener failures from dispatch, skip persistence for streaming deltas, remove unused PubSub
- Bug 1: Succeed the deferred before running listener notifications so that listener failures (e.g. WebSocket send errors) don't fail the caller after the event is already persisted and the read model updated. Listener errors are now caught and logged as warnings. - Bug 2: Mark streaming text delta dispatches as transient so they update the in-memory read model and notify listeners but skip SQLite persistence. On turn completion, the accumulated message text is read from the snapshot and persisted as a single event, preventing unbounded event store growth and slow bootstrap replay. - Bug 3: Remove readModelPubSub and eventPubSub instances that were created and published to but never subscribed to anywhere in the codebase.
This commit is contained in:
1 parent
e7357970e1
commit
0813882522
3 files changed
+45
-26
No files matched your search
@@ -4,7 +4,7 @@ import type {
|
||||
OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { OrchestrationCommandSchema } from "@t3tools/contracts";
|
||||
import { Deferred, Effect, Layer, PubSub, Queue, Schema } from "effect";
|
||||
import { Deferred, Effect, Layer, Queue, Schema } from "effect";
|
||||
|
||||
import { createLogger } from "../logger.ts";
|
||||
import { OrchestrationEventRepository } from "../persistence/Services/OrchestrationEvents.ts";
|
||||
@@ -20,6 +20,7 @@ import { OrchestrationEngineService, type OrchestrationEngineShape } from "./Ser
|
||||
interface CommandEnvelope {
|
||||
command: OrchestrationCommand;
|
||||
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
|
||||
transient?: boolean | undefined;
|
||||
}
|
||||
|
||||
function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEvent, "sequence"> {
|
||||
@@ -169,8 +170,6 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
let readModel = createEmptyReadModel(new Date().toISOString());
|
||||
|
||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||
const readModelPubSub = yield* PubSub.unbounded<OrchestrationReadModel>();
|
||||
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
|
||||
const readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>();
|
||||
const domainEventListeners = new Set<(event: OrchestrationEvent) => void>();
|
||||
@@ -194,19 +193,28 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const eventBase = mapCommandToEvent(envelope.command);
|
||||
const savedEvent = yield* eventStore.append(eventBase);
|
||||
|
||||
let savedEvent: OrchestrationEvent;
|
||||
if (envelope.transient) {
|
||||
savedEvent = { ...eventBase, sequence: readModel.sequence };
|
||||
} else {
|
||||
savedEvent = yield* eventStore.append(eventBase);
|
||||
}
|
||||
readModel = yield* reduceEvent(readModel, savedEvent);
|
||||
|
||||
const snapshot = readModel;
|
||||
yield* Effect.all([
|
||||
PubSub.publish(eventPubSub, savedEvent),
|
||||
PubSub.publish(readModelPubSub, snapshot),
|
||||
]);
|
||||
|
||||
yield* notifyDomainEventListeners(savedEvent);
|
||||
yield* notifyReadModelListeners(snapshot);
|
||||
|
||||
yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence });
|
||||
|
||||
const snapshot = readModel;
|
||||
yield* notifyDomainEventListeners(savedEvent).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => logger.warn("domain event listener failed", { error: String(error) })),
|
||||
),
|
||||
);
|
||||
yield* notifyReadModelListeners(snapshot).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => logger.warn("read model listener failed", { error: String(error) })),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid)));
|
||||
|
||||
const bootstrapReadModel: Effect.Effect<void, OrchestrationDispatchError> = Effect.gen(
|
||||
@@ -232,10 +240,10 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const replayEvents: OrchestrationEngineShape["replayEvents"] = (fromSequenceExclusive) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive);
|
||||
|
||||
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
|
||||
const dispatch: OrchestrationEngineShape["dispatch"] = (command, options) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
|
||||
yield* Queue.offer(commandQueue, { command, result });
|
||||
yield* Queue.offer(commandQueue, { command, result, transient: options?.transient });
|
||||
return yield* Deferred.await(result);
|
||||
});
|
||||
|
||||
|
||||
@@ -51,10 +51,12 @@ export interface OrchestrationEngineShape {
|
||||
* Dispatch a validated orchestration command.
|
||||
*
|
||||
* @param command - Valid orchestration command.
|
||||
* @param options - Optional dispatch options. Set `transient` to skip persistence.
|
||||
* @returns Effect containing the sequence of the persisted event.
|
||||
*/
|
||||
readonly dispatch: (
|
||||
command: OrchestrationCommand,
|
||||
options?: { transient?: boolean | undefined } | undefined,
|
||||
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>;
|
||||
|
||||
/**
|
||||
|
||||
+20
-11
@@ -250,20 +250,29 @@ export function createServer(options: ServerOptions) {
|
||||
if (event.textDelta && event.textDelta.length > 0) {
|
||||
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
|
||||
await runtime.runPromise(
|
||||
liveOrchestrationEngine.dispatch({
|
||||
type: "message.send",
|
||||
commandId: crypto.randomUUID(),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: event.textDelta,
|
||||
streaming: true,
|
||||
createdAt: now,
|
||||
}),
|
||||
liveOrchestrationEngine.dispatch(
|
||||
{
|
||||
type: "message.send",
|
||||
commandId: crypto.randomUUID(),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: event.textDelta,
|
||||
streaming: true,
|
||||
createdAt: now,
|
||||
},
|
||||
{ transient: true },
|
||||
),
|
||||
);
|
||||
}
|
||||
if (event.method === "turn/completed") {
|
||||
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
|
||||
const latestSnapshot = await runtime.runPromise(liveOrchestrationEngine.getSnapshot());
|
||||
const latestThread = latestSnapshot.threads.find(
|
||||
(entry) => entry.session?.sessionId === event.sessionId,
|
||||
);
|
||||
const existingMessage = latestThread?.messages.find((m) => m.id === assistantMessageId);
|
||||
const accumulatedText = existingMessage?.text ?? "";
|
||||
await runtime.runPromise(
|
||||
liveOrchestrationEngine.dispatch({
|
||||
type: "message.send",
|
||||
@@ -271,7 +280,7 @@ export function createServer(options: ServerOptions) {
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: "",
|
||||
text: accumulatedText,
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
}),
|
||||
|
||||
Reference in new issue
Block a user