From 49c4df38bf6e7c3b80fa8a2d14a25c14aca7b703 Mon Sep 17 00:00:00 2001 From: kshitjj Date: Sat, 16 Sep 2023 23:19:10 +0530 Subject: [PATCH] Implement lazy cache cleanup for DNS entries This commit replaces the timer based approach for purging the expired dns cache with lazy cleanup approach. The DNS cache is now cleaned before adding a new DNS entry and before performing a lookup. This change simplifies the code and eliminates the need for a separate cleanup timer. --- lib/dns.js | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/lib/dns.js b/lib/dns.js index 5a1a0255db6cbe..82266effe908ed 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -134,21 +134,13 @@ function onlookupall(err, addresses) { } } -function cleanDnsCache() { +function cleanExpiredDnsCache() { + const currentTime = DateNow(); for (const key in dnsCache) { - delete dnsCache[key]; - } -} - -function scheduleCleanup() { - if (cleanupTimeout) { - return; + if (currentTime - dnsCache[key].timestamp >= 1000) { + delete dnsCache[key]; + } } - - cleanupTimeout = setTimeout(() => { - cleanDnsCache(); - cleanupTimeout = null; - }, 1000).ref(); } function addDnsEntry(cacheKey, address, family) { @@ -158,7 +150,7 @@ function addDnsEntry(cacheKey, address, family) { timestamp: DateNow(), }; - scheduleCleanup(); + cleanExpiredDnsCache(); return dnsCache[cacheKey]; } @@ -175,6 +167,7 @@ function lookup(hostname, options, callback) { let all = false; let verbatim = getDefaultVerbatim(); + cleanExpiredDnsCache(); // Parse arguments if (hostname) { @@ -248,7 +241,7 @@ function lookup(hostname, options, callback) { const cacheKey = `${hostname}_${family || 'default'}`; const cachedResult = dnsCache[cacheKey]; - if (cachedResult && DateNow() - cachedResult.timestamp < 1000) { + if (cachedResult) { callback(null, cachedResult.address, cachedResult.family); return {}; }