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

OrchestrationEventStore.ts

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