Open History to see the last commit
1/**
2 * Historical name for the shared application event store.
3 *
4 * Owns durable append/replay access for project events and V2 agent-thread
5 * events under one global sequence. It does not reduce events into read models
6 * or apply command validation rules.
7 *
8 * Uses Effect `Context.Service` for dependency injection and exposes typed
9 * persistence/decode errors for event append and replay operations.
10 *
11 * @module OrchestrationEventStore
12 */
13import {
14 ApplicationEventMetadata,
15 ApplicationProjectEvent,
16 type ApplicationStoredEvent,
17 CommandId,
18 EventId,
19 IsoDateTime,
20 isKnownOrchestrationV2EventType,
21 NonNegativeInt,
22 OrchestrationV2DomainEventJson,
23 OrchestrationV2StoredEvent,
24 ProjectId,
25 StoredProjectIcon,
26 ThreadId,
27 type OrchestrationV2DomainEvent,
28} from "@t3tools/contracts";
29import * as Context from "effect/Context";
30import * as SqlClient from "effect/sql/SqlClient";
31import * as SqlSchema from "effect/sql/SqlSchema";
32import * as Effect from "effect/Effect";
33import * as Layer from "effect/Layer";
34import * as PubSub from "effect/PubSub";
35import * as Option from "effect/Option";
36import * as Schema from "effect/Schema";
37import * as Stream from "effect/Stream";
38
39import { replayAndBufferProjectedLiveEvents } from "../orchestration-v2/LiveStreamBudget.ts";
40
41import {
42 toPersistenceDecodeError,
43 toPersistenceSqlError,
44 type OrchestrationEventStoreError,
45} from "./Errors.ts";
46
47/** A project event before the store assigns its sequence. */
48export type UnsequencedProjectEvent = ApplicationProjectEvent extends infer Event
49 ? Event extends ApplicationProjectEvent
50 ? Omit<Event, "sequence">
51 : never
52 : never;
53
54/** OrchestrationEventStore - Service tag for the shared application event log. */
55export class OrchestrationEventStore extends Context.Service<
56 OrchestrationEventStore,
57 {
58 /** Append one project event to the shared application log. */
59 readonly appendProjectEvent: (
60 event: UnsequencedProjectEvent,
61 ) => Effect.Effect<ApplicationProjectEvent, OrchestrationEventStoreError>;
62
63 /** Append V2 agent events to the same globally ordered application log. */
64 readonly appendAgentEvents: (input: {
65 readonly commandId?: CommandId;
66 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
67 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, OrchestrationEventStoreError>;
68
69 /**
70 * Read only V2 thread events from the application log.
71 *
72 * Reads in fixed-size sequence pages until the filtered range is exhausted;
73 * `limit` caps raw rows across pages, including skipped unknown types.
74 *
75 * A row whose `event_type` this build does not know fails the read unless
76 * `skipUnknownEventTypes` is set, which logs and drops it instead. Only
77 * client thread replay opts in; anything that builds server state stays strict.
78 */
79 readonly readAgentEvents: (input?: {
80 readonly afterSequence?: number;
81 readonly throughSequence?: number;
82 readonly threadId?: ThreadId;
83 readonly commandId?: CommandId;
84 readonly eventType?: OrchestrationV2DomainEvent["type"];
85 readonly limit?: number;
86 readonly skipUnknownEventTypes?: boolean;
87 }) => Stream.Stream<OrchestrationV2StoredEvent, OrchestrationEventStoreError>;
88
89 /** Measure one thread's bounded replay without loading or decoding its payloads. */
90 readonly getAgentReplayStats: (input: {
91 readonly threadId: ThreadId;
92 readonly afterSequence: number;
93 readonly throughSequence: number;
94 readonly maxEvents: number;
95 }) => Effect.Effect<
96 {
97 readonly eventCount: number;
98 /** UTF-8 bytes in persisted payload JSON before decoding or wire projection. */
99 readonly rawPayloadBytes: number;
100 readonly hasCreateEvent: boolean;
101 },
102 OrchestrationEventStoreError
103 >;
104
105 /**
106 * Measure the retained application-event range `(afterSequence, throughSequence]`
107 * without loading or decoding its payloads.
108 */
109 readonly getReplayStats: (input: {
110 readonly afterSequence: number;
111 readonly throughSequence: number;
112 }) => Effect.Effect<
113 {
114 readonly eventCount: number;
115 /** UTF-8 bytes in persisted payload JSON before decoding or wire projection. */
116 readonly rawPayloadBytes: number;
117 },
118 OrchestrationEventStoreError
119 >;
120
121 readonly latestAgentSequence: (
122 threadId?: ThreadId,
123 ) => Effect.Effect<number, OrchestrationEventStoreError>;
124
125 readonly latestApplicationSequence: Effect.Effect<number, OrchestrationEventStoreError>;
126
127 /**
128 * Read the finite retained application-event range `(afterSequence, throughSequence]`.
129 *
130 * A row whose `event_type` this build does not know fails the read unless
131 * `skipUnknownEventTypes` is set, which logs and drops it instead. Only
132 * client shell replay opts in; anything that builds server state stays strict.
133 */
134 readonly readApplicationEvents: (input: {
135 readonly afterSequence: number;
136 readonly throughSequence: number;
137 readonly skipUnknownEventTypes?: boolean;
138 }) => Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError>;
139
140 /** Publish only after the surrounding event/projection transaction commits. */
141 readonly publishCommitted: (
142 events: ReadonlyArray<ApplicationStoredEvent>,
143 ) => Effect.Effect<void>;
144
145 /** Race-free replay-to-live stream for project and V2 thread events. */
146 readonly streamApplicationEvents: (input?: {
147 readonly afterSequence?: number;
148 }) => Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError>;
149 /** Project transport events before bounding replay and the live tail. */
150 readonly streamProjectedApplicationEvents: <A extends { readonly sequence: number }>(input: {
151 readonly afterSequence?: number;
152 readonly project: (event: ApplicationStoredEvent) => A;
153 }) => Stream.Stream<A, OrchestrationEventStoreError>;
154 }
155>()("t3/persistence/OrchestrationEventStore") {}
156
157const encodeProjectIcon = Schema.encodeSync(StoredProjectIcon);
158const decodeProjectEvent = Schema.decodeUnknownEffect(ApplicationProjectEvent);
159const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
160const EventMetadataFromJsonString = Schema.fromJsonString(ApplicationEventMetadata);
161const ProjectEventType = Schema.Literals([
162 "project.created",
163 "project.meta-updated",
164 "project.deleted",
165]);
166const ActorKind = Schema.Literals(["client", "server", "provider"]);
167
168const AppendProjectEventRequestSchema = Schema.Struct({
169 eventId: EventId,
170 streamId: ProjectId,
171 type: ProjectEventType,
172 causationEventId: Schema.NullOr(EventId),
173 correlationId: Schema.NullOr(CommandId),
174 actorKind: ActorKind,
175 occurredAt: IsoDateTime,
176 commandId: Schema.NullOr(CommandId),
177 payloadJson: UnknownFromJsonString,
178 metadataJson: EventMetadataFromJsonString,
179});
180
181const ProjectEventPersistedRowSchema = Schema.Struct({
182 sequence: NonNegativeInt,
183 eventId: EventId,
184 type: ProjectEventType,
185 aggregateKind: Schema.Literal("project"),
186 aggregateId: ProjectId,
187 occurredAt: IsoDateTime,
188 commandId: Schema.NullOr(CommandId),
189 causationEventId: Schema.NullOr(EventId),
190 correlationId: Schema.NullOr(CommandId),
191 payload: UnknownFromJsonString,
192 metadata: EventMetadataFromJsonString,
193});
194
195const READ_PAGE_SIZE = 500;
196
197interface ApplicationEventRow {
198 readonly sequence: number;
199 readonly event_id: string;
200 readonly command_id: string | null;
201 readonly aggregate_kind: "project" | "thread";
202 readonly stream_id: string;
203 readonly event_type: string;
204 readonly occurred_at: string;
205 readonly payload_json: string;
206 readonly metadata_json: string;
207 readonly application_event_version: number;
208 readonly causation_event_id: string | null;
209 readonly correlation_id: string | null;
210}
211
212const decodeV2EventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson);
213const encodeV2EventJson = Schema.encodeEffect(OrchestrationV2DomainEventJson);
214const decodeV2StoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent);
215const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
216const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
217
218function metadataForV2Event(event: OrchestrationV2DomainEvent): Record<string, unknown> {
219 return {
220 ...(event.runId === undefined ? {} : { runId: event.runId }),
221 ...(event.nodeId === undefined ? {} : { nodeId: event.nodeId }),
222 ...(event.driver === undefined ? {} : { driver: event.driver }),
223 ...(event.providerInstanceId === undefined
224 ? {}
225 : { providerInstanceId: event.providerInstanceId }),
226 ...(event.rawEventId === undefined ? {} : { rawEventId: event.rawEventId }),
227 };
228}
229
230const rowToV2StoredEvent = Effect.fn("OrchestrationEventStore.rowToV2StoredEvent")(function* (
231 row: ApplicationEventRow,
232) {
233 const payload = yield* decodeJson(row.payload_json);
234 const metadata = yield* decodeJson(row.metadata_json);
235 const values =
236 typeof metadata === "object" && metadata !== null ? (metadata as Record<string, unknown>) : {};
237 const event = yield* decodeV2EventJson({
238 id: row.event_id,
239 threadId: row.stream_id,
240 type: row.event_type,
241 occurredAt: row.occurred_at,
242 payload,
243 ...(values.runId === undefined ? {} : { runId: values.runId }),
244 ...(values.nodeId === undefined ? {} : { nodeId: values.nodeId }),
245 ...(values.driver === undefined ? {} : { driver: values.driver }),
246 ...(values.providerInstanceId === undefined
247 ? {}
248 : { providerInstanceId: values.providerInstanceId }),
249 ...(values.rawEventId === undefined ? {} : { rawEventId: values.rawEventId }),
250 });
251 return yield* decodeV2StoredEvent({
252 sequence: row.sequence,
253 commandId: row.command_id,
254 event,
255 });
256});
257
258const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent")(function* (
259 row: ApplicationEventRow,
260) {
261 return yield* decodeProjectEvent({
262 sequence: row.sequence,
263 eventId: row.event_id,
264 type: row.event_type,
265 aggregateKind: row.aggregate_kind,
266 aggregateId: row.stream_id,
267 occurredAt: row.occurred_at,
268 commandId: row.command_id,
269 causationEventId: row.causation_event_id,
270 correlationId: row.correlation_id,
271 payload: yield* decodeJson(row.payload_json),
272 metadata: yield* decodeJson(row.metadata_json),
273 });
274});
275
276function rowToApplicationStoredEvent(
277 row: ApplicationEventRow,
278): Effect.Effect<ApplicationStoredEvent, Schema.SchemaError> {
279 return row.aggregate_kind === "project" ? rowToProjectEvent(row) : rowToV2StoredEvent(row);
280}
281
282const isKnownProjectEventType = Schema.is(ProjectEventType);
283
284/** Filter only unknown discriminants; known types still undergo strict payload decoding. */
285const keepReplayRow = (row: ApplicationEventRow, skipUnknownEventTypes?: boolean) =>
286 skipUnknownEventTypes !== true ||
287 (row.aggregate_kind === "project"
288 ? isKnownProjectEventType(row.event_type)
289 : isKnownOrchestrationV2EventType(row.event_type))
290 ? Effect.succeed(true)
291 : Effect.logWarning("Skipping an application event row with an unknown event type", {
292 aggregateKind: row.aggregate_kind,
293 sequence: row.sequence,
294 eventTypeLength: row.event_type.length,
295 }).pipe(Effect.as(false));
296
297function inferActorKind(event: UnsequencedProjectEvent): typeof ActorKind.Type {
298 if (event.commandId !== null && event.commandId.startsWith("provider:")) {
299 return "provider";
300 }
301 if (event.commandId !== null && event.commandId.startsWith("server:")) {
302 return "server";
303 }
304 if (
305 event.metadata.providerTurnId !== undefined ||
306 event.metadata.providerItemId !== undefined ||
307 event.metadata.adapterKey !== undefined
308 ) {
309 return "provider";
310 }
311 if (event.commandId === null) {
312 return "server";
313 }
314 return "client";
315}
316
317function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
318 return (cause: unknown): OrchestrationEventStoreError =>
319 Schema.isSchemaError(cause)
320 ? toPersistenceDecodeError(decodeOperation)(cause)
321 : toPersistenceSqlError(sqlOperation)(cause);
322}
323
324const makeEventStore = Effect.gen(function* () {
325 const sql = yield* SqlClient.SqlClient;
326 const committedEvents = yield* PubSub.unbounded<ApplicationStoredEvent>();
327
328 const appendProjectEventRow = SqlSchema.findOne({
329 Request: AppendProjectEventRequestSchema,
330 Result: ProjectEventPersistedRowSchema,
331 execute: (request) =>
332 sql`
333 INSERT INTO orchestration_events (
334 event_id,
335 aggregate_kind,
336 stream_id,
337 stream_version,
338 event_type,
339 occurred_at,
340 command_id,
341 causation_event_id,
342 correlation_id,
343 actor_kind,
344 payload_json,
345 metadata_json,
346 application_event_version
347 )
348 VALUES (
349 ${request.eventId},
350 'project',
351 ${request.streamId},
352 COALESCE(
353 (
354 SELECT stream_version + 1
355 FROM orchestration_events
356 WHERE aggregate_kind = 'project'
357 AND stream_id = ${request.streamId}
358 ORDER BY stream_version DESC
359 LIMIT 1
360 ),
361 0
362 ),
363 ${request.type},
364 ${request.occurredAt},
365 ${request.commandId},
366 ${request.causationEventId},
367 ${request.correlationId},
368 ${request.actorKind},
369 ${request.payloadJson},
370 ${request.metadataJson},
371 2
372 )
373 RETURNING
374 sequence,
375 event_id AS "eventId",
376 event_type AS "type",
377 aggregate_kind AS "aggregateKind",
378 stream_id AS "aggregateId",
379 occurred_at AS "occurredAt",
380 command_id AS "commandId",
381 causation_event_id AS "causationEventId",
382 correlation_id AS "correlationId",
383 payload_json AS "payload",
384 metadata_json AS "metadata"
385 `,
386 });
387
388 const appendProjectEvent: OrchestrationEventStore["Service"]["appendProjectEvent"] = (event) =>
389 appendProjectEventRow({
390 eventId: event.eventId,
391 streamId: event.aggregateId,
392 type: event.type,
393 causationEventId: event.causationEventId,
394 correlationId: event.correlationId,
395 actorKind: inferActorKind(event),
396 occurredAt: event.occurredAt,
397 commandId: event.commandId,
398 payloadJson:
399 event.type === "project.deleted" || !event.payload.projectIcon
400 ? event.payload
401 : { ...event.payload, projectIcon: encodeProjectIcon(event.payload.projectIcon) },
402 metadataJson: event.metadata,
403 }).pipe(
404 Effect.flatMap((row) => decodeProjectEvent(row)),
405 Effect.mapError(
406 toPersistenceSqlOrDecodeError(
407 "OrchestrationEventStore.appendProjectEvent:insert",
408 "OrchestrationEventStore.appendProjectEvent:decode",
409 ),
410 ),
411 );
412
413 const readApplicationRows = (input: {
414 readonly afterSequence: number;
415 readonly throughSequence?: number;
416 readonly threadId?: ThreadId;
417 readonly commandId?: CommandId;
418 readonly eventType?: OrchestrationV2DomainEvent["type"];
419 readonly onlyAgentEvents?: boolean;
420 readonly limit: number;
421 }) =>
422 sql<ApplicationEventRow>`
423 SELECT
424 sequence,
425 event_id,
426 command_id,
427 aggregate_kind,
428 stream_id,
429 event_type,
430 occurred_at,
431 payload_json,
432 metadata_json,
433 application_event_version,
434 causation_event_id,
435 correlation_id
436 FROM orchestration_events
437 ${
438 // The sequence range otherwise wins and a command lookup scans every
439 // V2 event, which blocks the server for seconds on large histories.
440 input.commandId !== undefined
441 ? sql`INDEXED BY idx_orch_events_command_id`
442 : input.onlyAgentEvents === true
443 ? sql``
444 : sql`INDEXED BY idx_orchestration_events_application_high_water`
445 }
446 WHERE sequence > ${input.afterSequence}
447 AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER}
448 AND (
449 ${
450 input.onlyAgentEvents === true
451 ? sql`application_event_version = 2 AND aggregate_kind = 'thread'`
452 : sql`aggregate_kind = 'project'
453 OR (application_event_version = 2 AND aggregate_kind = 'thread')`
454 }
455 )
456 AND ${sql.and([
457 ...(input.threadId === undefined ? [] : [sql`stream_id = ${input.threadId}`]),
458 ...(input.commandId === undefined ? [] : [sql`command_id = ${input.commandId}`]),
459 ...(input.eventType === undefined ? [] : [sql`event_type = ${input.eventType}`]),
460 ])}
461 ORDER BY sequence ASC
462 LIMIT ${input.limit}
463 `;
464
465 const appendAgentEvents: OrchestrationEventStore["Service"]["appendAgentEvents"] = (input) =>
466 Effect.forEach(
467 input.events,
468 (event) =>
469 Effect.gen(function* () {
470 const encoded = yield* encodeV2EventJson(event);
471 const rows = yield* sql<{ readonly sequence: number }>`
472 INSERT INTO orchestration_events (
473 event_id,
474 aggregate_kind,
475 stream_id,
476 stream_version,
477 event_type,
478 occurred_at,
479 command_id,
480 causation_event_id,
481 correlation_id,
482 actor_kind,
483 payload_json,
484 metadata_json,
485 application_event_version
486 )
487 VALUES (
488 ${event.id},
489 'thread',
490 ${event.threadId},
491 COALESCE(
492 (
493 SELECT MAX(stream_version) + 1
494 FROM orchestration_events
495 WHERE aggregate_kind = 'thread' AND stream_id = ${event.threadId}
496 ),
497 0
498 ),
499 ${event.type},
500 ${encoded.occurredAt},
501 ${input.commandId ?? null},
502 NULL,
503 ${input.commandId ?? null},
504 ${event.rawEventId === undefined ? "server" : "provider"},
505 ${yield* encodeJson(encoded.payload)},
506 ${yield* encodeJson(metadataForV2Event(event))},
507 2
508 )
509 RETURNING sequence
510 `;
511 return yield* decodeV2StoredEvent({
512 sequence: rows[0]?.sequence,
513 commandId: input.commandId ?? null,
514 event,
515 });
516 }),
517 { concurrency: 1 },
518 ).pipe(
519 Effect.mapError(
520 toPersistenceSqlOrDecodeError(
521 "OrchestrationEventStore.appendAgentEvents:insert",
522 "OrchestrationEventStore.appendAgentEvents:decode",
523 ),
524 ),
525 );
526
527 const readAgentEvents: OrchestrationEventStore["Service"]["readAgentEvents"] = (input) => {
528 const totalLimit =
529 input?.limit === undefined ? Number.MAX_SAFE_INTEGER : Math.max(0, Math.floor(input.limit));
530 if (totalLimit === 0) {
531 return Stream.empty;
532 }
533 return Stream.paginate(
534 { cursor: input?.afterSequence ?? 0, remaining: totalLimit },
535 ({ cursor, remaining }) => {
536 const pageLimit = Math.min(remaining, READ_PAGE_SIZE);
537 return readApplicationRows({
538 afterSequence: cursor,
539 ...(input?.throughSequence === undefined
540 ? {}
541 : { throughSequence: input.throughSequence }),
542 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
543 ...(input?.commandId === undefined ? {} : { commandId: input.commandId }),
544 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
545 onlyAgentEvents: true,
546 limit: pageLimit,
547 }).pipe(
548 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")),
549 Effect.map((rows) => {
550 const last = rows.at(-1);
551 const nextRemaining = remaining - rows.length;
552 return [
553 rows,
554 last === undefined ||
555 rows.length < pageLimit ||
556 nextRemaining <= 0 ||
557 (input?.throughSequence !== undefined && last.sequence >= input.throughSequence)
558 ? Option.none()
559 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
560 ] as const;
561 }),
562 );
563 },
564 ).pipe(
565 Stream.filterEffect((row) => keepReplayRow(row, input?.skipUnknownEventTypes)),
566 Stream.mapEffect((row) =>
567 rowToV2StoredEvent(row).pipe(
568 Effect.mapError(
569 toPersistenceDecodeError("OrchestrationEventStore.readAgentEvents:decode"),
570 ),
571 ),
572 ),
573 );
574 };
575
576 const getAgentReplayStats: OrchestrationEventStore["Service"]["getAgentReplayStats"] = (input) =>
577 sql<{
578 readonly eventCount: number;
579 readonly rawPayloadBytes: number;
580 readonly hasCreateEvent: number;
581 }>`
582 SELECT
583 COUNT(*) AS "eventCount",
584 COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes",
585 COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent"
586 FROM (
587 SELECT payload_json, event_type
588 FROM orchestration_events
589 WHERE aggregate_kind = 'thread'
590 AND stream_id = ${input.threadId}
591 AND application_event_version = 2
592 AND sequence > ${input.afterSequence}
593 AND sequence <= ${input.throughSequence}
594 ORDER BY sequence ASC
595 LIMIT ${Math.max(0, Math.floor(input.maxEvents)) + 1}
596 )
597 `.pipe(
598 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getAgentReplayStats:query")),
599 Effect.map((rows) => ({
600 eventCount: rows[0]?.eventCount ?? 0,
601 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
602 hasCreateEvent: (rows[0]?.hasCreateEvent ?? 0) !== 0,
603 })),
604 );
605
606 const getReplayStats: OrchestrationEventStore["Service"]["getReplayStats"] = (input) =>
607 sql<{ readonly eventCount: number; readonly rawPayloadBytes: number }>`
608 SELECT
609 COUNT(*) AS "eventCount",
610 COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes"
611 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
612 WHERE sequence > ${input.afterSequence}
613 AND sequence <= ${input.throughSequence}
614 AND (
615 aggregate_kind = 'project'
616 OR (application_event_version = 2 AND aggregate_kind = 'thread')
617 )
618 `.pipe(
619 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getReplayStats:query")),
620 Effect.map((rows) => ({
621 eventCount: rows[0]?.eventCount ?? 0,
622 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
623 })),
624 );
625
626 const latestAgentSequence: OrchestrationEventStore["Service"]["latestAgentSequence"] = (
627 threadId,
628 ) =>
629 sql<{ readonly sequence: number | null }>`
630 SELECT MAX(sequence) AS sequence
631 FROM orchestration_events
632 ${
633 threadId === undefined
634 ? sql``
635 : sql`INDEXED BY idx_orchestration_events_agent_stream_sequence`
636 }
637 WHERE application_event_version = 2
638 AND aggregate_kind = 'thread'
639 ${threadId === undefined ? sql`` : sql`AND stream_id = ${threadId}`}
640 `.pipe(
641 Effect.map((rows) => rows[0]?.sequence ?? 0),
642 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")),
643 );
644
645 // The OR planner otherwise scans every V2 event instead of seeking the final sequence.
646 const latestApplicationSequence = sql<{ readonly sequence: number | null }>`
647 SELECT MAX(sequence) AS sequence
648 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
649 WHERE aggregate_kind = 'project'
650 OR (application_event_version = 2 AND aggregate_kind = 'thread')
651 `.pipe(
652 Effect.map((rows) => rows[0]?.sequence ?? 0),
653 Effect.mapError(
654 toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"),
655 ),
656 );
657
658 // Advance over raw rows so even a full page of unknown types cannot end replay early.
659 const catchUpApplicationEvents = (input: {
660 readonly afterSequence: number;
661 readonly throughSequence: number;
662 readonly skipUnknownEventTypes?: boolean;
663 }): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
664 Stream.paginate(input.afterSequence, (afterSequence) =>
665 readApplicationRows({
666 afterSequence,
667 throughSequence: input.throughSequence,
668 limit: READ_PAGE_SIZE,
669 }).pipe(
670 Effect.mapError(
671 toPersistenceSqlError("OrchestrationEventStore.readApplicationEvents:query"),
672 ),
673 Effect.map((rows) => {
674 const last = rows.at(-1);
675 return [
676 rows,
677 last === undefined ||
678 rows.length < READ_PAGE_SIZE ||
679 last.sequence >= input.throughSequence
680 ? Option.none()
681 : Option.some(last.sequence),
682 ] as const;
683 }),
684 ),
685 ).pipe(
686 Stream.filterEffect((row) => keepReplayRow(row, input.skipUnknownEventTypes)),
687 Stream.mapEffect((row) =>
688 rowToApplicationStoredEvent(row).pipe(
689 Effect.mapError(
690 toPersistenceDecodeError("OrchestrationEventStore.readApplicationEvents:decode"),
691 ),
692 ),
693 ),
694 );
695
696 const streamProjectedApplicationEvents: OrchestrationEventStore["Service"]["streamProjectedApplicationEvents"] =
697 (input) =>
698 replayAndBufferProjectedLiveEvents({
699 subscribe: PubSub.subscribe(committedEvents),
700 latestSequence: latestApplicationSequence,
701 afterSequence: input.afterSequence ?? 0,
702 project: input.project,
703 replay: (throughSequence) =>
704 catchUpApplicationEvents({
705 afterSequence: input?.afterSequence ?? 0,
706 throughSequence,
707 }),
708 }).pipe(
709 Stream.catchTag("LiveStreamBufferError", (cause) =>
710 Stream.fail(
711 toPersistenceSqlError("OrchestrationEventStore.streamApplicationEvents:buffer")(cause),
712 ),
713 ),
714 );
715
716 const streamApplicationEvents: OrchestrationEventStore["Service"]["streamApplicationEvents"] = (
717 input,
718 ) => streamProjectedApplicationEvents({ ...input, project: (event) => event });
719
720 return {
721 appendProjectEvent,
722 appendAgentEvents,
723 readAgentEvents,
724 getAgentReplayStats,
725 getReplayStats,
726 latestAgentSequence,
727 latestApplicationSequence,
728 readApplicationEvents: catchUpApplicationEvents,
729 publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
730 streamApplicationEvents,
731 streamProjectedApplicationEvents,
732 } satisfies OrchestrationEventStore["Service"];
733});
734
735export const layer = Layer.effect(OrchestrationEventStore, makeEventStore);