Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 IsoDateTime,
5 NonNegativeInt,
6 OrchestrationActorKind,
7 OrchestrationAggregateKind,
8 OrchestrationEvent,
9 OrchestrationEventMetadata,
10 OrchestrationEventType,
11 ProjectId,
12 ThreadId,
13} from "@t3tools/contracts";
14import * as SqlClient from "effect/unstable/sql/SqlClient";
15import * as SqlSchema from "effect/unstable/sql/SqlSchema";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20import * as Stream from "effect/Stream";
21
22import {
23 toPersistenceDecodeError,
24 toPersistenceSqlError,
25 type OrchestrationEventStoreError,
26} from "../Errors.ts";
27import {
28 OrchestrationEventStore,
29 type OrchestrationEventStoreShape,
30} from "../Services/OrchestrationEventStore.ts";
31
32const decodeEvent = Schema.decodeUnknownEffect(OrchestrationEvent);
33const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
34const EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetadata);
35
36const AppendEventRequestSchema = Schema.Struct({
37 eventId: EventId,
38 aggregateKind: OrchestrationAggregateKind,
39 streamId: Schema.Union([ProjectId, ThreadId]),
40 type: OrchestrationEventType,
41 causationEventId: Schema.NullOr(EventId),
42 correlationId: Schema.NullOr(CommandId),
43 actorKind: OrchestrationActorKind,
44 occurredAt: IsoDateTime,
45 commandId: Schema.NullOr(CommandId),
46 payloadJson: UnknownFromJsonString,
47 metadataJson: EventMetadataFromJsonString,
48});
49
50const OrchestrationEventPersistedRowSchema = Schema.Struct({
51 sequence: NonNegativeInt,
52 eventId: EventId,
53 type: OrchestrationEventType,
54 aggregateKind: OrchestrationAggregateKind,
55 aggregateId: Schema.Union([ProjectId, ThreadId]),
56 occurredAt: IsoDateTime,
57 commandId: Schema.NullOr(CommandId),
58 causationEventId: Schema.NullOr(EventId),
59 correlationId: Schema.NullOr(CommandId),
60 payload: UnknownFromJsonString,
61 metadata: EventMetadataFromJsonString,
62});
63
64const HasEventAfterRequestSchema = Schema.Struct({
65 aggregateKind: Schema.String,
66 aggregateId: Schema.String,
67 type: Schema.optional(Schema.String),
68 sequenceExclusive: NonNegativeInt,
69});
70
71const ReadFromSequenceRequestSchema = Schema.Struct({
72 sequenceExclusive: NonNegativeInt,
73 limit: Schema.Number,
74});
75const AggregateReplayRequestSchema = Schema.Struct({
76 aggregateKind: OrchestrationAggregateKind,
77 aggregateId: Schema.String,
78 fromSequenceExclusive: NonNegativeInt,
79 toSequenceInclusive: NonNegativeInt,
80 limit: Schema.Number,
81});
82const AggregateReplayStatsRowSchema = Schema.Struct({
83 eventCount: Schema.Number,
84 payloadBytes: Schema.Number,
85 hasCreateEvent: Schema.Number,
86});
87const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
88const READ_PAGE_SIZE = 500;
89
90function inferActorKind(
91 event: Omit<OrchestrationEvent, "sequence">,
92): Schema.Schema.Type<typeof OrchestrationActorKind> {
93 if (event.commandId !== null && event.commandId.startsWith("provider:")) {
94 return "provider";
95 }
96 if (event.commandId !== null && event.commandId.startsWith("server:")) {
97 return "server";
98 }
99 if (
100 event.metadata.providerTurnId !== undefined ||
101 event.metadata.providerItemId !== undefined ||
102 event.metadata.adapterKey !== undefined
103 ) {
104 return "provider";
105 }
106 if (event.commandId === null) {
107 return "server";
108 }
109 return "client";
110}
111
112function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
113 return (cause: unknown): OrchestrationEventStoreError =>
114 Schema.isSchemaError(cause)
115 ? toPersistenceDecodeError(decodeOperation)(cause)
116 : toPersistenceSqlError(sqlOperation)(cause);
117}
118
119const makeEventStore = Effect.gen(function* () {
120 const sql = yield* SqlClient.SqlClient;
121
122 const appendEventRow = SqlSchema.findOne({
123 Request: AppendEventRequestSchema,
124 Result: OrchestrationEventPersistedRowSchema,
125 execute: (request) =>
126 sql`
127 INSERT INTO orchestration_events (
128 event_id,
129 aggregate_kind,
130 stream_id,
131 stream_version,
132 event_type,
133 occurred_at,
134 command_id,
135 causation_event_id,
136 correlation_id,
137 actor_kind,
138 payload_json,
139 metadata_json
140 )
141 VALUES (
142 ${request.eventId},
143 ${request.aggregateKind},
144 ${request.streamId},
145 COALESCE(
146 (
147 SELECT stream_version + 1
148 FROM orchestration_events
149 WHERE aggregate_kind = ${request.aggregateKind}
150 AND stream_id = ${request.streamId}
151 ORDER BY stream_version DESC
152 LIMIT 1
153 ),
154 0
155 ),
156 ${request.type},
157 ${request.occurredAt},
158 ${request.commandId},
159 ${request.causationEventId},
160 ${request.correlationId},
161 ${request.actorKind},
162 ${request.payloadJson},
163 ${request.metadataJson}
164 )
165 RETURNING
166 sequence,
167 event_id AS "eventId",
168 event_type AS "type",
169 aggregate_kind AS "aggregateKind",
170 stream_id AS "aggregateId",
171 occurred_at AS "occurredAt",
172 command_id AS "commandId",
173 causation_event_id AS "causationEventId",
174 correlation_id AS "correlationId",
175 payload_json AS "payload",
176 metadata_json AS "metadata"
177 `,
178 });
179
180 const readEventRowsFromSequence = SqlSchema.findAll({
181 Request: ReadFromSequenceRequestSchema,
182 Result: OrchestrationEventPersistedRowSchema,
183 execute: (request) =>
184 sql`
185 SELECT
186 sequence,
187 event_id AS "eventId",
188 event_type AS "type",
189 aggregate_kind AS "aggregateKind",
190 stream_id AS "aggregateId",
191 occurred_at AS "occurredAt",
192 command_id AS "commandId",
193 causation_event_id AS "causationEventId",
194 correlation_id AS "correlationId",
195 payload_json AS "payload",
196 metadata_json AS "metadata"
197 FROM orchestration_events
198 WHERE sequence > ${request.sequenceExclusive}
199 ORDER BY sequence ASC
200 LIMIT ${request.limit}
201 `,
202 });
203
204 const readAggregateEventRows = SqlSchema.findAll({
205 Request: AggregateReplayRequestSchema,
206 Result: OrchestrationEventPersistedRowSchema,
207 execute: (request) =>
208 sql`
209 SELECT
210 sequence,
211 event_id AS "eventId",
212 event_type AS "type",
213 aggregate_kind AS "aggregateKind",
214 stream_id AS "aggregateId",
215 occurred_at AS "occurredAt",
216 command_id AS "commandId",
217 causation_event_id AS "causationEventId",
218 correlation_id AS "correlationId",
219 payload_json AS "payload",
220 metadata_json AS "metadata"
221 FROM orchestration_events
222 WHERE aggregate_kind = ${request.aggregateKind}
223 AND stream_id = ${request.aggregateId}
224 AND sequence > ${request.fromSequenceExclusive}
225 AND sequence <= ${request.toSequenceInclusive}
226 ORDER BY sequence ASC
227 LIMIT ${request.limit}
228 `,
229 });
230
231 const readAggregateReplayStats = SqlSchema.findOne({
232 Request: AggregateReplayRequestSchema,
233 Result: AggregateReplayStatsRowSchema,
234 execute: (request) =>
235 sql`
236 SELECT
237 COUNT(*) AS "eventCount",
238 COALESCE(SUM(octet_length(payload_json)), 0) AS "payloadBytes",
239 COALESCE(MAX(event_type IN (
240 'thread.created', 'project.created'
241 )), 0) AS "hasCreateEvent"
242 FROM (
243 SELECT payload_json, event_type
244 FROM orchestration_events
245 WHERE aggregate_kind = ${request.aggregateKind}
246 AND stream_id = ${request.aggregateId}
247 AND sequence > ${request.fromSequenceExclusive}
248 AND sequence <= ${request.toSequenceInclusive}
249 ORDER BY sequence ASC
250 LIMIT ${request.limit}
251 )
252 `,
253 });
254
255 const append: OrchestrationEventStoreShape["append"] = (event) =>
256 appendEventRow({
257 eventId: event.eventId,
258 aggregateKind: event.aggregateKind,
259 streamId: event.aggregateId,
260 type: event.type,
261 causationEventId: event.causationEventId,
262 correlationId: event.correlationId,
263 actorKind: inferActorKind(event),
264 occurredAt: event.occurredAt,
265 commandId: event.commandId,
266 payloadJson: event.payload,
267 metadataJson: event.metadata,
268 }).pipe(
269 Effect.mapError(
270 toPersistenceSqlOrDecodeError(
271 "OrchestrationEventStore.append:insert",
272 "OrchestrationEventStore.append:decodeRow",
273 ),
274 ),
275 Effect.flatMap((row) =>
276 decodeEvent(row).pipe(
277 Effect.mapError(toPersistenceDecodeError("OrchestrationEventStore.append:rowToEvent")),
278 ),
279 ),
280 );
281
282 const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
283 sequenceExclusive,
284 limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
285 ) => {
286 const normalizedLimit = Math.max(0, Math.floor(limit));
287 if (normalizedLimit === 0) {
288 return Stream.empty;
289 }
290 return Stream.paginate(
291 { cursor: sequenceExclusive, remaining: normalizedLimit },
292 ({ cursor, remaining }) =>
293 readEventRowsFromSequence({
294 sequenceExclusive: cursor,
295 limit: Math.min(remaining, READ_PAGE_SIZE),
296 }).pipe(
297 Effect.mapError(
298 toPersistenceSqlOrDecodeError(
299 "OrchestrationEventStore.readFromSequence:query",
300 "OrchestrationEventStore.readFromSequence:decodeRows",
301 ),
302 ),
303 Effect.flatMap((rows) =>
304 Effect.forEach(rows, (row) =>
305 decodeEvent(row).pipe(
306 Effect.mapError(
307 toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
308 ),
309 ),
310 ),
311 ),
312 Effect.map((events) => {
313 const last = events.at(-1);
314 const nextRemaining = remaining - events.length;
315 return [
316 events,
317 last === undefined || nextRemaining <= 0
318 ? Option.none()
319 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
320 ] as const;
321 }),
322 ),
323 );
324 };
325
326 const findEventAfter = SqlSchema.findOneOption({
327 Request: HasEventAfterRequestSchema,
328 Result: Schema.Struct({ sequence: Schema.Number }),
329 execute: (request) => sql`
330 SELECT sequence
331 FROM orchestration_events
332 WHERE aggregate_kind = ${request.aggregateKind}
333 AND stream_id = ${request.aggregateId}
334 AND ${sql.and([
335 sql`sequence > ${request.sequenceExclusive}`,
336 ...(request.type === undefined ? [] : [sql`event_type = ${request.type}`]),
337 ])}
338 LIMIT 1
339 `,
340 });
341
342 const hasEventAfter: OrchestrationEventStoreShape["hasEventAfter"] = (input) =>
343 findEventAfter(input).pipe(
344 Effect.map(Option.isSome),
345 Effect.mapError(
346 toPersistenceSqlOrDecodeError(
347 "OrchestrationEventStore.hasEventAfter:query",
348 "OrchestrationEventStore.hasEventAfter:decodeRow",
349 ),
350 ),
351 );
352
353 const readAggregateRange: OrchestrationEventStoreShape["readAggregateRange"] = (input) => {
354 const limit = Math.max(0, Math.floor(input.limit ?? DEFAULT_READ_FROM_SEQUENCE_LIMIT));
355 if (limit === 0 || input.fromSequenceExclusive >= input.toSequenceInclusive) {
356 return Stream.empty;
357 }
358 return Stream.paginate(
359 { cursor: input.fromSequenceExclusive, remaining: limit },
360 ({ cursor, remaining }) =>
361 readAggregateEventRows({
362 ...input,
363 fromSequenceExclusive: cursor,
364 limit: Math.min(remaining, READ_PAGE_SIZE),
365 }).pipe(
366 Effect.mapError(
367 toPersistenceSqlOrDecodeError(
368 "OrchestrationEventStore.readAggregateRange:query",
369 "OrchestrationEventStore.readAggregateRange:decodeRows",
370 ),
371 ),
372 Effect.flatMap((rows) =>
373 Effect.forEach(rows, (row) =>
374 decodeEvent(row).pipe(
375 Effect.mapError(
376 toPersistenceDecodeError("OrchestrationEventStore.readAggregateRange:rowToEvent"),
377 ),
378 ),
379 ),
380 ),
381 Effect.map((events) => {
382 const last = events.at(-1);
383 const nextRemaining = remaining - events.length;
384 return [
385 events,
386 last === undefined ||
387 events.length < READ_PAGE_SIZE ||
388 nextRemaining === 0 ||
389 last.sequence >= input.toSequenceInclusive
390 ? Option.none()
391 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
392 ] as const;
393 }),
394 ),
395 );
396 };
397
398 const getAggregateReplayStats: OrchestrationEventStoreShape["getAggregateReplayStats"] = (
399 input,
400 ) =>
401 readAggregateReplayStats({
402 ...input,
403 limit: Math.max(0, Math.floor(input.maxEvents)) + 1,
404 }).pipe(
405 Effect.mapError(
406 toPersistenceSqlOrDecodeError(
407 "OrchestrationEventStore.getAggregateReplayStats:query",
408 "OrchestrationEventStore.getAggregateReplayStats:decodeRow",
409 ),
410 ),
411 Effect.map((row) => ({ ...row, hasCreateEvent: row.hasCreateEvent !== 0 })),
412 );
413
414 return {
415 append,
416 readFromSequence,
417 readAggregateRange,
418 getAggregateReplayStats,
419 readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
420 hasEventAfter,
421 } satisfies OrchestrationEventStoreShape;
422});
423
424export const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore);