From 2453bc12e819c96b6122874dfdba2e4849d0b227 Mon Sep 17 00:00:00 2001 From: Dillon Amburgey Date: Mon, 19 Dec 2016 22:00:00 -0500 Subject: [PATCH] joyent/node-triton#158 tritonapi image cache never expires Reviewed by: Chris Burroughs Approved by: Chris Burroughs --- CHANGES.md | 2 ++ lib/tritonapi.js | 57 +++++++++++++++++++++++++++++------------------- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 17d414d..e63eb97 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -7,6 +7,8 @@ Known issues: ## not yet released +- [joyent/node-triton#158] tritonapi image cache never expires + - [joyent/node-triton#153] Bump restify-clients dep. Thanks, github.com/tomgco. - [joyent/node-triton#154] Fix `triton cloudapi ...` after #108 changes. diff --git a/lib/tritonapi.js b/lib/tritonapi.js index 9b34f15..648a900 100644 --- a/lib/tritonapi.js +++ b/lib/tritonapi.js @@ -375,33 +375,44 @@ TritonApi.prototype._cacheGetJson = function _cacheGetJson(key, cb) { assert.string(key, 'key'); assert.func(cb, 'cb'); + var ttl = 5 * 60 * 1000; // timeout of cache file info (ms) + var keyPath = path.resolve(this.cacheDir, key); - fs.readFile(keyPath, 'utf8', function (err, data) { - if (err && err.code === 'ENOENT') { - self.log.trace({keyPath: keyPath}, - 'cache file does not exist'); - return cb(); - } else if (err) { - self.log.warn({err: err, keyPath: keyPath}, - 'error reading cache file'); - return cb(); - } - var obj; - try { - obj = JSON.parse(data); - } catch (dataErr) { - self.log.trace({err: dataErr, keyPath: keyPath}, - 'error parsing JSON cache file, removing'); - fs.unlink(keyPath, function (err2) { - if (err2) { - self.log.warn({err: err2}, - 'failed to remove JSON cache file'); + fs.stat(keyPath, function (statErr, stats) { + if (!statErr && + stats.mtime.getTime() + ttl >= (new Date()).getTime()) { + fs.readFile(keyPath, 'utf8', function (err, data) { + if (err && err.code === 'ENOENT') { + self.log.trace({keyPath: keyPath}, + 'cache file does not exist'); + cb(); + } else if (err) { + self.log.warn({err: err, keyPath: keyPath}, + 'error reading cache file'); + cb(); } - cb(err2); + var obj; + try { + obj = JSON.parse(data); + } catch (dataErr) { + self.log.trace({err: dataErr, keyPath: keyPath}, + 'error parsing JSON cache file, removing'); + fs.unlink(keyPath, function (err2) { + if (err2) { + self.log.warn({err: err2}, + 'failed to remove JSON cache file'); + } + cb(); + }); + return; + } + cb(null, obj); }); - return; + } else if (statErr && statErr.code !== 'ENOENT') { + cb(statErr); + } else { + cb(); } - cb(null, obj); }); };