Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationV2Run,
4 OrchestrationV2DomainEvent,
5 type OrchestrationV2ProviderThread,
6 OrchestrationV2StoredEvent,
7 ProviderThreadId,
8 RunAttemptId,
9 RunId,
10 RuntimeRequestId,
11 NodeId,
12 type ProjectId,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as Context from "effect/Context";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Semaphore from "effect/Semaphore";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24import * as SqlClient from "effect/sql/SqlClient";
25
26import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts";
27import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
28import { projectDomainEventForWire } from "./WireProjection.ts";
29import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts";
30
31import * as CommandReceiptStore from "./CommandReceiptStore.ts";
32import * as EffectOutbox from "./EffectOutbox.ts";
33import * as EventStore from "./EventStore.ts";
34import * as ProjectionStore from "./ProjectionStore.ts";
35import * as ProjectStore from "./ProjectStore.ts";
36import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
37
38export class EventSinkWriteError extends Schema.TaggedError<EventSinkWriteError>()(
39 "EventSinkWriteError",
40 {
41 eventCount: Schema.Number,
42 commandId: Schema.optional(CommandId),
43 cause: Schema.optional(Schema.Defect()),
44 },
45) {
46 override get message(): string {
47 return `Failed to write ${this.eventCount} orchestration V2 event(s).`;
48 }
49}
50
51export class EventSinkStreamError extends Schema.TaggedError<EventSinkStreamError>()(
52 "EventSinkStreamError",
53 {
54 threadId: Schema.optional(ThreadId),
55 afterSequence: Schema.optional(Schema.Number),
56 cause: Schema.optional(Schema.Defect()),
57 },
58) {
59 override get message(): string {
60 return this.threadId === undefined
61 ? "Failed to stream orchestration V2 events."
62 : `Failed to stream orchestration V2 events for thread ${this.threadId}.`;
63 }
64}
65
66export const EventSinkV2Error = Schema.Union([EventSinkWriteError, EventSinkStreamError]);
67export type EventSinkV2Error = typeof EventSinkV2Error.Type;
68
69export interface EventSinkV2Shape {
70 readonly write: (input: {
71 /** Return no events if another thread owns this native session at commit time. */
72 readonly unlessNativeThreadOwned?: Pick<
73 OrchestrationV2ProviderThread,
74 "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
75 >;
76 readonly guardPendingUserInputCancellations?: boolean;
77 readonly commandId?: CommandId;
78 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
79 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
80 readonly writeWithEffects: (input: {
81 /**
82 * Rebuilds each run.updated from the stored row with only its delegatedCompletion replaced.
83 * The batch must not also change that run's lifecycle.
84 */
85 readonly updateDelegatedCompletionOnly?: boolean;
86 readonly unlessNativeThreadOwned?: Pick<
87 OrchestrationV2ProviderThread,
88 "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
89 >;
90 readonly guardPendingUserInputCancellations?: boolean;
91 readonly commandId?: CommandId;
92 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
93 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
94 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
95 readonly writeIfRunCurrent: (input: {
96 readonly guardPendingUserInputCancellations?: boolean;
97 readonly commandId?: CommandId;
98 readonly threadId: ThreadId;
99 readonly runId: RunId;
100 readonly activeAttemptId: RunAttemptId;
101 readonly expectedStatus: OrchestrationV2Run["status"];
102 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
103 readonly effects?: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
104 }) => Effect.Effect<
105 {
106 readonly committed: boolean;
107 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
108 },
109 EventSinkV2Error
110 >;
111 /**
112 * Atomically commit only when the provider thread is still owned by the
113 * expected run attempt and ordinal. Used for late post-terminal
114 * provider_thread updates so a completed or superseded attempt cannot clobber
115 * a newer attempt that already claimed the thread.
116 */
117 readonly writeIfProviderThreadOwner: (input: {
118 readonly guardPendingUserInputCancellations?: boolean;
119 readonly commandId?: CommandId;
120 readonly providerThreadId: ProviderThreadId;
121 readonly runId: RunId;
122 readonly activeAttemptId: RunAttemptId;
123 readonly expectedLastRunOrdinal: number;
124 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
125 }) => Effect.Effect<
126 {
127 readonly committed: boolean;
128 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
129 },
130 EventSinkV2Error
131 >;
132 /**
133 * Atomically commit only while the stored provider thread still equals
134 * `expected`, the row its writer read, so a read-modify-write of the row
135 * cannot overwrite an update published in between. The whole row is
136 * compared because not every writer moves `updatedAt`.
137 */
138 readonly writeIfProviderThreadUnchanged: (input: {
139 readonly expected: OrchestrationV2ProviderThread;
140 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
141 }) => Effect.Effect<
142 {
143 readonly committed: boolean;
144 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
145 },
146 EventSinkV2Error
147 >;
148 readonly commitCommand: (input: {
149 readonly commandId: CommandId;
150 readonly threadId: ThreadId;
151 readonly commandType: string;
152 readonly acceptedAt: DateTime.Utc;
153 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
154 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
155 readonly cancelUnsettledEffects?: {
156 readonly effectTypes: ReadonlyArray<EffectOutbox.OrchestrationEffectRequestV2["type"]>;
157 readonly reason: string;
158 };
159 }) => Effect.Effect<
160 {
161 readonly receipt: CommandReceiptStore.CommandReceiptV2;
162 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
163 readonly committed: boolean;
164 readonly cancelledEffectCount: number;
165 },
166 EventSinkV2Error
167 >;
168 readonly commitRejectedCommand: (input: {
169 readonly commandId: CommandId;
170 readonly threadId: ThreadId;
171 readonly commandType: string;
172 readonly rejectedAt: DateTime.Utc;
173 readonly error: string;
174 }) => Effect.Effect<CommandReceiptStore.CommandReceiptV2, EventSinkV2Error>;
175 readonly commitProjectCommand: (input: {
176 readonly commandId: CommandId;
177 readonly projectId: ProjectId;
178 readonly commandType: string;
179 readonly acceptedAt: DateTime.Utc;
180 readonly event: UnsequencedProjectEvent;
181 }) => Effect.Effect<
182 { readonly receipt: CommandReceiptStore.ProjectCommandReceiptV2; readonly committed: boolean },
183 EventSinkV2Error
184 >;
185 readonly commitRejectedProjectCommand: (input: {
186 readonly commandId: CommandId;
187 readonly projectId: ProjectId;
188 readonly commandType: string;
189 readonly rejectedAt: DateTime.Utc;
190 readonly error: string;
191 }) => Effect.Effect<CommandReceiptStore.ProjectCommandReceiptV2, EventSinkV2Error>;
192 readonly stream: (input?: {
193 readonly threadId?: ThreadId;
194 readonly afterSequence?: number;
195 readonly eventType?: OrchestrationV2DomainEvent["type"];
196 /** Bound RPC subscribers; internal workers must not drop their subscription under load. */
197 readonly bounded?: boolean;
198 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
199 readonly latestSequence: (input?: {
200 readonly threadId?: ThreadId;
201 }) => Effect.Effect<number, EventSinkV2Error>;
202 readonly readByCommandId: (input: {
203 readonly commandId: CommandId;
204 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
205}
206
207export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
208 "t3/orchestration-v2/EventSink/EventSinkV2",
209) {}
210
211const layerBase: Layer.Layer<
212 EventSinkV2,
213 never,
214 | CommandReceiptStore.CommandReceiptStoreV2
215 | EffectOutbox.EffectOutboxV2
216 | EventStore.EventStoreV2
217 | ProjectionStore.ProjectionStoreV2
218 | ProjectStore.ProjectStoreV2
219 | SqlClient.SqlClient
220 | TurnItemPositionStore.TurnItemPositionStoreV2
221> = Layer.effect(
222 EventSinkV2,
223 Effect.gen(function* () {
224 const sql = yield* SqlClient.SqlClient;
225 const commandReceipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
226 const effectOutbox = yield* EffectOutbox.EffectOutboxV2;
227 const eventStore = yield* EventStore.EventStoreV2;
228 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
229 const projectStore = yield* ProjectStore.ProjectStoreV2;
230 const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
231 const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
232 const liveEventsByType = new Map<
233 OrchestrationV2DomainEvent["type"],
234 PubSub.PubSub<OrchestrationV2StoredEvent>
235 >();
236 const publishLiveEvents =
237 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
238 Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {
239 yield* PubSub.publishAll(liveEvents, events);
240 for (const [type, pubsub] of liveEventsByType) {
241 yield* PubSub.publishAll(
242 pubsub,
243 events.filter((stored) => stored.event.type === type),
244 );
245 }
246 });
247 const runOutcomes = makeRunOutcomeRecorder((threadId) =>
248 // One payload row; unlike the shell, it still resolves a deleted child thread.
249 projectionStore
250 .getThread(threadId)
251 .pipe(Effect.map((thread) => thread.lineage.relationshipToParent === "subagent")),
252 );
253 // Recorded before publication, so an interrupted publish cannot lose a committed outcome.
254 const publishStoredEvents = (
255 events: ReadonlyArray<OrchestrationV2StoredEvent>,
256 outcomes: ReadonlyArray<RunOutcome>,
257 ) =>
258 runOutcomes
259 .record(outcomes)
260 .pipe(
261 Effect.andThen(eventStore.publishCommitted(events)),
262 Effect.andThen(publishLiveEvents(events)),
263 );
264
265 // Transactions commit one at a time, but each writer publishes after its
266 // commit. If a writer is descheduled in between, a later commit reaches
267 // subscribers first, and clients drop any event at or below the newest
268 // sequence they have applied.
269 const publishLane = yield* Semaphore.make(1);
270 const commitThenPublish = <A, E, R>(
271 transaction: Effect.Effect<A, E, R>,
272 publish: (committed: A) => Effect.Effect<void>,
273 ) =>
274 Effect.suspend(() => {
275 let holdsLane = false;
276 const takeLane = publishLane.take(1).pipe(
277 Effect.andThen(
278 Effect.sync(() => {
279 holdsLane = true;
280 }),
281 ),
282 Effect.uninterruptible,
283 );
284 return sql
285 .withTransaction(Effect.tap(transaction, () => takeLane))
286 .pipe(
287 Effect.tap(publish),
288 Effect.ensuring(
289 Effect.suspend(() => (holdsLane ? publishLane.release(1) : Effect.void)),
290 ),
291 );
292 });
293
294 // A user can answer after terminal normalization reads the pending request.
295 // Recheck inside the write transaction so stale cleanup cannot erase answers.
296 const guardUserInputCancellations =
297 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
298 Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2DomainEvent>) {
299 const staleRequests = new Set<RuntimeRequestId>();
300 const staleNodes = new Set<NodeId>();
301 for (const event of events) {
302 if (
303 event.type !== "runtime-request.updated" ||
304 event.payload.kind !== "user_input" ||
305 event.payload.status !== "cancelled"
306 )
307 continue;
308 const current = yield* projectionStore.getRuntimeRequest(
309 event.threadId,
310 event.payload.id,
311 );
312 if (
313 current?.status !== "pending" ||
314 current.kind !== "user_input" ||
315 current.providerTurnId !== event.payload.providerTurnId ||
316 current.responseCapability.type === "message"
317 ) {
318 staleRequests.add(event.payload.id);
319 staleNodes.add(event.payload.nodeId);
320 }
321 }
322 return events.filter((event) => {
323 switch (event.type) {
324 case "runtime-request.updated":
325 return event.payload.status !== "cancelled" || !staleRequests.has(event.payload.id);
326 case "node.updated":
327 return event.payload.status !== "cancelled" || !staleNodes.has(event.payload.id);
328 case "turn-item.updated":
329 return (
330 event.payload.type !== "user_input_request" ||
331 event.payload.status !== "cancelled" ||
332 !staleRequests.has(event.payload.requestId)
333 );
334 default:
335 return true;
336 }
337 });
338 });
339
340 const normalizeEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) => {
341 const runOrdinals = new Map(
342 events.flatMap((event) =>
343 event.type === "run.created" || event.type === "run.updated"
344 ? [[event.payload.id, event.payload.ordinal] as const]
345 : [],
346 ),
347 );
348 return Effect.forEach(
349 events,
350 (event): Effect.Effect<OrchestrationV2DomainEvent, unknown> =>
351 event.type === "turn-item.updated"
352 ? turnItemPositions
353 .normalize(
354 event.payload,
355 event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
356 )
357 .pipe(Effect.map((payload) => ({ ...event, payload })))
358 : Effect.succeed(event),
359 { concurrency: 1 },
360 );
361 };
362
363 const applyStoredEvents =
364 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
365 Effect.fnUntraced(function* (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) {
366 yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
367 concurrency: 1,
368 });
369 const sequence = storedEvents.at(-1)?.sequence;
370 if (sequence !== undefined) {
371 const now = DateTime.formatIso(yield* DateTime.now);
372 yield* sql`
373 INSERT INTO orchestration_v2_projection_metadata (
374 projection_name,
375 schema_version,
376 last_sequence,
377 updated_at
378 )
379 VALUES (
380 'thread-projections',
381 ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
382 ${sequence},
383 ${now}
384 )
385 ON CONFLICT(projection_name)
386 DO UPDATE SET
387 schema_version = excluded.schema_version,
388 last_sequence = excluded.last_sequence,
389 updated_at = excluded.updated_at
390 `;
391 }
392 // Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder.
393 return yield* runOutcomes.prepare(storedEvents);
394 });
395
396 const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (
397 input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],
398 ) {
399 yield* Effect.annotateCurrentSpan({
400 "orchestration_v2.command_id": input.commandId ?? null,
401 "orchestration_v2.event_count": input.events.length,
402 "orchestration_v2.thread_id": input.events[0]?.threadId ?? null,
403 });
404
405 const { committed } = yield* commitThenPublish(
406 Effect.gen(function* () {
407 // Check ownership in the same transaction that claims the native session.
408 const imported = input.unlessNativeThreadOwned;
409 if (imported?.nativeThreadRef != null) {
410 const owners = yield* sql`
411 SELECT provider_thread_id
412 FROM orchestration_v2_projection_provider_threads
413 WHERE driver = ${imported.driver}
414 AND provider_instance_id = ${imported.providerInstanceId}
415 AND thread_id IS NOT ${imported.appThreadId}
416 AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId}
417 LIMIT 1
418 `;
419 if (owners.length > 0) return { committed: [], outcomes: [] };
420 }
421 // Checkpoint capture can finish after a cohort writer reads its parent run.
422 // Merge in this transaction so the event log and projection keep that completion.
423 const events = input.updateDelegatedCompletionOnly
424 ? yield* Effect.forEach(input.events, (event) =>
425 Effect.gen(function* () {
426 if (event.type !== "run.updated") return event;
427 const { runs } = yield* projectionStore.getThreadRecords(
428 event.threadId,
429 ["runs"],
430 { runIds: [event.payload.id] },
431 );
432 const current = runs[0];
433 return current === undefined
434 ? event
435 : {
436 ...event,
437 payload: {
438 ...current,
439 delegatedCompletion: event.payload.delegatedCompletion,
440 },
441 };
442 }),
443 )
444 : input.events;
445 const normalized = yield* normalizeEvents(
446 input.guardPendingUserInputCancellations === true
447 ? yield* guardUserInputCancellations(events)
448 : events,
449 );
450 const committed = yield* eventStore.append({
451 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
452 events: normalized,
453 });
454 const outcomes = yield* applyStoredEvents(committed);
455 yield* effectOutbox.enqueue(input.effects);
456 return { committed, outcomes };
457 }).pipe(Effect.withTracerEnabled(false)),
458 ({ committed, outcomes }) =>
459 Effect.gen(function* () {
460 if (input.effects.length > 0) {
461 yield* effectOutbox.notifyAvailable(input.effects.length);
462 }
463 yield* publishStoredEvents(committed, outcomes);
464 }),
465 );
466 return committed;
467 });
468
469 const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")(
470 function* (input: Parameters<EventSinkV2Shape["writeIfRunCurrent"]>[0]) {
471 yield* Effect.annotateCurrentSpan({
472 "orchestration_v2.command_id": input.commandId ?? null,
473 "orchestration_v2.event_count": input.events.length,
474 "orchestration_v2.run_id": input.runId,
475 "orchestration_v2.thread_id": input.threadId,
476 });
477
478 return yield* commitThenPublish(
479 Effect.gen(function* () {
480 const rows = yield* sql<{
481 readonly status: string;
482 readonly active_attempt_id: string | null;
483 }>`
484 SELECT
485 status,
486 json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id
487 FROM orchestration_v2_projection_runs
488 WHERE run_id = ${input.runId}
489 AND thread_id = ${input.threadId}
490 LIMIT 1
491 `;
492 const current = rows[0];
493 if (
494 current === undefined ||
495 current.status !== input.expectedStatus ||
496 current.active_attempt_id !== input.activeAttemptId
497 ) {
498 return {
499 committed: false as const,
500 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
501 };
502 }
503
504 const normalized = yield* normalizeEvents(
505 input.guardPendingUserInputCancellations === true
506 ? yield* guardUserInputCancellations(input.events)
507 : input.events,
508 );
509 const storedEvents = yield* eventStore.append({
510 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
511 events: normalized,
512 });
513 const outcomes = yield* applyStoredEvents(storedEvents);
514 yield* effectOutbox.enqueue(input.effects ?? []);
515 return { committed: true as const, storedEvents, outcomes };
516 }),
517 (result) =>
518 Effect.gen(function* () {
519 if (!result.committed) return;
520 if (input.effects !== undefined && input.effects.length > 0) {
521 yield* effectOutbox.notifyAvailable(input.effects.length);
522 }
523 yield* publishStoredEvents(result.storedEvents, result.outcomes);
524 }),
525 );
526 },
527 );
528
529 const writeIfProviderThreadOwnerEffect = Effect.fn(
530 "orchestrationV2.EventSink.writeIfProviderThreadOwner",
531 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadOwner"]>[0]) {
532 yield* Effect.annotateCurrentSpan({
533 "orchestration_v2.command_id": input.commandId ?? null,
534 "orchestration_v2.event_count": input.events.length,
535 "orchestration_v2.provider_thread_id": input.providerThreadId,
536 "orchestration_v2.run_id": input.runId,
537 "orchestration_v2.active_attempt_id": input.activeAttemptId,
538 "orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal,
539 });
540
541 return yield* commitThenPublish(
542 Effect.gen(function* () {
543 const rows = yield* sql<{
544 readonly active_attempt_id: string | null;
545 readonly last_run_ordinal: number | null;
546 }>`
547 SELECT
548 json_extract(r.payload_json, '$.activeAttemptId') AS active_attempt_id,
549 p.last_run_ordinal
550 FROM orchestration_v2_projection_provider_threads p
551 JOIN orchestration_v2_projection_runs r
552 ON r.run_id = ${input.runId}
553 AND r.thread_id = p.thread_id
554 WHERE p.provider_thread_id = ${input.providerThreadId}
555 LIMIT 1
556 `;
557 const current = rows[0];
558 if (
559 current === undefined ||
560 current.active_attempt_id !== input.activeAttemptId ||
561 current.last_run_ordinal !== input.expectedLastRunOrdinal
562 ) {
563 return {
564 committed: false as const,
565 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
566 };
567 }
568
569 const normalized = yield* normalizeEvents(
570 input.guardPendingUserInputCancellations === true
571 ? yield* guardUserInputCancellations(input.events)
572 : input.events,
573 );
574 const storedEvents = yield* eventStore.append({
575 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
576 events: normalized,
577 });
578 const outcomes = yield* applyStoredEvents(storedEvents);
579 return { committed: true as const, storedEvents, outcomes };
580 }),
581 (result) =>
582 result.committed
583 ? publishStoredEvents(result.storedEvents, result.outcomes)
584 : Effect.void,
585 );
586 });
587
588 const writeIfProviderThreadUnchangedEffect = Effect.fn(
589 "orchestrationV2.EventSink.writeIfProviderThreadUnchanged",
590 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadUnchanged"]>[0]) {
591 yield* Effect.annotateCurrentSpan({
592 "orchestration_v2.event_count": input.events.length,
593 "orchestration_v2.provider_thread_id": input.expected.id,
594 });
595 const expectedJson = yield* ProjectionStore.encodeProviderThreadPayload(input.expected);
596
597 return yield* commitThenPublish(
598 Effect.gen(function* () {
599 const rows = yield* sql<{ readonly payload_json: string }>`
600 SELECT payload_json
601 FROM orchestration_v2_projection_provider_threads
602 WHERE provider_thread_id = ${input.expected.id}
603 LIMIT 1
604 `;
605 if (rows[0]?.payload_json !== expectedJson) {
606 return {
607 committed: false as const,
608 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
609 };
610 }
611
612 const normalized = yield* normalizeEvents(input.events);
613 const storedEvents = yield* eventStore.append({ events: normalized });
614 const outcomes = yield* applyStoredEvents(storedEvents);
615 return { committed: true as const, storedEvents, outcomes };
616 }),
617 (result) =>
618 result.committed
619 ? publishStoredEvents(result.storedEvents, result.outcomes)
620 : Effect.void,
621 );
622 });
623
624 const existingCommandResult =
625 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
626 Effect.fnUntraced(function* (commandId: CommandId) {
627 const existing = yield* commandReceipts.getByCommandId(commandId);
628 if (Option.isNone(existing)) {
629 return yield* Effect.die(
630 new Error(`Command receipt ${commandId} disappeared during its transaction.`),
631 );
632 }
633 const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
634 Stream.runCollect,
635 Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
636 );
637 return { receipt: existing.value, storedEvents };
638 });
639
640 const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
641 input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
642 ) {
643 const result = yield* commitThenPublish(
644 Effect.gen(function* () {
645 const reserved = yield* commandReceipts.insertIfAbsent({
646 commandId: input.commandId,
647 threadId: input.threadId,
648 commandType: input.commandType,
649 acceptedAt: input.acceptedAt,
650 resultSequence: 0,
651 status: "accepted",
652 error: null,
653 });
654 if (!reserved) {
655 const existing = yield* existingCommandResult(input.commandId);
656 return { ...existing, committed: false as const, cancelledEffectIds: [] };
657 }
658
659 const normalized = yield* normalizeEvents(input.events);
660 const storedEvents = yield* eventStore.append({
661 commandId: input.commandId,
662 events: normalized,
663 });
664 const sequence = storedEvents.at(-1)?.sequence;
665 if (sequence === undefined) {
666 return yield* Effect.die(
667 new Error(`Command ${input.commandId} produced no orchestration events.`),
668 );
669 }
670 const outcomes = yield* applyStoredEvents(storedEvents);
671 yield* effectOutbox.enqueue(input.effects);
672 const receipt: CommandReceiptStore.CommandReceiptV2 = {
673 commandId: input.commandId,
674 threadId: input.threadId,
675 commandType: input.commandType,
676 acceptedAt: input.acceptedAt,
677 resultSequence: sequence,
678 status: "accepted",
679 error: null,
680 };
681 yield* commandReceipts.upsert(receipt);
682 const cancelledEffectIds =
683 input.cancelUnsettledEffects === undefined
684 ? []
685 : yield* effectOutbox.cancelUnsettled({
686 threadId: input.threadId,
687 ...input.cancelUnsettledEffects,
688 });
689 return { receipt, storedEvents, outcomes, committed: true as const, cancelledEffectIds };
690 }),
691 (result) =>
692 Effect.gen(function* () {
693 yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
694 if (result.committed && input.effects.length > 0) {
695 yield* effectOutbox.notifyAvailable(input.effects.length);
696 }
697 if (result.committed) yield* publishStoredEvents(result.storedEvents, result.outcomes);
698 }),
699 );
700 return {
701 receipt: result.receipt,
702 storedEvents: result.storedEvents,
703 committed: result.committed,
704 cancelledEffectCount: result.cancelledEffectIds.length,
705 };
706 });
707
708 const commitRejectedCommandEffect = Effect.fn(
709 "orchestrationV2.EventSink.commitRejectedCommand",
710 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
711 return yield* sql.withTransaction(
712 Effect.gen(function* () {
713 const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
714 const receipt: CommandReceiptStore.CommandReceiptV2 = {
715 commandId: input.commandId,
716 threadId: input.threadId,
717 commandType: input.commandType,
718 acceptedAt: input.rejectedAt,
719 resultSequence: sequence,
720 status: "rejected",
721 error: input.error,
722 };
723 const inserted = yield* commandReceipts.insertIfAbsent(receipt);
724 if (inserted) {
725 return receipt;
726 }
727 const existing = yield* commandReceipts.getByCommandId(input.commandId);
728 return Option.getOrElse(existing, () => receipt);
729 }),
730 );
731 });
732
733 const existingProjectReceipt = (commandId: CommandId) =>
734 commandReceipts.getProjectByCommandId(commandId).pipe(
735 Effect.flatMap(
736 Option.match({
737 onNone: () =>
738 Effect.fail(`Command ${commandId} was already used by a thread command.` as const),
739 onSome: Effect.succeed,
740 }),
741 ),
742 );
743
744 const commitProjectCommandEffect = Effect.fn("orchestrationV2.EventSink.commitProjectCommand")(
745 function* (input: Parameters<EventSinkV2Shape["commitProjectCommand"]>[0]) {
746 const result = yield* commitThenPublish(
747 Effect.gen(function* () {
748 const reserved: CommandReceiptStore.ProjectCommandReceiptV2 = {
749 commandId: input.commandId,
750 projectId: input.projectId,
751 commandType: input.commandType,
752 acceptedAt: input.acceptedAt,
753 resultSequence: 0,
754 status: "accepted",
755 error: null,
756 };
757 if (!(yield* commandReceipts.insertIfAbsent(reserved))) {
758 return { receipt: yield* existingProjectReceipt(input.commandId), event: undefined };
759 }
760 const event = yield* eventStore.appendProjectEvent(input.event);
761 yield* projectStore.apply(event);
762 const receipt = { ...reserved, resultSequence: event.sequence };
763 yield* commandReceipts.upsert(receipt);
764 return { receipt, event };
765 }),
766 (result) =>
767 result.event === undefined ? Effect.void : eventStore.publishCommitted([result.event]),
768 );
769 return { receipt: result.receipt, committed: result.event !== undefined };
770 },
771 );
772
773 const commitRejectedProjectCommandEffect = Effect.fn(
774 "orchestrationV2.EventSink.commitRejectedProjectCommand",
775 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedProjectCommand"]>[0]) {
776 return yield* sql.withTransaction(
777 Effect.gen(function* () {
778 const receipt: CommandReceiptStore.ProjectCommandReceiptV2 = {
779 commandId: input.commandId,
780 projectId: input.projectId,
781 commandType: input.commandType,
782 acceptedAt: input.rejectedAt,
783 resultSequence: yield* eventStore.latestApplicationSequence,
784 status: "rejected",
785 error: input.error,
786 };
787 return (yield* commandReceipts.insertIfAbsent(receipt))
788 ? receipt
789 : yield* existingProjectReceipt(input.commandId);
790 }),
791 );
792 });
793
794 const catchUp = (input: {
795 readonly afterSequence: number;
796 readonly throughSequence: number;
797 readonly threadId?: ThreadId;
798 readonly eventType?: OrchestrationV2DomainEvent["type"];
799 }): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
800 const pageSize = 256;
801 const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
802 Stream.unwrap(
803 eventStore
804 .read({
805 afterSequence,
806 throughSequence: input.throughSequence,
807 ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
808 ...(input.eventType === undefined ? {} : { eventType: input.eventType }),
809 limit: pageSize,
810 })
811 .pipe(
812 Stream.runCollect,
813 Effect.map((chunk) => Array.from(chunk)),
814 Effect.map((events) => {
815 if (events.length === 0) {
816 return Stream.empty;
817 }
818 const current = Stream.fromIterable(events);
819 const last = events.at(-1)?.sequence ?? input.throughSequence;
820 return events.length < pageSize || last >= input.throughSequence
821 ? current
822 : Stream.concat(current, loop(last));
823 }),
824 ),
825 );
826 return loop(input.afterSequence);
827 };
828
829 const stream = (input?: Parameters<EventSinkV2Shape["stream"]>[0]) => {
830 const afterSequence = input?.afterSequence ?? 0;
831 const matches = (stored: OrchestrationV2StoredEvent) =>
832 (input?.threadId === undefined || stored.event.threadId === input.threadId) &&
833 (input?.eventType === undefined || stored.event.type === input.eventType);
834 const replay = (throughSequence: number) =>
835 catchUp({
836 afterSequence,
837 throughSequence,
838 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
839 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
840 }).pipe(Stream.filter(matches));
841 return Stream.unwrap(
842 Effect.gen(function* () {
843 let pubsub = liveEvents;
844 if (input?.eventType !== undefined) {
845 const existing = liveEventsByType.get(input.eventType);
846 if (existing !== undefined) {
847 pubsub = existing;
848 } else {
849 const created = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
850 pubsub = liveEventsByType.get(input.eventType) ?? created;
851 liveEventsByType.set(input.eventType, pubsub);
852 }
853 }
854 if (input?.bounded === true) {
855 return replayAndBufferProjectedLiveEvents({
856 subscribe: PubSub.subscribe(pubsub),
857 latestSequence: eventStore.latestSequence(),
858 afterSequence,
859 filter: matches,
860 replay,
861 project: (stored) => ({ ...stored, event: projectDomainEventForWire(stored.event) }),
862 });
863 }
864 const subscription = yield* PubSub.subscribe(pubsub);
865 const highWater = yield* eventStore.latestSequence();
866 const live = Stream.fromSubscription(subscription).pipe(
867 Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)),
868 Stream.filter(matches),
869 );
870 return Stream.concat(replay(highWater), live);
871 }),
872 );
873 };
874
875 return EventSinkV2.of({
876 write: (input) =>
877 writeEffect({ ...input, effects: [] }).pipe(
878 Effect.mapError(
879 (cause) =>
880 new EventSinkWriteError({
881 eventCount: input.events.length,
882 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
883 cause,
884 }),
885 ),
886 ),
887 writeWithEffects: (input) =>
888 writeEffect(input).pipe(
889 Effect.mapError(
890 (cause) =>
891 new EventSinkWriteError({
892 eventCount: input.events.length,
893 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
894 cause,
895 }),
896 ),
897 ),
898 writeIfRunCurrent: (input) =>
899 writeIfRunCurrentEffect(input).pipe(
900 Effect.mapError(
901 (cause) =>
902 new EventSinkWriteError({
903 eventCount: input.events.length,
904 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
905 cause,
906 }),
907 ),
908 ),
909 writeIfProviderThreadOwner: (input) =>
910 writeIfProviderThreadOwnerEffect(input).pipe(
911 Effect.mapError(
912 (cause) =>
913 new EventSinkWriteError({
914 eventCount: input.events.length,
915 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
916 cause,
917 }),
918 ),
919 ),
920 writeIfProviderThreadUnchanged: (input) =>
921 writeIfProviderThreadUnchangedEffect(input).pipe(
922 Effect.mapError(
923 (cause) => new EventSinkWriteError({ eventCount: input.events.length, cause }),
924 ),
925 ),
926 commitCommand: (input) =>
927 commitCommandEffect(input).pipe(
928 Effect.mapError(
929 (cause) =>
930 new EventSinkWriteError({
931 commandId: input.commandId,
932 eventCount: input.events.length,
933 cause,
934 }),
935 ),
936 ),
937 commitRejectedCommand: (input) =>
938 commitRejectedCommandEffect(input).pipe(
939 Effect.mapError(
940 (cause) =>
941 new EventSinkWriteError({
942 commandId: input.commandId,
943 eventCount: 0,
944 cause,
945 }),
946 ),
947 ),
948 commitProjectCommand: (input) =>
949 commitProjectCommandEffect(input).pipe(
950 Effect.mapError(
951 (cause) =>
952 new EventSinkWriteError({ commandId: input.commandId, eventCount: 1, cause }),
953 ),
954 ),
955 commitRejectedProjectCommand: (input) =>
956 commitRejectedProjectCommandEffect(input).pipe(
957 Effect.mapError(
958 (cause) =>
959 new EventSinkWriteError({ commandId: input.commandId, eventCount: 0, cause }),
960 ),
961 ),
962 stream: (input) =>
963 stream(input).pipe(
964 Stream.mapError(
965 (cause) =>
966 new EventSinkStreamError({
967 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
968 ...(input?.afterSequence === undefined
969 ? {}
970 : { afterSequence: input.afterSequence }),
971 cause,
972 }),
973 ),
974 ),
975 latestSequence: (input) =>
976 eventStore.latestSequence(input).pipe(
977 Effect.mapError(
978 (cause) =>
979 new EventSinkStreamError({
980 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
981 cause,
982 }),
983 ),
984 ),
985 readByCommandId: (input) =>
986 eventStore.readByCommandId(input).pipe(
987 Stream.mapError(
988 (cause) =>
989 new EventSinkStreamError({
990 cause,
991 }),
992 ),
993 ),
994 } satisfies EventSinkV2Shape);
995 }),
996);
997
998/**
999 * Keeping the outbox instance shared with the worker is important because enqueue notifications
1000 * are in-memory wakeups backed by the durable SQL queue.
1001 */
1002export const layerFromStores = layerBase;
1003
1004export const layer: Layer.Layer<
1005 EventSinkV2,
1006 never,
1007 EventStore.EventStoreV2 | ProjectionStore.ProjectionStoreV2 | SqlClient.SqlClient
1008> = layerBase.pipe(
1009 Layer.provide(
1010 Layer.mergeAll(
1011 CommandReceiptStore.layer,
1012 EffectOutbox.layer,
1013 ProjectStore.layer,
1014 TurnItemPositionStore.layer,
1015 ),
1016 ),
1017);