diff --git a/lib/postgresql_interface.js b/lib/postgresql_interface.js index ec427a9c..47aa11ba 100644 --- a/lib/postgresql_interface.js +++ b/lib/postgresql_interface.js @@ -9,6 +9,8 @@ var R = require('ramda') var logger = require('./logger') +const CACHED_SESSION_TTL = 60 * 60 * 1000 + /* function inspect(rec) { console.log(require('util').inspect(rec, {depth: null, colors: true})) @@ -52,6 +54,8 @@ exports.init = function init (_conString) { if (!conString) { throw new Error('Postgres connection string is required') } + + setInterval(pruneCachedResponses, CACHED_SESSION_TTL) } function connect (cb) { @@ -778,12 +782,12 @@ function insertCachedRequest (session, path, method, body) { 'body' ] - const sql = getInsertQuery('cached_requests', fields) + const sql = getInsertQuery('cached_responses', fields) return pquery(sql, [session.fingerprint, session.id, path, method, body]) } exports.cachedResponse = function (session, path, method) { - const sql = `select body from cached_requests + const sql = `select body from cached_responses where device_fingerprint=$1 and session_id=$2 and path=$3 @@ -800,8 +804,17 @@ exports.cachedResponse = function (session, path, method) { }) } +function pruneCachedResponses () { + const sql = `delete from cached_responses + where (EXTRACT(EPOCH FROM (now() - created))) * 1000 < $1` + + const values = [CACHED_SESSION_TTL] + + return pquery(sql, values) +} + exports.cacheResponse = function (session, path, method, body) { - const sql = `update cached_requests + const sql = `update cached_responses set body=$1 where device_fingerprint=$2 and session_id=$3 diff --git a/migrations/010-cached-requests.js b/migrations/010-cached-requests.js index 794fd9d9..fd6ee693 100644 --- a/migrations/010-cached-requests.js +++ b/migrations/010-cached-requests.js @@ -3,13 +3,14 @@ var db = require('./db') exports.up = function (next) { - db.query('CREATE TABLE IF NOT EXISTS cached_requests ( ' + + db.query('CREATE TABLE IF NOT EXISTS cached_responses ( ' + 'id serial PRIMARY KEY, ' + 'device_fingerprint text NOT NULL, ' + 'session_id uuid NOT NULL, ' + 'path text NOT NULL, ' + 'method text NOT NULL, ' + 'body json NOT NULL, ' + + 'created timestampz NOT NULL DEFAULT now(), ' + 'UNIQUE (device_fingerprint, session_id, path, method) ' + ')', next) } diff --git a/todo.txt b/todo.txt index a17f5cf5..a1965965 100644 --- a/todo.txt +++ b/todo.txt @@ -1,8 +1 @@ - change satoshis to crypto_atoms in db (ask neal about this) - -UTC: -http://justatheory.com/computers/databases/postgresql/use-timestamptz.html - -Upgrade instructions: - -AFTER migrating, set timezone in config to 'UTC', then restart server