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