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