Skip to content

Commit

Permalink
Implement lazy cache cleanup for DNS entries
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kshitjj committed Sep 16, 2023
1 parent 83586ef commit 49c4df3
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions lib/dns.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -158,7 +150,7 @@ function addDnsEntry(cacheKey, address, family) {
timestamp: DateNow(),
};

scheduleCleanup();
cleanExpiredDnsCache();

return dnsCache[cacheKey];
}
Expand All @@ -175,6 +167,7 @@ function lookup(hostname, options, callback) {
let all = false;
let verbatim = getDefaultVerbatim();

cleanExpiredDnsCache();

// Parse arguments
if (hostname) {
Expand Down Expand Up @@ -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 {};
}
Expand Down

0 comments on commit 49c4df3

Please sign in to comment.