Skip to content

Commit

Permalink
chore: add caching layer to dns resolved ips
Browse files Browse the repository at this point in the history
  • Loading branch information
Jayachand committed Apr 9, 2024
1 parent 007009f commit 3945114
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/util/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { Resolver } = require('dns').promises;
const fetch = require('node-fetch');

const util = require('util');
const NodeCache = require('node-cache');
const logger = require('../logger');
const stats = require('./stats');

Expand All @@ -16,11 +17,30 @@ const LOCAL_HOST_NAMES_LIST = ['localhost', '127.0.0.1', '[::]', '[::1]'];
const LOCALHOST_OCTET = '127.';
const RECORD_TYPE_A = 4; // ipv4

const DNS_CACHE_ENABLED = process.env.DNS_CACHE_ENABLED === 'true';
const DNS_CACHE_TTL = process.env.DNS_CACHE_TTL ? parseInt(process.env.DNS_CACHE_TTL, 10) : 300;
const dnsCache = new NodeCache({
useClones: false,
stdTTL: DNS_CACHE_TTL,
checkperiod: DNS_CACHE_TTL,
});

const fetchResolvedIps = async (hostname) => {
let ips = dnsCache.get(hostname);

Check warning on line 29 in src/util/utils.js

View check run for this annotation

Codecov / codecov/patch

src/util/utils.js#L29

Added line #L29 was not covered by tests
if (ips === undefined) {
ips = await resolver.resolve4(hostname);

Check warning on line 31 in src/util/utils.js

View check run for this annotation

Codecov / codecov/patch

src/util/utils.js#L31

Added line #L31 was not covered by tests
if (ips?.length > 0) {
dnsCache.set(hostname, ips);

Check warning on line 33 in src/util/utils.js

View check run for this annotation

Codecov / codecov/patch

src/util/utils.js#L33

Added line #L33 was not covered by tests
}
}
return ips;

Check warning on line 36 in src/util/utils.js

View check run for this annotation

Codecov / codecov/patch

src/util/utils.js#L36

Added line #L36 was not covered by tests
};

const staticLookup = (transformerVersionId) => async (hostname, _, cb) => {
let ips;
const resolveStartTime = new Date();
try {
ips = await resolver.resolve4(hostname);
ips = DNS_CACHE_ENABLED ? await fetchResolvedIps(hostname) : await resolver.resolve4(hostname);
} catch (error) {
logger.error(`DNS Error Code: ${error.code} | Message : ${error.message}`);
stats.timing('fetch_dns_resolve_time', resolveStartTime, {
Expand Down

0 comments on commit 3945114

Please sign in to comment.