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

ProjectionTurns.ts

629 lines20.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 AcknowledgeProjectionPendingTurnStartInput,
13 ClearCheckpointTurnConflictInput,
14 DeleteProjectionPendingTurnStartInput,
15 DeleteProjectionSubmittedTurnStartsByThreadInput,
16 DeleteProjectionSubmittedTurnStartsInput,
17 DeleteProjectionTurnsAfterCheckpointInput,
18 DeleteProjectionTurnsByThreadInput,
19 GetProjectionAdoptableTurnStartInput,
20 GetProjectionPendingTurnStartInput,
21 GetProjectionSubmittedTurnStartInput,
22 GetProjectionTurnByTurnIdInput,
23 ListProjectionTurnsByThreadInput,
24 ProjectionPendingTurnStart,
25 ProjectionSubmittedTurnStart,
26 ProjectionTurn,
27 ProjectionTurnById,
28 ProjectionTurnRepository,
29 type ProjectionTurnRepositoryShape,
30} from "../Services/ProjectionTurns.ts";
31​
32const ProjectionTurnDbRowSchema = ProjectionTurn.mapFields(
33 Struct.assign({
34 checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
35 }),
36);
37​
38const ProjectionTurnByIdDbRowSchema = ProjectionTurnById.mapFields(
39 Struct.assign({
40 checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
41 }),
42);
43​
44function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
45 return (cause: unknown) =>
46 Schema.isSchemaError(cause)
47 ? toPersistenceDecodeError(decodeOperation)(cause)
48 : toPersistenceSqlError(sqlOperation)(cause);
50​
51const makeProjectionTurnRepository = Effect.gen(function* () {
52 const sql = yield* SqlClient.SqlClient;
53​
54 const upsertProjectionTurnById = SqlSchema.void({
55 Request: ProjectionTurnByIdDbRowSchema,
56 execute: (row) =>
57 sql`
58 INSERT INTO projection_turns (
59 thread_id,
60 turn_id,
61 pending_message_id,
62 submitted_turn_id,
63 source_proposed_plan_thread_id,
64 source_proposed_plan_id,
65 assistant_message_id,
66 state,
67 requested_at,
68 started_at,
69 completed_at,
70 checkpoint_turn_count,
71 checkpoint_ref,
72 checkpoint_status,
73 checkpoint_files_json
74 )
75 VALUES (
76 ${row.threadId},
77 ${row.turnId},
78 ${row.pendingMessageId},
79 NULL,
80 ${row.sourceProposedPlanThreadId},
81 ${row.sourceProposedPlanId},
82 ${row.assistantMessageId},
83 ${row.state},
84 ${row.requestedAt},
85 ${row.startedAt},
86 ${row.completedAt},
87 ${row.checkpointTurnCount},
88 ${row.checkpointRef},
89 ${row.checkpointStatus},
90 ${row.checkpointFiles}
91 )
92 ON CONFLICT (thread_id, turn_id)
93 DO UPDATE SET
94 pending_message_id = excluded.pending_message_id,
95 source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,
96 source_proposed_plan_id = excluded.source_proposed_plan_id,
97 assistant_message_id = excluded.assistant_message_id,
98 state = excluded.state,
99 requested_at = excluded.requested_at,
100 started_at = excluded.started_at,
101 completed_at = excluded.completed_at,
102 checkpoint_turn_count = excluded.checkpoint_turn_count,
103 checkpoint_ref = excluded.checkpoint_ref,
104 checkpoint_status = excluded.checkpoint_status,
105 checkpoint_files_json = excluded.checkpoint_files_json
106 `,
107 });
108​
109 const deletePendingProjectionTurn = SqlSchema.void({
110 Request: DeleteProjectionPendingTurnStartInput,
111 execute: ({ threadId, messageId }) =>
112 sql`
113 DELETE FROM projection_turns
114 WHERE thread_id = ${threadId}
115 AND turn_id IS NULL
116 AND state IN ('pending', 'submitted')
117 AND pending_message_id = ${messageId}
118 AND checkpoint_turn_count IS NULL
119 `,
120 });
121​
122 const markPendingProjectionTurnSubmitted = SqlSchema.void({
123 Request: AcknowledgeProjectionPendingTurnStartInput,
124 execute: ({ threadId, messageId, turnId }) =>
125 sql`
126 UPDATE projection_turns
127 SET state = 'submitted', submitted_turn_id = ${turnId}
128 WHERE thread_id = ${threadId}
129 AND turn_id IS NULL
130 AND state = 'pending'
131 AND pending_message_id = ${messageId}
132 AND checkpoint_turn_count IS NULL
133 `,
134 });
135​
136 const deleteSubmittedProjectionTurnsByTurn = SqlSchema.void({
137 Request: DeleteProjectionSubmittedTurnStartsInput,
138 execute: ({ threadId, turnId }) =>
139 sql`
140 DELETE FROM projection_turns
141 WHERE thread_id = ${threadId}
142 AND turn_id IS NULL
143 AND state = 'submitted'
144 AND submitted_turn_id = ${turnId}
145 AND checkpoint_turn_count IS NULL
146 `,
147 });
148​
149 const deleteSubmittedProjectionTurnsByThread = SqlSchema.void({
150 Request: DeleteProjectionSubmittedTurnStartsByThreadInput,
151 execute: ({ threadId }) =>
152 sql`
153 DELETE FROM projection_turns
154 WHERE thread_id = ${threadId}
155 AND turn_id IS NULL
156 AND state = 'submitted'
157 AND checkpoint_turn_count IS NULL
158 `,
159 });
160​
161 const insertPendingProjectionTurn = SqlSchema.void({
162 Request: ProjectionPendingTurnStart,
163 execute: (row) =>
164 sql`
165 INSERT INTO projection_turns (
166 thread_id,
167 turn_id,
168 pending_message_id,
169 submitted_turn_id,
170 source_proposed_plan_thread_id,
171 source_proposed_plan_id,
172 assistant_message_id,
173 state,
174 requested_at,
175 started_at,
176 completed_at,
177 checkpoint_turn_count,
178 checkpoint_ref,
179 checkpoint_status,
180 checkpoint_files_json
181 )
182 SELECT
183 ${row.threadId},
184 NULL,
185 ${row.messageId},
186 NULL,
187 ${row.sourceProposedPlanThreadId},
188 ${row.sourceProposedPlanId},
189 NULL,
190 'pending',
191 ${row.requestedAt},
192 NULL,
193 NULL,
194 NULL,
195 NULL,
196 NULL,
197 '[]'
198 WHERE NOT EXISTS (
199 SELECT 1
200 FROM projection_turns
201 WHERE thread_id = ${row.threadId}
202 AND turn_id IS NULL
203 AND pending_message_id = ${row.messageId}
204 AND state IN ('pending', 'submitted')
205 AND checkpoint_turn_count IS NULL
206 )
207 `,
208 });
209​
210 const insertSubmittedProjectionTurn = SqlSchema.void({
211 Request: ProjectionSubmittedTurnStart,
212 execute: (row) =>
213 sql`
214 INSERT INTO projection_turns (
215 thread_id,
216 turn_id,
217 pending_message_id,
218 submitted_turn_id,
219 source_proposed_plan_thread_id,
220 source_proposed_plan_id,
221 assistant_message_id,
222 state,
223 requested_at,
224 started_at,
225 completed_at,
226 checkpoint_turn_count,
227 checkpoint_ref,
228 checkpoint_status,
229 checkpoint_files_json
230 )
231 VALUES (
232 ${row.threadId},
233 NULL,
234 ${row.messageId},
235 ${row.turnId},
236 ${row.sourceProposedPlanThreadId},
237 ${row.sourceProposedPlanId},
238 NULL,
239 'submitted',
240 ${row.requestedAt},
241 NULL,
242 NULL,
243 NULL,
244 NULL,
245 NULL,
246 '[]'
247 )
248 `,
249 });
250​
251 const getPendingProjectionTurn = SqlSchema.findOneOption({
252 Request: GetProjectionPendingTurnStartInput,
253 Result: ProjectionPendingTurnStart,
254 execute: ({ threadId }) =>
255 sql`
256 SELECT
257 thread_id AS "threadId",
258 pending_message_id AS "messageId",
259 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
260 source_proposed_plan_id AS "sourceProposedPlanId",
261 requested_at AS "requestedAt"
262 FROM projection_turns
263 WHERE thread_id = ${threadId}
264 AND turn_id IS NULL
265 AND state = 'pending'
266 AND pending_message_id IS NOT NULL
267 AND checkpoint_turn_count IS NULL
268 ORDER BY row_id ASC
269 LIMIT 1
270 `,
271 });
272​
273 const getUnresolvedProjectionTurn = SqlSchema.findOneOption({
274 Request: GetProjectionPendingTurnStartInput,
275 Result: ProjectionPendingTurnStart,
276 execute: ({ threadId }) =>
277 sql`
278 SELECT
279 thread_id AS "threadId",
280 pending_message_id AS "messageId",
281 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
282 source_proposed_plan_id AS "sourceProposedPlanId",
283 requested_at AS "requestedAt"
284 FROM projection_turns
285 WHERE thread_id = ${threadId}
286 AND turn_id IS NULL
287 AND state IN ('pending', 'submitted')
288 AND pending_message_id IS NOT NULL
289 AND checkpoint_turn_count IS NULL
290 ORDER BY row_id ASC
291 LIMIT 1
292 `,
293 });
294​
295 const getAdoptableProjectionTurn = SqlSchema.findOneOption({
296 Request: GetProjectionAdoptableTurnStartInput,
297 Result: ProjectionPendingTurnStart,
298 execute: ({ threadId, turnId }) =>
299 sql`
300 SELECT
301 thread_id AS "threadId",
302 pending_message_id AS "messageId",
303 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
304 source_proposed_plan_id AS "sourceProposedPlanId",
305 requested_at AS "requestedAt"
306 FROM projection_turns AS candidate
307 WHERE candidate.thread_id = ${threadId}
308 AND candidate.turn_id IS NULL
309 AND (
310 (candidate.state = 'submitted' AND candidate.submitted_turn_id = ${turnId})
311 OR (
312 candidate.state = 'pending'
313 AND (
314 SELECT COUNT(*)
315 FROM projection_turns AS pending
316 WHERE pending.thread_id = ${threadId}
317 AND pending.turn_id IS NULL
318 AND pending.state = 'pending'
319 AND pending.pending_message_id IS NOT NULL
320 AND pending.checkpoint_turn_count IS NULL
321 ) = 1
322 )
323 )
324 AND candidate.pending_message_id IS NOT NULL
325 AND candidate.checkpoint_turn_count IS NULL
326 ORDER BY
327 CASE
328 WHEN candidate.state = 'submitted' AND candidate.submitted_turn_id = ${turnId} THEN 0
329 ELSE 1
330 END,
331 candidate.row_id ASC
332 LIMIT 1
333 `,
334 });
335​
336 const getSubmittedProjectionTurn = SqlSchema.findOneOption({
337 Request: GetProjectionSubmittedTurnStartInput,
338 Result: ProjectionPendingTurnStart,
339 execute: ({ threadId, turnId }) =>
340 sql`
341 SELECT
342 thread_id AS "threadId",
343 pending_message_id AS "messageId",
344 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
345 source_proposed_plan_id AS "sourceProposedPlanId",
346 requested_at AS "requestedAt"
347 FROM projection_turns
348 WHERE thread_id = ${threadId}
349 AND turn_id IS NULL
350 AND state = 'submitted'
351 AND submitted_turn_id = ${turnId}
352 AND pending_message_id IS NOT NULL
353 AND checkpoint_turn_count IS NULL
354 ORDER BY row_id ASC
355 LIMIT 1
356 `,
357 });
358​
359 const listProjectionTurnsByThread = SqlSchema.findAll({
360 Request: ListProjectionTurnsByThreadInput,
361 Result: ProjectionTurnDbRowSchema,
362 execute: ({ threadId }) =>
363 sql`
364 SELECT
365 thread_id AS "threadId",
366 turn_id AS "turnId",
367 submitted_turn_id AS "submittedTurnId",
368 pending_message_id AS "pendingMessageId",
369 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
370 source_proposed_plan_id AS "sourceProposedPlanId",
371 assistant_message_id AS "assistantMessageId",
372 state,
373 requested_at AS "requestedAt",
374 started_at AS "startedAt",
375 completed_at AS "completedAt",
376 checkpoint_turn_count AS "checkpointTurnCount",
377 checkpoint_ref AS "checkpointRef",
378 checkpoint_status AS "checkpointStatus",
379 checkpoint_files_json AS "checkpointFiles"
380 FROM projection_turns
381 WHERE thread_id = ${threadId}
382 ORDER BY
383 CASE
384 WHEN checkpoint_turn_count IS NULL THEN 1
385 ELSE 0
386 END ASC,
387 checkpoint_turn_count ASC,
388 requested_at ASC,
389 turn_id ASC
390 `,
391 });
392​
393 const getProjectionTurnByTurnId = SqlSchema.findOneOption({
394 Request: GetProjectionTurnByTurnIdInput,
395 Result: ProjectionTurnByIdDbRowSchema,
396 execute: ({ threadId, turnId }) =>
397 sql`
398 SELECT
399 thread_id AS "threadId",
400 turn_id AS "turnId",
401 pending_message_id AS "pendingMessageId",
402 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
403 source_proposed_plan_id AS "sourceProposedPlanId",
404 assistant_message_id AS "assistantMessageId",
405 state,
406 requested_at AS "requestedAt",
407 started_at AS "startedAt",
408 completed_at AS "completedAt",
409 checkpoint_turn_count AS "checkpointTurnCount",
410 checkpoint_ref AS "checkpointRef",
411 checkpoint_status AS "checkpointStatus",
412 checkpoint_files_json AS "checkpointFiles"
413 FROM projection_turns
414 WHERE thread_id = ${threadId}
415 AND turn_id = ${turnId}
416 LIMIT 1
417 `,
418 });
419​
420 const clearCheckpointTurnConflictRow = SqlSchema.void({
421 Request: ClearCheckpointTurnConflictInput,
422 execute: ({ threadId, turnId, checkpointTurnCount }) =>
423 sql`
424 UPDATE projection_turns
425 SET
426 checkpoint_turn_count = NULL,
427 checkpoint_ref = NULL,
428 checkpoint_status = NULL,
429 checkpoint_files_json = '[]'
430 WHERE thread_id = ${threadId}
431 AND checkpoint_turn_count = ${checkpointTurnCount}
432 AND (turn_id IS NULL OR turn_id <> ${turnId})
433 `,
434 });
435​
436 const deleteProjectionTurnsByThread = SqlSchema.void({
437 Request: DeleteProjectionTurnsByThreadInput,
438 execute: ({ threadId }) =>
439 sql`
440 DELETE FROM projection_turns
441 WHERE thread_id = ${threadId}
442 `,
443 });
444​
445 const deleteProjectionTurnsAfterCheckpoint = SqlSchema.void({
446 Request: DeleteProjectionTurnsAfterCheckpointInput,
447 execute: ({ threadId, turnCount }) =>
448 sql`
449 DELETE FROM projection_turns
450 WHERE thread_id = ${threadId}
451 AND turn_id IS NOT NULL
452 AND (
453 checkpoint_turn_count IS NULL
454 OR checkpoint_turn_count > ${turnCount}
455 )
456 `,
457 });
458​
459 const upsertByTurnId: ProjectionTurnRepositoryShape["upsertByTurnId"] = (row) =>
460 upsertProjectionTurnById(row).pipe(
461 Effect.mapError(
462 toPersistenceSqlOrDecodeError(
463 "ProjectionTurnRepository.upsertByTurnId:query",
464 "ProjectionTurnRepository.upsertByTurnId:encodeRequest",
465 ),
466 ),
467 );
468​
469 const insertPendingTurnStart: ProjectionTurnRepositoryShape["insertPendingTurnStart"] = (row) =>
470 insertPendingProjectionTurn(row).pipe(
471 Effect.mapError(
472 toPersistenceSqlOrDecodeError(
473 "ProjectionTurnRepository.insertPendingTurnStart:query",
474 "ProjectionTurnRepository.insertPendingTurnStart:encodeRequest",
475 ),
476 ),
477 );
478​
479 const insertSubmittedTurnStart: ProjectionTurnRepositoryShape["insertSubmittedTurnStart"] = (
480 row,
481 ) =>
482 insertSubmittedProjectionTurn(row).pipe(
483 Effect.mapError(
484 toPersistenceSqlOrDecodeError(
485 "ProjectionTurnRepository.insertSubmittedTurnStart:query",
486 "ProjectionTurnRepository.insertSubmittedTurnStart:encodeRequest",
487 ),
488 ),
489 );
490​
491 const markPendingTurnStartSubmitted: ProjectionTurnRepositoryShape["markPendingTurnStartSubmitted"] =
492 (input) =>
493 markPendingProjectionTurnSubmitted(input).pipe(
494 Effect.mapError(
495 toPersistenceSqlError("ProjectionTurnRepository.markPendingTurnStartSubmitted:query"),
496 ),
497 );
498​
499 const deleteSubmittedTurnStartsByTurnId: ProjectionTurnRepositoryShape["deleteSubmittedTurnStartsByTurnId"] =
500 (input) =>
501 deleteSubmittedProjectionTurnsByTurn(input).pipe(
502 Effect.mapError(
503 toPersistenceSqlError("ProjectionTurnRepository.deleteSubmittedTurnStartsByTurnId:query"),
504 ),
505 );
506​
507 const deleteSubmittedTurnStartsByThreadId: ProjectionTurnRepositoryShape["deleteSubmittedTurnStartsByThreadId"] =
508 (input) =>
509 deleteSubmittedProjectionTurnsByThread(input).pipe(
510 Effect.mapError(
511 toPersistenceSqlError(
512 "ProjectionTurnRepository.deleteSubmittedTurnStartsByThreadId:query",
513 ),
514 ),
515 );
516​
517 const getPendingTurnStartByThreadId: ProjectionTurnRepositoryShape["getPendingTurnStartByThreadId"] =
518 (input) =>
519 getPendingProjectionTurn(input).pipe(
520 Effect.mapError(
521 toPersistenceSqlError("ProjectionTurnRepository.getPendingTurnStartByThreadId:query"),
522 ),
523 );
524​
525 const getUnresolvedTurnStartByThreadId: ProjectionTurnRepositoryShape["getUnresolvedTurnStartByThreadId"] =
526 (input) =>
527 getUnresolvedProjectionTurn(input).pipe(
528 Effect.mapError(
529 toPersistenceSqlError("ProjectionTurnRepository.getUnresolvedTurnStartByThreadId:query"),
530 ),
531 );
532​
533 const getAdoptableTurnStartByThreadId: ProjectionTurnRepositoryShape["getAdoptableTurnStartByThreadId"] =
534 (input) =>
535 getAdoptableProjectionTurn(input).pipe(
536 Effect.mapError(
537 toPersistenceSqlError("ProjectionTurnRepository.getAdoptableTurnStartByThreadId:query"),
538 ),
539 );
540​
541 const getSubmittedTurnStartByTurnId: ProjectionTurnRepositoryShape["getSubmittedTurnStartByTurnId"] =
542 (input) =>
543 getSubmittedProjectionTurn(input).pipe(
544 Effect.mapError(
545 toPersistenceSqlError("ProjectionTurnRepository.getSubmittedTurnStartByTurnId:query"),
546 ),
547 );
548​
549 const deletePendingTurnStart: ProjectionTurnRepositoryShape["deletePendingTurnStart"] = (input) =>
550 deletePendingProjectionTurn(input).pipe(
551 Effect.mapError(
552 toPersistenceSqlError("ProjectionTurnRepository.deletePendingTurnStart:query"),
553 ),
554 );
555​
556 const listByThreadId: ProjectionTurnRepositoryShape["listByThreadId"] = (input) =>
557 listProjectionTurnsByThread(input).pipe(
558 Effect.mapError(
559 toPersistenceSqlOrDecodeError(
560 "ProjectionTurnRepository.listByThreadId:query",
561 "ProjectionTurnRepository.listByThreadId:decodeRows",
562 ),
563 ),
564 Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionTurn>>),
565 );
566​
567 const getByTurnId: ProjectionTurnRepositoryShape["getByTurnId"] = (input) =>
568 getProjectionTurnByTurnId(input).pipe(
569 Effect.mapError(
570 toPersistenceSqlOrDecodeError(
571 "ProjectionTurnRepository.getByTurnId:query",
572 "ProjectionTurnRepository.getByTurnId:decodeRow",
573 ),
574 ),
575 Effect.flatMap((rowOption) =>
576 Option.match(rowOption, {
577 onNone: () => Effect.succeed(Option.none()),
578 onSome: (row) =>
579 Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionTurnById>)),
580 }),
581 ),
582 );
583​
584 const clearCheckpointTurnConflict: ProjectionTurnRepositoryShape["clearCheckpointTurnConflict"] =
585 (input) =>
586 clearCheckpointTurnConflictRow(input).pipe(
587 Effect.mapError(
588 toPersistenceSqlError("ProjectionTurnRepository.clearCheckpointTurnConflict:query"),
589 ),
590 );
591​
592 const deleteByThreadId: ProjectionTurnRepositoryShape["deleteByThreadId"] = (input) =>
593 deleteProjectionTurnsByThread(input).pipe(
594 Effect.mapError(toPersistenceSqlError("ProjectionTurnRepository.deleteByThreadId:query")),
595 );
596​
597 const deleteTurnsAfterCheckpoint: ProjectionTurnRepositoryShape["deleteTurnsAfterCheckpoint"] = (
598 input,
599 ) =>
600 deleteProjectionTurnsAfterCheckpoint(input).pipe(
601 Effect.mapError(
602 toPersistenceSqlError("ProjectionTurnRepository.deleteTurnsAfterCheckpoint:query"),
603 ),
604 );
605​
606 return {
607 upsertByTurnId,
608 insertPendingTurnStart,
609 insertSubmittedTurnStart,
610 markPendingTurnStartSubmitted,
611 deleteSubmittedTurnStartsByTurnId,
612 deleteSubmittedTurnStartsByThreadId,
613 getPendingTurnStartByThreadId,
614 getUnresolvedTurnStartByThreadId,
615 getAdoptableTurnStartByThreadId,
616 getSubmittedTurnStartByTurnId,
617 deletePendingTurnStart,
618 deleteTurnsAfterCheckpoint,
619 listByThreadId,
620 getByTurnId,
621 clearCheckpointTurnConflict,
622 deleteByThreadId,
623 } satisfies ProjectionTurnRepositoryShape;
624});
625​
626export const ProjectionTurnRepositoryLive = Layer.effect(
627 ProjectionTurnRepository,
628 makeProjectionTurnRepository,
629);