Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationV2Run,
4 OrchestrationV2DomainEvent,
5 OrchestrationV2StoredEvent,
6 ProviderThreadId,
7 RunAttemptId,
8 RunId,
9 RuntimeRequestId,
10 NodeId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as PubSub from "effect/PubSub";
19import * as Schema from "effect/Schema";
20import * as Stream from "effect/Stream";
21import * as SqlClient from "effect/unstable/sql/SqlClient";
22
23import { replayAndBufferProjectedLiveEvents } from "../orchestration/LiveStreamBudget.ts";
24import { projectDomainEventForWire } from "./WireProjection.ts";
25
26import {
27 CommandReceiptStoreV2,
28 type CommandReceiptV2,
29 layer as commandReceiptStoreLayer,
30} from "./CommandReceiptStore.ts";
31import {
32 EffectOutboxV2,
33 type OrchestrationEffectRequestV2,
34 type PendingOrchestrationEffectV2,
35 layer as effectOutboxLayer,
36} from "./EffectOutbox.ts";
37import { EventStoreV2 } from "./EventStore.ts";
38import {
39 ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
40 ProjectionStoreV2,
41} from "./ProjectionStore.ts";
42import {
43 TurnItemPositionStoreV2,
44 layer as turnItemPositionStoreLayer,
45} from "./TurnItemPositionStore.ts";
46
47/**
48 * ERRORS
49 */
50export class EventSinkWriteError extends Schema.TaggedError<EventSinkWriteError>()(
51 "EventSinkWriteError",
52 {
53 eventCount: Schema.Number,
54 commandId: Schema.optional(CommandId),
55 cause: Schema.optional(Schema.Defect()),
56 },
57) {
58 override get message(): string {
59 return `Failed to write ${this.eventCount} orchestration V2 event(s).`;
60 }
61}
62
63export class EventSinkStreamError extends Schema.TaggedError<EventSinkStreamError>()(
64 "EventSinkStreamError",
65 {
66 threadId: Schema.optional(ThreadId),
67 afterSequence: Schema.optional(Schema.Number),
68 cause: Schema.optional(Schema.Defect()),
69 },
70) {
71 override get message(): string {
72 return this.threadId === undefined
73 ? "Failed to stream orchestration V2 events."
74 : `Failed to stream orchestration V2 events for thread ${this.threadId}.`;
75 }
76}
77
78export const EventSinkV2Error = Schema.Union([EventSinkWriteError, EventSinkStreamError]);
79export type EventSinkV2Error = typeof EventSinkV2Error.Type;
80
81/**
82 * SERVICE DEFINITION
83 */
84export interface EventSinkV2Shape {
85 readonly write: (input: {
86 readonly guardPendingUserInputCancellations?: boolean;
87 readonly commandId?: CommandId;
88 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
89 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
90 readonly writeWithEffects: (input: {
91 readonly guardPendingUserInputCancellations?: boolean;
92 readonly commandId?: CommandId;
93 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
94 readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
95 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
96 readonly writeIfRunCurrent: (input: {
97 readonly guardPendingUserInputCancellations?: boolean;
98 readonly commandId?: CommandId;
99 readonly threadId: ThreadId;
100 readonly runId: RunId;
101 readonly activeAttemptId: RunAttemptId;
102 readonly expectedStatus: OrchestrationV2Run["status"];
103 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
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 readonly commitCommand: (input: {
133 readonly commandId: CommandId;
134 readonly threadId: ThreadId;
135 readonly commandType: string;
136 readonly acceptedAt: DateTime.Utc;
137 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
138 readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
139 readonly cancelUnsettledEffects?: {
140 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
141 readonly reason: string;
142 };
143 }) => Effect.Effect<
144 {
145 readonly receipt: CommandReceiptV2;
146 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
147 readonly committed: boolean;
148 readonly cancelledEffectCount: number;
149 },
150 EventSinkV2Error
151 >;
152 readonly commitRejectedCommand: (input: {
153 readonly commandId: CommandId;
154 readonly threadId: ThreadId;
155 readonly commandType: string;
156 readonly rejectedAt: DateTime.Utc;
157 readonly error: string;
158 }) => Effect.Effect<CommandReceiptV2, EventSinkV2Error>;
159 readonly stream: (input?: {
160 readonly threadId?: ThreadId;
161 readonly afterSequence?: number;
162 /** Bound RPC subscribers; internal workers must not drop their subscription under load. */
163 readonly bounded?: boolean;
164 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
165 readonly latestSequence: (input?: {
166 readonly threadId?: ThreadId;
167 }) => Effect.Effect<number, EventSinkV2Error>;
168 readonly readByCommandId: (input: {
169 readonly commandId: CommandId;
170 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
171}
172
173export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
174 "t3/orchestration-v2/EventSink/EventSinkV2",
175) {}
176
177/**
178 * IMPLEMENTATIONS
179 */
180const baseLayer: Layer.Layer<
181 EventSinkV2,
182 never,
183 | CommandReceiptStoreV2
184 | EffectOutboxV2
185 | EventStoreV2
186 | ProjectionStoreV2
187 | SqlClient.SqlClient
188 | TurnItemPositionStoreV2
189> = Layer.effect(
190 EventSinkV2,
191 Effect.gen(function* () {
192 const sql = yield* SqlClient.SqlClient;
193 const commandReceipts = yield* CommandReceiptStoreV2;
194 const effectOutbox = yield* EffectOutboxV2;
195 const eventStore = yield* EventStoreV2;
196 const projectionStore = yield* ProjectionStoreV2;
197 const turnItemPositions = yield* TurnItemPositionStoreV2;
198 const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
199
200 // A user can answer after terminal normalization reads the pending request.
201 // Recheck inside the write transaction so stale cleanup cannot erase answers.
202 const guardUserInputCancellations = (events: ReadonlyArray<OrchestrationV2DomainEvent>) =>
203 Effect.gen(function* () {
204 const staleRequests = new Set<RuntimeRequestId>();
205 const staleNodes = new Set<NodeId>();
206 for (const event of events) {
207 if (
208 event.type !== "runtime-request.updated" ||
209 event.payload.kind !== "user_input" ||
210 event.payload.status !== "cancelled"
211 )
212 continue;
213 const current = yield* projectionStore.getRuntimeRequest(
214 event.threadId,
215 event.payload.id,
216 );
217 if (
218 current?.status !== "pending" ||
219 current.kind !== "user_input" ||
220 current.providerTurnId !== event.payload.providerTurnId ||
221 current.responseCapability.type === "message"
222 ) {
223 staleRequests.add(event.payload.id);
224 staleNodes.add(event.payload.nodeId);
225 }
226 }
227 return events.filter((event) => {
228 switch (event.type) {
229 case "runtime-request.updated":
230 return event.payload.status !== "cancelled" || !staleRequests.has(event.payload.id);
231 case "node.updated":
232 return event.payload.status !== "cancelled" || !staleNodes.has(event.payload.id);
233 case "turn-item.updated":
234 return (
235 event.payload.type !== "user_input_request" ||
236 event.payload.status !== "cancelled" ||
237 !staleRequests.has(event.payload.requestId)
238 );
239 default:
240 return true;
241 }
242 });
243 });
244
245 const normalizeEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) => {
246 const runOrdinals = new Map(
247 events.flatMap((event) =>
248 event.type === "run.created" || event.type === "run.updated"
249 ? [[event.payload.id, event.payload.ordinal] as const]
250 : [],
251 ),
252 );
253 return Effect.forEach(
254 events,
255 (event): Effect.Effect<OrchestrationV2DomainEvent, unknown> =>
256 event.type === "turn-item.updated"
257 ? turnItemPositions
258 .normalize(
259 event.payload,
260 event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
261 )
262 .pipe(Effect.map((payload) => ({ ...event, payload })))
263 : Effect.succeed(event),
264 { concurrency: 1 },
265 );
266 };
267
268 const applyStoredEvents = (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) =>
269 Effect.gen(function* () {
270 yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
271 concurrency: 1,
272 });
273 const sequence = storedEvents.at(-1)?.sequence;
274 if (sequence !== undefined) {
275 const now = DateTime.formatIso(yield* DateTime.now);
276 yield* sql`
277 INSERT INTO orchestration_v2_projection_metadata (
278 projection_name,
279 schema_version,
280 last_sequence,
281 updated_at
282 )
283 VALUES (
284 'thread-projections',
285 ${ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
286 ${sequence},
287 ${now}
288 )
289 ON CONFLICT(projection_name)
290 DO UPDATE SET
291 schema_version = excluded.schema_version,
292 last_sequence = excluded.last_sequence,
293 updated_at = excluded.updated_at
294 `;
295 }
296 });
297
298 const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (
299 input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],
300 ) {
301 yield* Effect.annotateCurrentSpan({
302 "orchestration_v2.command_id": input.commandId ?? null,
303 "orchestration_v2.event_count": input.events.length,
304 "orchestration_v2.thread_id": input.events[0]?.threadId ?? null,
305 });
306
307 const storedEvents = yield* sql.withTransaction(
308 Effect.gen(function* () {
309 const normalized = yield* normalizeEvents(
310 input.guardPendingUserInputCancellations === true
311 ? yield* guardUserInputCancellations(input.events)
312 : input.events,
313 );
314 const committed = yield* eventStore.append({
315 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
316 events: normalized,
317 });
318 yield* applyStoredEvents(committed);
319 yield* effectOutbox.enqueue(input.effects);
320 return committed;
321 }),
322 );
323 if (input.effects.length > 0) {
324 yield* effectOutbox.notifyAvailable(input.effects.length);
325 }
326 yield* eventStore.publishCommitted(storedEvents);
327 yield* PubSub.publishAll(liveEvents, storedEvents);
328 return storedEvents;
329 });
330
331 const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")(
332 function* (input: Parameters<EventSinkV2Shape["writeIfRunCurrent"]>[0]) {
333 yield* Effect.annotateCurrentSpan({
334 "orchestration_v2.command_id": input.commandId ?? null,
335 "orchestration_v2.event_count": input.events.length,
336 "orchestration_v2.run_id": input.runId,
337 "orchestration_v2.thread_id": input.threadId,
338 });
339
340 const result = yield* sql.withTransaction(
341 Effect.gen(function* () {
342 const rows = yield* sql<{
343 readonly status: string;
344 readonly active_attempt_id: string | null;
345 }>`
346 SELECT
347 status,
348 json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id
349 FROM orchestration_v2_projection_runs
350 WHERE run_id = ${input.runId}
351 AND thread_id = ${input.threadId}
352 LIMIT 1
353 `;
354 const current = rows[0];
355 if (
356 current === undefined ||
357 current.status !== input.expectedStatus ||
358 current.active_attempt_id !== input.activeAttemptId
359 ) {
360 return {
361 committed: false as const,
362 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
363 };
364 }
365
366 const normalized = yield* normalizeEvents(
367 input.guardPendingUserInputCancellations === true
368 ? yield* guardUserInputCancellations(input.events)
369 : input.events,
370 );
371 const storedEvents = yield* eventStore.append({
372 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
373 events: normalized,
374 });
375 yield* applyStoredEvents(storedEvents);
376 return { committed: true as const, storedEvents };
377 }),
378 );
379 if (result.committed) {
380 yield* eventStore.publishCommitted(result.storedEvents);
381 yield* PubSub.publishAll(liveEvents, result.storedEvents);
382 }
383 return result;
384 },
385 );
386
387 const writeIfProviderThreadOwnerEffect = Effect.fn(
388 "orchestrationV2.EventSink.writeIfProviderThreadOwner",
389 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadOwner"]>[0]) {
390 yield* Effect.annotateCurrentSpan({
391 "orchestration_v2.command_id": input.commandId ?? null,
392 "orchestration_v2.event_count": input.events.length,
393 "orchestration_v2.provider_thread_id": input.providerThreadId,
394 "orchestration_v2.run_id": input.runId,
395 "orchestration_v2.active_attempt_id": input.activeAttemptId,
396 "orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal,
397 });
398
399 const result = yield* sql.withTransaction(
400 Effect.gen(function* () {
401 const rows = yield* sql<{
402 readonly active_attempt_id: string | null;
403 readonly last_run_ordinal: number | null;
404 }>`
405 SELECT
406 json_extract(r.payload_json, '$.activeAttemptId') AS active_attempt_id,
407 p.last_run_ordinal
408 FROM orchestration_v2_projection_provider_threads p
409 JOIN orchestration_v2_projection_runs r
410 ON r.run_id = ${input.runId}
411 AND r.thread_id = p.thread_id
412 WHERE p.provider_thread_id = ${input.providerThreadId}
413 LIMIT 1
414 `;
415 const current = rows[0];
416 if (
417 current === undefined ||
418 current.active_attempt_id !== input.activeAttemptId ||
419 current.last_run_ordinal !== input.expectedLastRunOrdinal
420 ) {
421 return {
422 committed: false as const,
423 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
424 };
425 }
426
427 const normalized = yield* normalizeEvents(
428 input.guardPendingUserInputCancellations === true
429 ? yield* guardUserInputCancellations(input.events)
430 : input.events,
431 );
432 const storedEvents = yield* eventStore.append({
433 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
434 events: normalized,
435 });
436 yield* applyStoredEvents(storedEvents);
437 return { committed: true as const, storedEvents };
438 }),
439 );
440 if (result.committed) {
441 yield* eventStore.publishCommitted(result.storedEvents);
442 yield* PubSub.publishAll(liveEvents, result.storedEvents);
443 }
444 return result;
445 });
446
447 const existingCommandResult = (commandId: CommandId) =>
448 Effect.gen(function* () {
449 const existing = yield* commandReceipts.getByCommandId(commandId);
450 if (Option.isNone(existing)) {
451 return yield* Effect.die(
452 new Error(`Command receipt ${commandId} disappeared during its transaction.`),
453 );
454 }
455 const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
456 Stream.runCollect,
457 Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
458 );
459 return { receipt: existing.value, storedEvents };
460 });
461
462 const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
463 input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
464 ) {
465 const result = yield* sql.withTransaction(
466 Effect.gen(function* () {
467 const reserved = yield* commandReceipts.insertIfAbsent({
468 commandId: input.commandId,
469 threadId: input.threadId,
470 commandType: input.commandType,
471 acceptedAt: input.acceptedAt,
472 resultSequence: 0,
473 status: "accepted",
474 error: null,
475 });
476 if (!reserved) {
477 const existing = yield* existingCommandResult(input.commandId);
478 return { ...existing, committed: false as const, cancelledEffectIds: [] };
479 }
480
481 const normalized = yield* normalizeEvents(input.events);
482 const storedEvents = yield* eventStore.append({
483 commandId: input.commandId,
484 events: normalized,
485 });
486 const sequence = storedEvents.at(-1)?.sequence;
487 if (sequence === undefined) {
488 return yield* Effect.die(
489 new Error(`Command ${input.commandId} produced no orchestration events.`),
490 );
491 }
492 yield* applyStoredEvents(storedEvents);
493 yield* effectOutbox.enqueue(input.effects);
494 const receipt: CommandReceiptV2 = {
495 commandId: input.commandId,
496 threadId: input.threadId,
497 commandType: input.commandType,
498 acceptedAt: input.acceptedAt,
499 resultSequence: sequence,
500 status: "accepted",
501 error: null,
502 };
503 yield* commandReceipts.upsert(receipt);
504 const cancelledEffectIds =
505 input.cancelUnsettledEffects === undefined
506 ? []
507 : yield* effectOutbox.cancelUnsettled({
508 threadId: input.threadId,
509 ...input.cancelUnsettledEffects,
510 });
511 return { receipt, storedEvents, committed: true as const, cancelledEffectIds };
512 }),
513 );
514 yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
515 if (result.committed && input.effects.length > 0) {
516 yield* effectOutbox.notifyAvailable(input.effects.length);
517 }
518 if (result.committed) {
519 yield* eventStore.publishCommitted(result.storedEvents);
520 yield* PubSub.publishAll(liveEvents, result.storedEvents);
521 }
522 return {
523 receipt: result.receipt,
524 storedEvents: result.storedEvents,
525 committed: result.committed,
526 cancelledEffectCount: result.cancelledEffectIds.length,
527 };
528 });
529
530 const commitRejectedCommandEffect = Effect.fn(
531 "orchestrationV2.EventSink.commitRejectedCommand",
532 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
533 return yield* sql.withTransaction(
534 Effect.gen(function* () {
535 const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
536 const receipt: CommandReceiptV2 = {
537 commandId: input.commandId,
538 threadId: input.threadId,
539 commandType: input.commandType,
540 acceptedAt: input.rejectedAt,
541 resultSequence: sequence,
542 status: "rejected",
543 error: input.error,
544 };
545 const inserted = yield* commandReceipts.insertIfAbsent(receipt);
546 if (inserted) {
547 return receipt;
548 }
549 const existing = yield* commandReceipts.getByCommandId(input.commandId);
550 return Option.getOrElse(existing, () => receipt);
551 }),
552 );
553 });
554
555 const catchUp = (input: {
556 readonly afterSequence: number;
557 readonly throughSequence: number;
558 readonly threadId?: ThreadId;
559 }): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
560 const pageSize = 256;
561 const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
562 Stream.unwrap(
563 eventStore
564 .read({
565 afterSequence,
566 throughSequence: input.throughSequence,
567 ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
568 limit: pageSize,
569 })
570 .pipe(
571 Stream.runCollect,
572 Effect.map((chunk) => Array.from(chunk)),
573 Effect.map((events) => {
574 if (events.length === 0) {
575 return Stream.empty;
576 }
577 const current = Stream.fromIterable(events);
578 const last = events.at(-1)?.sequence ?? input.throughSequence;
579 return events.length < pageSize || last >= input.throughSequence
580 ? current
581 : Stream.concat(current, loop(last));
582 }),
583 ),
584 );
585 return loop(input.afterSequence);
586 };
587
588 const stream = (input?: Parameters<EventSinkV2Shape["stream"]>[0]) => {
589 const afterSequence = input?.afterSequence ?? 0;
590 const matchesThread = (stored: OrchestrationV2StoredEvent) =>
591 input?.threadId === undefined || stored.event.threadId === input.threadId;
592 const replay = (throughSequence: number) =>
593 catchUp({
594 afterSequence,
595 throughSequence,
596 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
597 });
598 if (input?.bounded === true) {
599 return replayAndBufferProjectedLiveEvents({
600 subscribe: PubSub.subscribe(liveEvents),
601 latestSequence: eventStore.latestSequence(),
602 afterSequence,
603 filter: matchesThread,
604 replay,
605 project: (stored) => ({ ...stored, event: projectDomainEventForWire(stored.event) }),
606 });
607 }
608 return Stream.unwrap(
609 Effect.gen(function* () {
610 const subscription = yield* PubSub.subscribe(liveEvents);
611 const highWater = yield* eventStore.latestSequence();
612 const live = Stream.fromSubscription(subscription).pipe(
613 Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)),
614 Stream.filter(matchesThread),
615 );
616 return Stream.concat(replay(highWater), live);
617 }),
618 );
619 };
620
621 return EventSinkV2.of({
622 write: (input) =>
623 writeEffect({ ...input, effects: [] }).pipe(
624 Effect.mapError(
625 (cause) =>
626 new EventSinkWriteError({
627 eventCount: input.events.length,
628 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
629 cause,
630 }),
631 ),
632 ),
633 writeWithEffects: (input) =>
634 writeEffect(input).pipe(
635 Effect.mapError(
636 (cause) =>
637 new EventSinkWriteError({
638 eventCount: input.events.length,
639 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
640 cause,
641 }),
642 ),
643 ),
644 writeIfRunCurrent: (input) =>
645 writeIfRunCurrentEffect(input).pipe(
646 Effect.mapError(
647 (cause) =>
648 new EventSinkWriteError({
649 eventCount: input.events.length,
650 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
651 cause,
652 }),
653 ),
654 ),
655 writeIfProviderThreadOwner: (input) =>
656 writeIfProviderThreadOwnerEffect(input).pipe(
657 Effect.mapError(
658 (cause) =>
659 new EventSinkWriteError({
660 eventCount: input.events.length,
661 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
662 cause,
663 }),
664 ),
665 ),
666 commitCommand: (input) =>
667 commitCommandEffect(input).pipe(
668 Effect.mapError(
669 (cause) =>
670 new EventSinkWriteError({
671 commandId: input.commandId,
672 eventCount: input.events.length,
673 cause,
674 }),
675 ),
676 ),
677 commitRejectedCommand: (input) =>
678 commitRejectedCommandEffect(input).pipe(
679 Effect.mapError(
680 (cause) =>
681 new EventSinkWriteError({
682 commandId: input.commandId,
683 eventCount: 0,
684 cause,
685 }),
686 ),
687 ),
688 stream: (input) =>
689 stream(input).pipe(
690 Stream.mapError(
691 (cause) =>
692 new EventSinkStreamError({
693 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
694 ...(input?.afterSequence === undefined
695 ? {}
696 : { afterSequence: input.afterSequence }),
697 cause,
698 }),
699 ),
700 ),
701 latestSequence: (input) =>
702 eventStore.latestSequence(input).pipe(
703 Effect.mapError(
704 (cause) =>
705 new EventSinkStreamError({
706 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
707 cause,
708 }),
709 ),
710 ),
711 readByCommandId: (input) =>
712 eventStore.readByCommandId(input).pipe(
713 Stream.mapError(
714 (cause) =>
715 new EventSinkStreamError({
716 cause,
717 }),
718 ),
719 ),
720 } satisfies EventSinkV2Shape);
721 }),
722);
723
724/**
725 * Event sink layer for application compositions that already own the
726 * persistence services. Keeping the outbox instance shared with the worker is
727 * important because enqueue notifications are in-memory wakeups backed by the
728 * durable SQL queue.
729 */
730export const layerFromStores = baseLayer;
731
732export const layer: Layer.Layer<
733 EventSinkV2,
734 never,
735 EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient
736> = baseLayer.pipe(
737 Layer.provide(
738 Layer.mergeAll(commandReceiptStoreLayer, effectOutboxLayer, turnItemPositionStoreLayer),
739 ),
740);