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 Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20
21import {
22 toPersistenceDecodeError,
23 toPersistenceSqlError,
24 type OrchestrationEventStoreError,
25} from "../Errors.ts";
26import {
27 OrchestrationEventStore,
28 type OrchestrationEventStoreShape,
29} from "../Services/OrchestrationEventStore.ts";
30
31const decodeEvent = Schema.decodeUnknownEffect(OrchestrationEvent);
32const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
33const EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetadata);
34
35const AppendEventRequestSchema = Schema.Struct({
36 eventId: EventId,
37 aggregateKind: OrchestrationAggregateKind,
38 streamId: Schema.Union([ProjectId, ThreadId]),
39 type: OrchestrationEventType,
40 causationEventId: Schema.NullOr(EventId),
41 correlationId: Schema.NullOr(CommandId),
42 actorKind: OrchestrationActorKind,
43 occurredAt: IsoDateTime,
44 commandId: Schema.NullOr(CommandId),
45 payloadJson: UnknownFromJsonString,
46 metadataJson: EventMetadataFromJsonString,
47});
48
49const OrchestrationEventPersistedRowSchema = Schema.Struct({
50 sequence: NonNegativeInt,
51 eventId: EventId,
52 type: OrchestrationEventType,
53 aggregateKind: OrchestrationAggregateKind,
54 aggregateId: Schema.Union([ProjectId, ThreadId]),
55 occurredAt: IsoDateTime,
56 commandId: Schema.NullOr(CommandId),
57 causationEventId: Schema.NullOr(EventId),
58 correlationId: Schema.NullOr(CommandId),
59 payload: UnknownFromJsonString,
60 metadata: EventMetadataFromJsonString,
61});
62
63const ReadFromSequenceRequestSchema = Schema.Struct({
64 sequenceExclusive: NonNegativeInt,
65 limit: Schema.Number,
66});
67const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
68const READ_PAGE_SIZE = 500;
69
70function inferActorKind(
71 event: Omit<OrchestrationEvent, "sequence">,
72): Schema.Schema.Type<typeof OrchestrationActorKind> {
73 if (event.commandId !== null && event.commandId.startsWith("provider:")) {
74 return "provider";
75 }
76 if (event.commandId !== null && event.commandId.startsWith("server:")) {
77 return "server";
78 }
79 if (
80 event.metadata.providerTurnId !== undefined ||
81 event.metadata.providerItemId !== undefined ||
82 event.metadata.adapterKey !== undefined
83 ) {
84 return "provider";
85 }
86 if (event.commandId === null) {
87 return "server";
88 }
89 return "client";
90}
91
92function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
93 return (cause: unknown): OrchestrationEventStoreError =>
94 Schema.isSchemaError(cause)
95 ? toPersistenceDecodeError(decodeOperation)(cause)
96 : toPersistenceSqlError(sqlOperation)(cause);
97}
98
99const makeEventStore = Effect.gen(function* () {
100 const sql = yield* SqlClient.SqlClient;
101
102 const appendEventRow = SqlSchema.findOne({
103 Request: AppendEventRequestSchema,
104 Result: OrchestrationEventPersistedRowSchema,
105 execute: (request) =>
106 sql`
107 INSERT INTO orchestration_events (
108 event_id,
109 aggregate_kind,
110 stream_id,
111 stream_version,
112 event_type,
113 occurred_at,
114 command_id,
115 causation_event_id,
116 correlation_id,
117 actor_kind,
118 payload_json,
119 metadata_json
120 )
121 VALUES (
122 ${request.eventId},
123 ${request.aggregateKind},
124 ${request.streamId},
125 COALESCE(
126 (
127 SELECT stream_version + 1
128 FROM orchestration_events
129 WHERE aggregate_kind = ${request.aggregateKind}
130 AND stream_id = ${request.streamId}
131 ORDER BY stream_version DESC
132 LIMIT 1
133 ),
134 0
135 ),
136 ${request.type},
137 ${request.occurredAt},
138 ${request.commandId},
139 ${request.causationEventId},
140 ${request.correlationId},
141 ${request.actorKind},
142 ${request.payloadJson},
143 ${request.metadataJson}
144 )
145 RETURNING
146 sequence,
147 event_id AS "eventId",
148 event_type AS "type",
149 aggregate_kind AS "aggregateKind",
150 stream_id AS "aggregateId",
151 occurred_at AS "occurredAt",
152 command_id AS "commandId",
153 causation_event_id AS "causationEventId",
154 correlation_id AS "correlationId",
155 payload_json AS "payload",
156 metadata_json AS "metadata"
157 `,
158 });
159
160 const readEventRowsFromSequence = SqlSchema.findAll({
161 Request: ReadFromSequenceRequestSchema,
162 Result: OrchestrationEventPersistedRowSchema,
163 execute: (request) =>
164 sql`
165 SELECT
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 FROM orchestration_events
178 WHERE sequence > ${request.sequenceExclusive}
179 ORDER BY sequence ASC
180 LIMIT ${request.limit}
181 `,
182 });
183
184 const append: OrchestrationEventStoreShape["append"] = (event) =>
185 appendEventRow({
186 eventId: event.eventId,
187 aggregateKind: event.aggregateKind,
188 streamId: event.aggregateId,
189 type: event.type,
190 causationEventId: event.causationEventId,
191 correlationId: event.correlationId,
192 actorKind: inferActorKind(event),
193 occurredAt: event.occurredAt,
194 commandId: event.commandId,
195 payloadJson: event.payload,
196 metadataJson: event.metadata,
197 }).pipe(
198 Effect.mapError(
199 toPersistenceSqlOrDecodeError(
200 "OrchestrationEventStore.append:insert",
201 "OrchestrationEventStore.append:decodeRow",
202 ),
203 ),
204 Effect.flatMap((row) =>
205 decodeEvent(row).pipe(
206 Effect.mapError(toPersistenceDecodeError("OrchestrationEventStore.append:rowToEvent")),
207 ),
208 ),
209 );
210
211 const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
212 sequenceExclusive,
213 limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
214 ) => {
215 const normalizedLimit = Math.max(0, Math.floor(limit));
216 if (normalizedLimit === 0) {
217 return Stream.empty;
218 }
219 const readPage = (
220 cursor: number,
221 remaining: number,
222 ): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
223 Stream.fromEffect(
224 readEventRowsFromSequence({
225 sequenceExclusive: cursor,
226 limit: Math.min(remaining, READ_PAGE_SIZE),
227 }).pipe(
228 Effect.mapError(
229 toPersistenceSqlOrDecodeError(
230 "OrchestrationEventStore.readFromSequence:query",
231 "OrchestrationEventStore.readFromSequence:decodeRows",
232 ),
233 ),
234 Effect.flatMap((rows) =>
235 Effect.forEach(rows, (row) =>
236 decodeEvent(row).pipe(
237 Effect.mapError(
238 toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
239 ),
240 ),
241 ),
242 ),
243 ),
244 ).pipe(
245 Stream.flatMap((events) => {
246 if (events.length === 0) {
247 return Stream.empty;
248 }
249 const nextRemaining = remaining - events.length;
250 if (nextRemaining <= 0) {
251 return Stream.fromIterable(events);
252 }
253 return Stream.concat(
254 Stream.fromIterable(events),
255 readPage(events[events.length - 1]!.sequence, nextRemaining),
256 );
257 }),
258 );
259
260 return readPage(sequenceExclusive, normalizedLimit);
261 };
262
263 return {
264 append,
265 readFromSequence,
266 readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
267 } satisfies OrchestrationEventStoreShape;
268});
269
270export const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore);