Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OrchestrationEngine.ts

432 lines16.8 KB

1import type {
2 OrchestrationClientOrigin,
3 OrchestrationEvent,
4 OrchestrationReadModel,
5 ProjectId,
6 ThreadId,
7} from "@t3tools/contracts";
8import { OrchestrationCommand } from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Clock from "effect/Clock";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Deferred from "effect/Deferred";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Layer from "effect/Layer";
18import * as Metric from "effect/Metric";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Queue from "effect/Queue";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24import * as SqlClient from "effect/unstable/sql/SqlClient";
25​
26import {
27 metricAttributes,
28 orchestrationCommandAckDuration,
29 orchestrationCommandsTotal,
30 orchestrationCommandDuration,
31} from "../../observability/Metrics.ts";
32import { toPersistenceSqlError } from "../../persistence/Errors.ts";
33import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
34import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
35import {
36 isOrchestrationCommandRejection,
37 OrchestrationCommandIdConflictError,
38 OrchestrationCommandInvariantError,
39 OrchestrationCommandPreviouslyRejectedError,
40 type OrchestrationDispatchError,
41 type OrchestrationProjectorDecodeError,
42} from "../Errors.ts";
43import { decideOrchestrationCommand } from "../decider.ts";
44import { createEmptyReadModel, projectEvent } from "../projector.ts";
45import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
46import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
47import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
48import {
49 OrchestrationEngineService,
50 type OrchestrationEngineShape,
51} from "../Services/OrchestrationEngine.ts";
52const isOrchestrationCommandPreviouslyRejectedError = Schema.is(
53 OrchestrationCommandPreviouslyRejectedError,
54);
55const isOrchestrationCommandIdConflictError = Schema.is(OrchestrationCommandIdConflictError);
56​
57interface CommandEnvelope {
58 command: OrchestrationCommand;
59 origin: OrchestrationClientOrigin | undefined;
60 result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
61 startedAtMs: number;
63​
64function commandToAggregateRef(command: OrchestrationCommand): {
65 readonly aggregateKind: "project" | "thread";
66 readonly aggregateId: ProjectId | ThreadId;
67} {
68 switch (command.type) {
69 case "project.create":
70 case "project.meta.update":
71 case "project.delete":
72 return {
73 aggregateKind: "project",
74 aggregateId: command.projectId,
75 };
76 default:
77 return {
78 aggregateKind: "thread",
79 aggregateId: command.threadId,
80 };
81 }
83​
84const makeOrchestrationEngine = Effect.gen(function* () {
85 const sql = yield* SqlClient.SqlClient;
86 const eventStore = yield* OrchestrationEventStore;
87 const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
88 const projectionPipeline = yield* OrchestrationProjectionPipeline;
89 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
90 const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
91 const crypto = yield* Crypto.Crypto;
92​
93 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
94 let commandReadModel = createEmptyReadModel(yield* nowIso);
95​
96 const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
97 const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
98​
99 const projectEventsOntoReadModel = (
100 baseReadModel: OrchestrationReadModel,
101 events: ReadonlyArray<OrchestrationEvent>,
102 ): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
103 Effect.gen(function* () {
104 let nextReadModel = baseReadModel;
105 for (const event of events) {
106 nextReadModel = yield* projectEvent(nextReadModel, event);
107 }
108 return nextReadModel;
109 });
110​
111 const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
112 const dispatchStartSequence = commandReadModel.snapshotSequence;
113 let processingStartedAtMs = 0;
114 const aggregateRef = commandToAggregateRef(envelope.command);
115 const baseMetricAttributes = {
116 commandType: envelope.command.type,
117 aggregateKind: aggregateRef.aggregateKind,
118 } as const;
119 const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
120 const persistedEvents = yield* Stream.runCollect(
121 eventStore.readFromSequence(dispatchStartSequence),
122 ).pipe(Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)));
123 if (persistedEvents.length === 0) {
124 return;
125 }
126​
127 commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
128​
129 for (const persistedEvent of persistedEvents) {
130 yield* PubSub.publish(eventPubSub, persistedEvent);
131 }
132 });
133​
134 return Effect.exit(
135 Effect.gen(function* () {
136 processingStartedAtMs = yield* Clock.currentTimeMillis;
137 yield* Effect.annotateCurrentSpan({
138 "orchestration.command_id": envelope.command.commandId,
139 "orchestration.command_type": envelope.command.type,
140 "orchestration.aggregate_kind": aggregateRef.aggregateKind,
141 "orchestration.aggregate_id": aggregateRef.aggregateId,
142 });
143​
144 const existingReceipt = yield* commandReceiptRepository.getByCommandId({
145 commandId: envelope.command.commandId,
146 });
147 if (Option.isSome(existingReceipt)) {
148 // A receipt only proves this exact command was handled. Replaying it
149 // for a command aimed at another aggregate would report success for
150 // work that never happened.
151 if (
152 existingReceipt.value.aggregateKind !== aggregateRef.aggregateKind ||
153 existingReceipt.value.aggregateId !== aggregateRef.aggregateId
154 ) {
155 return yield* new OrchestrationCommandIdConflictError({
156 commandId: envelope.command.commandId,
157 receiptAggregateKind: existingReceipt.value.aggregateKind,
158 receiptAggregateId: existingReceipt.value.aggregateId,
159 commandAggregateKind: aggregateRef.aggregateKind,
160 commandAggregateId: aggregateRef.aggregateId,
161 });
162 }
163 if (existingReceipt.value.status === "accepted") {
164 return {
165 sequence: existingReceipt.value.resultSequence,
166 };
167 }
168 return yield* new OrchestrationCommandPreviouslyRejectedError({
169 commandId: envelope.command.commandId,
170 detail: existingReceipt.value.error ?? "Previously rejected.",
171 });
172 }
173​
174 if (
175 envelope.command.type === "thread.auto-settle" &&
176 (yield* eventStore.hasEventAfter({
177 aggregateKind: "thread",
178 aggregateId: envelope.command.threadId,
179 sequenceExclusive: envelope.command.snapshotSequence,
180 }))
181 ) {
182 return yield* new OrchestrationCommandInvariantError({
183 commandType: envelope.command.type,
184 detail: `thread ${envelope.command.threadId} changed before automatic settlement`,
185 });
186 }
187​
188 if (
189 envelope.command.type === "thread.auto-settle" &&
190 threadBackgroundLiveness.getThreadBackgroundLiveness(envelope.command.threadId) !== null
191 ) {
192 return yield* new OrchestrationCommandInvariantError({
193 commandType: envelope.command.type,
194 detail: `thread ${envelope.command.threadId} has live background work`,
195 });
196 }
197​
198 // Command snapshots omit activities at startup and cap them while running.
199 // Read this request's durable state before deciding how to send the answer.
200 const userInputActivity =
201 envelope.command.type === "thread.user-input.respond"
202 ? yield* projectionSnapshotQuery.getUserInputActivity(envelope.command)
203 : Option.none();
204 const eventBase = yield* decideOrchestrationCommand({
205 command: envelope.command,
206 readModel: commandReadModel,
207 ...(Option.isSome(userInputActivity)
208 ? { userInputActivity: userInputActivity.value }
209 : {}),
210 }).pipe(
211 Effect.provideService(Crypto.Crypto, crypto),
212 Effect.mapError((cause) =>
213 isOrchestrationCommandRejection(cause)
214 ? cause
215 : new OrchestrationCommandInvariantError({
216 commandType: envelope.command.type,
217 detail: "Failed to generate an event identifier.",
218 cause,
219 }),
220 ),
221 );
222 const plannedEvents = Array.isArray(eventBase) ? eventBase : [eventBase];
223 // Stamp the dispatching client's origin onto every event the command
224 // produced. The decider stays pure; attribution is an engine concern.
225 const eventBases =
226 envelope.origin === undefined
227 ? plannedEvents
228 : plannedEvents.map((planned) => ({
229 ...planned,
230 metadata: { ...planned.metadata, origin: envelope.origin },
231 }));
232 const committedCommand = yield* sql
233 .withTransaction(
234 Effect.gen(function* () {
235 const committedEvents: OrchestrationEvent[] = [];
236 const attachmentCleanups: Effect.Effect<void>[] = [];
237 let nextCommandReadModel = commandReadModel;
238​
239 for (const nextEvent of eventBases) {
240 const savedEvent = yield* eventStore.append(nextEvent);
241 nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
242 const cleanup = yield* projectionPipeline.projectEventDeferred(savedEvent);
243 attachmentCleanups.push(cleanup);
244 committedEvents.push(savedEvent);
245 }
246​
247 const lastSavedEvent = committedEvents.at(-1) ?? null;
248 if (lastSavedEvent === null) {
249 return yield* new OrchestrationCommandInvariantError({
250 commandType: envelope.command.type,
251 detail: "Command produced no events.",
252 });
253 }
254​
255 yield* commandReceiptRepository.upsert({
256 commandId: envelope.command.commandId,
257 aggregateKind: lastSavedEvent.aggregateKind,
258 aggregateId: lastSavedEvent.aggregateId,
259 acceptedAt: lastSavedEvent.occurredAt,
260 resultSequence: lastSavedEvent.sequence,
261 status: "accepted",
262 error: null,
263 });
264​
265 return {
266 committedEvents,
267 attachmentCleanups,
268 lastSequence: lastSavedEvent.sequence,
269 nextCommandReadModel,
270 } as const;
271 }),
272 )
273 .pipe(
274 Effect.catchTag("SqlError", (sqlError) =>
275 Effect.fail(
276 toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
277 ),
278 ),
279 );
280​
281 commandReadModel = committedCommand.nextCommandReadModel;
282 for (const cleanup of committedCommand.attachmentCleanups) {
283 yield* cleanup;
284 }
285 for (const [index, event] of committedCommand.committedEvents.entries()) {
286 yield* PubSub.publish(eventPubSub, event);
287 if (index === 0) {
288 yield* Metric.update(
289 Metric.withAttributes(
290 orchestrationCommandAckDuration,
291 metricAttributes({
292 ...baseMetricAttributes,
293 ackEventType: event.type,
294 }),
295 ),
296 Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),
297 );
298 }
299 }
300 return { sequence: committedCommand.lastSequence };
301 }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
302 ).pipe(
303 Effect.flatMap((exit) =>
304 Effect.gen(function* () {
305 const outcome = Exit.isSuccess(exit)
306 ? "success"
307 : Cause.hasInterruptsOnly(exit.cause)
308 ? "interrupt"
309 : "failure";
310 yield* Metric.update(
311 Metric.withAttributes(
312 orchestrationCommandDuration,
313 metricAttributes(baseMetricAttributes),
314 ),
315 Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - processingStartedAtMs)),
316 );
317 yield* Metric.update(
318 Metric.withAttributes(
319 orchestrationCommandsTotal,
320 metricAttributes({
321 ...baseMetricAttributes,
322 outcome,
323 }),
324 ),
325 1,
326 );
327​
328 if (Exit.isSuccess(exit)) {
329 yield* Deferred.succeed(envelope.result, exit.value);
330 return;
331 }
332​
333 const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
334 if (
335 !isOrchestrationCommandPreviouslyRejectedError(error) &&
336 !isOrchestrationCommandIdConflictError(error)
337 ) {
338 yield* reconcileReadModelAfterDispatchFailure.pipe(
339 Effect.catch(() =>
340 Effect.logWarning(
341 "failed to reconcile orchestration read model after dispatch failure",
342 ).pipe(
343 Effect.annotateLogs({
344 commandId: envelope.command.commandId,
345 snapshotSequence: commandReadModel.snapshotSequence,
346 }),
347 ),
348 ),
349 );
350​
351 if (isOrchestrationCommandRejection(error)) {
352 yield* commandReceiptRepository
353 .upsert({
354 commandId: envelope.command.commandId,
355 aggregateKind: aggregateRef.aggregateKind,
356 aggregateId: aggregateRef.aggregateId,
357 acceptedAt: yield* nowIso,
358 resultSequence: commandReadModel.snapshotSequence,
359 status: "rejected",
360 error: error.message,
361 })
362 .pipe(Effect.catch(() => Effect.void));
363 }
364 }
365​
366 yield* Deferred.fail(envelope.result, error);
367 }),
368 ),
369 );
370 };
371​
372 yield* projectionPipeline.bootstrap;
373 commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
374​
375 const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
376 yield* Effect.forkScoped(worker);
377 yield* Effect.logDebug("orchestration engine started").pipe(
378 Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
379 );
380​
381 const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
382 eventStore.readFromSequence(fromSequenceExclusive, limit);
383​
384 const readThreadEvents: OrchestrationEngineShape["readThreadEvents"] = ({ threadId, ...range }) =>
385 eventStore.readAggregateRange({ ...range, aggregateKind: "thread", aggregateId: threadId });
386​
387 const getThreadReplayStats: OrchestrationEngineShape["getThreadReplayStats"] = ({
388 threadId,
389 ...range
390 }) =>
391 eventStore.getAggregateReplayStats({
392 ...range,
393 aggregateKind: "thread",
394 aggregateId: threadId,
395 });
396​
397 const dispatch: OrchestrationEngineShape["dispatch"] = (command, options) =>
398 Effect.gen(function* () {
399 const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
400 yield* Queue.offer(commandQueue, {
401 command,
402 origin: options?.origin,
403 result,
404 startedAtMs: yield* Clock.currentTimeMillis,
405 });
406 return yield* Deferred.await(result);
407 });
408​
409 return {
410 readEvents,
411 readThreadEvents,
412 getThreadReplayStats,
413 dispatch,
414 subscribeDomainEvents: PubSub.subscribe(eventPubSub).pipe(Effect.map(Stream.fromSubscription)),
415 // Each access creates a fresh PubSub subscription so that multiple
416 // consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
417 // each independently receive all domain events.
418 get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] {
419 return Stream.fromPubSub(eventPubSub);
420 },
421 // The command read model's snapshotSequence tracks the latest committed
422 // event sequence (updated on the worker fiber). A plain property read is a
423 // consistent, committed value — reassignment of `commandReadModel` is
424 // atomic on the single-threaded event loop.
425 latestSequence: Effect.sync(() => commandReadModel.snapshotSequence),
426 } satisfies OrchestrationEngineShape;
427});
428​
429export const OrchestrationEngineLive = Layer.effect(
430 OrchestrationEngineService,
431 makeOrchestrationEngine,
432);