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

EventSink.ts

891 lines33.6 KB

1import {
2 CommandId,
3 type OrchestrationV2Run,
4 OrchestrationV2DomainEvent,
5 OrchestrationV2StoredEvent,
6 ProviderThreadId,
7 RunAttemptId,
8 RunId,
9 RuntimeRequestId,
10 NodeId,
11 type ProjectId,
12 ThreadId,
13} from "@t3tools/contracts";
14import * as Context from "effect/Context";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as PubSub from "effect/PubSub";
20import * as Semaphore from "effect/Semaphore";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23import * as SqlClient from "effect/sql/SqlClient";
24​
25import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts";
26import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
27import { projectDomainEventForWire } from "./WireProjection.ts";
28​
29import * as CommandReceiptStore from "./CommandReceiptStore.ts";
30import * as EffectOutbox from "./EffectOutbox.ts";
31import * as EventStore from "./EventStore.ts";
32import * as ProjectionStore from "./ProjectionStore.ts";
33import * as ProjectStore from "./ProjectStore.ts";
34import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
35​
36/**
37 * ERRORS
38 */
39export class EventSinkWriteError extends Schema.TaggedError<EventSinkWriteError>()(
40 "EventSinkWriteError",
41 {
42 eventCount: Schema.Number,
43 commandId: Schema.optional(CommandId),
44 cause: Schema.optional(Schema.Defect()),
45 },
46) {
47 override get message(): string {
48 return `Failed to write ${this.eventCount} orchestration V2 event(s).`;
49 }
51​
52export class EventSinkStreamError extends Schema.TaggedError<EventSinkStreamError>()(
53 "EventSinkStreamError",
54 {
55 threadId: Schema.optional(ThreadId),
56 afterSequence: Schema.optional(Schema.Number),
57 cause: Schema.optional(Schema.Defect()),
58 },
59) {
60 override get message(): string {
61 return this.threadId === undefined
62 ? "Failed to stream orchestration V2 events."
63 : `Failed to stream orchestration V2 events for thread ${this.threadId}.`;
64 }
66​
67export const EventSinkV2Error = Schema.Union([EventSinkWriteError, EventSinkStreamError]);
68export type EventSinkV2Error = typeof EventSinkV2Error.Type;
69​
70/**
71 * SERVICE DEFINITION
72 */
73export interface EventSinkV2Shape {
74 readonly write: (input: {
75 readonly guardPendingUserInputCancellations?: boolean;
76 readonly commandId?: CommandId;
77 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
78 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
79 readonly writeWithEffects: (input: {
80 readonly guardPendingUserInputCancellations?: boolean;
81 readonly commandId?: CommandId;
82 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
83 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
84 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
85 readonly writeIfRunCurrent: (input: {
86 readonly guardPendingUserInputCancellations?: boolean;
87 readonly commandId?: CommandId;
88 readonly threadId: ThreadId;
89 readonly runId: RunId;
90 readonly activeAttemptId: RunAttemptId;
91 readonly expectedStatus: OrchestrationV2Run["status"];
92 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
93 }) => Effect.Effect<
94 {
95 readonly committed: boolean;
96 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
97 },
98 EventSinkV2Error
99 >;
100 /**
101 * Atomically commit only when the provider thread is still owned by the
102 * expected run attempt and ordinal. Used for late post-terminal
103 * provider_thread updates so a completed or superseded attempt cannot clobber
104 * a newer attempt that already claimed the thread.
105 */
106 readonly writeIfProviderThreadOwner: (input: {
107 readonly guardPendingUserInputCancellations?: boolean;
108 readonly commandId?: CommandId;
109 readonly providerThreadId: ProviderThreadId;
110 readonly runId: RunId;
111 readonly activeAttemptId: RunAttemptId;
112 readonly expectedLastRunOrdinal: number;
113 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
114 }) => Effect.Effect<
115 {
116 readonly committed: boolean;
117 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
118 },
119 EventSinkV2Error
120 >;
121 readonly commitCommand: (input: {
122 readonly commandId: CommandId;
123 readonly threadId: ThreadId;
124 readonly commandType: string;
125 readonly acceptedAt: DateTime.Utc;
126 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
127 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
128 readonly cancelUnsettledEffects?: {
129 readonly effectTypes: ReadonlyArray<EffectOutbox.OrchestrationEffectRequestV2["type"]>;
130 readonly reason: string;
131 };
132 }) => Effect.Effect<
133 {
134 readonly receipt: CommandReceiptStore.CommandReceiptV2;
135 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
136 readonly committed: boolean;
137 readonly cancelledEffectCount: number;
138 },
139 EventSinkV2Error
140 >;
141 readonly commitRejectedCommand: (input: {
142 readonly commandId: CommandId;
143 readonly threadId: ThreadId;
144 readonly commandType: string;
145 readonly rejectedAt: DateTime.Utc;
146 readonly error: string;
147 }) => Effect.Effect<CommandReceiptStore.CommandReceiptV2, EventSinkV2Error>;
148 /**
149 * Append a project event, fold it into its row and record the receipt in one
150 * transaction. A reused command id commits nothing and returns its receipt.
151 */
152 readonly commitProjectCommand: (input: {
153 readonly commandId: CommandId;
154 readonly projectId: ProjectId;
155 readonly commandType: string;
156 readonly acceptedAt: DateTime.Utc;
157 readonly event: UnsequencedProjectEvent;
158 }) => Effect.Effect<
159 { readonly receipt: CommandReceiptStore.ProjectCommandReceiptV2; readonly committed: boolean },
160 EventSinkV2Error
161 >;
162 /** Record a rejected project command, or return the receipt its command id already has. */
163 readonly commitRejectedProjectCommand: (input: {
164 readonly commandId: CommandId;
165 readonly projectId: ProjectId;
166 readonly commandType: string;
167 readonly rejectedAt: DateTime.Utc;
168 readonly error: string;
169 }) => Effect.Effect<CommandReceiptStore.ProjectCommandReceiptV2, EventSinkV2Error>;
170 readonly stream: (input?: {
171 readonly threadId?: ThreadId;
172 readonly afterSequence?: number;
173 /** Filter before queuing live events so a busy worker retains only the events it handles. */
174 readonly eventType?: OrchestrationV2DomainEvent["type"];
175 /** Bound RPC subscribers; internal workers must not drop their subscription under load. */
176 readonly bounded?: boolean;
177 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
178 readonly latestSequence: (input?: {
179 readonly threadId?: ThreadId;
180 }) => Effect.Effect<number, EventSinkV2Error>;
181 readonly readByCommandId: (input: {
182 readonly commandId: CommandId;
183 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
185​
186export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
187 "t3/orchestration-v2/EventSink/EventSinkV2",
188) {}
189​
190/**
191 * IMPLEMENTATIONS
192 */
193const layerBase: Layer.Layer<
194 EventSinkV2,
195 never,
196 | CommandReceiptStore.CommandReceiptStoreV2
197 | EffectOutbox.EffectOutboxV2
198 | EventStore.EventStoreV2
199 | ProjectionStore.ProjectionStoreV2
200 | ProjectStore.ProjectStoreV2
201 | SqlClient.SqlClient
202 | TurnItemPositionStore.TurnItemPositionStoreV2
203> = Layer.effect(
204 EventSinkV2,
205 Effect.gen(function* () {
206 const sql = yield* SqlClient.SqlClient;
207 const commandReceipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
208 const effectOutbox = yield* EffectOutbox.EffectOutboxV2;
209 const eventStore = yield* EventStore.EventStoreV2;
210 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
211 const projectStore = yield* ProjectStore.ProjectStoreV2;
212 const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
213 const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
214 const liveEventsByType = new Map<
215 OrchestrationV2DomainEvent["type"],
216 PubSub.PubSub<OrchestrationV2StoredEvent>
217 >();
218 const publishLiveEvents = (events: ReadonlyArray<OrchestrationV2StoredEvent>) =>
219 Effect.gen(function* () {
220 yield* PubSub.publishAll(liveEvents, events);
221 for (const [type, pubsub] of liveEventsByType) {
222 yield* PubSub.publishAll(
223 pubsub,
224 events.filter((stored) => stored.event.type === type),
225 );
226 }
227 });
228 const publishStoredEvents = (events: ReadonlyArray<OrchestrationV2StoredEvent>) =>
229 eventStore.publishCommitted(events).pipe(Effect.andThen(publishLiveEvents(events)));
230​
231 // Transactions commit one at a time, but each writer publishes after its
232 // commit. If a writer is descheduled in between, a later commit reaches
233 // subscribers first, and clients drop any event at or below the newest
234 // sequence they have applied. So a writer takes this lane as the last step
235 // of its transaction and holds it until it has published. Publishing never
236 // waits, so a writer that holds the transaction while it waits for the
237 // lane is not blocked for long.
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 }),
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 return { committed: true as const, storedEvents };
441 }),
442 (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void),
443 );
444 },
445 );
446​
447 const writeIfProviderThreadOwnerEffect = Effect.fn(
448 "orchestrationV2.EventSink.writeIfProviderThreadOwner",
449 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadOwner"]>[0]) {
450 yield* Effect.annotateCurrentSpan({
451 "orchestration_v2.command_id": input.commandId ?? null,
452 "orchestration_v2.event_count": input.events.length,
453 "orchestration_v2.provider_thread_id": input.providerThreadId,
454 "orchestration_v2.run_id": input.runId,
455 "orchestration_v2.active_attempt_id": input.activeAttemptId,
456 "orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal,
457 });
458​
459 return yield* commitThenPublish(
460 Effect.gen(function* () {
461 const rows = yield* sql<{
462 readonly active_attempt_id: string | null;
463 readonly last_run_ordinal: number | null;
464 }>`
465 SELECT
466 json_extract(r.payload_json, '$.activeAttemptId') AS active_attempt_id,
467 p.last_run_ordinal
468 FROM orchestration_v2_projection_provider_threads p
469 JOIN orchestration_v2_projection_runs r
470 ON r.run_id = ${input.runId}
471 AND r.thread_id = p.thread_id
472 WHERE p.provider_thread_id = ${input.providerThreadId}
473 LIMIT 1
474 `;
475 const current = rows[0];
476 if (
477 current === undefined ||
478 current.active_attempt_id !== input.activeAttemptId ||
479 current.last_run_ordinal !== input.expectedLastRunOrdinal
480 ) {
481 return {
482 committed: false as const,
483 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
484 };
485 }
486​
487 const normalized = yield* normalizeEvents(
488 input.guardPendingUserInputCancellations === true
489 ? yield* guardUserInputCancellations(input.events)
490 : input.events,
491 );
492 const storedEvents = yield* eventStore.append({
493 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
494 events: normalized,
495 });
496 yield* applyStoredEvents(storedEvents);
497 return { committed: true as const, storedEvents };
498 }),
499 (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void),
500 );
501 });
502​
503 const existingCommandResult = (commandId: CommandId) =>
504 Effect.gen(function* () {
505 const existing = yield* commandReceipts.getByCommandId(commandId);
506 if (Option.isNone(existing)) {
507 return yield* Effect.die(
508 new Error(`Command receipt ${commandId} disappeared during its transaction.`),
509 );
510 }
511 const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
512 Stream.runCollect,
513 Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
514 );
515 return { receipt: existing.value, storedEvents };
516 });
517​
518 const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
519 input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
520 ) {
521 const result = yield* commitThenPublish(
522 Effect.gen(function* () {
523 const reserved = yield* commandReceipts.insertIfAbsent({
524 commandId: input.commandId,
525 threadId: input.threadId,
526 commandType: input.commandType,
527 acceptedAt: input.acceptedAt,
528 resultSequence: 0,
529 status: "accepted",
530 error: null,
531 });
532 if (!reserved) {
533 const existing = yield* existingCommandResult(input.commandId);
534 return { ...existing, committed: false as const, cancelledEffectIds: [] };
535 }
536​
537 const normalized = yield* normalizeEvents(input.events);
538 const storedEvents = yield* eventStore.append({
539 commandId: input.commandId,
540 events: normalized,
541 });
542 const sequence = storedEvents.at(-1)?.sequence;
543 if (sequence === undefined) {
544 return yield* Effect.die(
545 new Error(`Command ${input.commandId} produced no orchestration events.`),
546 );
547 }
548 yield* applyStoredEvents(storedEvents);
549 yield* effectOutbox.enqueue(input.effects);
550 const receipt: CommandReceiptStore.CommandReceiptV2 = {
551 commandId: input.commandId,
552 threadId: input.threadId,
553 commandType: input.commandType,
554 acceptedAt: input.acceptedAt,
555 resultSequence: sequence,
556 status: "accepted",
557 error: null,
558 };
559 yield* commandReceipts.upsert(receipt);
560 const cancelledEffectIds =
561 input.cancelUnsettledEffects === undefined
562 ? []
563 : yield* effectOutbox.cancelUnsettled({
564 threadId: input.threadId,
565 ...input.cancelUnsettledEffects,
566 });
567 return { receipt, storedEvents, committed: true as const, cancelledEffectIds };
568 }),
569 (result) =>
570 Effect.gen(function* () {
571 yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
572 if (result.committed && input.effects.length > 0) {
573 yield* effectOutbox.notifyAvailable(input.effects.length);
574 }
575 if (result.committed) yield* publishStoredEvents(result.storedEvents);
576 }),
577 );
578 return {
579 receipt: result.receipt,
580 storedEvents: result.storedEvents,
581 committed: result.committed,
582 cancelledEffectCount: result.cancelledEffectIds.length,
583 };
584 });
585​
586 const commitRejectedCommandEffect = Effect.fn(
587 "orchestrationV2.EventSink.commitRejectedCommand",
588 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
589 return yield* sql.withTransaction(
590 Effect.gen(function* () {
591 const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
592 const receipt: CommandReceiptStore.CommandReceiptV2 = {
593 commandId: input.commandId,
594 threadId: input.threadId,
595 commandType: input.commandType,
596 acceptedAt: input.rejectedAt,
597 resultSequence: sequence,
598 status: "rejected",
599 error: input.error,
600 };
601 const inserted = yield* commandReceipts.insertIfAbsent(receipt);
602 if (inserted) {
603 return receipt;
604 }
605 const existing = yield* commandReceipts.getByCommandId(input.commandId);
606 return Option.getOrElse(existing, () => receipt);
607 }),
608 );
609 });
610​
611 const existingProjectReceipt = (commandId: CommandId) =>
612 commandReceipts.getProjectByCommandId(commandId).pipe(
613 Effect.flatMap(
614 Option.match({
615 onNone: () =>
616 Effect.fail(`Command ${commandId} was already used by a thread command.` as const),
617 onSome: Effect.succeed,
618 }),
619 ),
620 );
621​
622 const commitProjectCommandEffect = Effect.fn("orchestrationV2.EventSink.commitProjectCommand")(
623 function* (input: Parameters<EventSinkV2Shape["commitProjectCommand"]>[0]) {
624 const result = yield* commitThenPublish(
625 Effect.gen(function* () {
626 const reserved: CommandReceiptStore.ProjectCommandReceiptV2 = {
627 commandId: input.commandId,
628 projectId: input.projectId,
629 commandType: input.commandType,
630 acceptedAt: input.acceptedAt,
631 resultSequence: 0,
632 status: "accepted",
633 error: null,
634 };
635 if (!(yield* commandReceipts.insertIfAbsent(reserved))) {
636 return { receipt: yield* existingProjectReceipt(input.commandId), event: undefined };
637 }
638 const event = yield* eventStore.appendProjectEvent(input.event);
639 yield* projectStore.apply(event);
640 const receipt = { ...reserved, resultSequence: event.sequence };
641 yield* commandReceipts.upsert(receipt);
642 return { receipt, event };
643 }),
644 (result) =>
645 result.event === undefined ? Effect.void : eventStore.publishCommitted([result.event]),
646 );
647 return { receipt: result.receipt, committed: result.event !== undefined };
648 },
649 );
650​
651 const commitRejectedProjectCommandEffect = Effect.fn(
652 "orchestrationV2.EventSink.commitRejectedProjectCommand",
653 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedProjectCommand"]>[0]) {
654 return yield* sql.withTransaction(
655 Effect.gen(function* () {
656 const receipt: CommandReceiptStore.ProjectCommandReceiptV2 = {
657 commandId: input.commandId,
658 projectId: input.projectId,
659 commandType: input.commandType,
660 acceptedAt: input.rejectedAt,
661 resultSequence: yield* eventStore.latestApplicationSequence,
662 status: "rejected",
663 error: input.error,
664 };
665 return (yield* commandReceipts.insertIfAbsent(receipt))
666 ? receipt
667 : yield* existingProjectReceipt(input.commandId);
668 }),
669 );
670 });
671​
672 const catchUp = (input: {
673 readonly afterSequence: number;
674 readonly throughSequence: number;
675 readonly threadId?: ThreadId;
676 readonly eventType?: OrchestrationV2DomainEvent["type"];
677 }): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
678 const pageSize = 256;
679 const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
680 Stream.unwrap(
681 eventStore
682 .read({
683 afterSequence,
684 throughSequence: input.throughSequence,
685 ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
686 ...(input.eventType === undefined ? {} : { eventType: input.eventType }),
687 limit: pageSize,
688 })
689 .pipe(
690 Stream.runCollect,
691 Effect.map((chunk) => Array.from(chunk)),
692 Effect.map((events) => {
693 if (events.length === 0) {
694 return Stream.empty;
695 }
696 const current = Stream.fromIterable(events);
697 const last = events.at(-1)?.sequence ?? input.throughSequence;
698 return events.length < pageSize || last >= input.throughSequence
699 ? current
700 : Stream.concat(current, loop(last));
701 }),
702 ),
703 );
704 return loop(input.afterSequence);
705 };
706​
707 const stream = (input?: Parameters<EventSinkV2Shape["stream"]>[0]) => {
708 const afterSequence = input?.afterSequence ?? 0;
709 const matches = (stored: OrchestrationV2StoredEvent) =>
710 (input?.threadId === undefined || stored.event.threadId === input.threadId) &&
711 (input?.eventType === undefined || stored.event.type === input.eventType);
712 const replay = (throughSequence: number) =>
713 catchUp({
714 afterSequence,
715 throughSequence,
716 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
717 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
718 }).pipe(Stream.filter(matches));
719 return Stream.unwrap(
720 Effect.gen(function* () {
721 let pubsub = liveEvents;
722 if (input?.eventType !== undefined) {
723 const existing = liveEventsByType.get(input.eventType);
724 if (existing !== undefined) {
725 pubsub = existing;
726 } else {
727 const created = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
728 pubsub = liveEventsByType.get(input.eventType) ?? created;
729 liveEventsByType.set(input.eventType, pubsub);
730 }
731 }
732 if (input?.bounded === true) {
733 return replayAndBufferProjectedLiveEvents({
734 subscribe: PubSub.subscribe(pubsub),
735 latestSequence: eventStore.latestSequence(),
736 afterSequence,
737 filter: matches,
738 replay,
739 project: (stored) => ({ ...stored, event: projectDomainEventForWire(stored.event) }),
740 });
741 }
742 const subscription = yield* PubSub.subscribe(pubsub);
743 const highWater = yield* eventStore.latestSequence();
744 const live = Stream.fromSubscription(subscription).pipe(
745 Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)),
746 Stream.filter(matches),
747 );
748 return Stream.concat(replay(highWater), live);
749 }),
750 );
751 };
752​
753 return EventSinkV2.of({
754 write: (input) =>
755 writeEffect({ ...input, effects: [] }).pipe(
756 Effect.mapError(
757 (cause) =>
758 new EventSinkWriteError({
759 eventCount: input.events.length,
760 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
761 cause,
762 }),
763 ),
764 ),
765 writeWithEffects: (input) =>
766 writeEffect(input).pipe(
767 Effect.mapError(
768 (cause) =>
769 new EventSinkWriteError({
770 eventCount: input.events.length,
771 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
772 cause,
773 }),
774 ),
775 ),
776 writeIfRunCurrent: (input) =>
777 writeIfRunCurrentEffect(input).pipe(
778 Effect.mapError(
779 (cause) =>
780 new EventSinkWriteError({
781 eventCount: input.events.length,
782 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
783 cause,
784 }),
785 ),
786 ),
787 writeIfProviderThreadOwner: (input) =>
788 writeIfProviderThreadOwnerEffect(input).pipe(
789 Effect.mapError(
790 (cause) =>
791 new EventSinkWriteError({
792 eventCount: input.events.length,
793 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
794 cause,
795 }),
796 ),
797 ),
798 commitCommand: (input) =>
799 commitCommandEffect(input).pipe(
800 Effect.mapError(
801 (cause) =>
802 new EventSinkWriteError({
803 commandId: input.commandId,
804 eventCount: input.events.length,
805 cause,
806 }),
807 ),
808 ),
809 commitRejectedCommand: (input) =>
810 commitRejectedCommandEffect(input).pipe(
811 Effect.mapError(
812 (cause) =>
813 new EventSinkWriteError({
814 commandId: input.commandId,
815 eventCount: 0,
816 cause,
817 }),
818 ),
819 ),
820 commitProjectCommand: (input) =>
821 commitProjectCommandEffect(input).pipe(
822 Effect.mapError(
823 (cause) =>
824 new EventSinkWriteError({ commandId: input.commandId, eventCount: 1, cause }),
825 ),
826 ),
827 commitRejectedProjectCommand: (input) =>
828 commitRejectedProjectCommandEffect(input).pipe(
829 Effect.mapError(
830 (cause) =>
831 new EventSinkWriteError({ commandId: input.commandId, eventCount: 0, cause }),
832 ),
833 ),
834 stream: (input) =>
835 stream(input).pipe(
836 Stream.mapError(
837 (cause) =>
838 new EventSinkStreamError({
839 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
840 ...(input?.afterSequence === undefined
841 ? {}
842 : { afterSequence: input.afterSequence }),
843 cause,
844 }),
845 ),
846 ),
847 latestSequence: (input) =>
848 eventStore.latestSequence(input).pipe(
849 Effect.mapError(
850 (cause) =>
851 new EventSinkStreamError({
852 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
853 cause,
854 }),
855 ),
856 ),
857 readByCommandId: (input) =>
858 eventStore.readByCommandId(input).pipe(
859 Stream.mapError(
860 (cause) =>
861 new EventSinkStreamError({
862 cause,
863 }),
864 ),
865 ),
866 } satisfies EventSinkV2Shape);
867 }),
868);
869​
870/**
871 * Event sink layer for application compositions that already own the
872 * persistence services. Keeping the outbox instance shared with the worker is
873 * important because enqueue notifications are in-memory wakeups backed by the
874 * durable SQL queue.
875 */
876export const layerFromStores = layerBase;
877​
878export const layer: Layer.Layer<
879 EventSinkV2,
880 never,
881 EventStore.EventStoreV2 | ProjectionStore.ProjectionStoreV2 | SqlClient.SqlClient
882> = layerBase.pipe(
883 Layer.provide(
884 Layer.mergeAll(
885 CommandReceiptStore.layer,
886 EffectOutbox.layer,
887 ProjectStore.layer,
888 TurnItemPositionStore.layer,
889 ),
890 ),
891);