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

ProjectionThreadMessages.ts

205 lines6.4 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 { ChatAttachment, TrimmedNonEmptyString } from "@t3tools/contracts";
9​
10import { toPersistenceSqlError } from "../Errors.ts";
11import {
12 GetProjectionThreadMessageInput,
13 ProjectionThreadMessageRepository,
14 type ProjectionThreadMessageRepositoryShape,
15 DeleteProjectionThreadMessagesInput,
16 ListProjectionThreadMessagesInput,
17 ProjectionThreadMessage,
18} from "../Services/ProjectionThreadMessages.ts";
19​
20const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
21 Struct.assign({
22 isStreaming: Schema.Number,
23 actualModel: Schema.NullOr(TrimmedNonEmptyString),
24 attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
25 }),
26);
27​
28function toProjectionThreadMessage(
29 row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,
30): ProjectionThreadMessage {
31 return {
32 messageId: row.messageId,
33 threadId: row.threadId,
34 turnId: row.turnId,
35 role: row.role,
36 text: row.text,
37 ...(row.actualModel !== null ? { actualModel: row.actualModel } : {}),
38 isStreaming: row.isStreaming === 1,
39 createdAt: row.createdAt,
40 updatedAt: row.updatedAt,
41 ...(row.attachments !== null ? { attachments: row.attachments } : {}),
42 };
44​
45const makeProjectionThreadMessageRepository = Effect.gen(function* () {
46 const sql = yield* SqlClient.SqlClient;
47​
48 const upsertProjectionThreadMessageRow = SqlSchema.void({
49 Request: ProjectionThreadMessage,
50 execute: (row) => {
51 const nextAttachmentsJson =
52 row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
53 return sql`
54 INSERT INTO projection_thread_messages (
55 message_id,
56 thread_id,
57 turn_id,
58 role,
59 text,
60 actual_model,
61 attachments_json,
62 is_streaming,
63 created_at,
64 updated_at
65 )
66 VALUES (
67 ${row.messageId},
68 ${row.threadId},
69 ${row.turnId},
70 ${row.role},
71 ${row.text},
72 COALESCE(
73 ${row.actualModel ?? null},
74 (
75 SELECT actual_model
76 FROM projection_thread_messages
77 WHERE message_id = ${row.messageId}
78 )
79 ),
80 COALESCE(
81 ${nextAttachmentsJson},
82 (
83 SELECT attachments_json
84 FROM projection_thread_messages
85 WHERE message_id = ${row.messageId}
86 )
87 ),
88 ${row.isStreaming ? 1 : 0},
89 ${row.createdAt},
90 ${row.updatedAt}
91 )
92 ON CONFLICT (message_id)
93 DO UPDATE SET
94 thread_id = excluded.thread_id,
95 turn_id = excluded.turn_id,
96 role = excluded.role,
97 text = excluded.text,
98 actual_model = COALESCE(
99 excluded.actual_model,
100 projection_thread_messages.actual_model
101 ),
102 attachments_json = COALESCE(
103 excluded.attachments_json,
104 projection_thread_messages.attachments_json
105 ),
106 is_streaming = excluded.is_streaming,
107 created_at = excluded.created_at,
108 updated_at = excluded.updated_at
109 `;
110 },
111 });
112​
113 const getProjectionThreadMessageRow = SqlSchema.findOneOption({
114 Request: GetProjectionThreadMessageInput,
115 Result: ProjectionThreadMessageDbRowSchema,
116 execute: ({ messageId }) =>
117 sql`
118 SELECT
119 message_id AS "messageId",
120 thread_id AS "threadId",
121 turn_id AS "turnId",
122 role,
123 text,
124 actual_model AS "actualModel",
125 attachments_json AS "attachments",
126 is_streaming AS "isStreaming",
127 created_at AS "createdAt",
128 updated_at AS "updatedAt"
129 FROM projection_thread_messages
130 WHERE message_id = ${messageId}
131 LIMIT 1
132 `,
133 });
134​
135 const listProjectionThreadMessageRows = SqlSchema.findAll({
136 Request: ListProjectionThreadMessagesInput,
137 Result: ProjectionThreadMessageDbRowSchema,
138 execute: ({ threadId }) =>
139 sql`
140 SELECT
141 message_id AS "messageId",
142 thread_id AS "threadId",
143 turn_id AS "turnId",
144 role,
145 text,
146 actual_model AS "actualModel",
147 attachments_json AS "attachments",
148 is_streaming AS "isStreaming",
149 created_at AS "createdAt",
150 updated_at AS "updatedAt"
151 FROM projection_thread_messages
152 WHERE thread_id = ${threadId}
153 ORDER BY created_at ASC, message_id ASC
154 `,
155 });
156​
157 const deleteProjectionThreadMessageRows = SqlSchema.void({
158 Request: DeleteProjectionThreadMessagesInput,
159 execute: ({ threadId }) =>
160 sql`
161 DELETE FROM projection_thread_messages
162 WHERE thread_id = ${threadId}
163 `,
164 });
165​
166 const upsert: ProjectionThreadMessageRepositoryShape["upsert"] = (row) =>
167 upsertProjectionThreadMessageRow(row).pipe(
168 Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
169 );
170​
171 const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
172 getProjectionThreadMessageRow(input).pipe(
173 Effect.mapError(
174 toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
175 ),
176 Effect.map(Option.map(toProjectionThreadMessage)),
177 );
178​
179 const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) =>
180 listProjectionThreadMessageRows(input).pipe(
181 Effect.mapError(
182 toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
183 ),
184 Effect.map((rows) => rows.map(toProjectionThreadMessage)),
185 );
186​
187 const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) =>
188 deleteProjectionThreadMessageRows(input).pipe(
189 Effect.mapError(
190 toPersistenceSqlError("ProjectionThreadMessageRepository.deleteByThreadId:query"),
191 ),
192 );
193​
194 return {
195 upsert,
196 getByMessageId,
197 listByThreadId,
198 deleteByThreadId,
199 } satisfies ProjectionThreadMessageRepositoryShape;
200});
201​
202export const ProjectionThreadMessageRepositoryLive = Layer.effect(
203 ProjectionThreadMessageRepository,
204 makeProjectionThreadMessageRepository,
205);