Skip to content

Commit

Permalink
fix: update TTL of cached results (#4)
Browse files Browse the repository at this point in the history
To allow downstream users to know when a cached result will drop
out of the cache, update the TTL of returned cached results to
reflect time passing since the answer was cached.
  • Loading branch information
achingbrain committed Mar 14, 2024
1 parent 5020c6c commit 876432e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/utils/cache.ts
Expand Up @@ -56,8 +56,9 @@ class CachedAnswers {
.filter((entry) => {
return entry.expires > Date.now()
})
.map(({ value }) => ({
.map(({ expires, value }) => ({
...value,
TTL: Math.round((expires - Date.now()) / 1000),
type: RecordType[value.type]
}))

Expand Down
35 changes: 35 additions & 0 deletions test/index.spec.ts
@@ -1,6 +1,7 @@
import { expect } from 'aegir/chai'
import Sinon from 'sinon'
import { RecordType, dns } from '../src/index.js'
import type { Answer } from '../src/index.js'

describe('dns', () => {
it('should query dns', async () => {
Expand Down Expand Up @@ -69,6 +70,40 @@ describe('dns', () => {
expect(defaultResolver.calledOnce).to.be.true()
})

it('should update the TTL of cached results', async () => {
const defaultResolver = Sinon.stub()

const answerA: Answer = {
name: 'result-with-update-ttl.com',
data: '123.123.123.123',
type: RecordType.A,
TTL: 60
}

defaultResolver.withArgs('result-with-update-ttl.com').resolves({
Answer: [answerA]
})

const resolver = dns({
resolvers: {
'.': defaultResolver
}
})
const resultA = await resolver.query('result-with-update-ttl.com')

// wait for long enough that TTL changes
await new Promise<void>((resolve) => {
setTimeout(() => {
resolve()
}, 5000)
})

const resultB = await resolver.query('result-with-update-ttl.com')

expect(defaultResolver.calledOnce).to.be.true()
expect(resultA.Answer[0].TTL).to.be.greaterThan(resultB.Answer[0].TTL)
})

it('should use separate caches', async () => {
const defaultResolver = Sinon.stub()

Expand Down

0 comments on commit 876432e

Please sign in to comment.