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

OrchestrationEngine.ts

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