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

EventSink.ts

1,019 lines39.9 KB

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