Skip to content

Commit 210312b

Browse files
feat: telegram chat throttle cleanup
1 parent c989da5 commit 210312b

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

lib/notification/adapter/telegram.js

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,15 @@ const MAX_ENTITIES_PER_CHUNK = 8;
77
const RATE_LIMIT_INTERVAL = 1000;
88
const chatThrottleMap = new Map();
99

10+
function cleanupOldThrottles() {
11+
const now = Date.now();
12+
for (const [chatId, chatThrottle] of chatThrottleMap.entries()) {
13+
if (now - chatThrottle.lastUsedAt > RATE_LIMIT_INTERVAL) {
14+
chatThrottleMap.delete(chatId);
15+
}
16+
}
17+
}
18+
1019
/**
1120
* Returns a throttled async function for sending messages to a specific chat.
1221
* Telegram enforces a rate limit of 1 message per second per chat (chatId).
@@ -15,11 +24,24 @@ const chatThrottleMap = new Map();
1524
* @param {Function} fn - The async function to throttle (should send the message).
1625
* @returns {Function} Throttled async function for sending messages.
1726
*/
18-
function getThrottled(chatId, fn) {
19-
if (!chatThrottleMap.has(chatId)) {
20-
chatThrottleMap.set(chatId, pThrottle({ limit: 1, interval: RATE_LIMIT_INTERVAL })(fn));
27+
function getThrottled(chatId, call) {
28+
cleanupOldThrottles();
29+
30+
const now = Date.now();
31+
const chatThrottle = chatThrottleMap.get(chatId);
32+
33+
if (chatThrottle) {
34+
chatThrottle.lastUsedAt = now;
35+
return chatThrottle.throttled;
2136
}
22-
return chatThrottleMap.get(chatId);
37+
38+
// Create new throttled function
39+
const newThrottle = {
40+
lastUsedAt: now,
41+
throttled: pThrottle({ limit: 1, interval: RATE_LIMIT_INTERVAL })(call),
42+
};
43+
chatThrottleMap.set(chatId, newThrottle);
44+
return newThrottle.throttled;
2345
}
2446

2547
/**

0 commit comments

Comments
 (0)