Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/Utils/event-buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
let data = makeBufferData()
let isBuffering = false
let bufferTimeout: NodeJS.Timeout | null = null
let flushPendingTimeout: NodeJS.Timeout | null = null // Add a specific timer for the debounced flush to prevent leak
let bufferCount = 0
const MAX_HISTORY_CACHE_SIZE = 10000 // Limit the history cache size to prevent memory bloat
const BUFFER_TIMEOUT_MS = 30000 // 30 seconds
Expand All @@ -89,9 +90,8 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
if (!isBuffering) {
logger.debug('Event buffer activated')
isBuffering = true
bufferCount++
bufferCount = 0

// Auto-flush after a timeout to prevent infinite buffering
if (bufferTimeout) {
clearTimeout(bufferTimeout)
}
Expand All @@ -102,9 +102,10 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
flush()
}
}, BUFFER_TIMEOUT_MS)
} else {
bufferCount++
}

// Always increment count when requested
bufferCount++
}

function flush() {
Expand All @@ -122,6 +123,11 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
bufferTimeout = null
}

if (flushPendingTimeout) {
clearTimeout(flushPendingTimeout)
flushPendingTimeout = null
}

// Clear history cache if it exceeds the max size
if (historyCache.size > MAX_HISTORY_CACHE_SIZE) {
logger.debug({ cacheSize: historyCache.size }, 'Clearing history cache')
Expand Down Expand Up @@ -195,8 +201,10 @@ export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter
} finally {
bufferCount = Math.max(0, bufferCount - 1)
if (bufferCount === 0) {
// Auto-flush when no other buffers are active
setTimeout(flush, 100)
// Only schedule ONE timeout, not 10,000
if (!flushPendingTimeout) {
flushPendingTimeout = setTimeout(flush, 100)
}
}
}
}
Expand Down
Loading