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