mirror of
https://github.com/pockethost/pockethost.git
synced 2025-11-24 06:25:48 +00:00
refactor: enhance MultiChannelLimiter with idle cleanup and scheduling
This commit is contained in:
parent
fa3175c044
commit
6bb396fd24
@ -30,20 +30,49 @@ export type LogEntry = {
|
|||||||
|
|
||||||
const MultiChannelLimiter = () => {
|
const MultiChannelLimiter = () => {
|
||||||
const channels = new Map<string, Bottleneck>()
|
const channels = new Map<string, Bottleneck>()
|
||||||
setInterval(() => {
|
const timeouts = new Map<string, NodeJS.Timeout>()
|
||||||
for (const [channel, limiter] of channels.entries()) {
|
const IDLE_TIMEOUT = 1000 * 60 // 1 minute idle timeout per channel
|
||||||
if (limiter.empty()) {
|
|
||||||
// console.log(`Deleting empty limiter for ${channel}`)
|
const cleanupChannel = (channel: string) => {
|
||||||
channels.delete(channel)
|
const limiter = channels.get(channel)
|
||||||
}
|
if (limiter && limiter.empty()) {
|
||||||
|
// console.log(`Deleting idle limiter for ${channel}`)
|
||||||
|
channels.delete(channel)
|
||||||
|
timeouts.delete(channel)
|
||||||
}
|
}
|
||||||
}, 1000 * 60)
|
}
|
||||||
|
|
||||||
|
const scheduleCleanup = (channel: string) => {
|
||||||
|
// Clear existing timeout if any
|
||||||
|
const existingTimeout = timeouts.get(channel)
|
||||||
|
if (existingTimeout) {
|
||||||
|
clearTimeout(existingTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule new cleanup
|
||||||
|
const timeout = setTimeout(() => cleanupChannel(channel), IDLE_TIMEOUT)
|
||||||
|
timeouts.set(channel, timeout)
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
schedule(channel: string, fn: () => Promise<void>) {
|
schedule(channel: string, fn: () => Promise<void>) {
|
||||||
if (!channels.has(channel)) {
|
if (!channels.has(channel)) {
|
||||||
channels.set(channel, new Bottleneck({ maxConcurrent: 1 }))
|
const limiter = new Bottleneck({ maxConcurrent: 1 })
|
||||||
|
channels.set(channel, limiter)
|
||||||
|
|
||||||
|
// Set up cleanup when limiter becomes empty
|
||||||
|
limiter.on('idle', () => {
|
||||||
|
scheduleCleanup(channel)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clear any pending cleanup since channel is active
|
||||||
|
const existingTimeout = timeouts.get(channel)
|
||||||
|
if (existingTimeout) {
|
||||||
|
clearTimeout(existingTimeout)
|
||||||
|
timeouts.delete(channel)
|
||||||
|
}
|
||||||
|
|
||||||
return channels.get(channel)!.schedule(fn)!
|
return channels.get(channel)!.schedule(fn)!
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user