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