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