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

ProviderSessionRuntime.ts

386 lines12.7 KB

1import * as Arr from "effect/Array";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Result from "effect/Result";
7import * as Schema from "effect/Schema";
8import * as Struct from "effect/Struct";
9import * as SqlClient from "effect/unstable/sql/SqlClient";
10import * as SqlSchema from "effect/unstable/sql/SqlSchema";
11​
12import {
13 IsoDateTime,
14 ProviderInstanceId,
15 ProviderSessionRuntimeStatus,
16 RuntimeMode,
17 ThreadId,
18} from "@t3tools/contracts";
19​
20import {
21 PersistenceDecodeError,
22 type PersistenceErrorCorrelation,
23 PersistenceSqlError,
24 type ProviderSessionRuntimeRepositoryError,
25} from "./Errors.ts";
26​
27/**
28 * ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.
29 *
30 * Owns persistence operations for provider runtime metadata and resume cursors.
31 *
32 * @module ProviderSessionRuntimeRepository
33 */
34​
35export const ProviderSessionRuntime = Schema.Struct({
36 threadId: ThreadId,
37 providerName: Schema.String,
38 /**
39 * User-defined routing key for the configured provider instance that
40 * owns this session. Nullable only at the storage/migration boundary:
41 * rows persisted before the driver/instance split carry only
42 * `providerName`. Repository consumers must materialize a concrete
43 * instance id before routing.
44 */
45 providerInstanceId: Schema.NullOr(ProviderInstanceId),
46 adapterKey: Schema.String,
47 runtimeMode: RuntimeMode,
48 status: ProviderSessionRuntimeStatus,
49 lastSeenAt: IsoDateTime,
50 resumeCursor: Schema.NullOr(Schema.Unknown),
51 runtimePayload: Schema.NullOr(Schema.Unknown),
52});
53export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
54​
55export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
56export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
57​
58export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
59export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
60​
61export const UpdateProviderSessionRuntimeResumeCursorInput = Schema.Struct({
62 threadId: ThreadId,
63 providerInstanceId: ProviderInstanceId,
64 lastSeenAt: IsoDateTime,
65 resumeCursor: Schema.Unknown,
66});
67export type UpdateProviderSessionRuntimeResumeCursorInput =
68 typeof UpdateProviderSessionRuntimeResumeCursorInput.Type;
69​
70/**
71 * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
72 */
73export class ProviderSessionRuntimeRepository extends Context.Service<
74 ProviderSessionRuntimeRepository,
75 {
76 /**
77 * Insert or replace a provider runtime row.
78 *
79 * Upserts by canonical `threadId`, including JSON payload/cursor fields.
80 */
81 readonly upsert: (
82 runtime: ProviderSessionRuntime,
83 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
84​
85 /**
86 * Read provider runtime state by canonical thread id.
87 */
88 readonly getByThreadId: (
89 input: GetProviderSessionRuntimeInput,
90 ) => Effect.Effect<
91 Option.Option<ProviderSessionRuntime>,
92 ProviderSessionRuntimeRepositoryError
93 >;
94​
95 /**
96 * Update a cursor only while the named provider instance still owns the row.
97 *
98 * Returns false when the session was removed or rebound before the update.
99 */
100 readonly updateResumeCursorIfCurrentInstance: (
101 input: UpdateProviderSessionRuntimeResumeCursorInput,
102 ) => Effect.Effect<boolean, ProviderSessionRuntimeRepositoryError>;
103​
104 /**
105 * List all provider runtime rows.
106 *
107 * Returned in ascending last-seen order.
108 */
109 readonly list: () => Effect.Effect<
110 ReadonlyArray<ProviderSessionRuntime>,
111 ProviderSessionRuntimeRepositoryError
112 >;
113​
114 /**
115 * Delete provider runtime state by canonical thread id.
116 */
117 readonly deleteByThreadId: (
118 input: DeleteProviderSessionRuntimeInput,
119 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
120 }
121>()("t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
122​
123const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
124 Struct.assign({
125 resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
126 runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
127 }),
128);
129​
130const ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({
131 threadId: Schema.String,
132 providerName: Schema.Unknown,
133 providerInstanceId: Schema.Unknown,
134 adapterKey: Schema.Unknown,
135 runtimeMode: Schema.Unknown,
136 status: Schema.Unknown,
137 lastSeenAt: Schema.Unknown,
138 resumeCursor: Schema.Unknown,
139 runtimePayload: Schema.Unknown,
140});
141​
142const decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);
143​
144const GetRuntimeRequestSchema = Schema.Struct({
145 threadId: ThreadId,
146});
147​
148const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
149​
150const UpdateRuntimeResumeCursorDbInput = UpdateProviderSessionRuntimeResumeCursorInput.mapFields(
151 Struct.assign({
152 resumeCursor: Schema.fromJsonString(Schema.Unknown),
153 }),
154);
155​
156function toPersistenceSqlOrDecodeError(
157 sqlOperation: string,
158 decodeOperation: string,
159 correlation?: PersistenceErrorCorrelation,
160) {
161 return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
162 Schema.isSchemaError(cause)
163 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
164 : new PersistenceSqlError({
165 operation: sqlOperation,
166 ...(correlation === undefined ? {} : { correlation }),
167 cause,
168 });
170​
171export const make = Effect.gen(function* () {
172 const sql = yield* SqlClient.SqlClient;
173​
174 const upsertRuntimeRow = SqlSchema.void({
175 Request: ProviderSessionRuntimeDbRowSchema,
176 execute: (runtime) =>
177 sql`
178 INSERT INTO provider_session_runtime (
179 thread_id,
180 provider_name,
181 provider_instance_id,
182 adapter_key,
183 runtime_mode,
184 status,
185 last_seen_at,
186 resume_cursor_json,
187 runtime_payload_json
188 )
189 VALUES (
190 ${runtime.threadId},
191 ${runtime.providerName},
192 ${runtime.providerInstanceId},
193 ${runtime.adapterKey},
194 ${runtime.runtimeMode},
195 ${runtime.status},
196 ${runtime.lastSeenAt},
197 ${runtime.resumeCursor},
198 ${runtime.runtimePayload}
199 )
200 ON CONFLICT (thread_id)
201 DO UPDATE SET
202 provider_name = excluded.provider_name,
203 provider_instance_id = excluded.provider_instance_id,
204 adapter_key = excluded.adapter_key,
205 runtime_mode = excluded.runtime_mode,
206 status = excluded.status,
207 last_seen_at = excluded.last_seen_at,
208 resume_cursor_json = excluded.resume_cursor_json,
209 runtime_payload_json = excluded.runtime_payload_json
210 `,
211 });
212​
213 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
214 Request: GetRuntimeRequestSchema,
215 Result: ProviderSessionRuntimeRawDbRowSchema,
216 execute: ({ threadId }) =>
217 sql`
218 SELECT
219 thread_id AS "threadId",
220 provider_name AS "providerName",
221 provider_instance_id AS "providerInstanceId",
222 adapter_key AS "adapterKey",
223 runtime_mode AS "runtimeMode",
224 status,
225 last_seen_at AS "lastSeenAt",
226 resume_cursor_json AS "resumeCursor",
227 runtime_payload_json AS "runtimePayload"
228 FROM provider_session_runtime
229 WHERE thread_id = ${threadId}
230 `,
231 });
232​
233 const updateRuntimeResumeCursorIfCurrentInstance = SqlSchema.findOneOption({
234 Request: UpdateRuntimeResumeCursorDbInput,
235 Result: Schema.Struct({ threadId: ThreadId }),
236 execute: ({ threadId, providerInstanceId, lastSeenAt, resumeCursor }) =>
237 sql`
238 UPDATE provider_session_runtime
239 SET
240 last_seen_at = ${lastSeenAt},
241 resume_cursor_json = ${resumeCursor}
242 WHERE thread_id = ${threadId}
243 AND provider_instance_id = ${providerInstanceId}
244 RETURNING thread_id AS "threadId"
245 `,
246 });
247​
248 const listRuntimeRows = SqlSchema.findAll({
249 Request: Schema.Void,
250 Result: ProviderSessionRuntimeRawDbRowSchema,
251 execute: () =>
252 sql`
253 SELECT
254 thread_id AS "threadId",
255 provider_name AS "providerName",
256 provider_instance_id AS "providerInstanceId",
257 adapter_key AS "adapterKey",
258 runtime_mode AS "runtimeMode",
259 status,
260 last_seen_at AS "lastSeenAt",
261 resume_cursor_json AS "resumeCursor",
262 runtime_payload_json AS "runtimePayload"
263 FROM provider_session_runtime
264 ORDER BY last_seen_at ASC, thread_id ASC
265 `,
266 });
267​
268 const deleteRuntimeByThreadId = SqlSchema.void({
269 Request: DeleteRuntimeRequestSchema,
270 execute: ({ threadId }) =>
271 sql`
272 DELETE FROM provider_session_runtime
273 WHERE thread_id = ${threadId}
274 `,
275 });
276​
277 const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime) =>
278 upsertRuntimeRow(runtime).pipe(
279 Effect.mapError(
280 toPersistenceSqlOrDecodeError(
281 "ProviderSessionRuntimeRepository.upsert:query",
282 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
283 { threadId: runtime.threadId },
284 ),
285 ),
286 );
287​
288 const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
289 getRuntimeRowByThreadId(input).pipe(
290 Effect.mapError(
291 toPersistenceSqlOrDecodeError(
292 "ProviderSessionRuntimeRepository.getByThreadId:query",
293 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
294 { threadId: input.threadId },
295 ),
296 ),
297 Effect.flatMap((runtimeRowOption) =>
298 Option.match(runtimeRowOption, {
299 onNone: () => Effect.succeed(Option.none()),
300 onSome: (row) =>
301 decodeRuntimeRow(row).pipe(
302 Effect.mapError((cause) =>
303 PersistenceDecodeError.fromSchemaError(
304 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
305 cause,
306 { threadId: input.threadId },
307 ),
308 ),
309 Effect.map((runtime) => Option.some(runtime)),
310 ),
311 }),
312 ),
313 );
314​
315 const updateResumeCursorIfCurrentInstance: ProviderSessionRuntimeRepository["Service"]["updateResumeCursorIfCurrentInstance"] =
316 (input) =>
317 updateRuntimeResumeCursorIfCurrentInstance(input).pipe(
318 Effect.map(Option.isSome),
319 Effect.mapError(
320 toPersistenceSqlOrDecodeError(
321 "ProviderSessionRuntimeRepository.updateResumeCursorIfCurrentInstance:query",
322 "ProviderSessionRuntimeRepository.updateResumeCursorIfCurrentInstance:decodeRow",
323 { threadId: input.threadId },
324 ),
325 ),
326 );
327​
328 const list: ProviderSessionRuntimeRepository["Service"]["list"] = () =>
329 listRuntimeRows(undefined).pipe(
330 Effect.mapError(
331 toPersistenceSqlOrDecodeError(
332 "ProviderSessionRuntimeRepository.list:query",
333 "ProviderSessionRuntimeRepository.list:decodeRows",
334 ),
335 ),
336 Effect.flatMap((rows) =>
337 // Skip rows that no longer decode (e.g. written by an older build)
338 // instead of failing the whole list — one stale row must not disable
339 // every consumer that enumerates sessions, such as the reaper.
340 Effect.forEach(rows, (row) =>
341 decodeRuntimeRow(row).pipe(
342 Effect.map(Option.some),
343 Effect.catch((cause) =>
344 Effect.logWarning("provider.session.runtime.row-skipped", {
345 threadId: row.threadId,
346 error: PersistenceDecodeError.fromSchemaError(
347 "ProviderSessionRuntimeRepository.list:decodeRows",
348 cause,
349 { threadId: row.threadId },
350 ).message,
351 }).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
352 ),
353 ),
354 ),
355 ),
356 Effect.map((decoded) =>
357 Arr.filterMap(decoded, (row) =>
358 Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
359 ),
360 ),
361 );
362​
363 const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
364 input,
365 ) =>
366 deleteRuntimeByThreadId(input).pipe(
367 Effect.mapError(
368 (cause) =>
369 new PersistenceSqlError({
370 operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
371 correlation: { threadId: input.threadId },
372 cause,
373 }),
374 ),
375 );
376​
377 return {
378 upsert,
379 getByThreadId,
380 updateResumeCursorIfCurrentInstance,
381 list,
382 deleteByThreadId,
383 } satisfies ProviderSessionRuntimeRepository["Service"];
384});
385​
386export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);