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

OrchestrationEventStore.ts

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