-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchatHistory.ts
More file actions
301 lines (279 loc) · 7.77 KB
/
chatHistory.ts
File metadata and controls
301 lines (279 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { headers } from "next/headers";
import { getAuthServer } from "./auth";
import { getDrizzle } from "./drizzle";
import { chat, diff, message, section } from "@/schema/chat";
import { and, asc, eq, exists } from "drizzle-orm";
import { Auth } from "better-auth";
import { revalidateTag } from "next/cache";
import { isCloudflare } from "./detectCloudflare";
import { getPagesList, LangId, PagePath, PageSlug, SectionId } from "./docs";
export interface CreateChatMessage {
role: "user" | "ai" | "error";
content: string;
}
export interface CreateChatDiff {
search: string;
replace: string;
sectionId: SectionId;
targetMD5: string;
}
// cacheに使うキーで、実際のURLではない
const CACHE_KEY_BASE = "https://my-code.utcode.net/chatHistory";
export function cacheKeyForPage(path: PagePath, userId: string) {
return `${CACHE_KEY_BASE}/getChat?path=${path.lang}/${path.page}&userId=${userId}`;
}
export function cacheKeyForChat(chatId: string) {
return `${CACHE_KEY_BASE}/getChatOne?chatId=${chatId}`;
}
// nextjsのキャッシュのrevalidateはRouteHandlerではなくServerActionから呼ばないと正しく動作しないらしい。
// https://github.com/vercel/next.js/issues/69064
// そのためlib/以下の関数では直接revalidateChatを呼ばず、ServerActionの関数から呼ぶようにする。
// Nextjs 16 に更新したらこれをupdateTag()で置き換える。
export async function revalidateChat(
chatId: string,
userId: string,
pagePath: string | PagePath
) {
if (typeof pagePath === "string") {
const [lang, page] = pagePath.split("/") as [LangId, PageSlug];
pagePath = { lang, page };
}
revalidateTag(cacheKeyForChat(chatId));
revalidateTag(cacheKeyForPage(pagePath, userId));
if (isCloudflare()) {
const cache = await caches.open("chatHistory");
await cache.delete(cacheKeyForChat(chatId));
await cache.delete(cacheKeyForPage(pagePath, userId));
}
}
interface Context {
drizzle: Awaited<ReturnType<typeof getDrizzle>>;
auth: Auth;
userId?: string;
}
/**
* drizzleとbetterAuthをまとめて初期化する関数
*
* drizzleが初期化されてなければ初期化し、
* authが初期化されてなければ初期化し、
* userIdがなければセッションから取得してセットする。
*/
export async function initContext(ctx?: Partial<Context>): Promise<Context> {
if (!ctx) {
ctx = {};
}
if (!ctx.drizzle) {
ctx.drizzle = await getDrizzle();
}
if (!ctx.auth) {
ctx.auth = await getAuthServer(ctx.drizzle);
}
if (!ctx.userId) {
const session = await ctx.auth.api.getSession({
headers: await headers(),
});
if (session) {
ctx.userId = session.user.id;
}
}
return ctx as Context;
}
export async function addChat(
path: PagePath,
sectionId: SectionId,
title: string,
messages: CreateChatMessage[],
diffRaw: CreateChatDiff[],
context: Context
) {
const { drizzle, userId } = context;
if (!userId) {
throw new Error("Not authenticated");
}
const [newChat] = await drizzle
.insert(chat)
.values({
userId,
sectionId,
title,
})
.returning();
const chatMessages = await drizzle
.insert(message)
.values(
messages.map((msg) => ({
chatId: newChat.chatId,
role: msg.role,
content: msg.content,
}))
)
.returning();
let chatDiffs;
if (diffRaw.length > 0) {
chatDiffs = await drizzle
.insert(diff)
.values(
diffRaw.map((d) => ({
chatId: newChat.chatId,
...d,
}))
)
.returning();
} else {
chatDiffs = [] as never[];
}
return {
...newChat,
section: {
sectionId,
pagePath: `${path.lang}/${path.page}`,
},
messages: chatMessages,
diff: chatDiffs,
};
}
export type ChatWithMessages = Awaited<ReturnType<typeof addChat>>;
/**
* 既存のチャットにメッセージと差分を追加し、キャッシュを再検証する。
* ストリーミング完了後に使用する。
*/
export async function addMessagesAndDiffs(
chatId: string,
path: PagePath,
messages: CreateChatMessage[],
diffRaw: CreateChatDiff[],
context: Context
) {
const { drizzle, userId } = context;
if (!userId) {
throw new Error("Not authenticated");
}
await drizzle.insert(message).values(
messages.map((msg) => ({
chatId,
role: msg.role,
content: msg.content,
}))
);
if (diffRaw.length > 0) {
await drizzle.insert(diff).values(
diffRaw.map((d) => ({
chatId,
...d,
}))
);
}
}
export async function deleteChat(chatId: string, context: Context) {
const { drizzle, userId } = context;
if (!userId) {
throw new Error("Not authenticated");
}
const deletedChat = await drizzle
.delete(chat)
.where(and(eq(chat.chatId, chatId), eq(chat.userId, userId)))
.returning();
if (deletedChat.length === 0) {
throw new Error("Chat not found or not authorized");
}
await drizzle.delete(message).where(eq(message.chatId, chatId));
await drizzle.delete(diff).where(eq(diff.chatId, chatId));
return deletedChat;
}
export async function getAllChat(
path: PagePath,
context: Context
): Promise<ChatWithMessages[]> {
const { drizzle, userId } = context;
if (!userId) {
return [];
}
const chats = await drizzle.query.chat.findMany({
where: and(
eq(chat.userId, userId),
exists(
drizzle
.select()
.from(section)
.where(
and(
eq(section.sectionId, chat.sectionId),
eq(section.pagePath, `${path.lang}/${path.page}`)
)
)
)
),
with: {
section: true,
messages: {
orderBy: [asc(message.createdAt)],
},
diff: true,
},
orderBy: [asc(chat.createdAt)],
});
if (isCloudflare()) {
const cache = await caches.open("chatHistory");
await cache.put(
cacheKeyForPage(path, userId),
new Response(JSON.stringify(chats), {
headers: { "Cache-Control": "max-age=86400, s-maxage=86400" },
})
);
}
// @ts-expect-error なぜかchatsの型にsectionとmessagesが含まれていないことになっているが、正しくwithを指定しているし、console.logしてみるとちゃんと含まれている
return chats;
}
export async function getChatOne(chatId: string, context: Context) {
const { drizzle, userId } = context;
if (!userId) {
throw new Error("Not authenticated");
}
const chatData = (await drizzle.query.chat.findFirst({
where: and(eq(chat.chatId, chatId), eq(chat.userId, userId)),
with: {
section: true,
messages: {
orderBy: [asc(message.createdAt)],
},
diff: {
orderBy: [asc(diff.createdAt)],
},
},
})) as ChatWithMessages | undefined;
if (isCloudflare()) {
const cache = await caches.open("chatHistory");
await cache.put(
cacheKeyForChat(chatId),
new Response(JSON.stringify(chatData), {
headers: { "Cache-Control": "max-age=86400, s-maxage=86400" },
})
);
}
return chatData;
}
export async function migrateChatUser(oldUserId: string, newUserId: string) {
const drizzle = await getDrizzle();
await drizzle
.update(chat)
.set({ userId: newUserId })
.where(eq(chat.userId, oldUserId));
const pagesList = await getPagesList();
for (const lang of pagesList) {
for (const page of lang.pages) {
revalidateTag(
cacheKeyForPage({ lang: lang.id, page: page.slug }, newUserId)
);
}
}
if (isCloudflare()) {
const cache = await caches.open("chatHistory");
for (const lang of pagesList) {
for (const page of lang.pages) {
await cache.delete(
cacheKeyForPage({ lang: lang.id, page: page.slug }, newUserId)
);
}
}
}
}