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

EventSink.ts

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