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

EventSink.ts

771 lines28.1 KB

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