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

OrchestrationEventStore.ts

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