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

OrchestrationEventStore.ts

756 lines27.3 KB

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