From d9e9d4f90a14ad181c1b47153d19ff36d1e53eaa Mon Sep 17 00:00:00 2001 From: emad-salah Date: Thu, 25 Jun 2020 21:50:49 +0100 Subject: [PATCH] Caching now only works on GET requests and added .env toggles for toggling caching and warnings related to it. --- .env.example | 7 ++++++- src/server.js | 53 +++++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/.env.example b/.env.example index 8a042b30..4ea11d88 100644 --- a/.env.example +++ b/.env.example @@ -1 +1,6 @@ -DISABLE_SHOCK_ENCRYPTION=false \ No newline at end of file +DATA_FILE_NAME=data3 +PEERS=["http://gun.shock.network:8765/gun"] +MS_TO_TOKEN_EXPIRATION=4500000 +DISABLE_SHOCK_ENCRYPTION=false +CACHE_HEADERS_MANDATORY=true +SHOCK_CACHE=true \ No newline at end of file diff --git a/src/server.js b/src/server.js index c0a8b9b7..20b4b3c7 100644 --- a/src/server.js +++ b/src/server.js @@ -68,6 +68,46 @@ const server = program => { .digest('hex') } + const cacheCheck = ({ req, res, args, send }) => { + if ( + (process.env.SHOCK_CACHE === 'true' || !process.env.SHOCK_CACHE) && + req.method === 'GET' + ) { + const dataHash = hashData(args[0]).slice(-8) + res.set('shock-cache-hash', dataHash) + + logger.debug('shock-cache-hash:', req.headers['shock-cache-hash']) + logger.debug('Data Hash:', dataHash) + if ( + !req.headers['shock-cache-hash'] && + (process.env.CACHE_HEADERS_MANDATORY === 'true' || + !process.env.CACHE_HEADERS_MANDATORY) + ) { + logger.warn( + "Request is missing 'shock-cache-hash' header, please make sure to include that in each GET request in order to benefit from reduced data usage" + ) + return { cached: false, hash: dataHash } + } + + if (req.headers['shock-cache-hash'] === dataHash) { + logger.debug('Same Hash Detected!') + args[0] = null + res.status(304) + send.apply(res, args) + return { cached: true, hash: dataHash } + } + + return { cached: false, hash: dataHash } + } + + return { cached: false, hash: null } + } + + /** + * @param {Express.Request} req + * @param {Express.Response} res + * @param {(() => void)} next + */ const modifyResponseBody = (req, res, next) => { const deviceId = req.headers['x-shockwallet-device-id'] const oldSend = res.send @@ -80,16 +120,9 @@ const server = program => { return } - const dataHash = hashData(args[0]).slice(-8) - res.set('shock-cache-hash', dataHash) + const { cached, hash } = cacheCheck({ req, res, args, send: oldSend }) - logger.debug('shock-cache-hash:', req.headers['shock-cache-hash']) - logger.debug('Data Hash:', dataHash) - if (req.headers['shock-cache-hash'] === dataHash) { - logger.debug('Same Hash Detected!') - args[0] = null - res.status(304) - oldSend.apply(res, args) + if (cached) { return } @@ -100,7 +133,7 @@ const server = program => { message: args[0] ? args[0] : {}, deviceId, metadata: { - hash: dataHash + hash } }) : args[0]