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

EventSink.ts

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