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