Skip to content

Commit

Permalink
Merge c5d06c5 into cf34ee1
Browse files Browse the repository at this point in the history
  • Loading branch information
pimterry committed Oct 5, 2021
2 parents cf34ee1 + c5d06c5 commit 82a4e40
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 35 deletions.
59 changes: 29 additions & 30 deletions source/index.js
Expand Up @@ -63,8 +63,20 @@ const isIterable = map => {
return Symbol.iterator in map;
};

const ignoreNoResultErrors = dnsPromise => {
return dnsPromise.catch(error => {
if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') {
return [];
}

throw error;
});
};

const ttl = {ttl: true};
const all = {all: true};
const all4 = {all: true, family: 4};
const all6 = {all: true, family: 6};

class CacheableLookup {
constructor({
Expand Down Expand Up @@ -222,23 +234,11 @@ class CacheableLookup {
}

async _resolve(hostname) {
const wrap = async promise => {
try {
return await promise;
} catch (error) {
if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') {
return [];
}

throw error;
}
};

// ANY is unsafe as it doesn't trigger new queries in the underlying server.
const [A, AAAA] = await Promise.all([
this._resolve4(hostname, ttl),
this._resolve6(hostname, ttl)
].map(promise => wrap(promise)));
ignoreNoResultErrors(this._resolve4(hostname, ttl)),
ignoreNoResultErrors(this._resolve6(hostname, ttl))
]);

let aTtl = 0;
let aaaaTtl = 0;
Expand Down Expand Up @@ -280,21 +280,20 @@ class CacheableLookup {
}

async _lookup(hostname) {
try {
const entries = await this._dnsLookup(hostname, {
all: true
});

return {
entries,
cacheTtl: 0
};
} catch (_) {
return {
entries: [],
cacheTtl: 0
};
}
const [A, AAAA] = await Promise.all([
// Passing {all: true} doesn't return all IPv4 and IPv6 entries.
// See https://github.com/szmarczak/cacheable-lookup/issues/42
ignoreNoResultErrors(this._dnsLookup(hostname, all4)),
ignoreNoResultErrors(this._dnsLookup(hostname, all6))
]);

return {
entries: [
...A,
...AAAA
],
cacheTtl: 0
};
}

async _set(hostname, data, cacheTtl) {
Expand Down
19 changes: 14 additions & 5 deletions tests/test.js
Expand Up @@ -788,7 +788,7 @@ test.serial('fallback works', async t => {
t.deepEqual(resolver.counter, {
6: 1,
4: 1,
lookup: 2
lookup: 3
});

await sleep(100);
Expand Down Expand Up @@ -1015,12 +1015,21 @@ test('slow dns.lookup', async t => {
resolver,
lookup: (hostname, options, callback) => {
t.is(hostname, 'osHostname');
t.deepEqual(options, {all: true});
t.is(options.all, true);
t.true(options.family === 4 || options.family === 6);

setTimeout(() => {
callback(null, [
{address: '127.0.0.1', family: 4}
]);
if (options.family === 4) {
callback(null, [
{address: '127.0.0.1', family: 4}
]);
}

if (options.family === 6) {
callback(null, [
{address: '::1', family: 6}
]);
}
}, 10);
}
});
Expand Down

0 comments on commit 82a4e40

Please sign in to comment.