Skip to content

Commit

Permalink
Do not dns.lookup() in background to prevent memory leaks
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed May 11, 2020
1 parent 50c2cb0 commit ae7c02f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 41 deletions.
50 changes: 13 additions & 37 deletions source/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -329,53 +329,29 @@ class CacheableLookup {
return this._dnsLookup(hostname, all);
}

const resolverPromise = this._resolve(hostname);
const lookupPromise = this._lookup(hostname);

let query;

try {
query = await Promise.race([
resolverPromise,
lookupPromise
]);
let query = await this._resolve(hostname);

if (query.entries.length === 0) {
if (query.isLookup) {
query = await resolverPromise;
} else {
query = await lookupPromise;
query = await this._lookup(hostname);

if (query.entries.length !== 0) {
// Use `dns.lookup(...)` for that particular hostname
this._hostnamesToFallback.add(hostname);
}
}
} catch (error) {
delete this._pending[hostname];

throw error;
}

(async () => {
if (query.isLookup) {
try {
const realDnsQuery = await resolverPromise;

// If no DNS entries found
if (realDnsQuery.entries.length === 0) {
// Use `dns.lookup(...)` for that particular hostname
this._hostnamesToFallback.add(hostname);
} else {
await this._set(hostname, realDnsQuery.entries, realDnsQuery.cacheTtl);
}
} catch (_) {}
} else {
const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl;
const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl;
await this._set(hostname, query.entries, cacheTtl);

await this._set(hostname, query.entries, cacheTtl);
}
delete this._pending[hostname];

return query.entries;
} catch (error) {
delete this._pending[hostname];
})();

return query.entries;
throw error;
}
}

_tick(ms) {
Expand Down
8 changes: 4 additions & 4 deletions tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@ test.serial('fallback works', async t => {
});
});

test('fallback works #2', async t => {
test('real DNS queries first', async t => {
const resolver = createResolver({delay: 0});
const cacheable = new CacheableLookup({
resolver,
Expand All @@ -802,8 +802,8 @@ test('fallback works #2', async t => {

{
const entries = await cacheable.lookupAsync('outdated', {all: true});
t.deepEqual(entries, [
{address: '127.0.0.127', family: 4}
verify(t, entries, [
{address: '127.0.0.1', family: 4}
]);
}

Expand Down Expand Up @@ -875,7 +875,7 @@ test('prevents overloading DNS', async t => {
t.deepEqual(resolver.counter, {
4: 1,
6: 1,
lookup: 1
lookup: 0
});
});

Expand Down

0 comments on commit ae7c02f

Please sign in to comment.