Skip to content

Commit

Permalink
Add stats for query and cache requests (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
GKosheev authored Sep 7, 2022
1 parent 5b08a36 commit ab8d286
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
12 changes: 10 additions & 2 deletions source/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ class CacheableLookup {
this._cache = cache;
this._resolver = resolver;
this._dnsLookup = lookup && promisify(lookup);
this.stats = {
cache: 0,
query: 0
};

if (this._resolver instanceof AsyncResolver) {
this._resolve4 = this._resolver.resolve4.bind(this._resolver);
Expand Down Expand Up @@ -214,16 +218,20 @@ class CacheableLookup {
let source = 'cache';
let cached = await this._cache.get(hostname);

if (cached) {
this.stats.cache++;
}

if (!cached) {
const pending = this._pending[hostname];

if (pending) {
this.stats.cache++;
cached = await pending;
} else {
source = 'query';
const newPromise = this.queryAndCache(hostname);
this._pending[hostname] = newPromise;

this.stats.query++;
try {
cached = await newPromise;
} finally {
Expand Down
24 changes: 24 additions & 0 deletions tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1067,3 +1067,27 @@ test.cb.failing('throws original lookup error if not recognized', t => {
t.end();
});
});

test('cache and query stats', async t => {
const cacheable = new CacheableLookup({resolver});

t.is(cacheable.stats.query, 0);
t.is(cacheable.stats.cache, 0);

let entries = await cacheable.lookupAsync('temporary', {all: true, family: 4});
verify(t, entries, [
{address: '127.0.0.1', family: 4, source: 'query'}
]);

t.is(cacheable.stats.query, 1);
t.is(cacheable.stats.cache, 0);

entries = await cacheable.lookupAsync('temporary', {all: true, family: 4});

verify(t, entries, [
{address: '127.0.0.1', family: 4, source: 'cache'}
]);

t.is(cacheable.stats.query, 1);
t.is(cacheable.stats.cache, 1);
});

0 comments on commit ab8d286

Please sign in to comment.