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