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

ProviderSessionRuntime.ts

333 lines10.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​
61/**
62 * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
63 */
64export class ProviderSessionRuntimeRepository extends Context.Service<
65 ProviderSessionRuntimeRepository,
66 {
67 /**
68 * Insert or replace a provider runtime row.
69 *
70 * Upserts by canonical `threadId`, including JSON payload/cursor fields.
71 */
72 readonly upsert: (
73 runtime: ProviderSessionRuntime,
74 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
75​
76 /**
77 * Read provider runtime state by canonical thread id.
78 */
79 readonly getByThreadId: (
80 input: GetProviderSessionRuntimeInput,
81 ) => Effect.Effect<
82 Option.Option<ProviderSessionRuntime>,
83 ProviderSessionRuntimeRepositoryError
84 >;
85​
86 /**
87 * List all provider runtime rows.
88 *
89 * Returned in ascending last-seen order.
90 */
91 readonly list: () => Effect.Effect<
92 ReadonlyArray<ProviderSessionRuntime>,
93 ProviderSessionRuntimeRepositoryError
94 >;
95​
96 /**
97 * Delete provider runtime state by canonical thread id.
98 */
99 readonly deleteByThreadId: (
100 input: DeleteProviderSessionRuntimeInput,
101 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
102 }
103>()("t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
104​
105const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
106 Struct.assign({
107 resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
108 runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
109 }),
110);
111​
112const ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({
113 threadId: Schema.String,
114 providerName: Schema.Unknown,
115 providerInstanceId: Schema.Unknown,
116 adapterKey: Schema.Unknown,
117 runtimeMode: Schema.Unknown,
118 status: Schema.Unknown,
119 lastSeenAt: Schema.Unknown,
120 resumeCursor: Schema.Unknown,
121 runtimePayload: Schema.Unknown,
122});
123​
124const decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);
125​
126const GetRuntimeRequestSchema = Schema.Struct({
127 threadId: ThreadId,
128});
129​
130const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
131​
132function toPersistenceSqlOrDecodeError(
133 sqlOperation: string,
134 decodeOperation: string,
135 correlation?: PersistenceErrorCorrelation,
136) {
137 return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
138 Schema.isSchemaError(cause)
139 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
140 : new PersistenceSqlError({
141 operation: sqlOperation,
142 ...(correlation === undefined ? {} : { correlation }),
143 cause,
144 });
146​
147export const make = Effect.gen(function* () {
148 const sql = yield* SqlClient.SqlClient;
149​
150 const upsertRuntimeRow = SqlSchema.void({
151 Request: ProviderSessionRuntimeDbRowSchema,
152 execute: (runtime) =>
153 sql`
154 INSERT INTO provider_session_runtime (
155 thread_id,
156 provider_name,
157 provider_instance_id,
158 adapter_key,
159 runtime_mode,
160 status,
161 last_seen_at,
162 resume_cursor_json,
163 runtime_payload_json
164 )
165 VALUES (
166 ${runtime.threadId},
167 ${runtime.providerName},
168 ${runtime.providerInstanceId},
169 ${runtime.adapterKey},
170 ${runtime.runtimeMode},
171 ${runtime.status},
172 ${runtime.lastSeenAt},
173 ${runtime.resumeCursor},
174 ${runtime.runtimePayload}
175 )
176 ON CONFLICT (thread_id)
177 DO UPDATE SET
178 provider_name = excluded.provider_name,
179 provider_instance_id = excluded.provider_instance_id,
180 adapter_key = excluded.adapter_key,
181 runtime_mode = excluded.runtime_mode,
182 status = excluded.status,
183 last_seen_at = excluded.last_seen_at,
184 resume_cursor_json = excluded.resume_cursor_json,
185 runtime_payload_json = excluded.runtime_payload_json
186 `,
187 });
188​
189 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
190 Request: GetRuntimeRequestSchema,
191 Result: ProviderSessionRuntimeRawDbRowSchema,
192 execute: ({ threadId }) =>
193 sql`
194 SELECT
195 thread_id AS "threadId",
196 provider_name AS "providerName",
197 provider_instance_id AS "providerInstanceId",
198 adapter_key AS "adapterKey",
199 runtime_mode AS "runtimeMode",
200 status,
201 last_seen_at AS "lastSeenAt",
202 resume_cursor_json AS "resumeCursor",
203 runtime_payload_json AS "runtimePayload"
204 FROM provider_session_runtime
205 WHERE thread_id = ${threadId}
206 `,
207 });
208​
209 const listRuntimeRows = SqlSchema.findAll({
210 Request: Schema.Void,
211 Result: ProviderSessionRuntimeRawDbRowSchema,
212 execute: () =>
213 sql`
214 SELECT
215 thread_id AS "threadId",
216 provider_name AS "providerName",
217 provider_instance_id AS "providerInstanceId",
218 adapter_key AS "adapterKey",
219 runtime_mode AS "runtimeMode",
220 status,
221 last_seen_at AS "lastSeenAt",
222 resume_cursor_json AS "resumeCursor",
223 runtime_payload_json AS "runtimePayload"
224 FROM provider_session_runtime
225 ORDER BY last_seen_at ASC, thread_id ASC
226 `,
227 });
228​
229 const deleteRuntimeByThreadId = SqlSchema.void({
230 Request: DeleteRuntimeRequestSchema,
231 execute: ({ threadId }) =>
232 sql`
233 DELETE FROM provider_session_runtime
234 WHERE thread_id = ${threadId}
235 `,
236 });
237​
238 const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime) =>
239 upsertRuntimeRow(runtime).pipe(
240 Effect.mapError(
241 toPersistenceSqlOrDecodeError(
242 "ProviderSessionRuntimeRepository.upsert:query",
243 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
244 { threadId: runtime.threadId },
245 ),
246 ),
247 );
248​
249 const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
250 getRuntimeRowByThreadId(input).pipe(
251 Effect.mapError(
252 toPersistenceSqlOrDecodeError(
253 "ProviderSessionRuntimeRepository.getByThreadId:query",
254 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
255 { threadId: input.threadId },
256 ),
257 ),
258 Effect.flatMap((runtimeRowOption) =>
259 Option.match(runtimeRowOption, {
260 onNone: () => Effect.succeed(Option.none()),
261 onSome: (row) =>
262 decodeRuntimeRow(row).pipe(
263 Effect.mapError((cause) =>
264 PersistenceDecodeError.fromSchemaError(
265 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
266 cause,
267 { threadId: input.threadId },
268 ),
269 ),
270 Effect.map((runtime) => Option.some(runtime)),
271 ),
272 }),
273 ),
274 );
275​
276 const list: ProviderSessionRuntimeRepository["Service"]["list"] = () =>
277 listRuntimeRows(undefined).pipe(
278 Effect.mapError(
279 toPersistenceSqlOrDecodeError(
280 "ProviderSessionRuntimeRepository.list:query",
281 "ProviderSessionRuntimeRepository.list:decodeRows",
282 ),
283 ),
284 Effect.flatMap((rows) =>
285 // Skip rows that no longer decode (e.g. written by an older build)
286 // instead of failing the whole list — one stale row must not disable
287 // every consumer that enumerates sessions, such as the reaper.
288 Effect.forEach(rows, (row) =>
289 decodeRuntimeRow(row).pipe(
290 Effect.map(Option.some),
291 Effect.catch((cause) =>
292 Effect.logWarning("provider.session.runtime.row-skipped", {
293 threadId: row.threadId,
294 error: PersistenceDecodeError.fromSchemaError(
295 "ProviderSessionRuntimeRepository.list:decodeRows",
296 cause,
297 { threadId: row.threadId },
298 ).message,
299 }).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
300 ),
301 ),
302 ),
303 ),
304 Effect.map((decoded) =>
305 Arr.filterMap(decoded, (row) =>
306 Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
307 ),
308 ),
309 );
310​
311 const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
312 input,
313 ) =>
314 deleteRuntimeByThreadId(input).pipe(
315 Effect.mapError(
316 (cause) =>
317 new PersistenceSqlError({
318 operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
319 correlation: { threadId: input.threadId },
320 cause,
321 }),
322 ),
323 );
324​
325 return {
326 upsert,
327 getByThreadId,
328 list,
329 deleteByThreadId,
330 } satisfies ProviderSessionRuntimeRepository["Service"];
331});
332​
333export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);