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

ProviderSessionRuntime.ts

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