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