Skip to content

An AI-powered search engine with a generative UI

style: fix code formatting with Prettier

Yoshiki Miuraff6289c3be4b
diff --git a/lib/cache/memory-cache.ts b/lib/cache/memory-cache.ts
index 360d18c4..86d5134d 100644
--- a/lib/cache/memory-cache.ts
+++ b/lib/cache/memory-cache.ts
@@ -55,7 +55,7 @@ class MemoryCache<T> {
get(key: string): T | null {
try {
const item = this.cache.get(key)
-
+
if (!item) {
this.stats.misses++
return null
@@ -127,7 +127,10 @@ class MemoryCache<T> {
return {
...this.stats,
size: this.cache.size,
- hitRate: this.stats.hits > 0 ? this.stats.hits / (this.stats.hits + this.stats.misses) : 0
+ hitRate:
+ this.stats.hits > 0
+ ? this.stats.hits / (this.stats.hits + this.stats.misses)
+ : 0
}
}
}
@@ -136,20 +139,23 @@ class MemoryCache<T> {
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)
+export const chatCache = new MemoryCache<Chat & { messages: UIMessage[] }>(
+ config.ttl,
+ config.maxEntries
+)
// Store interval reference for cleanup
let cleanupInterval: NodeJS.Timeout | null = null
@@ -158,11 +164,13 @@ let cleanupInterval: NodeJS.Timeout | null = null
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)}%`)
+ console.log(
+ `Cache stats - Size: ${stats.size}, Hit rate: ${(stats.hitRate * 100).toFixed(2)}%`
+ )
}
}, 60000) // Run cleanup every minute
}
@@ -196,4 +204,4 @@ if (typeof process !== 'undefined' && process.on) {
process.on('beforeExit', () => {
cleanupCacheInterval()
})
-}
\ No newline at end of file
+}
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index e00820ef..e5d39f34 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -175,7 +175,9 @@ export async function loadChatWithMessages(
}
// Build result and cache it
- const uiMessages = messagesResult.map(msg => buildUIMessageFromDB(msg, msg.parts))
+ const uiMessages = messagesResult.map(msg =>
+ buildUIMessageFromDB(msg, msg.parts)
+ )
const result = { ...chat, messages: uiMessages }
chatCache.set(cacheKey, result)
return result
@@ -215,7 +217,7 @@ 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}-`)
}
@@ -250,7 +252,7 @@ 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}-`)
}
@@ -285,7 +287,7 @@ 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}-`)
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 9dc2be1f..67b4eba5 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -64,7 +64,8 @@ export async function createChatStreamResponse(
if (trigger === 'regenerate-assistant-message' && messageId) {
// Handle regeneration
// Use cached chat data or fetch if not available
- const currentChat = initialChat || await getChatAction(chatId, userId)
+ const currentChat =
+ initialChat || (await getChatAction(chatId, userId))
if (!currentChat || !currentChat.messages.length) {
throw new Error('No messages found')
}
@@ -194,7 +195,9 @@ export async function createChatStreamResponse(
// If no tool calls (just answering), skip related questions
if (!hasToolCallsInMessage) {
// Save research message and generate title in parallel
- const savePromises: Promise<any>[] = [saveMessage(chatId, validResearchMessage)]
+ const savePromises: Promise<any>[] = [
+ saveMessage(chatId, validResearchMessage)
+ ]
// Generate proper title after conversation starts
if (!initialChat && message) {
@@ -213,7 +216,7 @@ export async function createChatStreamResponse(
// Execute saves in background with exponential backoff retry
Promise.all(savePromises).catch(async error => {
console.error('Error saving message or title:', error)
-
+
// Retry critical save operations with backoff
try {
for (const promise of savePromises) {
@@ -223,7 +226,10 @@ export async function createChatStreamResponse(
)
}
} catch (retryError) {
- console.error('Failed to save after retries with backoff:', retryError)
+ console.error(
+ 'Failed to save after retries with backoff:',
+ retryError
+ )
// Consider implementing alerting mechanism here
// For now, we ensure the error is logged for monitoring
}
@@ -275,7 +281,7 @@ export async function createChatStreamResponse(
// Save the complete message after both agents finish
const savePromises: Promise<any>[] = []
-
+
if (validResearchMessage && relatedQuestionsMessage) {
const mergedMessage = mergeUIMessages(
validResearchMessage,
@@ -304,7 +310,7 @@ export async function createChatStreamResponse(
// Execute saves in background with exponential backoff retry
Promise.all(savePromises).catch(async error => {
console.error('Error saving message or title:', error)
-
+
// Retry critical save operations with backoff
try {
for (const promise of savePromises) {
@@ -314,7 +320,10 @@ export async function createChatStreamResponse(
)
}
} catch (retryError) {
- console.error('Failed to save after retries with backoff:', retryError)
+ console.error(
+ 'Failed to save after retries with backoff:',
+ retryError
+ )
// Consider implementing alerting mechanism here
// For now, we ensure the error is logged for monitoring
}
diff --git a/lib/utils/retry.ts b/lib/utils/retry.ts
index 5d8e0801..fd26fdcc 100644
--- a/lib/utils/retry.ts
+++ b/lib/utils/retry.ts
@@ -21,32 +21,32 @@ export async function retryWithBackoff<T>(
} = options
let lastError: any
-
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn()
} catch (error) {
lastError = error
-
+
if (attempt === maxRetries) {
throw error
}
-
+
// Calculate delay with exponential backoff
const delay = Math.min(
initialDelayMs * Math.pow(backoffMultiplier, attempt),
maxDelayMs
)
-
+
if (onRetry) {
onRetry(error, attempt + 1)
}
-
+
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, delay))
}
}
-
+
throw lastError
}
@@ -60,7 +60,10 @@ export async function retryDatabaseOperation<T>(
initialDelayMs: 200,
maxDelayMs: 2000,
onRetry: (error, attempt) => {
- console.log(`Retrying ${operationName} (attempt ${attempt}):`, error.message)
+ console.log(
+ `Retrying ${operationName} (attempt ${attempt}):`,
+ error.message
+ )
}
})
-}
\ No newline at end of file
+}