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