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