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

OrchestrationEngine.ts

473 lines18.6 KB

1import type {
2 OrchestrationClientOrigin,
3 OrchestrationEvent,
4 OrchestrationReadModel,
5 ProjectId,
6 ThreadId,
7} from "@t3tools/contracts";
8import { OrchestrationCommand } from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Clock from "effect/Clock";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Deferred from "effect/Deferred";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Layer from "effect/Layer";
18import * as Metric from "effect/Metric";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Queue from "effect/Queue";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24import * as SqlClient from "effect/unstable/sql/SqlClient";
25​
26import {
27 metricAttributes,
28 orchestrationCommandAckDuration,
29 orchestrationCommandsTotal,
30 orchestrationCommandDuration,
31} from "../../observability/Metrics.ts";
32import { toPersistenceSqlError } from "../../persistence/Errors.ts";
33import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
34import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
35import {
36 isOrchestrationCommandRejection,
37 OrchestrationCommandIdConflictError,
38 OrchestrationCommandInvariantError,
39 OrchestrationCommandPreviouslyRejectedError,
40 type OrchestrationDispatchError,
41 type OrchestrationProjectorDecodeError,
42} from "../Errors.ts";
43import { decideOrchestrationCommand } from "../decider.ts";
44import { createEmptyReadModel, projectEvent } from "../projector.ts";
45import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
46import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
47import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
48import {
49 OrchestrationEngineService,
50 type OrchestrationEngineShape,
51} from "../Services/OrchestrationEngine.ts";
52const isOrchestrationCommandPreviouslyRejectedError = Schema.is(
53 OrchestrationCommandPreviouslyRejectedError,
54);
55const isOrchestrationCommandIdConflictError = Schema.is(OrchestrationCommandIdConflictError);
56​
57interface CommandEnvelope {
58 command: OrchestrationCommand;
59 origin: OrchestrationClientOrigin | undefined;
60 result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
61 startedAtMs: number;
63​
64function commandToAggregateRef(command: OrchestrationCommand): {
65 readonly aggregateKind: "project" | "thread";
66 readonly aggregateId: ProjectId | ThreadId;
67} {
68 switch (command.type) {
69 case "project.create":
70 case "project.meta.update":
71 case "project.delete":
72 return {
73 aggregateKind: "project",
74 aggregateId: command.projectId,
75 };
76 default:
77 return {
78 aggregateKind: "thread",
79 aggregateId: command.threadId,
80 };
81 }
83​
84const makeOrchestrationEngine = Effect.gen(function* () {
85 const sql = yield* SqlClient.SqlClient;
86 const eventStore = yield* OrchestrationEventStore;
87 const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
88 const projectionPipeline = yield* OrchestrationProjectionPipeline;
89 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
90 const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
91 const crypto = yield* Crypto.Crypto;
92​
93 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
94 let commandReadModel = createEmptyReadModel(yield* nowIso);
95​
96 const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
97 const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
98​
99 const projectEventsOntoReadModel = (
100 baseReadModel: OrchestrationReadModel,
101 events: ReadonlyArray<OrchestrationEvent>,
102 ): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
103 Effect.gen(function* () {
104 let nextReadModel = baseReadModel;
105 for (const event of events) {
106 nextReadModel = yield* projectEvent(nextReadModel, event);
107 }
108 return nextReadModel;
109 });
110​
111 const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
112 const dispatchStartSequence = commandReadModel.snapshotSequence;
113 let processingStartedAtMs = 0;
114 const aggregateRef = commandToAggregateRef(envelope.command);
115 const baseMetricAttributes = {
116 commandType: envelope.command.type,
117 aggregateKind: aggregateRef.aggregateKind,
118 } as const;
119 const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
120 const persistedEvents = yield* Stream.runCollect(
121 eventStore.readFromSequence(dispatchStartSequence),
122 ).pipe(Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)));
123 if (persistedEvents.length === 0) {
124 return;
125 }
126​
127 commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
128​
129 for (const persistedEvent of persistedEvents) {
130 yield* PubSub.publish(eventPubSub, persistedEvent);
131 }
132 });
133​
134 return Effect.exit(
135 Effect.gen(function* () {
136 processingStartedAtMs = yield* Clock.currentTimeMillis;
137 yield* Effect.annotateCurrentSpan({
138 "orchestration.command_id": envelope.command.commandId,
139 "orchestration.command_type": envelope.command.type,
140 "orchestration.aggregate_kind": aggregateRef.aggregateKind,
141 "orchestration.aggregate_id": aggregateRef.aggregateId,
142 });
143​
144 const existingReceipt = yield* commandReceiptRepository.getByCommandId({
145 commandId: envelope.command.commandId,
146 });
147 if (Option.isSome(existingReceipt)) {
148 // A receipt only proves this exact command was handled. Replaying it
149 // for a command aimed at another aggregate would report success for
150 // work that never happened.
151 if (
152 existingReceipt.value.aggregateKind !== aggregateRef.aggregateKind ||
153 existingReceipt.value.aggregateId !== aggregateRef.aggregateId
154 ) {
155 return yield* new OrchestrationCommandIdConflictError({
156 commandId: envelope.command.commandId,
157 receiptAggregateKind: existingReceipt.value.aggregateKind,
158 receiptAggregateId: existingReceipt.value.aggregateId,
159 commandAggregateKind: aggregateRef.aggregateKind,
160 commandAggregateId: aggregateRef.aggregateId,
161 });
162 }
163 if (existingReceipt.value.status === "accepted") {
164 return {
165 sequence: existingReceipt.value.resultSequence,
166 };
167 }
168 return yield* new OrchestrationCommandPreviouslyRejectedError({
169 commandId: envelope.command.commandId,
170 detail: existingReceipt.value.error ?? "Previously rejected.",
171 });
172 }
173​
174 if (
175 envelope.command.type === "thread.auto-settle" &&
176 (yield* eventStore.hasEventAfter({
177 aggregateKind: "thread",
178 aggregateId: envelope.command.threadId,
179 sequenceExclusive: envelope.command.snapshotSequence,
180 }))
181 ) {
182 return yield* new OrchestrationCommandInvariantError({
183 commandType: envelope.command.type,
184 detail: `thread ${envelope.command.threadId} changed before automatic settlement`,
185 });
186 }
187​
188 // The decider compares the lookup inputs. Only recreation needs an
189 // event check, since it can reset a thread to the same field values.
190 if (
191 envelope.command.type === "thread.pull-request.sync" &&
192 (yield* eventStore.hasEventAfter({
193 aggregateKind: "thread",
194 aggregateId: envelope.command.threadId,
195 sequenceExclusive: envelope.command.snapshotSequence,
196 type: "thread.created",
197 }))
198 ) {
199 return yield* new OrchestrationCommandInvariantError({
200 commandType: envelope.command.type,
201 detail: `thread ${envelope.command.threadId} was recreated before pull request discovery`,
202 });
203 }
204​
205 if (
206 envelope.command.type === "thread.auto-settle" &&
207 threadBackgroundLiveness.getThreadBackgroundLiveness(envelope.command.threadId) !== null
208 ) {
209 return yield* new OrchestrationCommandInvariantError({
210 commandType: envelope.command.type,
211 detail: `thread ${envelope.command.threadId} has live background work`,
212 });
213 }
214​
215 // New and moved projects do not carry a resolved identity in the event-derived
216 // command model. Legacy PR edits need it to identify the link they replace.
217 if (
218 envelope.command.type === "thread.meta.update" &&
219 envelope.command.linkedPullRequest !== undefined
220 ) {
221 const threadId = envelope.command.threadId;
222 const thread = commandReadModel.threads.find((thread) => thread.id === threadId);
223 if (thread !== undefined) {
224 const project = yield* projectionSnapshotQuery.getProjectShellById(thread.projectId);
225 if (Option.isSome(project)) {
226 commandReadModel = {
227 ...commandReadModel,
228 projects: commandReadModel.projects.map((entry) =>
229 entry.id === thread.projectId
230 ? { ...entry, repositoryIdentity: project.value.repositoryIdentity }
231 : entry,
232 ),
233 };
234 }
235 }
236 }
237​
238 // Command snapshots omit activities at startup and cap them while running.
239 // Read this request's durable state before deciding how to send the answer.
240 const userInputActivity =
241 envelope.command.type === "thread.user-input.respond" ||
242 envelope.command.type === "thread.user-input.dismiss"
243 ? yield* projectionSnapshotQuery.getUserInputActivity(envelope.command)
244 : Option.none();
245 const eventBase = yield* decideOrchestrationCommand({
246 command: envelope.command,
247 readModel: commandReadModel,
248 ...(Option.isSome(userInputActivity)
249 ? { userInputActivity: userInputActivity.value }
250 : {}),
251 }).pipe(
252 Effect.provideService(Crypto.Crypto, crypto),
253 Effect.mapError((cause) =>
254 isOrchestrationCommandRejection(cause)
255 ? cause
256 : new OrchestrationCommandInvariantError({
257 commandType: envelope.command.type,
258 detail: "Failed to generate an event identifier.",
259 cause,
260 }),
261 ),
262 );
263 const plannedEvents = Array.isArray(eventBase) ? eventBase : [eventBase];
264 // Stamp the dispatching client's origin onto every event the command
265 // produced. The decider stays pure; attribution is an engine concern.
266 const eventBases =
267 envelope.origin === undefined
268 ? plannedEvents
269 : plannedEvents.map((planned) => ({
270 ...planned,
271 metadata: { ...planned.metadata, origin: envelope.origin },
272 }));
273 const committedCommand = yield* sql
274 .withTransaction(
275 Effect.gen(function* () {
276 const committedEvents: OrchestrationEvent[] = [];
277 const attachmentCleanups: Effect.Effect<void>[] = [];
278 let nextCommandReadModel = commandReadModel;
279​
280 for (const nextEvent of eventBases) {
281 const savedEvent = yield* eventStore.append(nextEvent);
282 nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
283 const cleanup = yield* projectionPipeline.projectEventDeferred(savedEvent);
284 attachmentCleanups.push(cleanup);
285 committedEvents.push(savedEvent);
286 }
287​
288 const lastSavedEvent = committedEvents.at(-1) ?? null;
289 if (lastSavedEvent === null) {
290 return yield* new OrchestrationCommandInvariantError({
291 commandType: envelope.command.type,
292 detail: "Command produced no events.",
293 });
294 }
295​
296 yield* commandReceiptRepository.upsert({
297 commandId: envelope.command.commandId,
298 aggregateKind: lastSavedEvent.aggregateKind,
299 aggregateId: lastSavedEvent.aggregateId,
300 acceptedAt: lastSavedEvent.occurredAt,
301 resultSequence: lastSavedEvent.sequence,
302 status: "accepted",
303 error: null,
304 });
305​
306 return {
307 committedEvents,
308 attachmentCleanups,
309 lastSequence: lastSavedEvent.sequence,
310 nextCommandReadModel,
311 } as const;
312 }),
313 )
314 .pipe(
315 Effect.catchTag("SqlError", (sqlError) =>
316 Effect.fail(
317 toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
318 ),
319 ),
320 );
321​
322 commandReadModel = committedCommand.nextCommandReadModel;
323 for (const cleanup of committedCommand.attachmentCleanups) {
324 yield* cleanup;
325 }
326 for (const [index, event] of committedCommand.committedEvents.entries()) {
327 yield* PubSub.publish(eventPubSub, event);
328 if (index === 0) {
329 yield* Metric.update(
330 Metric.withAttributes(
331 orchestrationCommandAckDuration,
332 metricAttributes({
333 ...baseMetricAttributes,
334 ackEventType: event.type,
335 }),
336 ),
337 Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),
338 );
339 }
340 }
341 return { sequence: committedCommand.lastSequence };
342 }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
343 ).pipe(
344 Effect.flatMap((exit) =>
345 Effect.gen(function* () {
346 const outcome = Exit.isSuccess(exit)
347 ? "success"
348 : Cause.hasInterruptsOnly(exit.cause)
349 ? "interrupt"
350 : "failure";
351 yield* Metric.update(
352 Metric.withAttributes(
353 orchestrationCommandDuration,
354 metricAttributes(baseMetricAttributes),
355 ),
356 Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - processingStartedAtMs)),
357 );
358 yield* Metric.update(
359 Metric.withAttributes(
360 orchestrationCommandsTotal,
361 metricAttributes({
362 ...baseMetricAttributes,
363 outcome,
364 }),
365 ),
366 1,
367 );
368​
369 if (Exit.isSuccess(exit)) {
370 yield* Deferred.succeed(envelope.result, exit.value);
371 return;
372 }
373​
374 const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
375 if (
376 !isOrchestrationCommandPreviouslyRejectedError(error) &&
377 !isOrchestrationCommandIdConflictError(error)
378 ) {
379 yield* reconcileReadModelAfterDispatchFailure.pipe(
380 Effect.catch(() =>
381 Effect.logWarning(
382 "failed to reconcile orchestration read model after dispatch failure",
383 ).pipe(
384 Effect.annotateLogs({
385 commandId: envelope.command.commandId,
386 snapshotSequence: commandReadModel.snapshotSequence,
387 }),
388 ),
389 ),
390 );
391​
392 if (isOrchestrationCommandRejection(error)) {
393 yield* commandReceiptRepository
394 .upsert({
395 commandId: envelope.command.commandId,
396 aggregateKind: aggregateRef.aggregateKind,
397 aggregateId: aggregateRef.aggregateId,
398 acceptedAt: yield* nowIso,
399 resultSequence: commandReadModel.snapshotSequence,
400 status: "rejected",
401 error: error.message,
402 })
403 .pipe(Effect.catch(() => Effect.void));
404 }
405 }
406​
407 yield* Deferred.fail(envelope.result, error);
408 }),
409 ),
410 );
411 };
412​
413 yield* projectionPipeline.bootstrap;
414 commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
415​
416 const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
417 yield* Effect.forkScoped(worker);
418 yield* Effect.logDebug("orchestration engine started").pipe(
419 Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
420 );
421​
422 const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
423 eventStore.readFromSequence(fromSequenceExclusive, limit);
424​
425 const readThreadEvents: OrchestrationEngineShape["readThreadEvents"] = ({ threadId, ...range }) =>
426 eventStore.readAggregateRange({ ...range, aggregateKind: "thread", aggregateId: threadId });
427​
428 const getThreadReplayStats: OrchestrationEngineShape["getThreadReplayStats"] = ({
429 threadId,
430 ...range
431 }) =>
432 eventStore.getAggregateReplayStats({
433 ...range,
434 aggregateKind: "thread",
435 aggregateId: threadId,
436 });
437​
438 const dispatch: OrchestrationEngineShape["dispatch"] = (command, options) =>
439 Effect.gen(function* () {
440 const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
441 yield* Queue.offer(commandQueue, {
442 command,
443 origin: options?.origin,
444 result,
445 startedAtMs: yield* Clock.currentTimeMillis,
446 });
447 return yield* Deferred.await(result);
448 });
449​
450 return {
451 readEvents,
452 readThreadEvents,
453 getThreadReplayStats,
454 dispatch,
455 subscribeDomainEvents: PubSub.subscribe(eventPubSub).pipe(Effect.map(Stream.fromSubscription)),
456 // Each access creates a fresh PubSub subscription so that multiple
457 // consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
458 // each independently receive all domain events.
459 get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] {
460 return Stream.fromPubSub(eventPubSub);
461 },
462 // The command read model's snapshotSequence tracks the latest committed
463 // event sequence (updated on the worker fiber). A plain property read is a
464 // consistent, committed value — reassignment of `commandReadModel` is
465 // atomic on the single-threaded event loop.
466 latestSequence: Effect.sync(() => commandReadModel.snapshotSequence),
467 } satisfies OrchestrationEngineShape;
468});
469​
470export const OrchestrationEngineLive = Layer.effect(
471 OrchestrationEngineService,
472 makeOrchestrationEngine,
473);