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

ProviderSessionRuntime.ts

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