Skip to content

Commit

Permalink
feat(resolve): Fallback to expired Cache if remote resolve fails
Browse files Browse the repository at this point in the history
  • Loading branch information
Prash74 committed Dec 6, 2019
1 parent 1a97695 commit e8fb764
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
4 changes: 2 additions & 2 deletions fs.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { dirname, resolve, join } = require('path')
const { toHex, writeCache } = require('./util')
const { dirname, resolve } = require('path')
const { createSwarm } = require('ara-network/discovery')
const { createCFS } = require('cfsnet/create')
const { normalize } = require('./did')
Expand Down Expand Up @@ -199,7 +199,7 @@ async function readFile(identifier, filename, opts) {
try {
const buffer = await cfs.readFile(filename)
if (false === isBrowser) {
await writeCache(did.identifier, buffer)
await writeCache(did.identifier, filename, buffer)
}
done(null, buffer)
} catch (err) {
Expand Down
15 changes: 14 additions & 1 deletion resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,19 @@ async function findResolution(did, opts, state) {
}

if (0 === pending && !didResolve && 0 === resolvers.length && !state.aborted) {

// Revert to expired cache copy if present
if (!isBrowser) {
try {
const cachePath = path.join(os.tmpdir(), 'aid', did.identifier, 'ddo.json')
const json = await pify(readFile)(cachePath, 'utf8')
done(null, (opts.parse || JSON.parse)(String(json)))
} catch (err) {
console.log(err)
debug(err)
}
}

cleanup()
done(null, result)
} else if (resolvers.length && !state.aborted && !didResolve) {
Expand All @@ -296,7 +309,7 @@ async function findResolution(did, opts, state) {

// Write DDO to temp cache folder
if (false === isBrowser) {
await writeCache(did.identifier, JSON.stringify(result))
await writeCache(did.identifier, 'ddo.json', JSON.stringify(result))
}
didResolve = true
cleanup()
Expand Down
6 changes: 3 additions & 3 deletions util.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { createIdentityKeyPath } = require('./key-path')
const { dirname, resolve, join } = require('path')
const { createIdentityKeyPath } = require('./key-path')
const isBuffer = require('is-buffer')
const mkdirp = require('mkdirp')
const debug = require('debug')('ara:identity:util')
Expand Down Expand Up @@ -106,9 +106,9 @@ async function resolveDNS(uri) {
return null
}

async function writeCache(identifier, buffer) {
async function writeCache(identifier, filename, buffer) {
try {
const cachePath = join(os.tmpdir(), 'aid', identifier, 'ddo.json')
const cachePath = join(os.tmpdir(), 'aid', identifier, filename)
await pify(mkdirp)(dirname(cachePath))
await pify(fs.writeFile)(cachePath, buffer)
} catch (err) {
Expand Down

0 comments on commit e8fb764

Please sign in to comment.