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

ProviderSessionRuntime.ts

479 lines16.0 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 AgentSessionImportSource,
14 IsoDateTime,
15 ProviderInstanceId,
16 ProviderSessionRuntimeStatus,
17 RuntimeMode,
18 ThreadId,
19} from "@t3tools/contracts";
20​
21import {
22 PersistenceDecodeError,
23 type PersistenceErrorCorrelation,
24 PersistenceSqlError,
25 type ProviderSessionRuntimeRepositoryError,
26} from "./Errors.ts";
27​
28/**
29 * ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.
30 *
31 * Owns persistence operations for provider runtime metadata and resume cursors.
32 *
33 * @module ProviderSessionRuntimeRepository
34 */
35​
36export const ProviderSessionRuntime = Schema.Struct({
37 threadId: ThreadId,
38 providerName: Schema.String,
39 /**
40 * User-defined routing key for the configured provider instance that
41 * owns this session. Nullable only at the storage/migration boundary:
42 * rows persisted before the driver/instance split carry only
43 * `providerName`. Repository consumers must materialize a concrete
44 * instance id before routing.
45 */
46 providerInstanceId: Schema.NullOr(ProviderInstanceId),
47 adapterKey: Schema.String,
48 runtimeMode: RuntimeMode,
49 status: ProviderSessionRuntimeStatus,
50 lastSeenAt: IsoDateTime,
51 resumeCursor: Schema.NullOr(Schema.Unknown),
52 runtimePayload: Schema.NullOr(Schema.Unknown),
53});
54export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
55​
56export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
57export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
58​
59export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
60export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
61​
62export const RecordImportedTranscriptInput = Schema.Struct({
63 threadId: ThreadId,
64 source: AgentSessionImportSource,
65});
66export type RecordImportedTranscriptInput = typeof RecordImportedTranscriptInput.Type;
67​
68export interface ProviderSessionRuntimeUpsertOptions {
69 readonly onConflict?: "update" | "ignore";
71​
72/**
73 * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
74 */
75export class ProviderSessionRuntimeRepository extends Context.Service<
76 ProviderSessionRuntimeRepository,
77 {
78 /**
79 * Insert or replace a provider runtime row.
80 *
81 * Upserts by canonical `threadId`, retaining imported transcript records
82 * from the current database row.
83 */
84 readonly upsert: (
85 runtime: ProviderSessionRuntime,
86 options?: ProviderSessionRuntimeUpsertOptions,
87 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
88​
89 /** Record one source file without replacing the current session state. */
90 readonly recordImportedTranscript: (
91 input: RecordImportedTranscriptInput,
92 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
93​
94 /**
95 * Read provider runtime state by canonical thread id.
96 */
97 readonly getByThreadId: (
98 input: GetProviderSessionRuntimeInput,
99 ) => Effect.Effect<
100 Option.Option<ProviderSessionRuntime>,
101 ProviderSessionRuntimeRepositoryError
102 >;
103​
104 /**
105 * List provider runtime rows.
106 *
107 * Returned in ascending last-seen order. `excludeStopped` filters stopped
108 * rows in SQL. Long-lived installs keep thousands for their resume cursors.
109 */
110 readonly list: (options?: {
111 readonly excludeStopped?: boolean;
112 }) => Effect.Effect<
113 ReadonlyArray<ProviderSessionRuntime>,
114 ProviderSessionRuntimeRepositoryError
115 >;
116​
117 /**
118 * Delete provider runtime state by canonical thread id.
119 */
120 readonly deleteByThreadId: (
121 input: DeleteProviderSessionRuntimeInput,
122 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
123 }
124>()("t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
125​
126const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
127 Struct.assign({
128 resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
129 runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
130 }),
131);
132​
133const ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({
134 threadId: Schema.String,
135 providerName: Schema.Unknown,
136 providerInstanceId: Schema.Unknown,
137 adapterKey: Schema.Unknown,
138 runtimeMode: Schema.Unknown,
139 status: Schema.Unknown,
140 lastSeenAt: Schema.Unknown,
141 resumeCursor: Schema.Unknown,
142 runtimePayload: Schema.Unknown,
143});
144​
145const decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);
146​
147const GetRuntimeRequestSchema = Schema.Struct({
148 threadId: ThreadId,
149});
150​
151const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
152​
153const RecordImportedTranscriptRequestSchema = RecordImportedTranscriptInput.mapFields(
154 Struct.assign({ source: Schema.fromJsonString(AgentSessionImportSource) }),
155);
156​
157function toPersistenceSqlOrDecodeError(
158 sqlOperation: string,
159 decodeOperation: string,
160 correlation?: PersistenceErrorCorrelation,
161) {
162 return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
163 Schema.isSchemaError(cause)
164 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
165 : new PersistenceSqlError({
166 operation: sqlOperation,
167 ...(correlation === undefined ? {} : { correlation }),
168 cause,
169 });
171​
172/** @public Service construction is part of the canonical Effect module API. */
173export const make = Effect.gen(function* () {
174 const sql = yield* SqlClient.SqlClient;
175​
176 // Runtime writes can carry stale payloads. Only recordImportedTranscript may
177 // change source records, so restore that field from the row being updated.
178 const upsertRuntimeRow = SqlSchema.void({
179 Request: ProviderSessionRuntimeDbRowSchema,
180 execute: (runtime) =>
181 sql`
182 INSERT INTO provider_session_runtime (
183 thread_id,
184 provider_name,
185 provider_instance_id,
186 adapter_key,
187 runtime_mode,
188 status,
189 last_seen_at,
190 resume_cursor_json,
191 runtime_payload_json
192 )
193 VALUES (
194 ${runtime.threadId},
195 ${runtime.providerName},
196 ${runtime.providerInstanceId},
197 ${runtime.adapterKey},
198 ${runtime.runtimeMode},
199 ${runtime.status},
200 ${runtime.lastSeenAt},
201 ${runtime.resumeCursor},
202 CASE
203 WHEN json_type(${runtime.runtimePayload}) = 'object'
204 THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
205 ELSE ${runtime.runtimePayload}
206 END
207 )
208 ON CONFLICT (thread_id)
209 DO UPDATE SET
210 provider_name = excluded.provider_name,
211 provider_instance_id = excluded.provider_instance_id,
212 adapter_key = excluded.adapter_key,
213 runtime_mode = excluded.runtime_mode,
214 status = excluded.status,
215 last_seen_at = excluded.last_seen_at,
216 resume_cursor_json = excluded.resume_cursor_json,
217 runtime_payload_json = CASE
218 WHEN json_type(
219 CASE
220 WHEN json_valid(provider_session_runtime.runtime_payload_json)
221 THEN provider_session_runtime.runtime_payload_json
222 ELSE '{}'
223 END,
224 '$.importedTranscripts'
225 ) IS NOT NULL
226 THEN json_set(
227 CASE
228 WHEN json_type(excluded.runtime_payload_json) = 'object'
229 THEN excluded.runtime_payload_json
230 ELSE '{}'
231 END,
232 '$.importedTranscripts',
233 json_extract(provider_session_runtime.runtime_payload_json, '$.importedTranscripts')
234 )
235 ELSE excluded.runtime_payload_json
236 END
237 `,
238 });
239​
240 const insertRuntimeRow = SqlSchema.void({
241 Request: ProviderSessionRuntimeDbRowSchema,
242 execute: (runtime) =>
243 sql`
244 INSERT INTO provider_session_runtime (
245 thread_id,
246 provider_name,
247 provider_instance_id,
248 adapter_key,
249 runtime_mode,
250 status,
251 last_seen_at,
252 resume_cursor_json,
253 runtime_payload_json
254 )
255 VALUES (
256 ${runtime.threadId},
257 ${runtime.providerName},
258 ${runtime.providerInstanceId},
259 ${runtime.adapterKey},
260 ${runtime.runtimeMode},
261 ${runtime.status},
262 ${runtime.lastSeenAt},
263 ${runtime.resumeCursor},
264 CASE
265 WHEN json_type(${runtime.runtimePayload}) = 'object'
266 THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
267 ELSE ${runtime.runtimePayload}
268 END
269 )
270 ON CONFLICT (thread_id) DO NOTHING
271 `,
272 });
273​
274 const recordImportedTranscriptRow = SqlSchema.void({
275 Request: RecordImportedTranscriptRequestSchema,
276 execute: ({ threadId, source }) =>
277 sql`
278 WITH current_runtime AS (
279 SELECT CASE
280 WHEN json_valid(runtime_payload_json) THEN CASE
281 WHEN json_type(runtime_payload_json) = 'object' THEN runtime_payload_json
282 ELSE '{}'
283 END
284 ELSE '{}'
285 END AS payload
286 FROM provider_session_runtime
287 WHERE thread_id = ${threadId}
288 )
289 UPDATE provider_session_runtime
290 SET runtime_payload_json = (
291 SELECT json_set(
292 payload,
293 '$.importedTranscripts',
294 json((
295 SELECT json_group_array(json(value))
296 FROM (
297 SELECT value
298 FROM json_each(CASE
299 WHEN json_type(payload, '$.importedTranscripts') = 'array'
300 THEN json_extract(payload, '$.importedTranscripts')
301 ELSE '[]'
302 END)
303 WHERE CASE
304 WHEN type = 'object' THEN
305 json_extract(value, '$.providerInstanceId')
306 IS NOT json_extract(${source}, '$.providerInstanceId')
307 OR json_extract(value, '$.filePath') IS NOT json_extract(${source}, '$.filePath')
308 ELSE 0
309 END
310 UNION ALL
311 SELECT ${source} AS value
312 )
313 ))
314 )
315 FROM current_runtime
316 )
317 WHERE thread_id = ${threadId}
318 `,
319 });
320​
321 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
322 Request: GetRuntimeRequestSchema,
323 Result: ProviderSessionRuntimeRawDbRowSchema,
324 execute: ({ threadId }) =>
325 sql`
326 SELECT
327 thread_id AS "threadId",
328 provider_name AS "providerName",
329 provider_instance_id AS "providerInstanceId",
330 adapter_key AS "adapterKey",
331 runtime_mode AS "runtimeMode",
332 status,
333 last_seen_at AS "lastSeenAt",
334 resume_cursor_json AS "resumeCursor",
335 runtime_payload_json AS "runtimePayload"
336 FROM provider_session_runtime
337 WHERE thread_id = ${threadId}
338 `,
339 });
340​
341 const listRuntimeRows = SqlSchema.findAll({
342 Request: Schema.Struct({ excludeStopped: Schema.Boolean }),
343 Result: ProviderSessionRuntimeRawDbRowSchema,
344 execute: ({ excludeStopped }) =>
345 sql`
346 SELECT
347 thread_id AS "threadId",
348 provider_name AS "providerName",
349 provider_instance_id AS "providerInstanceId",
350 adapter_key AS "adapterKey",
351 runtime_mode AS "runtimeMode",
352 status,
353 last_seen_at AS "lastSeenAt",
354 resume_cursor_json AS "resumeCursor",
355 runtime_payload_json AS "runtimePayload"
356 FROM provider_session_runtime
357 ${excludeStopped ? sql`WHERE status != 'stopped'` : sql``}
358 ORDER BY last_seen_at ASC, thread_id ASC
359 `,
360 });
361​
362 const deleteRuntimeByThreadId = SqlSchema.void({
363 Request: DeleteRuntimeRequestSchema,
364 execute: ({ threadId }) =>
365 sql`
366 DELETE FROM provider_session_runtime
367 WHERE thread_id = ${threadId}
368 `,
369 });
370​
371 const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime, options) =>
372 (options?.onConflict === "ignore" ? insertRuntimeRow(runtime) : upsertRuntimeRow(runtime)).pipe(
373 Effect.mapError(
374 toPersistenceSqlOrDecodeError(
375 "ProviderSessionRuntimeRepository.upsert:query",
376 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
377 { threadId: runtime.threadId },
378 ),
379 ),
380 );
381​
382 const recordImportedTranscript: ProviderSessionRuntimeRepository["Service"]["recordImportedTranscript"] =
383 (input) =>
384 recordImportedTranscriptRow(input).pipe(
385 Effect.mapError(
386 toPersistenceSqlOrDecodeError(
387 "ProviderSessionRuntimeRepository.recordImportedTranscript:query",
388 "ProviderSessionRuntimeRepository.recordImportedTranscript:encodeRequest",
389 { threadId: input.threadId },
390 ),
391 ),
392 );
393​
394 const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
395 getRuntimeRowByThreadId(input).pipe(
396 Effect.mapError(
397 toPersistenceSqlOrDecodeError(
398 "ProviderSessionRuntimeRepository.getByThreadId:query",
399 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
400 { threadId: input.threadId },
401 ),
402 ),
403 Effect.flatMap((runtimeRowOption) =>
404 Option.match(runtimeRowOption, {
405 onNone: () => Effect.succeedNone,
406 onSome: (row) =>
407 decodeRuntimeRow(row).pipe(
408 Effect.mapError((cause) =>
409 PersistenceDecodeError.fromSchemaError(
410 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
411 cause,
412 { threadId: input.threadId },
413 ),
414 ),
415 Effect.asSome,
416 ),
417 }),
418 ),
419 );
420​
421 const list: ProviderSessionRuntimeRepository["Service"]["list"] = (options) =>
422 listRuntimeRows({ excludeStopped: options?.excludeStopped === true }).pipe(
423 Effect.mapError(
424 toPersistenceSqlOrDecodeError(
425 "ProviderSessionRuntimeRepository.list:query",
426 "ProviderSessionRuntimeRepository.list:decodeRows",
427 ),
428 ),
429 Effect.flatMap((rows) =>
430 // Skip rows that no longer decode (e.g. written by an older build)
431 // instead of failing the whole list — one stale row must not disable
432 // every consumer that enumerates sessions, such as the reaper.
433 Effect.forEach(rows, (row) =>
434 decodeRuntimeRow(row).pipe(
435 Effect.asSome,
436 Effect.catch((cause) =>
437 Effect.logWarning("provider.session.runtime.row-skipped", {
438 threadId: row.threadId,
439 error: PersistenceDecodeError.fromSchemaError(
440 "ProviderSessionRuntimeRepository.list:decodeRows",
441 cause,
442 { threadId: row.threadId },
443 ).message,
444 }).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
445 ),
446 ),
447 ),
448 ),
449 Effect.map((decoded) =>
450 Arr.filterMap(decoded, (row) =>
451 Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
452 ),
453 ),
454 );
455​
456 const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
457 input,
458 ) =>
459 deleteRuntimeByThreadId(input).pipe(
460 Effect.mapError(
461 (cause) =>
462 new PersistenceSqlError({
463 operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
464 correlation: { threadId: input.threadId },
465 cause,
466 }),
467 ),
468 );
469​
470 return {
471 upsert,
472 recordImportedTranscript,
473 getByThreadId,
474 list,
475 deleteByThreadId,
476 } satisfies ProviderSessionRuntimeRepository["Service"];
477});
478​
479export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);