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 input.onlyAgentEvents === true
411 ? sql``
412 : sql`INDEXED BY idx_orchestration_events_application_high_water`
413 }
414 WHERE sequence > ${input.afterSequence}
415 AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER}
416 AND (
417 ${
418 input.onlyAgentEvents === true
419 ? sql`application_event_version = 2 AND aggregate_kind = 'thread'`
420 : sql`aggregate_kind = 'project'
421 OR (application_event_version = 2 AND aggregate_kind = 'thread')`
422 }
423 )
424 AND ${sql.and([
425 ...(input.threadId === undefined ? [] : [sql`stream_id = ${input.threadId}`]),
426 ...(input.commandId === undefined ? [] : [sql`command_id = ${input.commandId}`]),
427 ...(input.eventType === undefined ? [] : [sql`event_type = ${input.eventType}`]),
428 ])}
429 ORDER BY sequence ASC
430 LIMIT ${input.limit}
431 `;
432
433 const appendAgentEvents: OrchestrationEventStore["Service"]["appendAgentEvents"] = (input) =>
434 Effect.forEach(
435 input.events,
436 (event) =>
437 Effect.gen(function* () {
438 const encoded = yield* encodeV2EventJson(event);
439 const rows = yield* sql<{ readonly sequence: number }>`
440 INSERT INTO orchestration_events (
441 event_id,
442 aggregate_kind,
443 stream_id,
444 stream_version,
445 event_type,
446 occurred_at,
447 command_id,
448 causation_event_id,
449 correlation_id,
450 actor_kind,
451 payload_json,
452 metadata_json,
453 application_event_version
454 )
455 VALUES (
456 ${event.id},
457 'thread',
458 ${event.threadId},
459 COALESCE(
460 (
461 SELECT MAX(stream_version) + 1
462 FROM orchestration_events
463 WHERE aggregate_kind = 'thread' AND stream_id = ${event.threadId}
464 ),
465 0
466 ),
467 ${event.type},
468 ${encoded.occurredAt},
469 ${input.commandId ?? null},
470 NULL,
471 ${input.commandId ?? null},
472 ${event.rawEventId === undefined ? "server" : "provider"},
473 ${yield* encodeJson(encoded.payload)},
474 ${yield* encodeJson(metadataForV2Event(event))},
475 2
476 )
477 RETURNING sequence
478 `;
479 return yield* decodeV2StoredEvent({
480 sequence: rows[0]?.sequence,
481 commandId: input.commandId ?? null,
482 event,
483 });
484 }),
485 { concurrency: 1 },
486 ).pipe(
487 Effect.mapError(
488 toPersistenceSqlOrDecodeError(
489 "OrchestrationEventStore.appendAgentEvents:insert",
490 "OrchestrationEventStore.appendAgentEvents:decode",
491 ),
492 ),
493 );
494
495 const readAgentEvents: OrchestrationEventStore["Service"]["readAgentEvents"] = (input) => {
496 const totalLimit =
497 input?.limit === undefined ? Number.MAX_SAFE_INTEGER : Math.max(0, Math.floor(input.limit));
498 if (totalLimit === 0) {
499 return Stream.empty;
500 }
501 return Stream.paginate(
502 { cursor: input?.afterSequence ?? 0, remaining: totalLimit },
503 ({ cursor, remaining }) => {
504 const pageLimit = Math.min(remaining, READ_PAGE_SIZE);
505 return readApplicationRows({
506 afterSequence: cursor,
507 ...(input?.throughSequence === undefined
508 ? {}
509 : { throughSequence: input.throughSequence }),
510 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
511 ...(input?.commandId === undefined ? {} : { commandId: input.commandId }),
512 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
513 onlyAgentEvents: true,
514 limit: pageLimit,
515 }).pipe(
516 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")),
517 Effect.map((rows) => {
518 const last = rows.at(-1);
519 const nextRemaining = remaining - rows.length;
520 return [
521 rows,
522 last === undefined ||
523 rows.length < pageLimit ||
524 nextRemaining <= 0 ||
525 (input?.throughSequence !== undefined && last.sequence >= input.throughSequence)
526 ? Option.none()
527 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
528 ] as const;
529 }),
530 );
531 },
532 ).pipe(
533 Stream.mapEffect((row) =>
534 rowToV2StoredEvent(row).pipe(
535 Effect.mapError(
536 toPersistenceDecodeError("OrchestrationEventStore.readAgentEvents:decode"),
537 ),
538 ),
539 ),
540 );
541 };
542
543 const getAgentReplayStats: OrchestrationEventStore["Service"]["getAgentReplayStats"] = (input) =>
544 sql<{
545 readonly eventCount: number;
546 readonly rawPayloadBytes: number;
547 readonly hasCreateEvent: number;
548 }>`
549 SELECT
550 COUNT(*) AS "eventCount",
551 COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes",
552 COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent"
553 FROM (
554 SELECT payload_json, event_type
555 FROM orchestration_events
556 WHERE aggregate_kind = 'thread'
557 AND stream_id = ${input.threadId}
558 AND application_event_version = 2
559 AND sequence > ${input.afterSequence}
560 AND sequence <= ${input.throughSequence}
561 ORDER BY sequence ASC
562 LIMIT ${Math.max(0, Math.floor(input.maxEvents)) + 1}
563 )
564 `.pipe(
565 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getAgentReplayStats:query")),
566 Effect.map((rows) => ({
567 eventCount: rows[0]?.eventCount ?? 0,
568 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
569 hasCreateEvent: (rows[0]?.hasCreateEvent ?? 0) !== 0,
570 })),
571 );
572
573 const getReplayStats: OrchestrationEventStore["Service"]["getReplayStats"] = (input) =>
574 sql<{ readonly eventCount: number; readonly rawPayloadBytes: number }>`
575 SELECT
576 COUNT(*) AS "eventCount",
577 COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes"
578 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
579 WHERE sequence > ${input.afterSequence}
580 AND sequence <= ${input.throughSequence}
581 AND (
582 aggregate_kind = 'project'
583 OR (application_event_version = 2 AND aggregate_kind = 'thread')
584 )
585 `.pipe(
586 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getReplayStats:query")),
587 Effect.map((rows) => ({
588 eventCount: rows[0]?.eventCount ?? 0,
589 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
590 })),
591 );
592
593 const latestAgentSequence: OrchestrationEventStore["Service"]["latestAgentSequence"] = (
594 threadId,
595 ) =>
596 sql<{ readonly sequence: number | null }>`
597 SELECT MAX(sequence) AS sequence
598 FROM orchestration_events
599 ${
600 threadId === undefined
601 ? sql``
602 : sql`INDEXED BY idx_orchestration_events_agent_stream_sequence`
603 }
604 WHERE application_event_version = 2
605 AND aggregate_kind = 'thread'
606 ${threadId === undefined ? sql`` : sql`AND stream_id = ${threadId}`}
607 `.pipe(
608 Effect.map((rows) => rows[0]?.sequence ?? 0),
609 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")),
610 );
611
612 // The OR planner otherwise scans every V2 event instead of seeking the final sequence.
613 const latestApplicationSequence = sql<{ readonly sequence: number | null }>`
614 SELECT MAX(sequence) AS sequence
615 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
616 WHERE aggregate_kind = 'project'
617 OR (application_event_version = 2 AND aggregate_kind = 'thread')
618 `.pipe(
619 Effect.map((rows) => rows[0]?.sequence ?? 0),
620 Effect.mapError(
621 toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"),
622 ),
623 );
624
625 const readApplicationEventPage = (input: {
626 readonly afterSequence: number;
627 readonly throughSequence: number;
628 readonly limit: number;
629 }): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
630 Stream.fromEffect(
631 readApplicationRows(input).pipe(
632 Effect.mapError(
633 toPersistenceSqlError("OrchestrationEventStore.readApplicationEvents:query"),
634 ),
635 ),
636 ).pipe(
637 Stream.flatMap(Stream.fromIterable),
638 Stream.mapEffect((row) =>
639 rowToApplicationStoredEvent(row).pipe(
640 Effect.mapError(
641 toPersistenceDecodeError("OrchestrationEventStore.readApplicationEvents:decode"),
642 ),
643 ),
644 ),
645 );
646
647 const catchUpApplicationEvents = (input: {
648 readonly afterSequence: number;
649 readonly throughSequence: number;
650 }): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> => {
651 return Stream.paginate(input.afterSequence, (afterSequence) =>
652 readApplicationEventPage({
653 afterSequence,
654 throughSequence: input.throughSequence,
655 limit: READ_PAGE_SIZE,
656 }).pipe(
657 Stream.runCollect,
658 Effect.map((events) => {
659 const last = events.at(-1);
660 return [
661 events,
662 last === undefined ||
663 events.length < READ_PAGE_SIZE ||
664 last.sequence >= input.throughSequence
665 ? Option.none()
666 : Option.some(last.sequence),
667 ] as const;
668 }),
669 ),
670 );
671 };
672
673 const streamProjectedApplicationEvents: OrchestrationEventStore["Service"]["streamProjectedApplicationEvents"] =
674 (input) =>
675 replayAndBufferProjectedLiveEvents({
676 subscribe: PubSub.subscribe(committedEvents),
677 latestSequence: latestApplicationSequence,
678 afterSequence: input.afterSequence ?? 0,
679 project: input.project,
680 replay: (throughSequence) =>
681 catchUpApplicationEvents({
682 afterSequence: input?.afterSequence ?? 0,
683 throughSequence,
684 }),
685 }).pipe(
686 Stream.catchTag("LiveStreamBufferError", (cause) =>
687 Stream.fail(
688 toPersistenceSqlError("OrchestrationEventStore.streamApplicationEvents:buffer")(cause),
689 ),
690 ),
691 );
692
693 const streamApplicationEvents: OrchestrationEventStore["Service"]["streamApplicationEvents"] = (
694 input,
695 ) => streamProjectedApplicationEvents({ ...input, project: (event) => event });
696
697 return {
698 appendProjectEvent,
699 appendAgentEvents,
700 readAgentEvents,
701 getAgentReplayStats,
702 getReplayStats,
703 latestAgentSequence,
704 latestApplicationSequence,
705 readApplicationEvents: catchUpApplicationEvents,
706 publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
707 streamApplicationEvents,
708 streamProjectedApplicationEvents,
709 } satisfies OrchestrationEventStore["Service"];
710});
711
712export const layer = Layer.effect(OrchestrationEventStore, makeEventStore);