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

OrchestrationEventStore.ts

682 lines23.0 KB

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