mirror of
https://github.com/hicccc77/WeFlow.git
synced 2026-04-24 07:26:48 +00:00
fix(perf): prevent memory growth in chat and export flows
This commit is contained in:
@@ -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()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user