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

ProviderSessionRuntime.ts

357 lines11.3 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import * as Struct from "effect/Struct";
7import * as SqlClient from "effect/unstable/sql/SqlClient";
8import * as SqlSchema from "effect/unstable/sql/SqlSchema";
9​
10import {
11 IsoDateTime,
12 ProviderInstanceId,
13 ProviderSessionRuntimeStatus,
14 RuntimeMode,
15 ThreadId,
16} from "@t3tools/contracts";
17​
18import {
19 PersistenceDecodeError,
20 type PersistenceErrorCorrelation,
21 PersistenceSqlError,
22 type ProviderSessionRuntimeRepositoryError,
23} from "./Errors.ts";
24​
25/**
26 * ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.
27 *
28 * Owns persistence operations for provider runtime metadata and resume cursors.
29 *
30 * @module ProviderSessionRuntimeRepository
31 */
32​
33export const ProviderSessionRuntime = Schema.Struct({
34 threadId: ThreadId,
35 providerName: Schema.String,
36 /**
37 * User-defined routing key for the configured provider instance that
38 * owns this session. Nullable only at the storage/migration boundary:
39 * rows persisted before the driver/instance split carry only
40 * `providerName`. Repository consumers must materialize a concrete
41 * instance id before routing.
42 */
43 providerInstanceId: Schema.NullOr(ProviderInstanceId),
44 adapterKey: Schema.String,
45 runtimeMode: RuntimeMode,
46 status: ProviderSessionRuntimeStatus,
47 lastSeenAt: IsoDateTime,
48 resumeCursor: Schema.NullOr(Schema.Unknown),
49 runtimePayload: Schema.NullOr(Schema.Unknown),
50});
51export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
52​
53export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
54export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
55​
56export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
57export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
58​
59export const TouchProviderSessionRuntimeInput = Schema.Struct({
60 threadId: ThreadId,
61 lastSeenAt: IsoDateTime,
62});
63export type TouchProviderSessionRuntimeInput = typeof TouchProviderSessionRuntimeInput.Type;
64​
65/**
66 * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
67 */
68export class ProviderSessionRuntimeRepository extends Context.Service<
69 ProviderSessionRuntimeRepository,
70 {
71 /**
72 * Insert or replace a provider runtime row.
73 *
74 * Upserts by canonical `threadId`, including JSON payload/cursor fields.
75 */
76 readonly upsert: (
77 runtime: ProviderSessionRuntime,
78 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
79​
80 /**
81 * Read provider runtime state by canonical thread id.
82 */
83 readonly getByThreadId: (
84 input: GetProviderSessionRuntimeInput,
85 ) => Effect.Effect<
86 Option.Option<ProviderSessionRuntime>,
87 ProviderSessionRuntimeRepositoryError
88 >;
89​
90 /**
91 * List all provider runtime rows.
92 *
93 * Returned in ascending last-seen order.
94 */
95 readonly list: () => Effect.Effect<
96 ReadonlyArray<ProviderSessionRuntime>,
97 ProviderSessionRuntimeRepositoryError
98 >;
99​
100 /**
101 * Delete provider runtime state by canonical thread id.
102 */
103 readonly deleteByThreadId: (
104 input: DeleteProviderSessionRuntimeInput,
105 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
106​
107 /**
108 * Bump `last_seen_at` for an existing runtime row.
109 *
110 * No-op when no row matches. Cheaper than `upsert` for high-frequency
111 * activity signals because it skips the SELECT and JSON re-encoding.
112 */
113 readonly touchByThreadId: (
114 input: TouchProviderSessionRuntimeInput,
115 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
116 }
117>()("t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
118​
119const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
120 Struct.assign({
121 resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
122 runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
123 }),
124);
125​
126const ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({
127 threadId: Schema.String,
128 providerName: Schema.Unknown,
129 providerInstanceId: Schema.Unknown,
130 adapterKey: Schema.Unknown,
131 runtimeMode: Schema.Unknown,
132 status: Schema.Unknown,
133 lastSeenAt: Schema.Unknown,
134 resumeCursor: Schema.Unknown,
135 runtimePayload: Schema.Unknown,
136});
137​
138const decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);
139​
140const GetRuntimeRequestSchema = Schema.Struct({
141 threadId: ThreadId,
142});
143​
144const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
145​
146function toPersistenceSqlOrDecodeError(
147 sqlOperation: string,
148 decodeOperation: string,
149 correlation?: PersistenceErrorCorrelation,
150) {
151 return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
152 Schema.isSchemaError(cause)
153 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
154 : new PersistenceSqlError({
155 operation: sqlOperation,
156 ...(correlation === undefined ? {} : { correlation }),
157 cause,
158 });
160​
161export const make = Effect.gen(function* () {
162 const sql = yield* SqlClient.SqlClient;
163​
164 const upsertRuntimeRow = SqlSchema.void({
165 Request: ProviderSessionRuntimeDbRowSchema,
166 execute: (runtime) =>
167 sql`
168 INSERT INTO provider_session_runtime (
169 thread_id,
170 provider_name,
171 provider_instance_id,
172 adapter_key,
173 runtime_mode,
174 status,
175 last_seen_at,
176 resume_cursor_json,
177 runtime_payload_json
178 )
179 VALUES (
180 ${runtime.threadId},
181 ${runtime.providerName},
182 ${runtime.providerInstanceId},
183 ${runtime.adapterKey},
184 ${runtime.runtimeMode},
185 ${runtime.status},
186 ${runtime.lastSeenAt},
187 ${runtime.resumeCursor},
188 ${runtime.runtimePayload}
189 )
190 ON CONFLICT (thread_id)
191 DO UPDATE SET
192 provider_name = excluded.provider_name,
193 provider_instance_id = excluded.provider_instance_id,
194 adapter_key = excluded.adapter_key,
195 runtime_mode = excluded.runtime_mode,
196 status = excluded.status,
197 last_seen_at = excluded.last_seen_at,
198 resume_cursor_json = excluded.resume_cursor_json,
199 runtime_payload_json = excluded.runtime_payload_json
200 `,
201 });
202​
203 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
204 Request: GetRuntimeRequestSchema,
205 Result: ProviderSessionRuntimeRawDbRowSchema,
206 execute: ({ threadId }) =>
207 sql`
208 SELECT
209 thread_id AS "threadId",
210 provider_name AS "providerName",
211 provider_instance_id AS "providerInstanceId",
212 adapter_key AS "adapterKey",
213 runtime_mode AS "runtimeMode",
214 status,
215 last_seen_at AS "lastSeenAt",
216 resume_cursor_json AS "resumeCursor",
217 runtime_payload_json AS "runtimePayload"
218 FROM provider_session_runtime
219 WHERE thread_id = ${threadId}
220 `,
221 });
222​
223 const listRuntimeRows = SqlSchema.findAll({
224 Request: Schema.Void,
225 Result: ProviderSessionRuntimeRawDbRowSchema,
226 execute: () =>
227 sql`
228 SELECT
229 thread_id AS "threadId",
230 provider_name AS "providerName",
231 provider_instance_id AS "providerInstanceId",
232 adapter_key AS "adapterKey",
233 runtime_mode AS "runtimeMode",
234 status,
235 last_seen_at AS "lastSeenAt",
236 resume_cursor_json AS "resumeCursor",
237 runtime_payload_json AS "runtimePayload"
238 FROM provider_session_runtime
239 ORDER BY last_seen_at ASC, thread_id ASC
240 `,
241 });
242​
243 const deleteRuntimeByThreadId = SqlSchema.void({
244 Request: DeleteRuntimeRequestSchema,
245 execute: ({ threadId }) =>
246 sql`
247 DELETE FROM provider_session_runtime
248 WHERE thread_id = ${threadId}
249 `,
250 });
251​
252 const touchRuntimeByThreadId = SqlSchema.void({
253 Request: TouchProviderSessionRuntimeInput,
254 execute: ({ threadId, lastSeenAt }) =>
255 sql`
256 UPDATE provider_session_runtime
257 SET last_seen_at = ${lastSeenAt}
258 WHERE thread_id = ${threadId}
259 `,
260 });
261​
262 const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime) =>
263 upsertRuntimeRow(runtime).pipe(
264 Effect.mapError(
265 toPersistenceSqlOrDecodeError(
266 "ProviderSessionRuntimeRepository.upsert:query",
267 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
268 { threadId: runtime.threadId },
269 ),
270 ),
271 );
272​
273 const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
274 getRuntimeRowByThreadId(input).pipe(
275 Effect.mapError(
276 toPersistenceSqlOrDecodeError(
277 "ProviderSessionRuntimeRepository.getByThreadId:query",
278 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
279 { threadId: input.threadId },
280 ),
281 ),
282 Effect.flatMap((runtimeRowOption) =>
283 Option.match(runtimeRowOption, {
284 onNone: () => Effect.succeed(Option.none()),
285 onSome: (row) =>
286 decodeRuntimeRow(row).pipe(
287 Effect.mapError((cause) =>
288 PersistenceDecodeError.fromSchemaError(
289 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
290 cause,
291 { threadId: input.threadId },
292 ),
293 ),
294 Effect.map((runtime) => Option.some(runtime)),
295 ),
296 }),
297 ),
298 );
299​
300 const list: ProviderSessionRuntimeRepository["Service"]["list"] = () =>
301 listRuntimeRows(undefined).pipe(
302 Effect.mapError(
303 toPersistenceSqlOrDecodeError(
304 "ProviderSessionRuntimeRepository.list:query",
305 "ProviderSessionRuntimeRepository.list:decodeRows",
306 ),
307 ),
308 Effect.flatMap((rows) =>
309 Effect.forEach(rows, (row) =>
310 decodeRuntimeRow(row).pipe(
311 Effect.mapError((cause) =>
312 PersistenceDecodeError.fromSchemaError(
313 "ProviderSessionRuntimeRepository.list:decodeRows",
314 cause,
315 { threadId: row.threadId },
316 ),
317 ),
318 ),
319 ),
320 ),
321 );
322​
323 const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
324 input,
325 ) =>
326 deleteRuntimeByThreadId(input).pipe(
327 Effect.mapError(
328 (cause) =>
329 new PersistenceSqlError({
330 operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
331 correlation: { threadId: input.threadId },
332 cause,
333 }),
334 ),
335 );
336​
337 const touchByThreadId: ProviderSessionRuntimeRepository["Service"]["touchByThreadId"] = (input) =>
338 touchRuntimeByThreadId(input).pipe(
339 Effect.mapError(
340 toPersistenceSqlOrDecodeError(
341 "ProviderSessionRuntimeRepository.touchByThreadId:query",
342 "ProviderSessionRuntimeRepository.touchByThreadId:encodeRequest",
343 { threadId: input.threadId },
344 ),
345 ),
346 );
347​
348 return {
349 upsert,
350 getByThreadId,
351 list,
352 deleteByThreadId,
353 touchByThreadId,
354 } satisfies ProviderSessionRuntimeRepository["Service"];
355});
356​
357export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);