Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OrchestrationEventStore.ts

306 lines9.4 KB

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 DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
76const READ_PAGE_SIZE = 500;
77​
78function inferActorKind(
79 event: Omit<OrchestrationEvent, "sequence">,
80): Schema.Schema.Type<typeof OrchestrationActorKind> {
81 if (event.commandId !== null && event.commandId.startsWith("provider:")) {
82 return "provider";
83 }
84 if (event.commandId !== null && event.commandId.startsWith("server:")) {
85 return "server";
86 }
87 if (
88 event.metadata.providerTurnId !== undefined ||
89 event.metadata.providerItemId !== undefined ||
90 event.metadata.adapterKey !== undefined
91 ) {
92 return "provider";
93 }
94 if (event.commandId === null) {
95 return "server";
96 }
97 return "client";
99​
100function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
101 return (cause: unknown): OrchestrationEventStoreError =>
102 Schema.isSchemaError(cause)
103 ? toPersistenceDecodeError(decodeOperation)(cause)
104 : toPersistenceSqlError(sqlOperation)(cause);
106​
107const makeEventStore = Effect.gen(function* () {
108 const sql = yield* SqlClient.SqlClient;
109​
110 const appendEventRow = SqlSchema.findOne({
111 Request: AppendEventRequestSchema,
112 Result: OrchestrationEventPersistedRowSchema,
113 execute: (request) =>
114 sql`
115 INSERT INTO orchestration_events (
116 event_id,
117 aggregate_kind,
118 stream_id,
119 stream_version,
120 event_type,
121 occurred_at,
122 command_id,
123 causation_event_id,
124 correlation_id,
125 actor_kind,
126 payload_json,
127 metadata_json
128 )
129 VALUES (
130 ${request.eventId},
131 ${request.aggregateKind},
132 ${request.streamId},
133 COALESCE(
134 (
135 SELECT stream_version + 1
136 FROM orchestration_events
137 WHERE aggregate_kind = ${request.aggregateKind}
138 AND stream_id = ${request.streamId}
139 ORDER BY stream_version DESC
140 LIMIT 1
141 ),
142 0
143 ),
144 ${request.type},
145 ${request.occurredAt},
146 ${request.commandId},
147 ${request.causationEventId},
148 ${request.correlationId},
149 ${request.actorKind},
150 ${request.payloadJson},
151 ${request.metadataJson}
152 )
153 RETURNING
154 sequence,
155 event_id AS "eventId",
156 event_type AS "type",
157 aggregate_kind AS "aggregateKind",
158 stream_id AS "aggregateId",
159 occurred_at AS "occurredAt",
160 command_id AS "commandId",
161 causation_event_id AS "causationEventId",
162 correlation_id AS "correlationId",
163 payload_json AS "payload",
164 metadata_json AS "metadata"
165 `,
166 });
167​
168 const readEventRowsFromSequence = SqlSchema.findAll({
169 Request: ReadFromSequenceRequestSchema,
170 Result: OrchestrationEventPersistedRowSchema,
171 execute: (request) =>
172 sql`
173 SELECT
174 sequence,
175 event_id AS "eventId",
176 event_type AS "type",
177 aggregate_kind AS "aggregateKind",
178 stream_id AS "aggregateId",
179 occurred_at AS "occurredAt",
180 command_id AS "commandId",
181 causation_event_id AS "causationEventId",
182 correlation_id AS "correlationId",
183 payload_json AS "payload",
184 metadata_json AS "metadata"
185 FROM orchestration_events
186 WHERE sequence > ${request.sequenceExclusive}
187 ORDER BY sequence ASC
188 LIMIT ${request.limit}
189 `,
190 });
191​
192 const append: OrchestrationEventStoreShape["append"] = (event) =>
193 appendEventRow({
194 eventId: event.eventId,
195 aggregateKind: event.aggregateKind,
196 streamId: event.aggregateId,
197 type: event.type,
198 causationEventId: event.causationEventId,
199 correlationId: event.correlationId,
200 actorKind: inferActorKind(event),
201 occurredAt: event.occurredAt,
202 commandId: event.commandId,
203 payloadJson: event.payload,
204 metadataJson: event.metadata,
205 }).pipe(
206 Effect.mapError(
207 toPersistenceSqlOrDecodeError(
208 "OrchestrationEventStore.append:insert",
209 "OrchestrationEventStore.append:decodeRow",
210 ),
211 ),
212 Effect.flatMap((row) =>
213 decodeEvent(row).pipe(
214 Effect.mapError(toPersistenceDecodeError("OrchestrationEventStore.append:rowToEvent")),
215 ),
216 ),
217 );
218​
219 const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
220 sequenceExclusive,
221 limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
222 ) => {
223 const normalizedLimit = Math.max(0, Math.floor(limit));
224 if (normalizedLimit === 0) {
225 return Stream.empty;
226 }
227 const readPage = (
228 cursor: number,
229 remaining: number,
230 ): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
231 Stream.fromEffect(
232 readEventRowsFromSequence({
233 sequenceExclusive: cursor,
234 limit: Math.min(remaining, READ_PAGE_SIZE),
235 }).pipe(
236 Effect.mapError(
237 toPersistenceSqlOrDecodeError(
238 "OrchestrationEventStore.readFromSequence:query",
239 "OrchestrationEventStore.readFromSequence:decodeRows",
240 ),
241 ),
242 Effect.flatMap((rows) =>
243 Effect.forEach(rows, (row) =>
244 decodeEvent(row).pipe(
245 Effect.mapError(
246 toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
247 ),
248 ),
249 ),
250 ),
251 ),
252 ).pipe(
253 Stream.flatMap((events) => {
254 if (events.length === 0) {
255 return Stream.empty;
256 }
257 const nextRemaining = remaining - events.length;
258 if (nextRemaining <= 0) {
259 return Stream.fromIterable(events);
260 }
261 return Stream.concat(
262 Stream.fromIterable(events),
263 readPage(events[events.length - 1]!.sequence, nextRemaining),
264 );
265 }),
266 );
267​
268 return readPage(sequenceExclusive, normalizedLimit);
269 };
270​
271 const findEventAfter = SqlSchema.findOneOption({
272 Request: HasEventAfterRequestSchema,
273 Result: Schema.Struct({ sequence: Schema.Number }),
274 execute: (request) => sql`
275 SELECT sequence
276 FROM orchestration_events
277 WHERE aggregate_kind = ${request.aggregateKind}
278 AND stream_id = ${request.aggregateId}
279 AND ${sql.and([
280 sql`sequence > ${request.sequenceExclusive}`,
281 ...(request.type === undefined ? [] : [sql`event_type = ${request.type}`]),
282 ])}
283 LIMIT 1
284 `,
285 });
286​
287 const hasEventAfter: OrchestrationEventStoreShape["hasEventAfter"] = (input) =>
288 findEventAfter(input).pipe(
289 Effect.map(Option.isSome),
290 Effect.mapError(
291 toPersistenceSqlOrDecodeError(
292 "OrchestrationEventStore.hasEventAfter:query",
293 "OrchestrationEventStore.hasEventAfter:decodeRow",
294 ),
295 ),
296 );
297​
298 return {
299 append,
300 readFromSequence,
301 readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
302 hasEventAfter,
303 } satisfies OrchestrationEventStoreShape;
304});
305​
306export const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore);