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