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