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

EventSink.ts

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