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

OrchestrationEventStore.ts

696 lines23.4 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 return Stream.paginate(
330 { cursor: sequenceExclusive, remaining: normalizedLimit },
331 ({ cursor, remaining }) =>
332 readEventRowsFromSequence({
333 sequenceExclusive: cursor,
334 limit: Math.min(remaining, READ_PAGE_SIZE),
335 }).pipe(
336 Effect.mapError(
337 toPersistenceSqlOrDecodeError(
338 "OrchestrationEventStore.readFromSequence:query",
339 "OrchestrationEventStore.readFromSequence:decodeRows",
340 ),
341 ),
342 Effect.flatMap((rows) =>
343 Effect.forEach(rows, (row) =>
344 decodeEvent(row).pipe(
345 Effect.mapError(
346 toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
347 ),
348 ),
349 ),
350 ),
351 Effect.map((events) => {
352 const last = events.at(-1);
353 const nextRemaining = remaining - events.length;
354 return [
355 events,
356 last === undefined || nextRemaining <= 0
357 ? Option.none()
358 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
359 ] as const;
360 }),
361 ),
362 );
363 };
364​
365 const readApplicationRows = (input: {
366 readonly afterSequence: number;
367 readonly throughSequence?: number;
368 readonly threadId?: ThreadId;
369 readonly commandId?: CommandId;
370 readonly onlyAgentEvents?: boolean;
371 readonly limit: number;
372 }) =>
373 sql<ApplicationEventRow>`
374 SELECT
375 sequence,
376 event_id,
377 command_id,
378 aggregate_kind,
379 stream_id,
380 event_type,
381 occurred_at,
382 payload_json,
383 metadata_json,
384 application_event_version,
385 causation_event_id,
386 correlation_id
387 FROM orchestration_events
388 ${
389 input.onlyAgentEvents === true
390 ? sql``
391 : sql`INDEXED BY idx_orchestration_events_application_high_water`
392 }
393 WHERE sequence > ${input.afterSequence}
394 AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER}
395 AND (
396 ${
397 input.onlyAgentEvents === true
398 ? sql`application_event_version = 2 AND aggregate_kind = 'thread'`
399 : sql`aggregate_kind = 'project'
400 OR (application_event_version = 2 AND aggregate_kind = 'thread')`
401 }
402 )
403 AND ${sql.and([
404 ...(input.threadId === undefined ? [] : [sql`stream_id = ${input.threadId}`]),
405 ...(input.commandId === undefined ? [] : [sql`command_id = ${input.commandId}`]),
406 ])}
407 ORDER BY sequence ASC
408 LIMIT ${input.limit}
409 `;
410​
411 const appendAgentEvents: OrchestrationEventStoreShape["appendAgentEvents"] = (input) =>
412 Effect.forEach(
413 input.events,
414 (event) =>
415 Effect.gen(function* () {
416 const encoded = yield* encodeV2EventJson(event);
417 const rows = yield* sql<{ readonly sequence: number }>`
418 INSERT INTO orchestration_events (
419 event_id,
420 aggregate_kind,
421 stream_id,
422 stream_version,
423 event_type,
424 occurred_at,
425 command_id,
426 causation_event_id,
427 correlation_id,
428 actor_kind,
429 payload_json,
430 metadata_json,
431 application_event_version
432 )
433 VALUES (
434 ${event.id},
435 'thread',
436 ${event.threadId},
437 COALESCE(
438 (
439 SELECT MAX(stream_version) + 1
440 FROM orchestration_events
441 WHERE aggregate_kind = 'thread' AND stream_id = ${event.threadId}
442 ),
443 0
444 ),
445 ${event.type},
446 ${encoded.occurredAt},
447 ${input.commandId ?? null},
448 NULL,
449 ${input.commandId ?? null},
450 ${event.rawEventId === undefined ? "server" : "provider"},
451 ${yield* encodeJson(encoded.payload)},
452 ${yield* encodeJson(metadataForV2Event(event))},
453 2
454 )
455 RETURNING sequence
456 `;
457 return yield* decodeV2StoredEvent({
458 sequence: rows[0]?.sequence,
459 commandId: input.commandId ?? null,
460 event,
461 });
462 }),
463 { concurrency: 1 },
464 ).pipe(
465 Effect.mapError(
466 toPersistenceSqlOrDecodeError(
467 "OrchestrationEventStore.appendAgentEvents:insert",
468 "OrchestrationEventStore.appendAgentEvents:decode",
469 ),
470 ),
471 );
472​
473 const readAgentEvents: OrchestrationEventStoreShape["readAgentEvents"] = (input) => {
474 const totalLimit =
475 input?.limit === undefined ? Number.MAX_SAFE_INTEGER : Math.max(0, Math.floor(input.limit));
476 if (totalLimit === 0) {
477 return Stream.empty;
478 }
479 return Stream.paginate(
480 { cursor: input?.afterSequence ?? 0, remaining: totalLimit },
481 ({ cursor, remaining }) => {
482 const pageLimit = Math.min(remaining, READ_PAGE_SIZE);
483 return readApplicationRows({
484 afterSequence: cursor,
485 ...(input?.throughSequence === undefined
486 ? {}
487 : { throughSequence: input.throughSequence }),
488 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
489 ...(input?.commandId === undefined ? {} : { commandId: input.commandId }),
490 onlyAgentEvents: true,
491 limit: pageLimit,
492 }).pipe(
493 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")),
494 Effect.map((rows) => {
495 const last = rows.at(-1);
496 const nextRemaining = remaining - rows.length;
497 return [
498 rows,
499 last === undefined ||
500 rows.length < pageLimit ||
501 nextRemaining <= 0 ||
502 (input?.throughSequence !== undefined && last.sequence >= input.throughSequence)
503 ? Option.none()
504 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
505 ] as const;
506 }),
507 );
508 },
509 ).pipe(
510 Stream.mapEffect((row) =>
511 rowToV2StoredEvent(row).pipe(
512 Effect.mapError(
513 toPersistenceDecodeError("OrchestrationEventStore.readAgentEvents:decode"),
514 ),
515 ),
516 ),
517 );
518 };
519​
520 const getAgentReplayStats: OrchestrationEventStoreShape["getAgentReplayStats"] = (input) =>
521 sql<{
522 readonly eventCount: number;
523 readonly rawPayloadBytes: number;
524 readonly hasCreateEvent: number;
525 }>`
526 SELECT
527 COUNT(*) AS "eventCount",
528 COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes",
529 COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent"
530 FROM (
531 SELECT payload_json, event_type
532 FROM orchestration_events
533 WHERE aggregate_kind = 'thread'
534 AND stream_id = ${input.threadId}
535 AND application_event_version = 2
536 AND sequence > ${input.afterSequence}
537 AND sequence <= ${input.throughSequence}
538 ORDER BY sequence ASC
539 LIMIT ${Math.max(0, Math.floor(input.maxEvents)) + 1}
540 )
541 `.pipe(
542 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getAgentReplayStats:query")),
543 Effect.map((rows) => ({
544 eventCount: rows[0]?.eventCount ?? 0,
545 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
546 hasCreateEvent: (rows[0]?.hasCreateEvent ?? 0) !== 0,
547 })),
548 );
549​
550 const latestAgentSequence: OrchestrationEventStoreShape["latestAgentSequence"] = (threadId) =>
551 sql<{ readonly sequence: number | null }>`
552 SELECT MAX(sequence) AS sequence
553 FROM orchestration_events
554 ${
555 threadId === undefined
556 ? sql``
557 : sql`INDEXED BY idx_orchestration_events_agent_stream_sequence`
558 }
559 WHERE application_event_version = 2
560 AND aggregate_kind = 'thread'
561 ${threadId === undefined ? sql`` : sql`AND stream_id = ${threadId}`}
562 `.pipe(
563 Effect.map((rows) => rows[0]?.sequence ?? 0),
564 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")),
565 );
566​
567 // The OR planner otherwise scans every V2 event instead of seeking the final sequence.
568 const latestApplicationSequence = sql<{ readonly sequence: number | null }>`
569 SELECT MAX(sequence) AS sequence
570 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
571 WHERE aggregate_kind = 'project'
572 OR (application_event_version = 2 AND aggregate_kind = 'thread')
573 `.pipe(
574 Effect.map((rows) => rows[0]?.sequence ?? 0),
575 Effect.mapError(
576 toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"),
577 ),
578 );
579​
580 const readApplicationEventPage = (input: {
581 readonly afterSequence: number;
582 readonly throughSequence: number;
583 readonly limit: number;
584 }): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
585 Stream.fromEffect(
586 readApplicationRows(input).pipe(
587 Effect.mapError(
588 toPersistenceSqlError("OrchestrationEventStore.readApplicationEvents:query"),
589 ),
590 ),
591 ).pipe(
592 Stream.flatMap(Stream.fromIterable),
593 Stream.mapEffect((row) =>
594 rowToApplicationStoredEvent(row).pipe(
595 Effect.mapError(
596 toPersistenceDecodeError("OrchestrationEventStore.readApplicationEvents:decode"),
597 ),
598 ),
599 ),
600 );
601​
602 const catchUpApplicationEvents = (input: {
603 readonly afterSequence: number;
604 readonly throughSequence: number;
605 }): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> => {
606 return Stream.paginate(input.afterSequence, (afterSequence) =>
607 readApplicationEventPage({
608 afterSequence,
609 throughSequence: input.throughSequence,
610 limit: READ_PAGE_SIZE,
611 }).pipe(
612 Stream.runCollect,
613 Effect.map((events) => {
614 const last = events.at(-1);
615 return [
616 events,
617 last === undefined ||
618 events.length < READ_PAGE_SIZE ||
619 last.sequence >= input.throughSequence
620 ? Option.none()
621 : Option.some(last.sequence),
622 ] as const;
623 }),
624 ),
625 );
626 };
627​
628 const streamProjectedApplicationEvents: OrchestrationEventStoreShape["streamProjectedApplicationEvents"] =
629 (input) =>
630 replayAndBufferProjectedLiveEvents({
631 subscribe: PubSub.subscribe(committedEvents),
632 latestSequence: latestApplicationSequence,
633 afterSequence: input.afterSequence ?? 0,
634 project: input.project,
635 replay: (throughSequence) =>
636 catchUpApplicationEvents({
637 afterSequence: input?.afterSequence ?? 0,
638 throughSequence,
639 }),
640 }).pipe(
641 Stream.catchTag("LiveStreamBufferError", (cause) =>
642 Stream.fail(
643 toPersistenceSqlError("OrchestrationEventStore.streamApplicationEvents:buffer")(cause),
644 ),
645 ),
646 );
647​
648 const streamApplicationEvents: OrchestrationEventStoreShape["streamApplicationEvents"] = (
649 input,
650 ) => streamProjectedApplicationEvents({ ...input, project: (event) => event });
651​
652 const findEventAfter = SqlSchema.findOneOption({
653 Request: HasEventAfterRequestSchema,
654 Result: Schema.Struct({ sequence: Schema.Number }),
655 execute: (request) => sql`
656 SELECT sequence
657 FROM orchestration_events
658 WHERE aggregate_kind = ${request.aggregateKind}
659 AND stream_id = ${request.aggregateId}
660 AND ${sql.and([
661 sql`sequence > ${request.sequenceExclusive}`,
662 ...(request.type === undefined ? [] : [sql`event_type = ${request.type}`]),
663 ])}
664 LIMIT 1
665 `,
666 });
667​
668 const hasEventAfter: OrchestrationEventStoreShape["hasEventAfter"] = (input) =>
669 findEventAfter(input).pipe(
670 Effect.map(Option.isSome),
671 Effect.mapError(
672 toPersistenceSqlOrDecodeError(
673 "OrchestrationEventStore.hasEventAfter:query",
674 "OrchestrationEventStore.hasEventAfter:decodeRow",
675 ),
676 ),
677 );
678​
679 return {
680 append,
681 readFromSequence,
682 readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
683 appendAgentEvents,
684 readAgentEvents,
685 getAgentReplayStats,
686 latestAgentSequence,
687 latestApplicationSequence,
688 readApplicationEvents: catchUpApplicationEvents,
689 publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
690 streamApplicationEvents,
691 streamProjectedApplicationEvents,
692 hasEventAfter,
693 } satisfies OrchestrationEventStoreShape;
694});
695​
696export const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore);