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

ProviderSessionRuntime.ts

319 lines10.0 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 "@v12/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​
59/**
60 * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
61 */
62export class ProviderSessionRuntimeRepository extends Context.Service<
63 ProviderSessionRuntimeRepository,
64 {
65 /**
66 * Insert or replace a provider runtime row.
67 *
68 * Upserts by canonical `threadId`, including JSON payload/cursor fields.
69 */
70 readonly upsert: (
71 runtime: ProviderSessionRuntime,
72 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
73​
74 /**
75 * Read provider runtime state by canonical thread id.
76 */
77 readonly getByThreadId: (
78 input: GetProviderSessionRuntimeInput,
79 ) => Effect.Effect<
80 Option.Option<ProviderSessionRuntime>,
81 ProviderSessionRuntimeRepositoryError
82 >;
83​
84 /**
85 * List all provider runtime rows.
86 *
87 * Returned in ascending last-seen order.
88 */
89 readonly list: () => Effect.Effect<
90 ReadonlyArray<ProviderSessionRuntime>,
91 ProviderSessionRuntimeRepositoryError
92 >;
93​
94 /**
95 * Delete provider runtime state by canonical thread id.
96 */
97 readonly deleteByThreadId: (
98 input: DeleteProviderSessionRuntimeInput,
99 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
100 }
101>()("v12/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
102​
103const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
104 Struct.assign({
105 resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
106 runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
107 }),
108);
109​
110const ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({
111 threadId: Schema.String,
112 providerName: Schema.Unknown,
113 providerInstanceId: Schema.Unknown,
114 adapterKey: Schema.Unknown,
115 runtimeMode: Schema.Unknown,
116 status: Schema.Unknown,
117 lastSeenAt: Schema.Unknown,
118 resumeCursor: Schema.Unknown,
119 runtimePayload: Schema.Unknown,
120});
121​
122const decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);
123​
124const GetRuntimeRequestSchema = Schema.Struct({
125 threadId: ThreadId,
126});
127​
128const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
129​
130function toPersistenceSqlOrDecodeError(
131 sqlOperation: string,
132 decodeOperation: string,
133 correlation?: PersistenceErrorCorrelation,
134) {
135 return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
136 Schema.isSchemaError(cause)
137 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
138 : new PersistenceSqlError({
139 operation: sqlOperation,
140 ...(correlation === undefined ? {} : { correlation }),
141 cause,
142 });
144​
145export const make = Effect.gen(function* () {
146 const sql = yield* SqlClient.SqlClient;
147​
148 const upsertRuntimeRow = SqlSchema.void({
149 Request: ProviderSessionRuntimeDbRowSchema,
150 execute: (runtime) =>
151 sql`
152 INSERT INTO provider_session_runtime (
153 thread_id,
154 provider_name,
155 provider_instance_id,
156 adapter_key,
157 runtime_mode,
158 status,
159 last_seen_at,
160 resume_cursor_json,
161 runtime_payload_json
162 )
163 VALUES (
164 ${runtime.threadId},
165 ${runtime.providerName},
166 ${runtime.providerInstanceId},
167 ${runtime.adapterKey},
168 ${runtime.runtimeMode},
169 ${runtime.status},
170 ${runtime.lastSeenAt},
171 ${runtime.resumeCursor},
172 ${runtime.runtimePayload}
173 )
174 ON CONFLICT (thread_id)
175 DO UPDATE SET
176 provider_name = excluded.provider_name,
177 provider_instance_id = excluded.provider_instance_id,
178 adapter_key = excluded.adapter_key,
179 runtime_mode = excluded.runtime_mode,
180 status = excluded.status,
181 last_seen_at = excluded.last_seen_at,
182 resume_cursor_json = excluded.resume_cursor_json,
183 runtime_payload_json = excluded.runtime_payload_json
184 `,
185 });
186​
187 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
188 Request: GetRuntimeRequestSchema,
189 Result: ProviderSessionRuntimeRawDbRowSchema,
190 execute: ({ threadId }) =>
191 sql`
192 SELECT
193 thread_id AS "threadId",
194 provider_name AS "providerName",
195 provider_instance_id AS "providerInstanceId",
196 adapter_key AS "adapterKey",
197 runtime_mode AS "runtimeMode",
198 status,
199 last_seen_at AS "lastSeenAt",
200 resume_cursor_json AS "resumeCursor",
201 runtime_payload_json AS "runtimePayload"
202 FROM provider_session_runtime
203 WHERE thread_id = ${threadId}
204 `,
205 });
206​
207 const listRuntimeRows = SqlSchema.findAll({
208 Request: Schema.Void,
209 Result: ProviderSessionRuntimeRawDbRowSchema,
210 execute: () =>
211 sql`
212 SELECT
213 thread_id AS "threadId",
214 provider_name AS "providerName",
215 provider_instance_id AS "providerInstanceId",
216 adapter_key AS "adapterKey",
217 runtime_mode AS "runtimeMode",
218 status,
219 last_seen_at AS "lastSeenAt",
220 resume_cursor_json AS "resumeCursor",
221 runtime_payload_json AS "runtimePayload"
222 FROM provider_session_runtime
223 ORDER BY last_seen_at ASC, thread_id ASC
224 `,
225 });
226​
227 const deleteRuntimeByThreadId = SqlSchema.void({
228 Request: DeleteRuntimeRequestSchema,
229 execute: ({ threadId }) =>
230 sql`
231 DELETE FROM provider_session_runtime
232 WHERE thread_id = ${threadId}
233 `,
234 });
235​
236 const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime) =>
237 upsertRuntimeRow(runtime).pipe(
238 Effect.mapError(
239 toPersistenceSqlOrDecodeError(
240 "ProviderSessionRuntimeRepository.upsert:query",
241 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
242 { threadId: runtime.threadId },
243 ),
244 ),
245 );
246​
247 const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
248 getRuntimeRowByThreadId(input).pipe(
249 Effect.mapError(
250 toPersistenceSqlOrDecodeError(
251 "ProviderSessionRuntimeRepository.getByThreadId:query",
252 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
253 { threadId: input.threadId },
254 ),
255 ),
256 Effect.flatMap((runtimeRowOption) =>
257 Option.match(runtimeRowOption, {
258 onNone: () => Effect.succeed(Option.none()),
259 onSome: (row) =>
260 decodeRuntimeRow(row).pipe(
261 Effect.mapError((cause) =>
262 PersistenceDecodeError.fromSchemaError(
263 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
264 cause,
265 { threadId: input.threadId },
266 ),
267 ),
268 Effect.map((runtime) => Option.some(runtime)),
269 ),
270 }),
271 ),
272 );
273​
274 const list: ProviderSessionRuntimeRepository["Service"]["list"] = () =>
275 listRuntimeRows(undefined).pipe(
276 Effect.mapError(
277 toPersistenceSqlOrDecodeError(
278 "ProviderSessionRuntimeRepository.list:query",
279 "ProviderSessionRuntimeRepository.list:decodeRows",
280 ),
281 ),
282 Effect.flatMap((rows) =>
283 Effect.forEach(rows, (row) =>
284 decodeRuntimeRow(row).pipe(
285 Effect.mapError((cause) =>
286 PersistenceDecodeError.fromSchemaError(
287 "ProviderSessionRuntimeRepository.list:decodeRows",
288 cause,
289 { threadId: row.threadId },
290 ),
291 ),
292 ),
293 ),
294 ),
295 );
296​
297 const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
298 input,
299 ) =>
300 deleteRuntimeByThreadId(input).pipe(
301 Effect.mapError(
302 (cause) =>
303 new PersistenceSqlError({
304 operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
305 correlation: { threadId: input.threadId },
306 cause,
307 }),
308 ),
309 );
310​
311 return {
312 upsert,
313 getByThreadId,
314 list,
315 deleteByThreadId,
316 } satisfies ProviderSessionRuntimeRepository["Service"];
317});
318​
319export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);