Open History to see the last commit
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 DeleteByThreadIdInput,
9 GetByThreadAndTurnCountInput,
10 ListByThreadIdInput,
11 ProjectionCheckpoint,
12 ProjectionCheckpointRepository,
13 type ProjectionCheckpointRepositoryShape,
14} from "../Services/ProjectionCheckpoints.ts";
15
16const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
17 Struct.assign({
18 files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
19 }),
20);
21
22function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
23 return (cause: unknown) =>
24 Schema.isSchemaError(cause)
25 ? toPersistenceDecodeError(decodeOperation)(cause)
26 : toPersistenceSqlError(sqlOperation)(cause);
27}
28
29const makeProjectionCheckpointRepository = Effect.gen(function* () {
30 const sql = yield* SqlClient.SqlClient;
31
32 const clearCheckpointConflict = SqlSchema.void({
33 Request: GetByThreadAndTurnCountInput,
34 execute: ({ threadId, checkpointTurnCount }) =>
35 sql`
36 UPDATE projection_turns
37 SET
38 checkpoint_turn_count = NULL,
39 checkpoint_ref = NULL,
40 checkpoint_status = NULL,
41 checkpoint_files_json = '[]'
42 WHERE thread_id = ${threadId}
43 AND checkpoint_turn_count = ${checkpointTurnCount}
44 `,
45 });
46
47 const upsertProjectionCheckpointRow = SqlSchema.void({
48 Request: ProjectionCheckpointDbRowSchema,
49 execute: (row) =>
50 sql`
51 INSERT INTO projection_turns (
52 thread_id,
53 turn_id,
54 pending_message_id,
55 assistant_message_id,
56 state,
57 requested_at,
58 started_at,
59 completed_at,
60 checkpoint_turn_count,
61 checkpoint_ref,
62 checkpoint_status,
63 checkpoint_files_json
64 )
65 VALUES (
66 ${row.threadId},
67 ${row.turnId},
68 NULL,
69 ${row.assistantMessageId},
70 ${row.status === "error" ? "error" : "completed"},
71 ${row.completedAt},
72 ${row.completedAt},
73 ${row.completedAt},
74 ${row.checkpointTurnCount},
75 ${row.checkpointRef},
76 ${row.status},
77 ${row.files}
78 )
79 ON CONFLICT (thread_id, turn_id)
80 DO UPDATE SET
81 assistant_message_id = excluded.assistant_message_id,
82 state = excluded.state,
83 completed_at = excluded.completed_at,
84 checkpoint_turn_count = excluded.checkpoint_turn_count,
85 checkpoint_ref = excluded.checkpoint_ref,
86 checkpoint_status = excluded.checkpoint_status,
87 checkpoint_files_json = excluded.checkpoint_files_json
88 `,
89 });
90
91 const listProjectionCheckpointRows = SqlSchema.findAll({
92 Request: ListByThreadIdInput,
93 Result: ProjectionCheckpointDbRowSchema,
94 execute: ({ threadId }) =>
95 sql`
96 SELECT
97 thread_id AS "threadId",
98 turn_id AS "turnId",
99 checkpoint_turn_count AS "checkpointTurnCount",
100 checkpoint_ref AS "checkpointRef",
101 checkpoint_status AS "status",
102 checkpoint_files_json AS "files",
103 assistant_message_id AS "assistantMessageId",
104 completed_at AS "completedAt"
105 FROM projection_turns
106 WHERE thread_id = ${threadId}
107 AND checkpoint_turn_count IS NOT NULL
108 ORDER BY checkpoint_turn_count ASC
109 `,
110 });
111
112 const getProjectionCheckpointRow = SqlSchema.findOneOption({
113 Request: GetByThreadAndTurnCountInput,
114 Result: ProjectionCheckpointDbRowSchema,
115 execute: ({ threadId, checkpointTurnCount }) =>
116 sql`
117 SELECT
118 thread_id AS "threadId",
119 turn_id AS "turnId",
120 checkpoint_turn_count AS "checkpointTurnCount",
121 checkpoint_ref AS "checkpointRef",
122 checkpoint_status AS "status",
123 checkpoint_files_json AS "files",
124 assistant_message_id AS "assistantMessageId",
125 completed_at AS "completedAt"
126 FROM projection_turns
127 WHERE thread_id = ${threadId}
128 AND checkpoint_turn_count = ${checkpointTurnCount}
129 `,
130 });
131
132 const deleteProjectionCheckpointRows = SqlSchema.void({
133 Request: DeleteByThreadIdInput,
134 execute: ({ threadId }) =>
135 sql`
136 UPDATE projection_turns
137 SET
138 checkpoint_turn_count = NULL,
139 checkpoint_ref = NULL,
140 checkpoint_status = NULL,
141 checkpoint_files_json = '[]'
142 WHERE thread_id = ${threadId}
143 AND checkpoint_turn_count IS NOT NULL
144 `,
145 });
146
147 const upsertCheckpointRow = (row: Schema.Schema.Type<typeof ProjectionCheckpointDbRowSchema>) =>
148 sql.withTransaction(
149 clearCheckpointConflict({
150 threadId: row.threadId,
151 checkpointTurnCount: row.checkpointTurnCount,
152 }).pipe(Effect.flatMap(() => upsertProjectionCheckpointRow(row))),
153 );
154
155 const upsert: ProjectionCheckpointRepositoryShape["upsert"] = (row) =>
156 upsertCheckpointRow(row).pipe(
157 Effect.mapError(
158 toPersistenceSqlOrDecodeError(
159 "ProjectionCheckpointRepository.upsert:query",
160 "ProjectionCheckpointRepository.upsert:encodeRequest",
161 ),
162 ),
163 );
164
165 const listByThreadId: ProjectionCheckpointRepositoryShape["listByThreadId"] = (input) =>
166 listProjectionCheckpointRows(input).pipe(
167 Effect.mapError(
168 toPersistenceSqlOrDecodeError(
169 "ProjectionCheckpointRepository.listByThreadId:query",
170 "ProjectionCheckpointRepository.listByThreadId:decodeRows",
171 ),
172 ),
173 Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionCheckpoint>>),
174 );
175
176 const getByThreadAndTurnCount: ProjectionCheckpointRepositoryShape["getByThreadAndTurnCount"] = (
177 input,
178 ) =>
179 getProjectionCheckpointRow(input).pipe(
180 Effect.mapError(
181 toPersistenceSqlOrDecodeError(
182 "ProjectionCheckpointRepository.getByThreadAndTurnCount:query",
183 "ProjectionCheckpointRepository.getByThreadAndTurnCount:decodeRow",
184 ),
185 ),
186 Effect.flatMap((rowOption) =>
187 Option.match(rowOption, {
188 onNone: () => Effect.succeed(Option.none()),
189 onSome: (row) =>
190 Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionCheckpoint>)),
191 }),
192 ),
193 );
194
195 const deleteByThreadId: ProjectionCheckpointRepositoryShape["deleteByThreadId"] = (input) =>
196 deleteProjectionCheckpointRows(input).pipe(
197 Effect.mapError(
198 toPersistenceSqlError("ProjectionCheckpointRepository.deleteByThreadId:query"),
199 ),
200 );
201
202 return {
203 upsert,
204 listByThreadId,
205 getByThreadAndTurnCount,
206 deleteByThreadId,
207 } satisfies ProjectionCheckpointRepositoryShape;
208});
209
210export const ProjectionCheckpointRepositoryLive = Layer.effect(
211 ProjectionCheckpointRepository,
212 makeProjectionCheckpointRepository,
213);