fix(perf): prevent memory growth in chat and export flows

This commit is contained in:
Jason
2026-04-22 23:23:01 +08:00
parent 30d54fcdb1
commit 6304c9ed51
6 changed files with 243 additions and 70 deletions

View File

@@ -12,6 +12,7 @@ export class MessageCacheService {
private readonly cacheFilePath: string
private cache: Record<string, SessionMessageCacheEntry> = {}
private readonly sessionLimit = 150
private readonly maxSessionEntries = 48
constructor(cacheBasePath?: string) {
const basePath = cacheBasePath && cacheBasePath.trim().length > 0
@@ -36,6 +37,7 @@ export class MessageCacheService {
const parsed = JSON.parse(raw)
if (parsed && typeof parsed === 'object') {
this.cache = parsed
this.pruneSessionEntries()
}
} catch (error) {
console.error('MessageCacheService: 载入缓存失败', error)
@@ -43,6 +45,19 @@ export class MessageCacheService {
}
}
private pruneSessionEntries(): void {
const entries = Object.entries(this.cache || {})
if (entries.length <= this.maxSessionEntries) return
entries.sort((left, right) => {
const leftAt = Number(left[1]?.updatedAt || 0)
const rightAt = Number(right[1]?.updatedAt || 0)
return rightAt - leftAt
})
this.cache = Object.fromEntries(entries.slice(0, this.maxSessionEntries))
}
get(sessionId: string): SessionMessageCacheEntry | undefined {
return this.cache[sessionId]
}
@@ -56,6 +71,7 @@ export class MessageCacheService {
updatedAt: Date.now(),
messages: trimmed
}
this.pruneSessionEntries()
this.persist()
}