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

ProjectionTurns.ts

335 lines10.6 KB

1import { OrchestrationCheckpointFile } 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 { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
7import {
8 ClearCheckpointTurnConflictInput,
9 DeleteProjectionTurnsByThreadInput,
10 GetProjectionPendingTurnStartInput,
11 GetProjectionTurnByTurnIdInput,
12 ListProjectionTurnsByThreadInput,
13 ProjectionPendingTurnStart,
14 ProjectionTurn,
15 ProjectionTurnById,
16 ProjectionTurnRepository,
17 type ProjectionTurnRepositoryShape,
18} from "../Services/ProjectionTurns.ts";
19​
20const ProjectionTurnDbRowSchema = ProjectionTurn.mapFields(
21 Struct.assign({
22 checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
23 }),
24);
25​
26const ProjectionTurnByIdDbRowSchema = ProjectionTurnById.mapFields(
27 Struct.assign({
28 checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
29 }),
30);
31​
32function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
33 return (cause: unknown) =>
34 Schema.isSchemaError(cause)
35 ? toPersistenceDecodeError(decodeOperation)(cause)
36 : toPersistenceSqlError(sqlOperation)(cause);
38​
39const makeProjectionTurnRepository = Effect.gen(function* () {
40 const sql = yield* SqlClient.SqlClient;
41​
42 const upsertProjectionTurnById = SqlSchema.void({
43 Request: ProjectionTurnByIdDbRowSchema,
44 execute: (row) =>
45 sql`
46 INSERT INTO projection_turns (
47 thread_id,
48 turn_id,
49 pending_message_id,
50 assistant_message_id,
51 state,
52 requested_at,
53 started_at,
54 completed_at,
55 checkpoint_turn_count,
56 checkpoint_ref,
57 checkpoint_status,
58 checkpoint_files_json
59 )
60 VALUES (
61 ${row.threadId},
62 ${row.turnId},
63 ${row.pendingMessageId},
64 ${row.assistantMessageId},
65 ${row.state},
66 ${row.requestedAt},
67 ${row.startedAt},
68 ${row.completedAt},
69 ${row.checkpointTurnCount},
70 ${row.checkpointRef},
71 ${row.checkpointStatus},
72 ${row.checkpointFiles}
73 )
74 ON CONFLICT (thread_id, turn_id)
75 DO UPDATE SET
76 pending_message_id = excluded.pending_message_id,
77 assistant_message_id = excluded.assistant_message_id,
78 state = excluded.state,
79 requested_at = excluded.requested_at,
80 started_at = excluded.started_at,
81 completed_at = excluded.completed_at,
82 checkpoint_turn_count = excluded.checkpoint_turn_count,
83 checkpoint_ref = excluded.checkpoint_ref,
84 checkpoint_status = excluded.checkpoint_status,
85 checkpoint_files_json = excluded.checkpoint_files_json
86 `,
87 });
88​
89 const clearPendingProjectionTurnsByThread = SqlSchema.void({
90 Request: DeleteProjectionTurnsByThreadInput,
91 execute: ({ threadId }) =>
92 sql`
93 DELETE FROM projection_turns
94 WHERE thread_id = ${threadId}
95 AND turn_id IS NULL
96 AND state = 'pending'
97 AND checkpoint_turn_count IS NULL
98 `,
99 });
100​
101 const insertPendingProjectionTurn = SqlSchema.void({
102 Request: ProjectionPendingTurnStart,
103 execute: (row) =>
104 sql`
105 INSERT INTO projection_turns (
106 thread_id,
107 turn_id,
108 pending_message_id,
109 assistant_message_id,
110 state,
111 requested_at,
112 started_at,
113 completed_at,
114 checkpoint_turn_count,
115 checkpoint_ref,
116 checkpoint_status,
117 checkpoint_files_json
118 )
119 VALUES (
120 ${row.threadId},
121 NULL,
122 ${row.messageId},
123 NULL,
124 'pending',
125 ${row.requestedAt},
126 NULL,
127 NULL,
128 NULL,
129 NULL,
130 NULL,
131 '[]'
132 )
133 `,
134 });
135​
136 const getPendingProjectionTurn = SqlSchema.findOneOption({
137 Request: GetProjectionPendingTurnStartInput,
138 Result: ProjectionPendingTurnStart,
139 execute: ({ threadId }) =>
140 sql`
141 SELECT
142 thread_id AS "threadId",
143 pending_message_id AS "messageId",
144 requested_at AS "requestedAt"
145 FROM projection_turns
146 WHERE thread_id = ${threadId}
147 AND turn_id IS NULL
148 AND state = 'pending'
149 AND pending_message_id IS NOT NULL
150 AND checkpoint_turn_count IS NULL
151 ORDER BY requested_at DESC
152 LIMIT 1
153 `,
154 });
155​
156 const listProjectionTurnsByThread = SqlSchema.findAll({
157 Request: ListProjectionTurnsByThreadInput,
158 Result: ProjectionTurnDbRowSchema,
159 execute: ({ threadId }) =>
160 sql`
161 SELECT
162 thread_id AS "threadId",
163 turn_id AS "turnId",
164 pending_message_id AS "pendingMessageId",
165 assistant_message_id AS "assistantMessageId",
166 state,
167 requested_at AS "requestedAt",
168 started_at AS "startedAt",
169 completed_at AS "completedAt",
170 checkpoint_turn_count AS "checkpointTurnCount",
171 checkpoint_ref AS "checkpointRef",
172 checkpoint_status AS "checkpointStatus",
173 checkpoint_files_json AS "checkpointFiles"
174 FROM projection_turns
175 WHERE thread_id = ${threadId}
176 ORDER BY
177 CASE
178 WHEN checkpoint_turn_count IS NULL THEN 1
179 ELSE 0
180 END ASC,
181 checkpoint_turn_count ASC,
182 requested_at ASC,
183 turn_id ASC
184 `,
185 });
186​
187 const getProjectionTurnByTurnId = SqlSchema.findOneOption({
188 Request: GetProjectionTurnByTurnIdInput,
189 Result: ProjectionTurnByIdDbRowSchema,
190 execute: ({ threadId, turnId }) =>
191 sql`
192 SELECT
193 thread_id AS "threadId",
194 turn_id AS "turnId",
195 pending_message_id AS "pendingMessageId",
196 assistant_message_id AS "assistantMessageId",
197 state,
198 requested_at AS "requestedAt",
199 started_at AS "startedAt",
200 completed_at AS "completedAt",
201 checkpoint_turn_count AS "checkpointTurnCount",
202 checkpoint_ref AS "checkpointRef",
203 checkpoint_status AS "checkpointStatus",
204 checkpoint_files_json AS "checkpointFiles"
205 FROM projection_turns
206 WHERE thread_id = ${threadId}
207 AND turn_id = ${turnId}
208 LIMIT 1
209 `,
210 });
211​
212 const clearCheckpointTurnConflictRow = SqlSchema.void({
213 Request: ClearCheckpointTurnConflictInput,
214 execute: ({ threadId, turnId, checkpointTurnCount }) =>
215 sql`
216 UPDATE projection_turns
217 SET
218 checkpoint_turn_count = NULL,
219 checkpoint_ref = NULL,
220 checkpoint_status = NULL,
221 checkpoint_files_json = '[]'
222 WHERE thread_id = ${threadId}
223 AND checkpoint_turn_count = ${checkpointTurnCount}
224 AND (turn_id IS NULL OR turn_id <> ${turnId})
225 `,
226 });
227​
228 const deleteProjectionTurnsByThread = SqlSchema.void({
229 Request: DeleteProjectionTurnsByThreadInput,
230 execute: ({ threadId }) =>
231 sql`
232 DELETE FROM projection_turns
233 WHERE thread_id = ${threadId}
234 `,
235 });
236​
237 const upsertByTurnId: ProjectionTurnRepositoryShape["upsertByTurnId"] = (row) =>
238 upsertProjectionTurnById(row).pipe(
239 Effect.mapError(
240 toPersistenceSqlOrDecodeError(
241 "ProjectionTurnRepository.upsertByTurnId:query",
242 "ProjectionTurnRepository.upsertByTurnId:encodeRequest",
243 ),
244 ),
245 );
246​
247 const replacePendingTurnStart: ProjectionTurnRepositoryShape["replacePendingTurnStart"] = (row) =>
248 sql
249 .withTransaction(
250 clearPendingProjectionTurnsByThread({ threadId: row.threadId }).pipe(
251 Effect.flatMap(() => insertPendingProjectionTurn(row)),
252 ),
253 )
254 .pipe(
255 Effect.mapError(
256 toPersistenceSqlOrDecodeError(
257 "ProjectionTurnRepository.replacePendingTurnStart:query",
258 "ProjectionTurnRepository.replacePendingTurnStart:encodeRequest",
259 ),
260 ),
261 );
262​
263 const getPendingTurnStartByThreadId: ProjectionTurnRepositoryShape["getPendingTurnStartByThreadId"] =
264 (input) =>
265 getPendingProjectionTurn(input).pipe(
266 Effect.mapError(
267 toPersistenceSqlError("ProjectionTurnRepository.getPendingTurnStartByThreadId:query"),
268 ),
269 );
270​
271 const deletePendingTurnStartByThreadId: ProjectionTurnRepositoryShape["deletePendingTurnStartByThreadId"] =
272 (input) =>
273 clearPendingProjectionTurnsByThread(input).pipe(
274 Effect.mapError(
275 toPersistenceSqlError("ProjectionTurnRepository.deletePendingTurnStartByThreadId:query"),
276 ),
277 );
278​
279 const listByThreadId: ProjectionTurnRepositoryShape["listByThreadId"] = (input) =>
280 listProjectionTurnsByThread(input).pipe(
281 Effect.mapError(
282 toPersistenceSqlOrDecodeError(
283 "ProjectionTurnRepository.listByThreadId:query",
284 "ProjectionTurnRepository.listByThreadId:decodeRows",
285 ),
286 ),
287 Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionTurn>>),
288 );
289​
290 const getByTurnId: ProjectionTurnRepositoryShape["getByTurnId"] = (input) =>
291 getProjectionTurnByTurnId(input).pipe(
292 Effect.mapError(
293 toPersistenceSqlOrDecodeError(
294 "ProjectionTurnRepository.getByTurnId:query",
295 "ProjectionTurnRepository.getByTurnId:decodeRow",
296 ),
297 ),
298 Effect.flatMap((rowOption) =>
299 Option.match(rowOption, {
300 onNone: () => Effect.succeed(Option.none()),
301 onSome: (row) =>
302 Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionTurnById>)),
303 }),
304 ),
305 );
306​
307 const clearCheckpointTurnConflict: ProjectionTurnRepositoryShape["clearCheckpointTurnConflict"] =
308 (input) =>
309 clearCheckpointTurnConflictRow(input).pipe(
310 Effect.mapError(
311 toPersistenceSqlError("ProjectionTurnRepository.clearCheckpointTurnConflict:query"),
312 ),
313 );
314​
315 const deleteByThreadId: ProjectionTurnRepositoryShape["deleteByThreadId"] = (input) =>
316 deleteProjectionTurnsByThread(input).pipe(
317 Effect.mapError(toPersistenceSqlError("ProjectionTurnRepository.deleteByThreadId:query")),
318 );
319​
320 return {
321 upsertByTurnId,
322 replacePendingTurnStart,
323 getPendingTurnStartByThreadId,
324 deletePendingTurnStartByThreadId,
325 listByThreadId,
326 getByTurnId,
327 clearCheckpointTurnConflict,
328 deleteByThreadId,
329 } satisfies ProjectionTurnRepositoryShape;
330});
331​
332export const ProjectionTurnRepositoryLive = Layer.effect(
333 ProjectionTurnRepository,
334 makeProjectionTurnRepository,
335);