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