Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationV2Run,
4 OrchestrationV2DomainEvent,
5 OrchestrationV2StoredEvent,
6 RunAttemptId,
7 RunId,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Context from "effect/Context";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as PubSub from "effect/PubSub";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import * as SqlClient from "effect/unstable/sql/SqlClient";
19
20import {
21 CommandReceiptStoreV2,
22 type CommandReceiptV2,
23 layer as commandReceiptStoreLayer,
24} from "./CommandReceiptStore.ts";
25import {
26 EffectOutboxV2,
27 type OrchestrationEffectRequestV2,
28 type PendingOrchestrationEffectV2,
29 layer as effectOutboxLayer,
30} from "./EffectOutbox.ts";
31import { EventStoreV2 } from "./EventStore.ts";
32import {
33 ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
34 ProjectionStoreV2,
35} from "./ProjectionStore.ts";
36import {
37 TurnItemPositionStoreV2,
38 layer as turnItemPositionStoreLayer,
39} from "./TurnItemPositionStore.ts";
40
41/**
42 * ERRORS
43 */
44export class EventSinkWriteError extends Schema.TaggedErrorClass<EventSinkWriteError>()(
45 "EventSinkWriteError",
46 {
47 eventCount: Schema.Number,
48 commandId: Schema.optional(CommandId),
49 cause: Schema.optional(Schema.Defect()),
50 },
51) {
52 override get message(): string {
53 return `Failed to write ${this.eventCount} orchestration V2 event(s).`;
54 }
55}
56
57export class EventSinkStreamError extends Schema.TaggedErrorClass<EventSinkStreamError>()(
58 "EventSinkStreamError",
59 {
60 threadId: Schema.optional(ThreadId),
61 afterSequence: Schema.optional(Schema.Number),
62 cause: Schema.optional(Schema.Defect()),
63 },
64) {
65 override get message(): string {
66 return this.threadId === undefined
67 ? "Failed to stream orchestration V2 events."
68 : `Failed to stream orchestration V2 events for thread ${this.threadId}.`;
69 }
70}
71
72export const EventSinkV2Error = Schema.Union([EventSinkWriteError, EventSinkStreamError]);
73export type EventSinkV2Error = typeof EventSinkV2Error.Type;
74
75/**
76 * SERVICE DEFINITION
77 */
78export interface EventSinkV2Shape {
79 readonly write: (input: {
80 readonly commandId?: CommandId;
81 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
82 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
83 readonly writeWithEffects: (input: {
84 readonly commandId?: CommandId;
85 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
86 readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
87 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
88 readonly writeIfRunCurrent: (input: {
89 readonly commandId?: CommandId;
90 readonly threadId: ThreadId;
91 readonly runId: RunId;
92 readonly activeAttemptId: RunAttemptId;
93 readonly expectedStatus: OrchestrationV2Run["status"];
94 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
95 }) => Effect.Effect<
96 {
97 readonly committed: boolean;
98 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
99 },
100 EventSinkV2Error
101 >;
102 readonly commitCommand: (input: {
103 readonly commandId: CommandId;
104 readonly threadId: ThreadId;
105 readonly commandType: string;
106 readonly acceptedAt: DateTime.Utc;
107 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
108 readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
109 readonly cancelUnsettledEffects?: {
110 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
111 readonly reason: string;
112 };
113 }) => Effect.Effect<
114 {
115 readonly receipt: CommandReceiptV2;
116 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
117 readonly committed: boolean;
118 readonly cancelledEffectCount: number;
119 },
120 EventSinkV2Error
121 >;
122 readonly commitRejectedCommand: (input: {
123 readonly commandId: CommandId;
124 readonly threadId: ThreadId;
125 readonly commandType: string;
126 readonly rejectedAt: DateTime.Utc;
127 readonly error: string;
128 }) => Effect.Effect<CommandReceiptV2, EventSinkV2Error>;
129 readonly stream: (input?: {
130 readonly threadId?: ThreadId;
131 readonly afterSequence?: number;
132 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
133 readonly latestSequence: (input?: {
134 readonly threadId?: ThreadId;
135 }) => Effect.Effect<number, EventSinkV2Error>;
136 readonly readByCommandId: (input: {
137 readonly commandId: CommandId;
138 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
139}
140
141export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
142 "t3/orchestration-v2/EventSink/EventSinkV2",
143) {}
144
145/**
146 * IMPLEMENTATIONS
147 */
148const baseLayer: Layer.Layer<
149 EventSinkV2,
150 never,
151 | CommandReceiptStoreV2
152 | EffectOutboxV2
153 | EventStoreV2
154 | ProjectionStoreV2
155 | SqlClient.SqlClient
156 | TurnItemPositionStoreV2
157> = Layer.effect(
158 EventSinkV2,
159 Effect.gen(function* () {
160 const sql = yield* SqlClient.SqlClient;
161 const commandReceipts = yield* CommandReceiptStoreV2;
162 const effectOutbox = yield* EffectOutboxV2;
163 const eventStore = yield* EventStoreV2;
164 const projectionStore = yield* ProjectionStoreV2;
165 const turnItemPositions = yield* TurnItemPositionStoreV2;
166 const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
167
168 const normalizeEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) => {
169 const runOrdinals = new Map(
170 events.flatMap((event) =>
171 event.type === "run.created" || event.type === "run.updated"
172 ? [[event.payload.id, event.payload.ordinal] as const]
173 : [],
174 ),
175 );
176 return Effect.forEach(
177 events,
178 (event): Effect.Effect<OrchestrationV2DomainEvent, unknown> =>
179 event.type === "turn-item.updated"
180 ? turnItemPositions
181 .normalize(
182 event.payload,
183 event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
184 )
185 .pipe(Effect.map((payload) => ({ ...event, payload })))
186 : Effect.succeed(event),
187 { concurrency: 1 },
188 );
189 };
190
191 const applyStoredEvents = (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) =>
192 Effect.gen(function* () {
193 yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
194 concurrency: 1,
195 });
196 const sequence = storedEvents.at(-1)?.sequence;
197 if (sequence !== undefined) {
198 const now = DateTime.formatIso(yield* DateTime.now);
199 yield* sql`
200 INSERT INTO orchestration_v2_projection_metadata (
201 projection_name,
202 schema_version,
203 last_sequence,
204 updated_at
205 )
206 VALUES (
207 'thread-projections',
208 ${ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
209 ${sequence},
210 ${now}
211 )
212 ON CONFLICT(projection_name)
213 DO UPDATE SET
214 schema_version = excluded.schema_version,
215 last_sequence = excluded.last_sequence,
216 updated_at = excluded.updated_at
217 `;
218 }
219 });
220
221 const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (
222 input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],
223 ) {
224 yield* Effect.annotateCurrentSpan({
225 "orchestration_v2.command_id": input.commandId ?? null,
226 "orchestration_v2.event_count": input.events.length,
227 "orchestration_v2.thread_id": input.events[0]?.threadId ?? null,
228 });
229
230 const storedEvents = yield* sql.withTransaction(
231 Effect.gen(function* () {
232 const normalized = yield* normalizeEvents(input.events);
233 const committed = yield* eventStore.append({
234 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
235 events: normalized,
236 });
237 yield* applyStoredEvents(committed);
238 yield* effectOutbox.enqueue(input.effects);
239 return committed;
240 }),
241 );
242 if (input.effects.length > 0) {
243 yield* effectOutbox.notifyAvailable;
244 }
245 yield* eventStore.publishCommitted(storedEvents);
246 yield* PubSub.publishAll(liveEvents, storedEvents);
247 return storedEvents;
248 });
249
250 const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")(
251 function* (input: Parameters<EventSinkV2Shape["writeIfRunCurrent"]>[0]) {
252 yield* Effect.annotateCurrentSpan({
253 "orchestration_v2.command_id": input.commandId ?? null,
254 "orchestration_v2.event_count": input.events.length,
255 "orchestration_v2.run_id": input.runId,
256 "orchestration_v2.thread_id": input.threadId,
257 });
258
259 const result = yield* sql.withTransaction(
260 Effect.gen(function* () {
261 const rows = yield* sql<{
262 readonly status: string;
263 readonly active_attempt_id: string | null;
264 }>`
265 SELECT
266 status,
267 json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id
268 FROM orchestration_v2_projection_runs
269 WHERE run_id = ${input.runId}
270 AND thread_id = ${input.threadId}
271 LIMIT 1
272 `;
273 const current = rows[0];
274 if (
275 current === undefined ||
276 current.status !== input.expectedStatus ||
277 current.active_attempt_id !== input.activeAttemptId
278 ) {
279 return {
280 committed: false as const,
281 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
282 };
283 }
284
285 const normalized = yield* normalizeEvents(input.events);
286 const storedEvents = yield* eventStore.append({
287 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
288 events: normalized,
289 });
290 yield* applyStoredEvents(storedEvents);
291 return { committed: true as const, storedEvents };
292 }),
293 );
294 if (result.committed) {
295 yield* eventStore.publishCommitted(result.storedEvents);
296 yield* PubSub.publishAll(liveEvents, result.storedEvents);
297 }
298 return result;
299 },
300 );
301
302 const existingCommandResult = (commandId: CommandId) =>
303 Effect.gen(function* () {
304 const existing = yield* commandReceipts.getByCommandId(commandId);
305 if (Option.isNone(existing)) {
306 return yield* Effect.die(
307 new Error(`Command receipt ${commandId} disappeared during its transaction.`),
308 );
309 }
310 const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
311 Stream.runCollect,
312 Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
313 );
314 return { receipt: existing.value, storedEvents };
315 });
316
317 const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
318 input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
319 ) {
320 const result = yield* sql.withTransaction(
321 Effect.gen(function* () {
322 const reserved = yield* commandReceipts.insertIfAbsent({
323 commandId: input.commandId,
324 threadId: input.threadId,
325 commandType: input.commandType,
326 acceptedAt: input.acceptedAt,
327 resultSequence: 0,
328 status: "accepted",
329 error: null,
330 });
331 if (!reserved) {
332 const existing = yield* existingCommandResult(input.commandId);
333 return { ...existing, committed: false as const, cancelledEffectIds: [] };
334 }
335
336 const normalized = yield* normalizeEvents(input.events);
337 const storedEvents = yield* eventStore.append({
338 commandId: input.commandId,
339 events: normalized,
340 });
341 const sequence = storedEvents.at(-1)?.sequence;
342 if (sequence === undefined) {
343 return yield* Effect.die(
344 new Error(`Command ${input.commandId} produced no orchestration events.`),
345 );
346 }
347 yield* applyStoredEvents(storedEvents);
348 yield* effectOutbox.enqueue(input.effects);
349 const receipt: CommandReceiptV2 = {
350 commandId: input.commandId,
351 threadId: input.threadId,
352 commandType: input.commandType,
353 acceptedAt: input.acceptedAt,
354 resultSequence: sequence,
355 status: "accepted",
356 error: null,
357 };
358 yield* commandReceipts.upsert(receipt);
359 const cancelledEffectIds =
360 input.cancelUnsettledEffects === undefined
361 ? []
362 : yield* effectOutbox.cancelUnsettled({
363 threadId: input.threadId,
364 ...input.cancelUnsettledEffects,
365 });
366 return { receipt, storedEvents, committed: true as const, cancelledEffectIds };
367 }),
368 );
369 yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
370 if (input.effects.length > 0) {
371 yield* effectOutbox.notifyAvailable;
372 }
373 if (result.committed) {
374 yield* eventStore.publishCommitted(result.storedEvents);
375 yield* PubSub.publishAll(liveEvents, result.storedEvents);
376 }
377 return {
378 receipt: result.receipt,
379 storedEvents: result.storedEvents,
380 committed: result.committed,
381 cancelledEffectCount: result.cancelledEffectIds.length,
382 };
383 });
384
385 const commitRejectedCommandEffect = Effect.fn(
386 "orchestrationV2.EventSink.commitRejectedCommand",
387 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
388 return yield* sql.withTransaction(
389 Effect.gen(function* () {
390 const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
391 const receipt: CommandReceiptV2 = {
392 commandId: input.commandId,
393 threadId: input.threadId,
394 commandType: input.commandType,
395 acceptedAt: input.rejectedAt,
396 resultSequence: sequence,
397 status: "rejected",
398 error: input.error,
399 };
400 const inserted = yield* commandReceipts.insertIfAbsent(receipt);
401 if (inserted) {
402 return receipt;
403 }
404 const existing = yield* commandReceipts.getByCommandId(input.commandId);
405 return Option.getOrElse(existing, () => receipt);
406 }),
407 );
408 });
409
410 const catchUp = (input: {
411 readonly afterSequence: number;
412 readonly throughSequence: number;
413 readonly threadId?: ThreadId;
414 }): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
415 const pageSize = 256;
416 const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
417 Stream.unwrap(
418 eventStore
419 .read({
420 afterSequence,
421 throughSequence: input.throughSequence,
422 ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
423 limit: pageSize,
424 })
425 .pipe(
426 Stream.runCollect,
427 Effect.map((chunk) => Array.from(chunk)),
428 Effect.map((events) => {
429 if (events.length === 0) {
430 return Stream.empty;
431 }
432 const current = Stream.fromIterable(events);
433 const last = events.at(-1)?.sequence ?? input.throughSequence;
434 return events.length < pageSize || last >= input.throughSequence
435 ? current
436 : Stream.concat(current, loop(last));
437 }),
438 ),
439 );
440 return loop(input.afterSequence);
441 };
442
443 const stream = (input?: { readonly threadId?: ThreadId; readonly afterSequence?: number }) =>
444 Stream.unwrap(
445 Effect.gen(function* () {
446 // Subscribe first, then capture the database high-water mark. Events
447 // committed between those operations are buffered by the subscription.
448 const subscription = yield* PubSub.subscribe(liveEvents);
449 const highWater = yield* eventStore.latestSequence();
450 const afterSequence = input?.afterSequence ?? 0;
451 const replay = catchUp({
452 afterSequence,
453 throughSequence: highWater,
454 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
455 });
456 const live = Stream.fromSubscription(subscription).pipe(
457 Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)),
458 Stream.filter(
459 (stored) => input?.threadId === undefined || stored.event.threadId === input.threadId,
460 ),
461 );
462 return Stream.concat(replay, live);
463 }),
464 );
465
466 return EventSinkV2.of({
467 write: (input) =>
468 writeEffect({ ...input, effects: [] }).pipe(
469 Effect.mapError(
470 (cause) =>
471 new EventSinkWriteError({
472 eventCount: input.events.length,
473 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
474 cause,
475 }),
476 ),
477 ),
478 writeWithEffects: (input) =>
479 writeEffect(input).pipe(
480 Effect.mapError(
481 (cause) =>
482 new EventSinkWriteError({
483 eventCount: input.events.length,
484 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
485 cause,
486 }),
487 ),
488 ),
489 writeIfRunCurrent: (input) =>
490 writeIfRunCurrentEffect(input).pipe(
491 Effect.mapError(
492 (cause) =>
493 new EventSinkWriteError({
494 eventCount: input.events.length,
495 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
496 cause,
497 }),
498 ),
499 ),
500 commitCommand: (input) =>
501 commitCommandEffect(input).pipe(
502 Effect.mapError(
503 (cause) =>
504 new EventSinkWriteError({
505 commandId: input.commandId,
506 eventCount: input.events.length,
507 cause,
508 }),
509 ),
510 ),
511 commitRejectedCommand: (input) =>
512 commitRejectedCommandEffect(input).pipe(
513 Effect.mapError(
514 (cause) =>
515 new EventSinkWriteError({
516 commandId: input.commandId,
517 eventCount: 0,
518 cause,
519 }),
520 ),
521 ),
522 stream: (input) =>
523 stream(input).pipe(
524 Stream.mapError(
525 (cause) =>
526 new EventSinkStreamError({
527 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
528 ...(input?.afterSequence === undefined
529 ? {}
530 : { afterSequence: input.afterSequence }),
531 cause,
532 }),
533 ),
534 ),
535 latestSequence: (input) =>
536 eventStore.latestSequence(input).pipe(
537 Effect.mapError(
538 (cause) =>
539 new EventSinkStreamError({
540 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
541 cause,
542 }),
543 ),
544 ),
545 readByCommandId: (input) =>
546 eventStore.readByCommandId(input).pipe(
547 Stream.mapError(
548 (cause) =>
549 new EventSinkStreamError({
550 cause,
551 }),
552 ),
553 ),
554 } satisfies EventSinkV2Shape);
555 }),
556);
557
558/**
559 * Event sink layer for application compositions that already own the
560 * persistence services. Keeping the outbox instance shared with the worker is
561 * important because enqueue notifications are in-memory wakeups backed by the
562 * durable SQL queue.
563 */
564export const layerFromStores = baseLayer;
565
566export const layer: Layer.Layer<
567 EventSinkV2,
568 never,
569 EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient
570> = baseLayer.pipe(
571 Layer.provide(
572 Layer.mergeAll(commandReceiptStoreLayer, effectOutboxLayer, turnItemPositionStoreLayer),
573 ),
574);