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

EventSink.ts

1,022 lines39.7 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 /**
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>;
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 // 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/**
1004 * Keeping the outbox instance shared with the worker is important because enqueue notifications
1005 * are in-memory wakeups backed by the durable SQL queue.
1006 */
1007export const layerFromStores = layerBase;
1008​
1009export const layer: Layer.Layer<
1010 EventSinkV2,
1011 never,
1012 EventStore.EventStoreV2 | ProjectionStore.ProjectionStoreV2 | SqlClient.SqlClient
1013> = layerBase.pipe(
1014 Layer.provide(
1015 Layer.mergeAll(
1016 CommandReceiptStore.layer,
1017 EffectOutbox.layer,
1018 ProjectStore.layer,
1019 TurnItemPositionStore.layer,
1020 ),
1021 ),