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

OrchestrationEngine.ts

389 lines15.3 KB

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