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 const readPage = (
291 cursor: number,
292 remaining: number,
293 ): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
294 Stream.fromEffect(
295 readEventRowsFromSequence({
296 sequenceExclusive: cursor,
297 limit: Math.min(remaining, READ_PAGE_SIZE),
298 }).pipe(
299 Effect.mapError(
300 toPersistenceSqlOrDecodeError(
301 "OrchestrationEventStore.readFromSequence:query",
302 "OrchestrationEventStore.readFromSequence:decodeRows",
303 ),
304 ),
305 Effect.flatMap((rows) =>
306 Effect.forEach(rows, (row) =>
307 decodeEvent(row).pipe(
308 Effect.mapError(
309 toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
310 ),
311 ),
312 ),
313 ),
314 ),
315 ).pipe(
316 Stream.flatMap((events) => {
317 if (events.length === 0) {
318 return Stream.empty;
319 }
320 const nextRemaining = remaining - events.length;
321 if (nextRemaining <= 0) {
322 return Stream.fromIterable(events);
323 }
324 return Stream.concat(
325 Stream.fromIterable(events),
326 readPage(events[events.length - 1]!.sequence, nextRemaining),
327 );
328 }),
329 );
330
331 return readPage(sequenceExclusive, normalizedLimit);
332 };
333
334 const findEventAfter = SqlSchema.findOneOption({
335 Request: HasEventAfterRequestSchema,
336 Result: Schema.Struct({ sequence: Schema.Number }),
337 execute: (request) => sql`
338 SELECT sequence
339 FROM orchestration_events
340 WHERE aggregate_kind = ${request.aggregateKind}
341 AND stream_id = ${request.aggregateId}
342 AND ${sql.and([
343 sql`sequence > ${request.sequenceExclusive}`,
344 ...(request.type === undefined ? [] : [sql`event_type = ${request.type}`]),
345 ])}
346 LIMIT 1
347 `,
348 });
349
350 const hasEventAfter: OrchestrationEventStoreShape["hasEventAfter"] = (input) =>
351 findEventAfter(input).pipe(
352 Effect.map(Option.isSome),
353 Effect.mapError(
354 toPersistenceSqlOrDecodeError(
355 "OrchestrationEventStore.hasEventAfter:query",
356 "OrchestrationEventStore.hasEventAfter:decodeRow",
357 ),
358 ),
359 );
360
361 const readAggregateRange: OrchestrationEventStoreShape["readAggregateRange"] = (input) => {
362 const limit = Math.max(0, Math.floor(input.limit ?? DEFAULT_READ_FROM_SEQUENCE_LIMIT));
363 if (limit === 0 || input.fromSequenceExclusive >= input.toSequenceInclusive) {
364 return Stream.empty;
365 }
366 const readPage = (
367 cursor: number,
368 remaining: number,
369 ): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
370 Stream.fromEffect(
371 readAggregateEventRows({
372 ...input,
373 fromSequenceExclusive: cursor,
374 limit: Math.min(remaining, READ_PAGE_SIZE),
375 }).pipe(
376 Effect.mapError(
377 toPersistenceSqlOrDecodeError(
378 "OrchestrationEventStore.readAggregateRange:query",
379 "OrchestrationEventStore.readAggregateRange:decodeRows",
380 ),
381 ),
382 Effect.flatMap((rows) =>
383 Effect.forEach(rows, (row) =>
384 decodeEvent(row).pipe(
385 Effect.mapError(
386 toPersistenceDecodeError("OrchestrationEventStore.readAggregateRange:rowToEvent"),
387 ),
388 ),
389 ),
390 ),
391 ),
392 ).pipe(
393 Stream.flatMap((events) => {
394 const last = events.at(-1);
395 if (last === undefined) {
396 return Stream.empty;
397 }
398 const nextRemaining = remaining - events.length;
399 if (
400 events.length < READ_PAGE_SIZE ||
401 nextRemaining === 0 ||
402 last.sequence >= input.toSequenceInclusive
403 ) {
404 return Stream.fromIterable(events);
405 }
406 return Stream.concat(Stream.fromIterable(events), readPage(last.sequence, nextRemaining));
407 }),
408 );
409 return readPage(input.fromSequenceExclusive, limit);
410 };
411
412 const getAggregateReplayStats: OrchestrationEventStoreShape["getAggregateReplayStats"] = (
413 input,
414 ) =>
415 readAggregateReplayStats({
416 ...input,
417 limit: Math.max(0, Math.floor(input.maxEvents)) + 1,
418 }).pipe(
419 Effect.mapError(
420 toPersistenceSqlOrDecodeError(
421 "OrchestrationEventStore.getAggregateReplayStats:query",
422 "OrchestrationEventStore.getAggregateReplayStats:decodeRow",
423 ),
424 ),
425 Effect.map((row) => ({ ...row, hasCreateEvent: row.hasCreateEvent !== 0 })),
426 );
427
428 return {
429 append,
430 readFromSequence,
431 readAggregateRange,
432 getAggregateReplayStats,
433 readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
434 hasEventAfter,
435 } satisfies OrchestrationEventStoreShape;
436});
437
438export const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore);