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

OrchestrationEngine.ts

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