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

OrchestrationEventStore.ts

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