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