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