Files
bruno/packages/bruno-requests/src/network/fast-lookup.ts
lohit bae5934137 perf: optimize DNS resolution to reduce request latency (#7664)
* perf: optimize DNS resolution to reduce request latency by ~31%

Replace default dns.lookup (libuv thread pool) with async dns.resolve4/6
(c-ares) that bypasses the thread pool bottleneck, falling back to
dns.lookup for /etc/hosts and mDNS hostnames.

* fix: address PR review feedback for DNS optimization

- Guard against undefined options in fastLookup to prevent runtime errors
- Document that options.family is not yet respected (safe today, noted for future)
- Replace callback as any with proper typed forwarding wrapper
- Extract shared agent config (defaultAgentOptions) to eliminate duplication
  between axios-instance.ts and agent-cache.ts, with documented rationale
- Mock DNS in test to avoid real network calls to google.com in CI

* fix: removed explicit resolve6 in fastLookup

---------

Co-authored-by: Chirag Chandrashekhar <cchirag85@gmail.com>
2026-04-02 21:27:51 +05:30

33 lines
1.2 KiB
TypeScript

import dns from 'node:dns';
/**
* Fast DNS lookup that bypasses the libuv thread pool.
*
* Tries dns.resolve4 then dns.resolve6 (async, c-ares based),
* falls back to dns.lookup for /etc/hosts and mDNS hostnames.
*
* NOTE: `options.family` is not currently respected — the function always
* tries IPv4 first regardless of the caller's preference. This is safe today
* because Bruno's HTTP agents use the default family (0), but should be
* addressed if any code path starts specifying a family.
*/
export function fastLookup(
hostname: string,
options: dns.LookupOptions | undefined,
callback: (err: Error | null, address: string | dns.LookupAddress[], family?: number) => void
): void {
dns.resolve4(hostname, (err4, addresses4) => {
if (!err4 && addresses4?.length) {
return options?.all
? callback(null, addresses4.map((a) => ({ address: a, family: 4 })))
: callback(null, addresses4[0], 4);
}
// Forward to standard dns.lookup for /etc/hosts, mDNS, and other
// non-public hostnames that c-ares cannot resolve.
dns.lookup(hostname, options ?? {}, (err, address, family) => {
callback(err, address, family);
});
});
}