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