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 { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";
9import * as SqlClient from "effect/unstable/sql/SqlClient";
10
11import { toPersistenceSqlError } from "../../persistence/Errors.ts";
12import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
13import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
14import {
15 OrchestrationCommandInvariantError,
16 OrchestrationCommandPreviouslyRejectedError,
17 type OrchestrationDispatchError,
18} from "../Errors.ts";
19import { decideOrchestrationCommand } from "../decider.ts";
20import { createEmptyReadModel, projectEvent } from "../projector.ts";
21import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
22import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
23import {
24 OrchestrationEngineService,
25 type OrchestrationEngineShape,
26} from "../Services/OrchestrationEngine.ts";
27
28interface CommandEnvelope {
29 command: OrchestrationCommand;
30 result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
31}
32
33function commandToAggregateRef(command: OrchestrationCommand): {
34 readonly aggregateKind: "project" | "thread";
35 readonly aggregateId: ProjectId | ThreadId;
36} {
37 switch (command.type) {
38 case "project.create":
39 case "project.meta.update":
40 case "project.delete":
41 return {
42 aggregateKind: "project",
43 aggregateId: command.projectId,
44 };
45 default:
46 return {
47 aggregateKind: "thread",
48 aggregateId: command.threadId,
49 };
50 }
51}
52
53const makeOrchestrationEngine = Effect.gen(function* () {
54 const sql = yield* SqlClient.SqlClient;
55 const eventStore = yield* OrchestrationEventStore;
56 const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
57 const projectionPipeline = yield* OrchestrationProjectionPipeline;
58 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
59
60 let readModel = createEmptyReadModel(new Date().toISOString());
61
62 const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
63 const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
64
65 const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
66 const dispatchStartSequence = readModel.snapshotSequence;
67 const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
68 const persistedEvents = yield* Stream.runCollect(
69 eventStore.readFromSequence(dispatchStartSequence),
70 ).pipe(Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)));
71 if (persistedEvents.length === 0) {
72 return;
73 }
74
75 let nextReadModel = readModel;
76 for (const persistedEvent of persistedEvents) {
77 nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
78 }
79 readModel = nextReadModel;
80
81 for (const persistedEvent of persistedEvents) {
82 yield* PubSub.publish(eventPubSub, persistedEvent);
83 }
84 });
85
86 return Effect.gen(function* () {
87 const existingReceipt = yield* commandReceiptRepository.getByCommandId({
88 commandId: envelope.command.commandId,
89 });
90 if (Option.isSome(existingReceipt)) {
91 if (existingReceipt.value.status === "accepted") {
92 yield* Deferred.succeed(envelope.result, {
93 sequence: existingReceipt.value.resultSequence,
94 });
95 return;
96 }
97 yield* Deferred.fail(
98 envelope.result,
99 new OrchestrationCommandPreviouslyRejectedError({
100 commandId: envelope.command.commandId,
101 detail: existingReceipt.value.error ?? "Previously rejected.",
102 }),
103 );
104 return;
105 }
106
107 const eventBase = yield* decideOrchestrationCommand({
108 command: envelope.command,
109 readModel,
110 });
111 const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
112 const committedCommand = yield* sql
113 .withTransaction(
114 Effect.gen(function* () {
115 const committedEvents: OrchestrationEvent[] = [];
116 let nextReadModel = readModel;
117
118 for (const nextEvent of eventBases) {
119 const savedEvent = yield* eventStore.append(nextEvent);
120 nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
121 yield* projectionPipeline.projectEvent(savedEvent);
122 committedEvents.push(savedEvent);
123 }
124
125 const lastSavedEvent = committedEvents.at(-1) ?? null;
126 if (lastSavedEvent === null) {
127 return yield* new OrchestrationCommandInvariantError({
128 commandType: envelope.command.type,
129 detail: "Command produced no events.",
130 });
131 }
132
133 yield* commandReceiptRepository.upsert({
134 commandId: envelope.command.commandId,
135 aggregateKind: lastSavedEvent.aggregateKind,
136 aggregateId: lastSavedEvent.aggregateId,
137 acceptedAt: lastSavedEvent.occurredAt,
138 resultSequence: lastSavedEvent.sequence,
139 status: "accepted",
140 error: null,
141 });
142
143 return {
144 committedEvents,
145 lastSequence: lastSavedEvent.sequence,
146 nextReadModel,
147 } as const;
148 }),
149 )
150 .pipe(
151 Effect.catchTag("SqlError", (sqlError) =>
152 Effect.fail(
153 toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
154 ),
155 ),
156 );
157
158 readModel = committedCommand.nextReadModel;
159 for (const event of committedCommand.committedEvents) {
160 yield* PubSub.publish(eventPubSub, event);
161 }
162 yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });
163 }).pipe(
164 Effect.catch((error) =>
165 Effect.gen(function* () {
166 yield* reconcileReadModelAfterDispatchFailure.pipe(
167 Effect.catch(() =>
168 Effect.logWarning(
169 "failed to reconcile orchestration read model after dispatch failure",
170 ).pipe(
171 Effect.annotateLogs({
172 commandId: envelope.command.commandId,
173 snapshotSequence: readModel.snapshotSequence,
174 }),
175 ),
176 ),
177 );
178
179 if (Schema.is(OrchestrationCommandInvariantError)(error)) {
180 const aggregateRef = commandToAggregateRef(envelope.command);
181 yield* commandReceiptRepository
182 .upsert({
183 commandId: envelope.command.commandId,
184 aggregateKind: aggregateRef.aggregateKind,
185 aggregateId: aggregateRef.aggregateId,
186 acceptedAt: new Date().toISOString(),
187 resultSequence: readModel.snapshotSequence,
188 status: "rejected",
189 error: error.message,
190 })
191 .pipe(Effect.catch(() => Effect.void));
192 }
193 yield* Deferred.fail(envelope.result, error);
194 }),
195 ),
196 );
197 };
198
199 yield* projectionPipeline.bootstrap;
200 readModel = yield* projectionSnapshotQuery.getSnapshot();
201
202 const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
203 yield* Effect.forkScoped(worker);
204 yield* Effect.logDebug("orchestration engine started").pipe(
205 Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
206 );
207
208 const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
209 Effect.sync((): OrchestrationReadModel => readModel);
210
211 const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
212 eventStore.readFromSequence(fromSequenceExclusive);
213
214 const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
215 Effect.gen(function* () {
216 const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
217 yield* Queue.offer(commandQueue, { command, result });
218 return yield* Deferred.await(result);
219 });
220
221 return {
222 getReadModel,
223 readEvents,
224 dispatch,
225 // Each access creates a fresh PubSub subscription so that multiple
226 // consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
227 // each independently receive all domain events.
228 get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] {
229 return Stream.fromPubSub(eventPubSub);
230 },
231 } satisfies OrchestrationEngineShape;
232});
233
234export const OrchestrationEngineLive = Layer.effect(
235 OrchestrationEngineService,
236 makeOrchestrationEngine,
237);