Open History to see the last commit
1import { ThreadId } from "@t3tools/contracts";
2import * as SqlClient from "effect/unstable/sql/SqlClient";
3import * as SqlSchema from "effect/unstable/sql/SqlSchema";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Struct from "effect/Struct";
9
10import {
11 toPersistenceDecodeError,
12 toPersistenceSqlError,
13 type ProviderSessionRuntimeRepositoryError,
14} from "../Errors.ts";
15import {
16 ProviderSessionRuntime,
17 ProviderSessionRuntimeRepository,
18 type ProviderSessionRuntimeRepositoryShape,
19} from "../Services/ProviderSessionRuntime.ts";
20
21const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
22 Struct.assign({
23 resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
24 runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
25 }),
26);
27
28const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime);
29
30const GetRuntimeRequestSchema = Schema.Struct({
31 threadId: ThreadId,
32});
33
34const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
35
36function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
37 return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
38 Schema.isSchemaError(cause)
39 ? toPersistenceDecodeError(decodeOperation)(cause)
40 : toPersistenceSqlError(sqlOperation)(cause);
41}
42
43const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
44 const sql = yield* SqlClient.SqlClient;
45
46 const upsertRuntimeRow = SqlSchema.void({
47 Request: ProviderSessionRuntimeDbRowSchema,
48 execute: (runtime) =>
49 sql`
50 INSERT INTO provider_session_runtime (
51 thread_id,
52 provider_name,
53 provider_instance_id,
54 adapter_key,
55 runtime_mode,
56 status,
57 last_seen_at,
58 resume_cursor_json,
59 runtime_payload_json
60 )
61 VALUES (
62 ${runtime.threadId},
63 ${runtime.providerName},
64 ${runtime.providerInstanceId},
65 ${runtime.adapterKey},
66 ${runtime.runtimeMode},
67 ${runtime.status},
68 ${runtime.lastSeenAt},
69 ${runtime.resumeCursor},
70 ${runtime.runtimePayload}
71 )
72 ON CONFLICT (thread_id)
73 DO UPDATE SET
74 provider_name = excluded.provider_name,
75 provider_instance_id = excluded.provider_instance_id,
76 adapter_key = excluded.adapter_key,
77 runtime_mode = excluded.runtime_mode,
78 status = excluded.status,
79 last_seen_at = excluded.last_seen_at,
80 resume_cursor_json = excluded.resume_cursor_json,
81 runtime_payload_json = excluded.runtime_payload_json
82 `,
83 });
84
85 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
86 Request: GetRuntimeRequestSchema,
87 Result: ProviderSessionRuntimeDbRowSchema,
88 execute: ({ threadId }) =>
89 sql`
90 SELECT
91 thread_id AS "threadId",
92 provider_name AS "providerName",
93 provider_instance_id AS "providerInstanceId",
94 adapter_key AS "adapterKey",
95 runtime_mode AS "runtimeMode",
96 status,
97 last_seen_at AS "lastSeenAt",
98 resume_cursor_json AS "resumeCursor",
99 runtime_payload_json AS "runtimePayload"
100 FROM provider_session_runtime
101 WHERE thread_id = ${threadId}
102 `,
103 });
104
105 const listRuntimeRows = SqlSchema.findAll({
106 Request: Schema.Void,
107 Result: ProviderSessionRuntimeDbRowSchema,
108 execute: () =>
109 sql`
110 SELECT
111 thread_id AS "threadId",
112 provider_name AS "providerName",
113 provider_instance_id AS "providerInstanceId",
114 adapter_key AS "adapterKey",
115 runtime_mode AS "runtimeMode",
116 status,
117 last_seen_at AS "lastSeenAt",
118 resume_cursor_json AS "resumeCursor",
119 runtime_payload_json AS "runtimePayload"
120 FROM provider_session_runtime
121 ORDER BY last_seen_at ASC, thread_id ASC
122 `,
123 });
124
125 const deleteRuntimeByThreadId = SqlSchema.void({
126 Request: DeleteRuntimeRequestSchema,
127 execute: ({ threadId }) =>
128 sql`
129 DELETE FROM provider_session_runtime
130 WHERE thread_id = ${threadId}
131 `,
132 });
133
134 const upsert: ProviderSessionRuntimeRepositoryShape["upsert"] = (runtime) =>
135 upsertRuntimeRow(runtime).pipe(
136 Effect.mapError(
137 toPersistenceSqlOrDecodeError(
138 "ProviderSessionRuntimeRepository.upsert:query",
139 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
140 ),
141 ),
142 );
143
144 const getByThreadId: ProviderSessionRuntimeRepositoryShape["getByThreadId"] = (input) =>
145 getRuntimeRowByThreadId(input).pipe(
146 Effect.mapError(
147 toPersistenceSqlOrDecodeError(
148 "ProviderSessionRuntimeRepository.getByThreadId:query",
149 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
150 ),
151 ),
152 Effect.flatMap((runtimeRowOption) =>
153 Option.match(runtimeRowOption, {
154 onNone: () => Effect.succeed(Option.none()),
155 onSome: (row) =>
156 decodeRuntime(row).pipe(
157 Effect.mapError(
158 toPersistenceDecodeError(
159 "ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
160 ),
161 ),
162 Effect.map((runtime) => Option.some(runtime)),
163 ),
164 }),
165 ),
166 );
167
168 const list: ProviderSessionRuntimeRepositoryShape["list"] = () =>
169 listRuntimeRows(undefined).pipe(
170 Effect.mapError(
171 toPersistenceSqlOrDecodeError(
172 "ProviderSessionRuntimeRepository.list:query",
173 "ProviderSessionRuntimeRepository.list:decodeRows",
174 ),
175 ),
176 Effect.flatMap((rows) =>
177 Effect.forEach(
178 rows,
179 (row) =>
180 decodeRuntime(row).pipe(
181 Effect.mapError(
182 toPersistenceDecodeError("ProviderSessionRuntimeRepository.list:rowToRuntime"),
183 ),
184 ),
185 { concurrency: "unbounded" },
186 ),
187 ),
188 );
189
190 const deleteByThreadId: ProviderSessionRuntimeRepositoryShape["deleteByThreadId"] = (input) =>
191 deleteRuntimeByThreadId(input).pipe(
192 Effect.mapError(
193 toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
194 ),
195 );
196
197 return {
198 upsert,
199 getByThreadId,
200 list,
201 deleteByThreadId,
202 } satisfies ProviderSessionRuntimeRepositoryShape;
203});
204
205export const ProviderSessionRuntimeRepositoryLive = Layer.effect(
206 ProviderSessionRuntimeRepository,
207 makeProviderSessionRuntimeRepository,
208);