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