Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OrchestrationEngine.ts

246 lines8.6 KB

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