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

OrchestrationEngine.ts

363 lines13.9 KB

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