Skip to content

Commit

Permalink
Cache getLocalAddress() to avoid per-request network address lookup (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jdb8 authored and adriancole committed Oct 25, 2019
1 parent e656521 commit b3b5a0c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/zipkin/src/InetAddress.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class InetAddress {
}

// In non-node environments we fallback to 127.0.0.1
InetAddress.getLocalAddress = function getLocalAddress() {
function getLocalAddress() {
const isNode = typeof process === 'object' && typeof process.on === 'function';
if (!isNode) {
return new InetAddress('127.0.0.1');
Expand All @@ -40,6 +40,11 @@ InetAddress.getLocalAddress = function getLocalAddress() {
// eslint-disable-next-line global-require
const networkAddress = require('./network');
return new InetAddress(networkAddress.ipv4());
};
}

// Cache this value at import time so as to avoid network interface
// lookup on every call
const cachedLocalAddress = getLocalAddress();
InetAddress.getLocalAddress = () => cachedLocalAddress;

module.exports = InetAddress;
4 changes: 4 additions & 0 deletions packages/zipkin/test/InetAddress.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ describe('InetAddress', () => {
InetAddress.getLocalAddress();
});

it('should return the same object reference for multiple calls (cached)', () => {
expect(InetAddress.getLocalAddress()).to.equal(InetAddress.getLocalAddress());
});

it('should convert an IP address to integer representation', () => {
const addr = new InetAddress('80.91.37.133');
expect(addr.toInt()).to.equal(1348150661);
Expand Down

0 comments on commit b3b5a0c

Please sign in to comment.