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

ProjectionThreadMessages.ts

372 lines12.0 KB

1import * as SqlClient from "effect/unstable/sql/SqlClient";
2import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as Struct from "effect/Struct";
8import {
9 ChatAttachment,
10 OrchestrationMessageContext,
11 TrimmedNonEmptyString,
12} from "@t3tools/contracts";
13​
14import { toPersistenceSqlError } from "../Errors.ts";
15import {
16 AppendStreamingProjectionThreadMessage,
17 GetLatestProjectionThreadAssistantMessageInput,
18 GetProjectionThreadMessageInput,
19 HasProjectionThreadAssistantMessageInput,
20 ProjectionThreadMessageRepository,
21 type ProjectionThreadMessageRepositoryShape,
22 DeleteProjectionThreadMessagesInput,
23 ListProjectionThreadMessagesInput,
24 ProjectionThreadMessage,
25} from "../Services/ProjectionThreadMessages.ts";
26​
27const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
28 Struct.assign({
29 isStreaming: Schema.Number,
30 actualModel: Schema.NullOr(TrimmedNonEmptyString),
31 attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
32 context: Schema.NullOr(Schema.fromJsonString(OrchestrationMessageContext)),
33 }),
34);
35const ProjectionThreadMessageExistsDbRowSchema = Schema.Struct({ exists: Schema.Number });
36const ProjectionThreadMessageIdDbRowSchema = Schema.Struct({
37 messageId: ProjectionThreadMessage.fields.messageId,
38});
39​
40function toProjectionThreadMessage(
41 row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,
42): ProjectionThreadMessage {
43 return {
44 messageId: row.messageId,
45 threadId: row.threadId,
46 turnId: row.turnId,
47 role: row.role,
48 text: row.text,
49 ...(row.actualModel !== null ? { actualModel: row.actualModel } : {}),
50 isStreaming: row.isStreaming === 1,
51 createdAt: row.createdAt,
52 updatedAt: row.updatedAt,
53 ...(row.attachments !== null ? { attachments: row.attachments } : {}),
54 ...(row.context !== null ? { context: row.context } : {}),
55 };
57​
58const makeProjectionThreadMessageRepository = Effect.gen(function* () {
59 const sql = yield* SqlClient.SqlClient;
60​
61 const upsertProjectionThreadMessageRow = SqlSchema.void({
62 Request: ProjectionThreadMessage,
63 execute: (row) => {
64 const nextAttachmentsJson =
65 row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
66 const nextContextJson = row.context !== undefined ? JSON.stringify(row.context) : null;
67 return sql`
68 INSERT INTO projection_thread_messages (
69 message_id,
70 thread_id,
71 turn_id,
72 role,
73 text,
74 actual_model,
75 attachments_json,
76 context_json,
77 is_streaming,
78 created_at,
79 updated_at
80 )
81 VALUES (
82 ${row.messageId},
83 ${row.threadId},
84 ${row.turnId},
85 ${row.role},
86 ${row.text},
87 COALESCE(
88 ${row.actualModel ?? null},
89 (
90 SELECT actual_model
91 FROM projection_thread_messages
92 WHERE message_id = ${row.messageId}
93 )
94 ),
95 COALESCE(
96 ${nextAttachmentsJson},
97 (
98 SELECT attachments_json
99 FROM projection_thread_messages
100 WHERE message_id = ${row.messageId}
101 )
102 ),
103 COALESCE(
104 ${nextContextJson},
105 (
106 SELECT context_json
107 FROM projection_thread_messages
108 WHERE message_id = ${row.messageId}
109 )
110 ),
111 ${row.isStreaming ? 1 : 0},
112 ${row.createdAt},
113 ${row.updatedAt}
114 )
115 ON CONFLICT (message_id)
116 DO UPDATE SET
117 thread_id = excluded.thread_id,
118 turn_id = excluded.turn_id,
119 role = excluded.role,
120 text = excluded.text,
121 actual_model = COALESCE(
122 excluded.actual_model,
123 projection_thread_messages.actual_model
124 ),
125 attachments_json = COALESCE(
126 excluded.attachments_json,
127 projection_thread_messages.attachments_json
128 ),
129 context_json = COALESCE(
130 excluded.context_json,
131 projection_thread_messages.context_json
132 ),
133 is_streaming = excluded.is_streaming,
134 created_at = excluded.created_at,
135 updated_at = excluded.updated_at
136 `;
137 },
138 });
139​
140 const appendStreamingProjectionThreadMessageRow = SqlSchema.void({
141 Request: AppendStreamingProjectionThreadMessage,
142 execute: (row) => {
143 const nextAttachmentsJson =
144 row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
145 const nextContextJson = row.context !== undefined ? JSON.stringify(row.context) : null;
146 return sql`
147 INSERT INTO projection_thread_messages (
148 message_id,
149 thread_id,
150 turn_id,
151 role,
152 text,
153 attachments_json,
154 context_json,
155 is_streaming,
156 created_at,
157 updated_at
158 )
159 VALUES (
160 ${row.messageId},
161 ${row.threadId},
162 ${row.turnId},
163 ${row.role},
164 ${row.text},
165 ${nextAttachmentsJson},
166 ${nextContextJson},
167 1,
168 ${row.createdAt},
169 ${row.updatedAt}
170 )
171 ON CONFLICT (message_id)
172 DO UPDATE SET
173 thread_id = excluded.thread_id,
174 turn_id = excluded.turn_id,
175 role = excluded.role,
176 text = projection_thread_messages.text || excluded.text,
177 attachments_json = COALESCE(
178 excluded.attachments_json,
179 projection_thread_messages.attachments_json
180 ),
181 context_json = COALESCE(
182 excluded.context_json,
183 projection_thread_messages.context_json
184 ),
185 is_streaming = 1,
186 updated_at = excluded.updated_at
187 `;
188 },
189 });
190​
191 const getProjectionThreadMessageRow = SqlSchema.findOneOption({
192 Request: GetProjectionThreadMessageInput,
193 Result: ProjectionThreadMessageDbRowSchema,
194 execute: ({ messageId }) =>
195 sql`
196 SELECT
197 message_id AS "messageId",
198 thread_id AS "threadId",
199 turn_id AS "turnId",
200 role,
201 text,
202 actual_model AS "actualModel",
203 attachments_json AS "attachments",
204 context_json AS "context",
205 is_streaming AS "isStreaming",
206 created_at AS "createdAt",
207 updated_at AS "updatedAt"
208 FROM projection_thread_messages
209 WHERE message_id = ${messageId}
210 LIMIT 1
211 `,
212 });
213​
214 const hasProjectionThreadAssistantMessageRow = SqlSchema.findOne({
215 Request: HasProjectionThreadAssistantMessageInput,
216 Result: ProjectionThreadMessageExistsDbRowSchema,
217 execute: ({ threadId, turnId, streamingOnly }) =>
218 sql`
219 SELECT EXISTS (
220 SELECT 1
221 FROM projection_thread_messages
222 WHERE thread_id = ${threadId}
223 AND turn_id = ${turnId}
224 AND role = 'assistant'
225 AND (${streamingOnly ? 1 : 0} = 0 OR is_streaming = 1)
226 LIMIT 1
227 ) AS "exists"
228 `,
229 });
230​
231 const getLatestProjectionThreadAssistantMessageIdRow = SqlSchema.findOneOption({
232 Request: GetLatestProjectionThreadAssistantMessageInput,
233 Result: ProjectionThreadMessageIdDbRowSchema,
234 execute: ({ threadId, turnId }) => sql`
235 SELECT message_id AS "messageId"
236 FROM projection_thread_messages
237 WHERE thread_id = ${threadId}
238 AND turn_id = ${turnId}
239 AND role = 'assistant'
240 ORDER BY created_at DESC, message_id DESC
241 LIMIT 1
242 `,
243 });
244​
245 const listProjectionThreadMessageRows = SqlSchema.findAll({
246 Request: ListProjectionThreadMessagesInput,
247 Result: ProjectionThreadMessageDbRowSchema,
248 execute: ({ threadId }) =>
249 sql`
250 SELECT
251 message_id AS "messageId",
252 thread_id AS "threadId",
253 turn_id AS "turnId",
254 role,
255 text,
256 actual_model AS "actualModel",
257 attachments_json AS "attachments",
258 context_json AS "context",
259 is_streaming AS "isStreaming",
260 created_at AS "createdAt",
261 updated_at AS "updatedAt"
262 FROM projection_thread_messages
263 WHERE thread_id = ${threadId}
264 ORDER BY created_at ASC, message_id ASC
265 `,
266 });
267​
268 const getLatestUserMessageAtRow = SqlSchema.findOne({
269 Request: ListProjectionThreadMessagesInput,
270 Result: Schema.Struct({
271 latestUserMessageAt: Schema.NullOr(ProjectionThreadMessage.fields.createdAt),
272 }),
273 execute: ({ threadId }) => sql`
274 SELECT MAX(created_at) AS "latestUserMessageAt"
275 FROM projection_thread_messages
276 WHERE thread_id = ${threadId} AND role = 'user'
277 AND message_id NOT GLOB 'import:*'
278 `,
279 });
280​
281 const deleteProjectionThreadMessageRows = SqlSchema.void({
282 Request: DeleteProjectionThreadMessagesInput,
283 execute: ({ threadId }) =>
284 sql`
285 DELETE FROM projection_thread_messages
286 WHERE thread_id = ${threadId}
287 `,
288 });
289​
290 const upsert: ProjectionThreadMessageRepositoryShape["upsert"] = (row) =>
291 upsertProjectionThreadMessageRow(row).pipe(
292 Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
293 );
294​
295 const appendStreaming: ProjectionThreadMessageRepositoryShape["appendStreaming"] = (row) =>
296 appendStreamingProjectionThreadMessageRow(row).pipe(
297 Effect.mapError(
298 toPersistenceSqlError("ProjectionThreadMessageRepository.appendStreaming:query"),
299 ),
300 );
301​
302 const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
303 getProjectionThreadMessageRow(input).pipe(
304 Effect.mapError(
305 toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
306 ),
307 Effect.map(Option.map(toProjectionThreadMessage)),
308 );
309​
310 const hasAssistantMessageForTurn: ProjectionThreadMessageRepositoryShape["hasAssistantMessageForTurn"] =
311 (input) =>
312 hasProjectionThreadAssistantMessageRow(input).pipe(
313 Effect.mapError(
314 toPersistenceSqlError(
315 "ProjectionThreadMessageRepository.hasAssistantMessageForTurn:query",
316 ),
317 ),
318 Effect.map((row) => row.exists === 1),
319 );
320​
321 const getLatestAssistantMessageIdForTurn: ProjectionThreadMessageRepositoryShape["getLatestAssistantMessageIdForTurn"] =
322 (input) =>
323 getLatestProjectionThreadAssistantMessageIdRow(input).pipe(
324 Effect.mapError(
325 toPersistenceSqlError(
326 "ProjectionThreadMessageRepository.getLatestAssistantMessageIdForTurn:query",
327 ),
328 ),
329 Effect.map(Option.map((row) => row.messageId)),
330 );
331​
332 const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) =>
333 listProjectionThreadMessageRows(input).pipe(
334 Effect.mapError(
335 toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
336 ),
337 Effect.map((rows) => rows.map(toProjectionThreadMessage)),
338 );
339​
340 const getLatestUserMessageAt: ProjectionThreadMessageRepositoryShape["getLatestUserMessageAt"] = (
341 input,
342 ) =>
343 getLatestUserMessageAtRow(input).pipe(
344 Effect.mapError(
345 toPersistenceSqlError("ProjectionThreadMessageRepository.getLatestUserMessageAt:query"),
346 ),
347 Effect.map((row) => row.latestUserMessageAt),
348 );
349​
350 const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) =>
351 deleteProjectionThreadMessageRows(input).pipe(
352 Effect.mapError(
353 toPersistenceSqlError("ProjectionThreadMessageRepository.deleteByThreadId:query"),
354 ),
355 );
356​
357 return {
358 upsert,
359 appendStreaming,
360 getByMessageId,
361 hasAssistantMessageForTurn,
362 getLatestAssistantMessageIdForTurn,
363 listByThreadId,
364 getLatestUserMessageAt,
365 deleteByThreadId,
366 } satisfies ProjectionThreadMessageRepositoryShape;
367});
368​
369export const ProjectionThreadMessageRepositoryLive = Layer.effect(
370 ProjectionThreadMessageRepository,
371 makeProjectionThreadMessageRepository,
372);