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

EventSink.ts

936 lines35.6 KB

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