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

ProjectionTurns.ts

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