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

ProjectionThreadMessages.ts

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