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

EventSink.ts

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