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

ProjectionTurns.ts

355 lines11.6 KB

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