Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dns: implement light dns caching #49560

Closed
wants to merge 15 commits into from
Closed
38 changes: 37 additions & 1 deletion lib/dns.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,32 @@ function onlookupall(err, addresses) {
}
}

function cleanExpiredDnsCache() {
const currentTime = DateNow();
for (const key in dnsCache) {
if (currentTime - dnsCache[key].timestamp >= 1000) {
dnsCache[key] = undefined;
}
}
}

function addDnsEntry(cacheKey, address, family) {
dnsCache[cacheKey] = {
address,
family,
timestamp: DateNow(),
};

cleanExpiredDnsCache();

return dnsCache[cacheKey];
}

// Easy DNS A/AAAA look up
// lookup(hostname, [options,] callback)
const validFamilies = [0, 4, 6];
const dnsCache = { __proto__: null };
const { DateNow } = primordials;
function lookup(hostname, options, callback) {
let hints = 0;
let family = 0;
Expand Down Expand Up @@ -212,8 +234,22 @@ function lookup(hostname, options, callback) {
return {};
}

const cacheKey = `${hostname}_${family || 'default'}_${all ? 'all' : 'single'}`;
const cachedResult = dnsCache[cacheKey];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A read-through cache approach would be a bit simpler here. essentially something like

cache.get(cacheKey, callback, () => {
  // If the cache lookup is a miss, this function is called to do the lookup and cache the result of the lookup.
});


if (cachedResult) {
cleanExpiredDnsCache();
callback(null, cachedResult.address, cachedResult.family);
return {};
}

const req = new GetAddrInfoReqWrap();
req.callback = callback;
req.callback = (error, address, family) => {
if (!error) {
addDnsEntry(cacheKey, address, family);
}
callback(error, address, family);
};
req.family = family;
req.hostname = hostname;
req.oncomplete = all ? onlookupall : onlookup;
Expand Down