From 210312b87c4f885a54dfd0748cc23a8c7c0bb079 Mon Sep 17 00:00:00 2001 From: Alexander Roidl <34438048+alexanderroidl@users.noreply.github.com> Date: Sat, 26 Jul 2025 09:16:23 +0200 Subject: [PATCH] feat: telegram chat throttle cleanup --- lib/notification/adapter/telegram.js | 30 ++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/lib/notification/adapter/telegram.js b/lib/notification/adapter/telegram.js index c387ba3..4a1d516 100644 --- a/lib/notification/adapter/telegram.js +++ b/lib/notification/adapter/telegram.js @@ -7,6 +7,15 @@ const MAX_ENTITIES_PER_CHUNK = 8; const RATE_LIMIT_INTERVAL = 1000; const chatThrottleMap = new Map(); +function cleanupOldThrottles() { + const now = Date.now(); + for (const [chatId, chatThrottle] of chatThrottleMap.entries()) { + if (now - chatThrottle.lastUsedAt > RATE_LIMIT_INTERVAL) { + chatThrottleMap.delete(chatId); + } + } +} + /** * Returns a throttled async function for sending messages to a specific chat. * Telegram enforces a rate limit of 1 message per second per chat (chatId). @@ -15,11 +24,24 @@ const chatThrottleMap = new Map(); * @param {Function} fn - The async function to throttle (should send the message). * @returns {Function} Throttled async function for sending messages. */ -function getThrottled(chatId, fn) { - if (!chatThrottleMap.has(chatId)) { - chatThrottleMap.set(chatId, pThrottle({ limit: 1, interval: RATE_LIMIT_INTERVAL })(fn)); +function getThrottled(chatId, call) { + cleanupOldThrottles(); + + const now = Date.now(); + const chatThrottle = chatThrottleMap.get(chatId); + + if (chatThrottle) { + chatThrottle.lastUsedAt = now; + return chatThrottle.throttled; } - return chatThrottleMap.get(chatId); + + // Create new throttled function + const newThrottle = { + lastUsedAt: now, + throttled: pThrottle({ limit: 1, interval: RATE_LIMIT_INTERVAL })(call), + }; + chatThrottleMap.set(chatId, newThrottle); + return newThrottle.throttled; } /**