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