Skip to content

Commit

Permalink
fix: hard dns cache reset on failure
Browse files Browse the repository at this point in the history
  • Loading branch information
dgreif committed Oct 1, 2020
1 parent a598405 commit 75dba2f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
24 changes: 13 additions & 11 deletions api/rest-client.ts
Expand Up @@ -13,17 +13,18 @@ import { AuthTokenResponse, SessionResponse } from './ring-types'
import { ReplaySubject } from 'rxjs'
import { parse as parseUrl } from 'url'

function createDnsCache() {
return new CacheableLookup({
maxTtl: 60,
fallbackDuration: 0,
})
}

let dnsCache = createDnsCache()
const defaultRequestOptions: RequestOptions = {
http2: true,
responseType: 'json',
method: 'GET',
},
dnsCache = new CacheableLookup({
maxTtl: 60,
fallbackDuration: 0,
}),
cacheKeepaliveRequestOptions = {
dnsCache,
agent: { http: new HttpAgent(), https: new HttpsAgent() },
},
ringErrorCodes: { [code: number]: string } = {
Expand Down Expand Up @@ -54,7 +55,7 @@ async function requestWithRetry<T>(
requestOptions: RequestOptions & { url: string }
): Promise<T & ExtendedResponse> {
try {
const options = { ...defaultRequestOptions, ...requestOptions },
const options = { ...defaultRequestOptions, dnsCache, ...requestOptions },
{ headers, body } = (await got(options)) as {
headers: Headers
body: any
Expand All @@ -74,13 +75,15 @@ async function requestWithRetry<T>(
if (e.code === 'ENOTFOUND' || e.code === 'EREFUSED') {
const url = parseUrl(requestOptions.url)
logDebug(
`DNS Cache for ${url.hostname}: ${JSON.stringify(
`Resetting DNS Cache. DNS Cache for ${
url.hostname
}: ${JSON.stringify(
await dnsCache
.query(url.hostname!)
.catch((queryError) => queryError)
)}`
)
dnsCache.clear(url.hostname!)
dnsCache = createDnsCache()
}

await delay(5000)
Expand Down Expand Up @@ -279,7 +282,6 @@ export class RingRestClient {
const authTokenResponse = await this.authPromise

return await requestWithRetry<T>({
...cacheKeepaliveRequestOptions,
...options,
headers: {
...options.headers,
Expand Down
1 change: 1 addition & 0 deletions examples/example.ts
Expand Up @@ -11,6 +11,7 @@ async function example() {
refreshToken: env.RING_REFRESH_TOKEN!,
// Listen for dings and motion events
cameraDingsPollingSeconds: 2,
debug: true,
}),
locations = await ringApi.getLocations(),
allCameras = await ringApi.getCameras()
Expand Down

0 comments on commit 75dba2f

Please sign in to comment.