Skip to content

An AI-powered search engine with a generative UI

refactor: remove all cache implementations and consolidate chat actions

Yoshiki Miura4a86a370ca98
diff --git a/app/api/chats/route.ts b/app/api/chats/route.ts
index befdc9f0..cf03c8d0 100644
--- a/app/api/chats/route.ts
+++ b/app/api/chats/route.ts
@@ -1,7 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
-import { getChatsPage } from '@/lib/actions/chat-db'
-import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getChatsPage } from '@/lib/actions/chat'
import { Chat as DBChat } from '@/lib/db/schema'
interface ChatPageResponse {
@@ -19,13 +18,8 @@ export async function GET(request: NextRequest) {
const offset = parseInt(searchParams.get('offset') || '0', 10)
const limit = parseInt(searchParams.get('limit') || '20', 10)
- const userId = await getCurrentUserId()
- if (!userId) {
- return NextResponse.json<ChatPageResponse>({ chats: [], nextOffset: null })
- }
-
try {
- const result = await getChatsPage(userId, limit, offset)
+ const result = await getChatsPage(limit, offset)
return NextResponse.json<ChatPageResponse>(result)
} catch (error) {
console.error('API route error fetching chats:', error)
diff --git a/components/chat-share.tsx b/components/chat-share.tsx
index be170ce1..a6acbb9e 100644
--- a/components/chat-share.tsx
+++ b/components/chat-share.tsx
@@ -5,7 +5,7 @@ import { useState, useTransition } from 'react'
import { Share } from 'lucide-react'
import { toast } from 'sonner'
-import { shareChat } from '@/lib/actions/chat-db'
+import { shareChat } from '@/lib/actions/chat'
import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard'
import { cn } from '@/lib/utils'
diff --git a/components/sidebar/chat-menu-item.tsx b/components/sidebar/chat-menu-item.tsx
index 6b94d723..aa5f577a 100644
--- a/components/sidebar/chat-menu-item.tsx
+++ b/components/sidebar/chat-menu-item.tsx
@@ -7,7 +7,7 @@ import { usePathname, useRouter } from 'next/navigation'
import { MoreHorizontal, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
-import { deleteChat } from '@/lib/actions/chat-db'
+import { deleteChat } from '@/lib/actions/chat'
import { Chat as DBChat } from '@/lib/db/schema'
import {
diff --git a/components/sidebar/clear-history-action.tsx b/components/sidebar/clear-history-action.tsx
index bc3f3655..e605e3a6 100644
--- a/components/sidebar/clear-history-action.tsx
+++ b/components/sidebar/clear-history-action.tsx
@@ -6,7 +6,7 @@ import { useRouter } from 'next/navigation'
import { MoreHorizontal, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
-import { clearChats } from '@/lib/actions/chat-db'
+import { clearChats } from '@/lib/actions/chat'
import {
AlertDialog,
diff --git a/lib/actions/__tests__/chat-db.test.ts b/lib/actions/__tests__/chat-db.test.ts
deleted file mode 100644
index 2a9c41c0..00000000
--- a/lib/actions/__tests__/chat-db.test.ts
+++ /dev/null
@@ -1,515 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-// Mock the chat database functions
-vi.mock('@/lib/db/chat', () => ({
- clearChats: vi.fn(),
- deleteChat: vi.fn(),
- getChats: vi.fn(),
- getChatsPage: vi.fn(),
- getChat: vi.fn(),
- getSharedChat: vi.fn(),
- getChatMessages: vi.fn(),
- addMessage: vi.fn(),
- saveChat: vi.fn(),
- deleteTrailingMessages: vi.fn(),
- shareChatDb: vi.fn()
-}))
-
-// Mock auth functions
-vi.mock('@/lib/auth/get-current-user', () => ({
- getCurrentUserId: vi.fn()
-}))
-
-// Now safe to import modules that depend on database
-import { getCurrentUserId } from '@/lib/auth/get-current-user'
-import * as chatDb from '@/lib/db/chat'
-import type { Chat as DBChat, Message as DBMessage } from '@/lib/db/schema'
-import { generateUUID } from '@/lib/utils'
-
-import {
- clearChats,
- deleteChat,
- getChat,
- getChats,
- saveChatMessage,
- saveSingleMessage
-} from '../chat-db'
-
-const mockClearChats = vi.mocked(chatDb.clearChats)
-const mockDeleteChatDb = vi.mocked(chatDb.deleteChat)
-const mockGetChatsDb = vi.mocked(chatDb.getChats)
-const mockGetChatDb = vi.mocked(chatDb.getChat)
-const mockGetSharedChatDb = vi.mocked(chatDb.getSharedChat)
-const mockGetChatMessagesDb = vi.mocked(chatDb.getChatMessages)
-const mockAddMessageDb = vi.mocked(chatDb.addMessage)
-const mockSaveChatDb = vi.mocked(chatDb.saveChat)
-const mockGetCurrentUserId = vi.mocked(getCurrentUserId)
-
-const now = new Date().toISOString()
-
-// Generate UUIDs for common test data to ensure uniqueness across test runs if needed,
-// or use fixed UUIDs if specific ID values are part of the test logic (not the case here generally).
-const commonChatId = generateUUID() // Use generateUUID
-const commonUserId = generateUUID() // Use generateUUID
-const commonMessageId = generateUUID() // Use generateUUID
-
-const testChatData: DBChat = {
- id: commonChatId,
- userId: commonUserId,
- title: 'Test Chat Title',
- createdAt: new Date(now),
- visibility: 'private'
-}
-
-const testMessageData: DBMessage = {
- id: commonMessageId,
- chatId: commonChatId,
- role: 'user',
- createdAt: new Date(now),
- updatedAt: null,
- metadata: null
-}
-
-describe('Chat Actions - clearChats', () => {
- let userId: string
- beforeEach(() => {
- vi.resetAllMocks()
- userId = generateUUID() // Generate a fresh UUID for each test if needed
- mockGetCurrentUserId.mockResolvedValue(userId)
- })
-
- it('should clear chats for an authenticated user and return success', async () => {
- mockClearChats.mockResolvedValue({})
- const result = await clearChats()
- expect(mockGetCurrentUserId).toHaveBeenCalledTimes(1)
- expect(mockClearChats).toHaveBeenCalledWith(userId)
- expect(result).toEqual({ success: true })
- })
-
- it('should return an error if the user is not authenticated', async () => {
- mockGetCurrentUserId.mockResolvedValue(null as unknown as string)
- const result = await clearChats()
- expect(mockClearChats).not.toHaveBeenCalled()
- expect(result).toEqual({ error: 'User not authenticated' })
- })
-
- it('should return an error if db operation returns error', async () => {
- mockClearChats.mockResolvedValue({ error: 'db-error' })
- const result = await clearChats()
- expect(result).toEqual({ error: 'db-error' })
- })
-
- it('should handle unexpected exception from db call', async () => {
- const dbError = new Error('unexpected')
- mockClearChats.mockRejectedValue(dbError)
- const result = await clearChats()
- expect(result).toEqual({
- error: 'Failed to clear chats at server action level'
- })
- })
-})
-
-// --- Tests for deleteChat ---
-describe('Chat Actions - deleteChat', () => {
- let userId: string
- let chatId: string
- beforeEach(() => {
- vi.resetAllMocks()
- userId = generateUUID()
- chatId = generateUUID()
- mockGetCurrentUserId.mockResolvedValue(userId)
- })
-
- it('should delete a chat for an authenticated user and return success', async () => {
- mockDeleteChatDb.mockResolvedValue({})
- const result = await deleteChat(chatId)
- expect(mockGetCurrentUserId).toHaveBeenCalledTimes(1)
- expect(mockDeleteChatDb).toHaveBeenCalledWith(chatId, userId)
- expect(result).toEqual({ success: true })
- })
-
- it('should return an error if the user is not authenticated', async () => {
- mockGetCurrentUserId.mockResolvedValue(null as unknown as string)
- const result = await deleteChat(chatId)
- expect(mockDeleteChatDb).not.toHaveBeenCalled()
- expect(result).toEqual({ error: 'User not authenticated' })
- })
-
- it('should return an error if db operation returns an error object', async () => {
- mockDeleteChatDb.mockResolvedValue({ error: 'DB delete failed' })
- const result = await deleteChat(chatId)
- expect(mockDeleteChatDb).toHaveBeenCalledWith(chatId, userId)
- expect(result).toEqual({ error: 'DB delete failed' })
- })
-
- it('should handle unexpected exception from db call', async () => {
- const dbError = new Error('Unexpected DB error')
- mockDeleteChatDb.mockRejectedValue(dbError)
- const result = await deleteChat(chatId)
- expect(mockDeleteChatDb).toHaveBeenCalledWith(chatId, userId)
- expect(result).toEqual({ error: dbError.message })
- })
-})
-
-// --- Tests for getChats ---
-describe('Chat Actions - getChats', () => {
- let userId: string
- beforeEach(() => {
- vi.resetAllMocks()
- userId = generateUUID()
- })
-
- it('should return chats for a given user ID', async () => {
- const mockChats = [
- { ...testChatData, id: generateUUID(), userId },
- { ...testChatData, id: generateUUID(), userId }
- ]
- mockGetChatsDb.mockResolvedValue(mockChats)
- const result = await getChats(userId)
- expect(mockGetChatsDb).toHaveBeenCalledWith(userId)
- expect(result).toEqual(mockChats)
- })
-
- it('should return an empty array if no chats are found', async () => {
- mockGetChatsDb.mockResolvedValue([])
- const result = await getChats(userId)
- expect(mockGetChatsDb).toHaveBeenCalledWith(userId)
- expect(result).toEqual([])
- })
-
- it('should propagate error if db operation fails', async () => {
- const dbError = new Error('DB connection error')
- mockGetChatsDb.mockRejectedValue(dbError)
- await expect(getChats(userId)).rejects.toThrow('DB connection error')
- expect(mockGetChatsDb).toHaveBeenCalledWith(userId)
- })
-})
-
-// --- Tests for getChat ---
-describe('Chat Actions - getChat', () => {
- let ownerUserId: string
- let publicChat: DBChat
- let privateChat: DBChat
- let messagesForChat: DBMessage[]
-
- beforeEach(() => {
- vi.resetAllMocks()
- ownerUserId = generateUUID()
- const publicChatId = generateUUID()
- const privateChatId = generateUUID()
-
- publicChat = {
- ...testChatData,
- id: publicChatId,
- userId: ownerUserId,
- visibility: 'public'
- }
- privateChat = {
- ...testChatData,
- id: privateChatId,
- userId: ownerUserId,
- visibility: 'private'
- }
- messagesForChat = [
- { ...testMessageData, id: generateUUID(), chatId: publicChatId },
- {
- ...testMessageData,
- id: generateUUID(),
- chatId: publicChatId,
- role: 'assistant'
- }
- ]
- })
-
- it('should return a public chat with messages if no requestingUserId is provided', async () => {
- mockGetSharedChatDb.mockResolvedValue(publicChat)
- mockGetChatMessagesDb.mockResolvedValue(messagesForChat)
- const result = await getChat(publicChat.id)
- expect(mockGetSharedChatDb).toHaveBeenCalledWith(publicChat.id)
- expect(mockGetChatDb).not.toHaveBeenCalled()
- expect(mockGetChatMessagesDb).toHaveBeenCalledWith(publicChat.id)
- expect(result).toEqual({ ...publicChat, messages: messagesForChat })
- })
-
- it('should return a private chat with messages if requestingUser is the owner', async () => {
- const privateMessages = messagesForChat.map(m => ({
- ...m,
- chatId: privateChat.id
- }))
- mockGetSharedChatDb.mockResolvedValue(null)
- mockGetChatDb.mockResolvedValue(privateChat)
- mockGetChatMessagesDb.mockResolvedValue(privateMessages)
- const result = await getChat(privateChat.id, ownerUserId)
- expect(mockGetSharedChatDb).toHaveBeenCalledWith(privateChat.id)
- expect(mockGetChatDb).toHaveBeenCalledWith(privateChat.id, ownerUserId)
- expect(mockGetChatMessagesDb).toHaveBeenCalledWith(privateChat.id)
- expect(result).toEqual({ ...privateChat, messages: privateMessages })
- })
-
- it('should return null if private chat is requested by a non-owner', async () => {
- const nonOwnerUserId = generateUUID()
- mockGetSharedChatDb.mockResolvedValue(null)
- mockGetChatDb.mockResolvedValue(privateChat)
- const result = await getChat(privateChat.id, nonOwnerUserId)
- expect(mockGetSharedChatDb).toHaveBeenCalledWith(privateChat.id)
- expect(mockGetChatDb).toHaveBeenCalledWith(privateChat.id, nonOwnerUserId)
- expect(mockGetChatMessagesDb).not.toHaveBeenCalled()
- expect(result).toBeNull()
- })
-
- it('should return null if private chat is requested without a requestingUserId', async () => {
- mockGetSharedChatDb.mockResolvedValue(null)
- const result = await getChat(privateChat.id)
- expect(mockGetSharedChatDb).toHaveBeenCalledWith(privateChat.id)
- expect(mockGetChatDb).not.toHaveBeenCalled()
- expect(mockGetChatMessagesDb).not.toHaveBeenCalled()
- expect(result).toBeNull()
- })
-
- it('should return null if chat is not found by any method', async () => {
- const nonExistentChatId = generateUUID()
- mockGetSharedChatDb.mockResolvedValue(null)
- mockGetChatDb.mockResolvedValue(null)
- // Scenario 1: With a requesting user
- const resultWithUser = await getChat(nonExistentChatId, ownerUserId)
- expect(mockGetSharedChatDb).toHaveBeenCalledWith(nonExistentChatId)
- expect(mockGetChatDb).toHaveBeenCalledWith(nonExistentChatId, ownerUserId)
- expect(resultWithUser).toBeNull()
- // Scenario 2: Without a requesting user
- vi.resetAllMocks()
- mockGetSharedChatDb.mockResolvedValue(null)
- const resultWithoutUser = await getChat(nonExistentChatId)
- expect(mockGetSharedChatDb).toHaveBeenCalledWith(nonExistentChatId)
- expect(mockGetChatDb).not.toHaveBeenCalled()
- expect(mockGetChatMessagesDb).not.toHaveBeenCalled()
- expect(resultWithoutUser).toBeNull()
- })
-
- it('should return null and log warning if chat has unhandled visibility', async () => {
- const consoleWarnSpy = vi
- .spyOn(console, 'warn')
- .mockImplementation(() => {})
- const unhandledVisibilityChat: DBChat = {
- ...publicChat,
- visibility: 'friends_only' as any
- }
- mockGetSharedChatDb.mockResolvedValue(unhandledVisibilityChat)
- const result = await getChat(unhandledVisibilityChat.id)
- expect(result).toBeNull()
- expect(mockGetChatMessagesDb).not.toHaveBeenCalled()
- expect(consoleWarnSpy).toHaveBeenCalledWith(
- `getChat: Chat ${unhandledVisibilityChat.id} has unhandled visibility 'friends_only'. Denying access.`
- )
- consoleWarnSpy.mockRestore()
- })
-
- it('should return null if chatDb.getChat for a user returns a chat owned by someone else (edge case)', async () => {
- const consoleWarnSpy = vi
- .spyOn(console, 'warn')
- .mockImplementation(() => {})
- const requestingUserId = generateUUID()
- const actualOwnerId = generateUUID()
- const chatDataOwnedByOther: DBChat = {
- ...privateChat,
- userId: actualOwnerId
- }
- mockGetSharedChatDb.mockResolvedValue(null)
- mockGetChatDb.mockResolvedValue(chatDataOwnedByOther)
- const result = await getChat(privateChat.id, requestingUserId)
- expect(mockGetSharedChatDb).toHaveBeenCalledWith(privateChat.id)
- expect(mockGetChatDb).toHaveBeenCalledWith(privateChat.id, requestingUserId)
- expect(mockGetChatMessagesDb).not.toHaveBeenCalled()
- expect(result).toBeNull()
- expect(consoleWarnSpy).toHaveBeenCalledWith(
- `getChat: chatDb.getChat for user ${requestingUserId} returned chat ${privateChat.id} owned by ${actualOwnerId}. Denying access.`
- )
- consoleWarnSpy.mockRestore()
- })
-})
-
-// --- Tests for saveSingleMessage ---
-describe('Chat Actions - saveSingleMessage', () => {
- let chatId: string
- let messageInput: {
- id: string
- role: 'user' | 'assistant'
- parts: Array<{ type: 'text'; text: string }>
- }
- let savedMessageOutput: DBMessage
-
- beforeEach(() => {
- vi.resetAllMocks()
- chatId = generateUUID()
- const messageId = generateUUID()
- messageInput = {
- id: messageId,
- role: 'user' as const,
- parts: [{ type: 'text' as const, text: 'Test message' }]
- }
- savedMessageOutput = {
- ...testMessageData,
- id: messageId,
- chatId: chatId,
- role: messageInput.role
- }
- })
-
- it('should save a single message and return the saved message', async () => {
- mockAddMessageDb.mockResolvedValue(savedMessageOutput)
- const result = await saveSingleMessage(chatId, messageInput as any)
- expect(mockAddMessageDb).toHaveBeenCalledWith(
- expect.objectContaining({
- id: messageInput.id,
- chatId: chatId,
- role: messageInput.role,
- parts: messageInput.parts
- })
- )
- expect(result).toEqual(savedMessageOutput)
- })
-
- it('should throw an error if db operation fails', async () => {
- const dbError = new Error('DB save failed')
- mockAddMessageDb.mockRejectedValue(dbError)
- await expect(
- saveSingleMessage(chatId, messageInput as any)
- ).rejects.toThrow('DB save failed')
- expect(mockAddMessageDb).toHaveBeenCalledWith(
- expect.objectContaining({
- id: messageInput.id,
- chatId: chatId,
- role: messageInput.role,
- parts: messageInput.parts
- })
- )
- })
-})
-
-// --- Tests for saveChatMessage ---
-describe('Chat Actions - saveChatMessage', () => {
- let userId: string
- let chatId: string
- let userMessageInput: any
- let newChatData: DBChat
- let newMessageData: DBMessage
-
- beforeEach(() => {
- vi.resetAllMocks()
- userId = generateUUID()
- chatId = generateUUID()
- const messageId = generateUUID()
- userMessageInput = {
- id: messageId,
- role: 'user',
- parts: [{ type: 'text', text: 'Saving this message' }]
- }
- newChatData = {
- ...testChatData,
- id: chatId,
- userId: userId,
- title: 'Saving this message'
- }
- newMessageData = {
- ...testMessageData,
- id: userMessageInput.id,
- chatId: chatId,
- role: userMessageInput.role
- }
- })
-
- it('should create a new chat and save message if chat does not exist', async () => {
- mockGetChatDb.mockResolvedValue(null)
- mockSaveChatDb.mockResolvedValue([newChatData])
- mockAddMessageDb.mockResolvedValue(newMessageData)
- const result = await saveChatMessage(
- chatId,
- userMessageInput as any,
- userId
- )
- expect(mockGetChatDb).toHaveBeenCalledWith(chatId, userId)
- expect(mockSaveChatDb).toHaveBeenCalledWith(
- expect.objectContaining({
- id: chatId,
- title: newChatData.title,
- userId: userId,
- visibility: 'private'
- }),
- userId
- )
- expect(mockAddMessageDb).toHaveBeenCalledWith({
- id: userMessageInput.id,
- chatId: chatId,
- role: userMessageInput.role,
- parts: userMessageInput.parts
- })
- expect(result).toEqual({ chat: newChatData, message: newMessageData })
- })
-
- it('should save message to existing chat if chat exists', async () => {
- const existingChatData: DBChat = {
- ...testChatData,
- id: chatId,
- userId: userId,
- title: 'Existing Chat'
- }
- mockGetChatDb.mockResolvedValue(existingChatData)
- mockAddMessageDb.mockResolvedValue(newMessageData)
- const result = await saveChatMessage(
- chatId,
- userMessageInput as any,
- userId,
- 'Custom Title'
- )
- expect(mockGetChatDb).toHaveBeenCalledWith(chatId, userId)
- expect(mockSaveChatDb).not.toHaveBeenCalled()
- expect(mockAddMessageDb).toHaveBeenCalledWith({
- id: userMessageInput.id,
- chatId: chatId,
- role: userMessageInput.role,
- parts: userMessageInput.parts
- })
- expect(result).toEqual({ chat: existingChatData, message: newMessageData })
- })
-
- it('should use provided title when creating a new chat', async () => {
- const customTitle = 'My Custom Chat Title'
- const chatWithCustomTitle: DBChat = { ...newChatData, title: customTitle }
- mockGetChatDb.mockResolvedValue(null)
- mockSaveChatDb.mockResolvedValue([chatWithCustomTitle])
- mockAddMessageDb.mockResolvedValue(newMessageData)
- const result = await saveChatMessage(
- chatId,
- userMessageInput as any,
- userId,
- customTitle
- )
- expect(mockSaveChatDb).toHaveBeenCalledWith(
- expect.objectContaining({
- id: chatId,
- title: customTitle,
- userId: userId,
- visibility: 'private'
- }),
- userId
- )
- expect(result.chat.title).toBe(customTitle)
- })
-
- it('should throw an error if saving chat fails', async () => {
- const dbError = new Error('Failed to save chat')
- mockGetChatDb.mockResolvedValue(null)
- mockSaveChatDb.mockRejectedValue(dbError)
- await expect(
- saveChatMessage(chatId, userMessageInput as any, userId)
- ).rejects.toThrow('Failed to save chat')
- })
-
- it('should throw an error if saving message fails', async () => {
- const dbError = new Error('Failed to save message')
- mockGetChatDb.mockResolvedValue(newChatData)
- mockAddMessageDb.mockRejectedValue(dbError)
- await expect(
- saveChatMessage(chatId, userMessageInput as any, userId)
- ).rejects.toThrow('Failed to save message')
- })
-})
diff --git a/lib/actions/__tests__/feedback.test.ts b/lib/actions/__tests__/feedback.test.ts
index d7308b79..30b59e89 100644
--- a/lib/actions/__tests__/feedback.test.ts
+++ b/lib/actions/__tests__/feedback.test.ts
@@ -2,14 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
// Mock the modules before any imports
vi.mock('@/lib/db')
-vi.mock('@/lib/cache/memory-cache')
vi.mock('langfuse')
vi.mock('@/lib/utils/telemetry')
// Import after mocking
import { Langfuse } from 'langfuse'
-import { chatCache } from '@/lib/cache/memory-cache'
import { db } from '@/lib/db'
import { isTracingEnabled } from '@/lib/utils/telemetry'
@@ -42,9 +40,6 @@ describe('Feedback Actions', () => {
const mockSet = vi.fn().mockReturnValue({ where: mockUpdateWhere })
vi.mocked(db).update = vi.fn().mockReturnValue({ set: mockSet })
- // Mock cache
- vi.mocked(chatCache).deletePattern = vi.fn()
-
// Mock tracing disabled
vi.mocked(isTracingEnabled).mockReturnValue(false)
@@ -53,7 +48,6 @@ describe('Feedback Actions', () => {
expect(result).toEqual({ success: true })
expect(db.select).toHaveBeenCalled()
expect(db.update).toHaveBeenCalled()
- expect(chatCache.deletePattern).toHaveBeenCalledWith(`${chatId}-`)
})
it('should return error when message not found', async () => {
@@ -125,9 +119,6 @@ describe('Feedback Actions', () => {
const mockSet = vi.fn().mockReturnValue({ where: mockUpdateWhere })
vi.mocked(db).update = vi.fn().mockReturnValue({ set: mockSet })
- // Mock cache
- vi.mocked(chatCache).deletePattern = vi.fn()
-
const result = await updateMessageFeedback(messageId, score)
expect(result).toEqual({ success: true })
diff --git a/lib/actions/chat-db.ts b/lib/actions/chat-db.ts
deleted file mode 100644
index cdb3ce42..00000000
--- a/lib/actions/chat-db.ts
+++ /dev/null
@@ -1,409 +0,0 @@
-'use server'
-
-import { revalidateTag, unstable_cache } from 'next/cache'
-
-import { UIMessage } from '@ai-sdk/react' // Import UIMessage
-
-import { getCurrentUserId } from '@/lib/auth/get-current-user' // Import getCurrentUserId
-import * as chatDb from '@/lib/db/chat'
-import { type Chat as DBChat, type Message as DBMessage } from '@/lib/db/schema' // Import DB schema types
-import { getTextFromParts } from '@/lib/utils/message-utils' // Corrected import path
-
-// Constants
-const DEFAULT_CHAT_TITLE = 'New Chat'
-
-// Get all chats for a user
-export async function getChats(userId: string) {
- return chatDb.getChats(userId)
-}
-
-// Get chats with pagination
-export async function getChatsPage(userId: string, limit = 20, offset = 0) {
- return chatDb.getChatsPage(userId, limit, offset)
-}
-
-// Get a single chat by ID, including its messages, with permission checks.
-const getChatUncached = async function (
- chatId: string,
- requestingUserId?: string // Optional: for logged-in user context
-): Promise<(DBChat & { messages: DBMessage[] }) | null> {
- let chat: DBChat | null = null
-
- // Step 1: Attempt to fetch the chat using a method that could find public/shared chats.
- // We assume chatDb.getSharedChat(chatId) is the best candidate for this.
- chat = await chatDb.getSharedChat(chatId)
-
- // Step 2: If not found by the general method, AND a user is logged in,
- // try to fetch it as a private chat belonging to that user.
- if (!chat && requestingUserId) {
- const privateChat = await chatDb.getChat(chatId, requestingUserId)
- // Ensure the fetched private chat actually belongs to the requesting user,
- // in case chatDb.getChat isn't strictly scoped or for an extra layer of caution.
- if (privateChat && privateChat.userId === requestingUserId) {
- chat = privateChat
- } else if (privateChat) {
- // This case should ideally not happen if chatDb.getChat is correctly scoped.
- // Logging it can help identify issues if it does occur.
- console.warn(
- `getChat: chatDb.getChat for user ${requestingUserId} returned chat ${chatId} owned by ${privateChat.userId}. Denying access.`
- )
- // Do not assign to 'chat', effectively treating it as not found for this user.
- }
- }
-
- // Step 3: If no chat record was found by any means, return null.
- if (!chat) {
- return null
- }
-
- // Step 4: Permission checks on the retrieved chat record.
- if (chat.visibility === 'public') {
- // Public chat: access granted to anyone (authenticated or not).
- const messages = await chatDb.getChatMessages(chatId)
- return { ...chat, messages }
- }
-
- if (chat.visibility === 'private') {
- // Private chat: access granted only if the requestingUser is the owner.
- if (requestingUserId && chat.userId === requestingUserId) {
- const messages = await chatDb.getChatMessages(chatId)
- return { ...chat, messages }
- } else {
- // User is not the owner, or user is not authenticated.
- return null
- }
- }
-
- // If chat visibility is neither 'public' nor 'private', or any other unhandled case.
- console.warn(
- `getChat: Chat ${chatId} has unhandled visibility '${chat.visibility}'. Denying access.`
- )
- return null
-}
-
-// Create a cached version for each chatId
-const createCachedGetChat = (chatId: string) =>
- unstable_cache(
- (id: string, userId?: string) => getChatUncached(id, userId),
- [`chat-${chatId}`],
- {
- revalidate: 300, // 5 minutes cache
- tags: [`chat-${chatId}`, 'chat']
- }
- )
-
-// Export function that uses the cached version
-export async function getChat(
- chatId: string,
- requestingUserId?: string
-): Promise<(DBChat & { messages: DBMessage[] }) | null> {
- const cachedGetChat = createCachedGetChat(chatId)
- return cachedGetChat(chatId, requestingUserId)
-}
-
-// Clear all chats for a user
-export async function clearChats(): Promise<{
- error?: string
- success?: boolean
-}> {
- const userId = await getCurrentUserId() // Get userId on the server
- if (!userId) {
- return { error: 'User not authenticated' }
- }
- try {
- const result = await chatDb.clearChats(userId) // Call the db function
- if (result.error) {
- return { error: result.error }
- }
-
- // Revalidate chat cache when all chats are cleared
- revalidateTag('chat')
-
- return { success: true } // Indicate success
- } catch (error) {
- // This catch might be redundant if chatDb.clearChats handles its own errors and returns { error: ... }
- // However, it can catch unexpected errors during the call to chatDb.clearChats itself.
- console.error('Error in server action clearChats:', error)
- return { error: 'Failed to clear chats at server action level' }
- }
-}
-
-// Delete a single chat
-export async function deleteChat(chatId: string): Promise<{
- error?: string
- success?: boolean
-}> {
- const userId = await getCurrentUserId()
- if (!userId) {
- return { error: 'User not authenticated' }
- }
- try {
- const result = await chatDb.deleteChat(chatId, userId)
- // Assuming chatDb.deleteChat also returns a similar object or throws an error
- // If chatDb.deleteChat returns something else, this part needs adjustment
- if (result && 'error' in result && result.error) {
- return { error: result.error }
- }
- // If chatDb.deleteChat signifies success differently, adjust this condition
- // For example, if it returns the deleted chat or a count > 0 on success
- // For now, let's assume if no error, it's a success. Consider a more explicit success check.
-
- // Revalidate specific chat cache when a chat is deleted
- revalidateTag(`chat-${chatId}`)
-
- return { success: true }
- } catch (error: any) {
- console.error(
- `Error in server action deleteChat for chat ID ${chatId}:`,
- error
- )
- return {
- error: error.message || 'Failed to delete chat at server action level'
- }
- }
-}
-
-// Interface for chat metadata input from the client
-interface ClientChatInput {
- id: string // Chat ID is required
- title: string // Title is also required
- visibility?: DBChat['visibility'] // Visibility setting is optional
-}
-
-// Interface for new message input from the client
-interface ClientNewMessageInput {
- role: UIMessage['role']
- parts: UIMessage['parts']
-}
-
-// Save a single message
-export async function saveSingleMessage(
- chatId: string,
- message: UIMessage
-): Promise<DBMessage> {
- try {
- const messageToSave = {
- id: message.id,
- chatId: chatId,
- role: message.role,
- parts: message.parts // Use UIMessage.parts directly
- }
- const result = await chatDb.addMessage(messageToSave as any)
-
- // Revalidate specific chat cache when new message is added
- revalidateTag(`chat-${chatId}`)
-
- return result
- } catch (error) {
- console.error(`Error saving message for chat ID ${chatId}:`, error)
- throw error
- }
-}
-
-// Save or create a chat and add a user message
-export async function saveChatMessage(
- chatId: string,
- userMessage: UIMessage,
- userId: string,
- title?: string
-): Promise<{ chat: DBChat; message: DBMessage }> {
- try {
- const existingChat = await chatDb.getChat(chatId, userId)
-
- let chat: DBChat
- if (!existingChat) {
- // Use userMessage.parts for title generation
- const messageTextForTitle = getTextFromParts(userMessage.parts as any[])
- const chatTitle = title || messageTextForTitle || DEFAULT_CHAT_TITLE
- const chatDataForDb: Partial<DBChat> = {
- id: chatId,
- title: chatTitle.substring(0, 255),
- userId: userId,
- visibility: 'private'
- }
- const savedChats = await chatDb.saveChat(chatDataForDb as DBChat, userId)
- if (!savedChats || savedChats.length === 0) {
- throw new Error(`Failed to create chat with id: ${chatId}`)
- }
- chat = savedChats[0]
- } else {
- chat = existingChat
- }
-
- const messageToSaveToDb = {
- id: userMessage.id,
- chatId,
- role: userMessage.role,
- parts: userMessage.parts // Use UIMessage.parts directly
- }
- const dbSavedMessage = await chatDb.addMessage(messageToSaveToDb as any)
-
- // Revalidate specific chat cache when new message is added
- revalidateTag(`chat-${chatId}`)
-
- return { chat, message: dbSavedMessage }
- } catch (error) {
- console.error(`Error in saveChatMessage for chat ID ${chatId}:`, error)
- throw error
- }
-}
-
-export async function saveChat(
- clientChatInput: ClientChatInput,
- clientNewMessages: ClientNewMessageInput[] | undefined, // New messages are optional (e.g., when only updating metadata)
- userId: string, // Authenticated user ID is passed as a separate argument
- updateMetadata: boolean = true // New parameter to control whether to update metadata for existing chats
-) {
- try {
- // 1. Check if chat exists
- const existingChat = await chatDb.getChat(clientChatInput.id, userId)
-
- // Variables to hold the saved/updated chat details
- let savedOrUpdatedChatDetails
-
- if (existingChat && !updateMetadata) {
- // If chat exists and we don't want to update metadata, use the existing chat details
- savedOrUpdatedChatDetails = existingChat
- } else {
- // Otherwise, prepare chat metadata and save/update it
- const chatDataForDb: Pick<
- DBChat,
- 'id' | 'title' | 'userId' | 'visibility'
- > &
- Partial<DBChat> = {
- id: clientChatInput.id,
- title: clientChatInput.title,
- userId: userId, // Ensure authenticated user ID is used
- visibility: clientChatInput.visibility || 'private' // Set default value
- }
-
- // Call lib/db/chat.ts saveChat to save/update chat metadata in the DB
- const savedOrUpdatedChatArray = await chatDb.saveChat(
- chatDataForDb as DBChat,
- userId
- )
- savedOrUpdatedChatDetails =
- savedOrUpdatedChatArray && savedOrUpdatedChatArray[0]
-
- if (!savedOrUpdatedChatDetails) {
- throw new Error(
- `Failed to save chat metadata for chat ID: ${clientChatInput.id}. The operation returned no details.`
- )
- }
- }
-
- // 2. Add new messages
- if (clientNewMessages && clientNewMessages.length > 0) {
- for (const message of clientNewMessages) {
- await chatDb.addMessage({
- chatId: savedOrUpdatedChatDetails.id, // Use the ID of the saved/updated chat
- role: message.role,
- parts: message.parts
- })
- }
-
- // Revalidate specific chat cache when new messages are added
- revalidateTag(`chat-${savedOrUpdatedChatDetails.id}`)
- }
-
- // Return the saved/updated chat metadata
- return savedOrUpdatedChatDetails
- } catch (error) {
- console.error(
- `Error in saveChat action for chat ID ${clientChatInput.id}:`,
- error
- )
- throw error // Rethrow the error to the caller
- }
-}
-
-// Action to delete messages in a chat after a specific message (the pivot)
-export async function deleteTrailingMessages(
- chatId: string,
- pivotMessageId: string
-): Promise<{ success?: boolean; deleted?: number; error?: string }> {
- const userId = await getCurrentUserId()
- if (!userId) {
- return { error: 'User not authenticated' }
- }
-
- try {
- // 1. Verify chat access for the current user
- // getChat handles non-existent chats and ownership/public visibility checks.
- const chat = await chatDb.getChat(chatId, userId)
- if (!chat) {
- // This means either chat doesn't exist or user doesn't have access.
- return { error: 'Chat not found or unauthorized' }
- }
-
- // 2. Get the pivot message to find its creation timestamp
- // We need to fetch all messages first to find the specific one by ID.
- // This is not ideal if there are many messages, but getChatMessages is what we have.
- // Alternatively, we could add a getMessageById db function if performance becomes an issue.
- const messagesInChat = await chatDb.getChatMessages(chatId)
- const pivotMessage = messagesInChat.find(msg => msg.id === pivotMessageId)
-
- if (!pivotMessage) {
- return { error: 'Pivot message not found' }
- }
-
- // The createdAt field from DBMessage is now a Date object
- const pivotTimestamp =
- pivotMessage.createdAt instanceof Date
- ? pivotMessage.createdAt.toISOString()
- : pivotMessage.createdAt
-
- // 3. Call the database function to delete messages after the pivot message
- const deleteResult = await chatDb.deleteMessagesByChatIdAfterTimestamp(
- chatId,
- pivotTimestamp
- )
-
- if (deleteResult.error) {
- return { error: deleteResult.error }
- }
-
- // Revalidate specific chat cache when messages are deleted
- revalidateTag(`chat-${chatId}`)
-
- return { success: true, deleted: deleteResult.count }
- } catch (error: any) {
- console.error(
- `Error in server action deleteTrailingMessages for chat ID ${chatId} and pivot message ID ${pivotMessageId}:`,
- error
- )
- return {
- error:
- error.message ||
- 'Failed to delete trailing messages at server action level'
- }
- }
-}
-
-// Share a chat (makes it public if authorized)
-export async function shareChat(id: string): Promise<DBChat | null> {
- const userId = await getCurrentUserId() // Get user ID on the server
-
- if (!userId) {
- // Or throw new Error('Authentication required to share a chat.');
- // Depending on how you want to handle unauthorized attempts at the action level.
- console.error('shareChat: User not authenticated')
- return null
- }
-
- // We assume chatDb.shareChat updates the chat in the DB (e.g., sets visibility to public)
- // and handles ownership check (i.e., if this userId can share this chat id).
- // It should return the updated chat object (DBChat), or null on failure/permission denied.
- const updatedChat = await chatDb.shareChat(id, userId)
-
- if (!updatedChat) {
- // The operation to share the chat in the database failed or was not permitted
- return null
- }
-
- // Revalidate specific chat cache when chat visibility is changed
- revalidateTag(`chat-${id}`)
-
- // Return the updated chat object. The concept of a specific sharePath is obsolete.
- return updatedChat
-}
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index 1eec77c7..fea0d544 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -24,6 +24,17 @@ export async function getChats() {
return dbActions.getChats(userId)
}
+/**
+ * Get chats with pagination for the current user
+ */
+export async function getChatsPage(limit = 20, offset = 0) {
+ const userId = await getCurrentUserId()
+ if (!userId) {
+ return { chats: [], nextOffset: null }
+ }
+ return dbActions.getChatsPage(userId, limit, offset)
+}
+
/**
* Get a chat with messages (no cache)
*/
@@ -139,7 +150,7 @@ export async function saveMessage(
export async function deleteChat(chatId: string) {
const userId = await getCurrentUserId()
if (!userId) {
- return { error: 'User not authenticated' }
+ return { success: false, error: 'User not authenticated' }
}
const result = await dbActions.deleteChat(chatId, userId)
@@ -158,7 +169,7 @@ export async function deleteChat(chatId: string) {
export async function clearChats() {
const userId = await getCurrentUserId()
if (!userId) {
- return { error: 'User not authenticated' }
+ return { success: false, error: 'User not authenticated' }
}
const chats = await dbActions.getChats(userId)
@@ -177,13 +188,13 @@ export async function clearChats() {
export async function deleteMessagesAfter(chatId: string, messageId: string) {
const userId = await getCurrentUserId()
if (!userId) {
- return { error: 'User not authenticated' }
+ return { success: false, error: 'User not authenticated' }
}
// Verify access
const chat = await dbActions.getChat(chatId, userId)
if (!chat || chat.userId !== userId) {
- return { error: 'Unauthorized' }
+ return { success: false, error: 'Unauthorized' }
}
const result = await dbActions.deleteMessagesAfter(chatId, messageId)
@@ -224,13 +235,13 @@ export async function deleteMessagesFromIndex(
) {
const userId = await getCurrentUserId()
if (!userId) {
- return { error: 'User not authenticated' }
+ return { success: false, error: 'User not authenticated' }
}
// Verify access
const chat = await dbActions.getChat(chatId, userId)
if (!chat || chat.userId !== userId) {
- return { error: 'Unauthorized' }
+ return { success: false, error: 'Unauthorized' }
}
const result = await dbActions.deleteMessagesFromIndex(chatId, messageId)
diff --git a/lib/actions/feedback.ts b/lib/actions/feedback.ts
index b2416bd5..004611f5 100644
--- a/lib/actions/feedback.ts
+++ b/lib/actions/feedback.ts
@@ -3,7 +3,6 @@
import { eq } from 'drizzle-orm'
import { Langfuse } from 'langfuse'
-import { chatCache } from '@/lib/cache/memory-cache'
import { db } from '@/lib/db'
import { messages } from '@/lib/db/schema'
import type { UIMessageMetadata } from '@/lib/types/ai'
@@ -53,11 +52,6 @@ export async function updateMessageFeedback(
await langfuse.flushAsync()
}
- // Invalidate cache for this chat to ensure fresh data is loaded
- if (currentMessage.chatId) {
- chatCache.deletePattern(`${currentMessage.chatId}-`)
- }
-
return { success: true }
} catch (error) {
console.error('Error updating message feedback:', error)
diff --git a/lib/cache/memory-cache.ts b/lib/cache/memory-cache.ts
deleted file mode 100644
index d586e592..00000000
--- a/lib/cache/memory-cache.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-import { Chat } from '@/lib/db/schema'
-import { UIMessage } from '@/lib/types/ai'
-
-// LRU cache entry type
-type CacheEntry<T> = {
- value: T
- expiry: number
- lastAccessed: number
-}
-
-// In-memory cache with TTL and LRU eviction
-class MemoryCache<T> {
- private cache = new Map<string, CacheEntry<T>>()
- private ttl: number
- private maxEntries: number
- private stats = { hits: 0, misses: 0 }
-
- constructor(ttlSeconds: number = 60, maxEntries: number = 1000) {
- this.ttl = ttlSeconds * 1000 // Convert to milliseconds
- this.maxEntries = maxEntries
- }
-
- set(key: string, value: T): void {
- try {
- // If we're at capacity, evict LRU entry
- if (this.cache.size >= this.maxEntries) {
- this.evictLRU()
- }
-
- const now = Date.now()
- const expiry = now + this.ttl
- this.cache.set(key, { value, expiry, lastAccessed: now })
- } catch (error) {
- console.error('Cache set error:', error)
- // Fail silently, don't impact main flow
- }
- }
-
- private evictLRU(): void {
- let oldestKey: string | null = null
- let oldestTime = Infinity
-
- for (const [key, entry] of this.cache.entries()) {
- if (entry.lastAccessed < oldestTime) {
- oldestTime = entry.lastAccessed
- oldestKey = key
- }
- }
-
- if (oldestKey) {
- this.cache.delete(oldestKey)
- }
- }
-
- get(key: string): T | null {
- try {
- const item = this.cache.get(key)
-
- if (!item) {
- this.stats.misses++
- return null
- }
-
- const now = Date.now()
- if (now > item.expiry) {
- this.cache.delete(key)
- this.stats.misses++
- return null
- }
-
- // Update last accessed time
- item.lastAccessed = now
- this.stats.hits++
- return item.value
- } catch (error) {
- console.error('Cache get error:', error)
- this.stats.misses++
- return null
- }
- }
-
- delete(key: string): void {
- try {
- this.cache.delete(key)
- } catch (error) {
- console.error('Cache delete error:', error)
- }
- }
-
- deletePattern(pattern: string): void {
- try {
- // Delete all keys that start with the pattern
- for (const key of this.cache.keys()) {
- if (key.startsWith(pattern)) {
- this.cache.delete(key)
- }
- }
- } catch (error) {
- console.error('Cache deletePattern error:', error)
- }
- }
-
- clear(): void {
- try {
- this.cache.clear()
- } catch (error) {
- console.error('Cache clear error:', error)
- }
- }
-
- // Clean up expired entries periodically
- cleanup(): void {
- try {
- const now = Date.now()
- for (const [key, item] of this.cache.entries()) {
- if (now > item.expiry) {
- this.cache.delete(key)
- }
- }
- } catch (error) {
- console.error('Cache cleanup error:', error)
- }
- }
-
- // Get cache statistics
- getStats() {
- return {
- ...this.stats,
- size: this.cache.size,
- hitRate:
- this.stats.hits > 0
- ? this.stats.hits / (this.stats.hits + this.stats.misses)
- : 0
- }
- }
-}
-
-// Get cache configuration from environment variables
-const getCacheConfig = () => {
- const ttl = process.env.CHAT_CACHE_TTL
- const maxEntries = process.env.CHAT_CACHE_MAX_ENTRIES
-
- const ttlValue = ttl ? parseInt(ttl, 10) : 300 // Default: 5 minutes
- const maxEntriesValue = maxEntries ? parseInt(maxEntries, 10) : 1000 // Default: 1000 entries
-
- // Validate configuration
- const validTtl = Math.max(10, Math.min(3600, ttlValue)) // Min: 10s, Max: 1 hour
- const validMaxEntries = Math.max(100, Math.min(10000, maxEntriesValue)) // Min: 100, Max: 10000
-
- return { ttl: validTtl, maxEntries: validMaxEntries }
-}
-
-// Cache instances with configurable TTLs and size limits
-const config = getCacheConfig()
-export const chatCache = new MemoryCache<Chat & { messages: UIMessage[] }>(
- config.ttl,
- config.maxEntries
-)
-
-// Store interval reference for cleanup
-let cleanupInterval: NodeJS.Timeout | null = null
-
-// Setup cleanup interval
-if (typeof setInterval !== 'undefined') {
- cleanupInterval = setInterval(() => {
- chatCache.cleanup()
-
- // Log stats periodically in development
- if (process.env.NODE_ENV === 'development') {
- const stats = chatCache.getStats()
- console.log(
- `Cache stats - Size: ${stats.size}, Hit rate: ${(stats.hitRate * 100).toFixed(2)}%`
- )
- }
- }, 60000) // Run cleanup every minute
-}
-
-// Cleanup function for graceful shutdown
-export const cleanupCacheInterval = () => {
- if (cleanupInterval) {
- clearInterval(cleanupInterval)
- cleanupInterval = null
- }
- chatCache.clear()
-}
-
-// Setup graceful shutdown handlers
-if (typeof process !== 'undefined' && process.on) {
- // Graceful shutdown on SIGINT (Ctrl+C)
- process.on('SIGINT', () => {
- console.log('\nGracefully shutting down cache...')
- cleanupCacheInterval()
- // Let the process exit naturally after cleanup
- process.exitCode = 0
- })
-
- // Graceful shutdown on SIGTERM
- process.on('SIGTERM', () => {
- console.log('\nGracefully shutting down cache...')
- cleanupCacheInterval()
- // Let the process exit naturally after cleanup
- process.exitCode = 0
- })
-
- // Cleanup before exit
- process.on('beforeExit', () => {
- cleanupCacheInterval()
- })
-}
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index e5d39f34..45a86036 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -2,7 +2,6 @@
import { and, asc, desc, eq, gt, inArray } from 'drizzle-orm'
-import { chatCache } from '@/lib/cache/memory-cache'
import type { UIMessage } from '@/lib/types/ai'
import type { PersistableUIMessage } from '@/lib/types/message-persistence'
import {
@@ -39,9 +38,6 @@ export async function createChat({
})
.returning()
- // Invalidate cache for this chat
- chatCache.deletePattern(`${id}-`)
-
return chat
}
@@ -106,12 +102,6 @@ export async function upsertMessage(
return dbMessage
})
- // Invalidate cache after successful transaction
- // Using setTimeout to ensure this happens after transaction commit
- setTimeout(() => {
- chatCache.deletePattern(`${message.chatId}-`)
- }, 0)
-
return result
}
@@ -167,20 +157,11 @@ export async function loadChatWithMessages(
return null
}
- // Now check cache with visibility included in key
- const cacheKey = `${chatId}-${userId || 'anonymous'}-${chat.visibility}`
- const cached = chatCache.get(cacheKey)
- if (cached) {
- return cached
- }
-
- // Build result and cache it
+ // Build result
const uiMessages = messagesResult.map(msg =>
buildUIMessageFromDB(msg, msg.parts)
)
- const result = { ...chat, messages: uiMessages }
- chatCache.set(cacheKey, result)
- return result
+ return { ...chat, messages: uiMessages }
}
/**
@@ -217,9 +198,6 @@ export async function deleteMessagesAfter(
if (messageIds.length > 0) {
// Delete messages (parts will be cascade deleted)
await db.delete(messages).where(inArray(messages.id, messageIds))
-
- // Invalidate cache for this chat
- chatCache.deletePattern(`${chatId}-`)
}
return { count: messageIds.length }
@@ -252,9 +230,6 @@ export async function deleteMessagesFromIndex(
if (messageIds.length > 0) {
await db.delete(messages).where(inArray(messages.id, messageIds))
-
- // Invalidate cache for this chat
- chatCache.deletePattern(`${chatId}-`)
}
return { count: messageIds.length }
@@ -271,6 +246,35 @@ export async function getChats(userId: string): Promise<Chat[]> {
.orderBy(desc(chats.createdAt))
}
+/**
+ * Get chats with pagination
+ */
+export async function getChatsPage(
+ userId: string,
+ limit = 20,
+ offset = 0
+): Promise<{ chats: Chat[]; nextOffset: number | null }> {
+ try {
+ const results = await db
+ .select()
+ .from(chats)
+ .where(eq(chats.userId, userId))
+ .orderBy(desc(chats.createdAt))
+ .limit(limit)
+ .offset(offset)
+
+ const nextOffset = results.length === limit ? offset + limit : null
+
+ return {
+ chats: results,
+ nextOffset
+ }
+ } catch (error) {
+ console.error('Error fetching chat page:', error)
+ return { chats: [], nextOffset: null }
+ }
+}
+
/**
* Delete a chat
*/
@@ -288,9 +292,6 @@ export async function deleteChat(
// Delete the chat (messages and parts will cascade)
await db.delete(chats).where(eq(chats.id, chatId))
- // Invalidate cache for this chat
- chatCache.deletePattern(`${chatId}-`)
-
return { success: true }
} catch (error) {
console.error('Error deleting chat:', error)
@@ -317,11 +318,6 @@ export async function updateChatVisibility(
.where(eq(chats.id, chatId))
.returning()
- // Invalidate cache for this chat
- if (updatedChat) {
- chatCache.deletePattern(`${chatId}-`)
- }
-
return updatedChat
}
@@ -338,10 +334,5 @@ export async function updateChatTitle(
.where(eq(chats.id, chatId))
.returning()
- // Invalidate cache for this chat
- if (updatedChat) {
- chatCache.deletePattern(`${chatId}-`)
- }
-
return updatedChat || null
}
diff --git a/lib/db/chat.ts b/lib/db/chat.ts
deleted file mode 100644
index 38eac81d..00000000
--- a/lib/db/chat.ts
+++ /dev/null
@@ -1,330 +0,0 @@
-import { revalidatePath } from 'next/cache'
-
-import { and, desc, eq, gte, inArray } from 'drizzle-orm'
-
-import { type Chat, chats, type Message, messages } from './schema'
-import { db } from '.'
-
-// Create a new chat
-export async function createChat({
- title,
- userId,
- visibility = 'private'
-}: {
- title: string
- userId: string
- visibility?: 'public' | 'private'
-}): Promise<Chat> {
- const [chat] = await db
- .insert(chats)
- .values({
- title,
- userId,
- visibility
- })
- .returning()
-
- return chat
-}
-
-// Get a chat by ID
-export async function getChat(
- id: string,
- userId: string
-): Promise<Chat | null> {
- const [chat] = await db.select().from(chats).where(eq(chats.id, id)).limit(1)
-
- // If userId is provided, check if the chat belongs to the user or is public
- if (chat && chat.userId !== userId && chat.visibility !== 'public') {
- return null // User doesn't have access to this chat
- }
-
- return chat || null
-}
-
-// Get all chats for a user
-export async function getChats(userId: string): Promise<Chat[]> {
- return db
- .select()
- .from(chats)
- .where(eq(chats.userId, userId))
- .orderBy(chats.createdAt)
-}
-
-// Get chats with pagination
-export async function getChatsPage(
- userId: string,
- limit = 20,
- offset = 0
-): Promise<{ chats: Chat[]; nextOffset: number | null }> {
- try {
- const results = await db
- .select()
- .from(chats)
- .where(eq(chats.userId, userId))
- .orderBy(desc(chats.createdAt))
- .limit(limit)
- .offset(offset)
-
- const nextOffset = results.length === limit ? offset + limit : null
-
- return {
- chats: results,
- nextOffset
- }
- } catch (error) {
- console.error('Error fetching chat page:', error)
- return { chats: [], nextOffset: null }
- }
-}
-
-// Update a chat
-export async function updateChat(
- id: string,
- data: Partial<Pick<Chat, 'title' | 'visibility'>>
-): Promise<Chat | null> {
- const [chat] = await db
- .update(chats)
- .set({
- ...data
- })
- .where(eq(chats.id, id))
- .returning()
-
- return chat || null
-}
-
-// Delete a chat and its messages
-export async function deleteChat(
- id: string,
- userId: string
-): Promise<{ error?: string }> {
- try {
- // First verify the chat exists and belongs to the user
- const chat = await getChat(id, userId)
-
- if (!chat) {
- console.warn(`Attempted to delete non-existent chat: ${id}`)
- return { error: 'Chat not found' }
- }
-
- // Check if the chat belongs to the user
- if (chat.userId !== userId) {
- return { error: 'Unauthorized' }
- }
-
- // Delete the chat
- await db.delete(chats).where(eq(chats.id, id))
-
- // Revalidate the root path where the chat history is displayed
- revalidatePath('/')
-
- return {}
- } catch (error) {
- console.error(`Error deleting chat ${id}:`, error)
- return { error: 'Failed to delete chat' }
- }
-}
-
-// Add a message to a chat
-export async function addMessage({
- id,
- chatId,
- role,
- parts
-}: {
- id?: string
- chatId: string
- role: string
- parts: any
-}): Promise<Message> {
- const attachments = Array.isArray(parts)
- ? parts
- .filter(part => part.type === 'file')
- .map(part => ({
- name: part.filename,
- url: part.url,
- contentType: part.mediaType
- }))
- : []
-
- const valuesToInsert: {
- id?: string
- chatId: string
- role: string
- parts: any
- attachments: any
- } = {
- chatId,
- role,
- parts,
- attachments
- }
-
- if (id) {
- valuesToInsert.id = id
- }
-
- const [message] = await db.insert(messages).values(valuesToInsert).returning()
-
- return message
-}
-
-// Get all messages for a chat
-export async function getChatMessages(chatId: string): Promise<Message[]> {
- return db
- .select()
- .from(messages)
- .where(eq(messages.chatId, chatId))
- .orderBy(messages.createdAt)
-}
-
-// Delete all messages created at or after the given timestamp in the same chat.
-// This will include the message whose createdAt matches the timestamp.
-export async function deleteMessagesByChatIdAfterTimestamp(
- chatId: string,
- timestamp: string // Expecting ISO 8601 string
-): Promise<{ count: number; error?: string }> {
- try {
- // Select IDs of messages to delete
- const messagesToDelete = await db
- .select({ id: messages.id })
- .from(messages)
- .where(
- and(
- eq(messages.chatId, chatId),
- gte(messages.createdAt, new Date(timestamp)) // Convert string to Date
- )
- )
-
- const messageIds = messagesToDelete.map(message => message.id)
-
- if (messageIds.length === 0) {
- return { count: 0 } // No messages to delete
- }
-
- // Delete the actual messages
- const result = await db
- .delete(messages)
- .where(and(eq(messages.chatId, chatId), inArray(messages.id, messageIds)))
- .returning({ id: messages.id })
-
- return { count: result.length }
- } catch (error) {
- console.error(
- `Error deleting messages for chat ${chatId} at or after ${timestamp}:`,
- error
- )
- return { count: 0, error: 'Failed to delete messages' }
- }
-}
-
-// Clear all chats for a user
-export async function clearChats(userId: string): Promise<{ error?: string }> {
- try {
- // Get all chat IDs for this user
- const userChats = await getChats(userId)
-
- if (!userChats.length) {
- return { error: 'No chats to clear' }
- }
-
- // Delete all chats for this user
- // Message deletion happens automatically due to ON DELETE CASCADE
- await db.delete(chats).where(eq(chats.userId, userId))
-
- revalidatePath('/')
-
- return { error: undefined }
- } catch (error) {
- console.error('Error clearing chats:', error)
- return { error: 'Failed to clear chats' }
- }
-}
-
-// Save a chat (create or update)
-export async function saveChat(chat: Chat, userId: string) {
- try {
- // Check if the chat exists
- const existingChat = await getChat(chat.id, userId)
-
- if (existingChat) {
- // Update existing chat
- return await db
- .update(chats)
- .set({
- title: chat.title,
- visibility: chat.visibility
- })
- .where(eq(chats.id, chat.id))
- .returning()
- } else {
- // Create new chat
- return await db
- .insert(chats)
- .values({
- id: chat.id,
- title: chat.title,
- userId,
- visibility: chat.visibility || 'private'
- })
- .returning()
- }
- } catch (error) {
- console.error('Error saving chat:', error)
- throw error
- }
-}
-
-// Get a shared chat
-export async function getSharedChat(id: string) {
- try {
- // For shared chats, we bypass the userId check and directly query the database
- const [chat] = await db
- .select()
- .from(chats)
- .where(eq(chats.id, id))
- .limit(1)
-
- if (!chat || chat.visibility !== 'public') {
- return null
- }
-
- return chat
- } catch (error) {
- console.error('Error getting shared chat:', error)
- return null
- }
-}
-
-// Share a chat (make it public)
-export async function shareChat(id: string, userId: string) {
- try {
- const chat = await getChat(id, userId)
-
- if (!chat || chat.userId !== userId) {
- return null
- }
-
- // Update the chat to be public
- const [updatedChat] = await db
- .update(chats)
- .set({
- visibility: 'public'
- })
- .where(eq(chats.id, id))
- .returning()
-
- if (updatedChat) {
- return {
- ...updatedChat,
- sharePath: `/share/${id}`
- }
- }
-
- return null
- } catch (error) {
- console.error('Error sharing chat:', error)
- return null
- }
-}
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index eedcf035..5dc7ec9a 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -18,18 +18,10 @@ export async function prepareMessages(
): Promise<UIMessage[]> {
const { chatId, userId, trigger, messageId, initialChat } = context
- // Performance logging
- if (process.env.NODE_ENV === 'development') {
- console.log('[prepareMessages] Using initialChat:', !!initialChat)
- }
-
if (trigger === 'regenerate-assistant-message' && messageId) {
// Handle regeneration - use initialChat if available to avoid DB call
let currentChat = initialChat
if (!currentChat) {
- if (process.env.NODE_ENV === 'development') {
- console.log('[prepareMessages] Fetching chat from DB (regeneration)')
- }
currentChat = await getChatAction(chatId, userId)
}
if (!currentChat || !currentChat.messages.length) {
@@ -92,19 +84,13 @@ export async function prepareMessages(
}
await saveMessage(chatId, messageWithId)
-
+
// If we have initialChat, append the new message instead of fetching all messages
if (initialChat && initialChat.messages) {
- if (process.env.NODE_ENV === 'development') {
- console.log('[prepareMessages] Using cached messages, skipping DB fetch')
- }
return [...initialChat.messages, messageWithId]
}
-
+
// Fallback to fetching if no initialChat
- if (process.env.NODE_ENV === 'development') {
- console.log('[prepareMessages] No initialChat, fetching from DB')
- }
const updatedChat = await getChatAction(chatId, userId)
return updatedChat?.messages || [messageWithId]
}
diff --git a/scripts/test-cache-performance.ts b/scripts/test-cache-performance.ts
new file mode 100755
index 00000000..66ee0e61
--- /dev/null
+++ b/scripts/test-cache-performance.ts
@@ -0,0 +1,134 @@
+#!/usr/bin/env bun
+
+import { config } from 'dotenv'
+
+config({ path: '.env.local' })
+
+const API_URL = process.env.API_URL || 'http://localhost:3001/api/chat'
+const COOKIES = process.env.MORPHIC_COOKIES
+
+async function measureRequest(
+ chatId: string,
+ message: string,
+ trigger: string = 'submit-user-message',
+ messageId?: string
+): Promise<number> {
+ const startTime = performance.now()
+
+ const payload: any = {
+ chatId,
+ trigger
+ }
+
+ if (trigger === 'submit-user-message') {
+ payload.message = {
+ id: `msg_${Date.now()}_${Math.random().toString(36).substring(7)}`,
+ role: 'user',
+ content: message,
+ parts: [{ type: 'text', text: message }],
+ createdAt: new Date().toISOString()
+ }
+ } else if (trigger === 'regenerate-assistant-message' && messageId) {
+ payload.messageId = messageId
+ }
+
+ const response = await fetch(API_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Cookie: COOKIES || ''
+ },
+ body: JSON.stringify(payload)
+ })
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`)
+ }
+
+ // Consume the stream
+ const reader = response.body?.getReader()
+ if (reader) {
+ while (true) {
+ const { done } = await reader.read()
+ if (done) break
+ }
+ }
+
+ const endTime = performance.now()
+ return endTime - startTime
+}
+
+async function runPerformanceTests() {
+ console.log('πŸš€ Cache Performance Test Suite')
+ console.log('================================\n')
+
+ const results = {
+ firstRequest: 0,
+ cachedRequest: 0,
+ regeneration: 0,
+ consecutiveRequests: [] as number[]
+ }
+
+ // Test 1: First request (cold cache)
+ console.log('Test 1: First request (cold cache)')
+ const chatId1 = `chat_perf_${Date.now()}_1`
+ results.firstRequest = await measureRequest(
+ chatId1,
+ 'What is the capital of France?'
+ )
+ console.log(`βœ“ Time: ${results.firstRequest.toFixed(2)}ms\n`)
+
+ // Test 2: Subsequent request (warm cache)
+ console.log('Test 2: Subsequent request (warm cache)')
+ results.cachedRequest = await measureRequest(chatId1, 'What about Germany?')
+ console.log(`βœ“ Time: ${results.cachedRequest.toFixed(2)}ms\n`)
+
+ // Test 3: Regeneration (should bypass cache)
+ console.log('Test 3: Regeneration (bypass cache)')
+ const messageId = `msg_${Date.now()}_test`
+ results.regeneration = await measureRequest(
+ chatId1,
+ '',
+ 'regenerate-assistant-message',
+ messageId
+ )
+ console.log(`βœ“ Time: ${results.regeneration.toFixed(2)}ms\n`)
+
+ // Test 4: Multiple consecutive requests
+ console.log('Test 4: Multiple consecutive requests')
+ const chatId2 = `chat_perf_${Date.now()}_2`
+ for (let i = 1; i <= 5; i++) {
+ const time = await measureRequest(chatId2, `Message ${i}`)
+ results.consecutiveRequests.push(time)
+ console.log(` Request ${i}: ${time.toFixed(2)}ms`)
+ }
+
+ // Summary
+ console.log('\n================================')
+ console.log('πŸ“Š Performance Summary')
+ console.log('================================')
+ console.log(`First Request: ${results.firstRequest.toFixed(2)}ms`)
+ console.log(`Cached Request: ${results.cachedRequest.toFixed(2)}ms`)
+ console.log(`Regeneration: ${results.regeneration.toFixed(2)}ms`)
+
+ const avgConsecutive =
+ results.consecutiveRequests.reduce((a, b) => a + b, 0) /
+ results.consecutiveRequests.length
+ console.log(`Avg Consecutive: ${avgConsecutive.toFixed(2)}ms`)
+
+ // Cache effectiveness
+ const cacheImprovement =
+ ((results.firstRequest - results.cachedRequest) / results.firstRequest) *
+ 100
+ console.log(`\nCache Improvement: ${cacheImprovement.toFixed(1)}%`)
+
+ // Check if cache is working effectively
+ if (results.cachedRequest < results.firstRequest) {
+ console.log('βœ… Cache is working effectively!')
+ } else {
+ console.log('⚠️ Cache may not be working as expected')
+ }
+}
+
+// Run tests
+runPerformanceTests().catch(console.error)