diff --git a/services/spelling/app/coffee/LearnedWordsManager.coffee b/services/spelling/app/coffee/LearnedWordsManager.coffee index 04febf6b8f..ede634e06e 100644 --- a/services/spelling/app/coffee/LearnedWordsManager.coffee +++ b/services/spelling/app/coffee/LearnedWordsManager.coffee @@ -1,7 +1,18 @@ db = require("./DB") +LRU = require("lru-cache") +cacheOpts = + max: 5000 + maxAge: 1000 * 60 * 60 + +cache = LRU(cacheOpts) +logger = require 'logger-sharelatex' +metrics = require('metrics-sharelatex') + + module.exports = LearnedWordsManager = learnWord: (user_token, word, callback = (error)->) -> + cache.del(user_token) db.spellingPreferences.update { token: user_token }, { @@ -11,8 +22,19 @@ module.exports = LearnedWordsManager = }, callback getLearnedWords: (user_token, callback = (error, words)->) -> + cachedWords = cache.get(user_token) + if cachedWords + logger.info user_token:user_token, "cache hit" + metrics.inc "cache-hit", 0.1 + return callback(null, cachedWords) + + metrics.inc "cache-miss", 0.1 + logger.info user_token:user_token, "cache miss" + db.spellingPreferences.findOne token: user_token, (error, preferences) -> return callback error if error? - callback null, (preferences?.learnedWords || []) + words = preferences?.learnedWords || [] + cache.set(user_token, words) + callback null, words diff --git a/services/spelling/package.json b/services/spelling/package.json index 9aed24c162..6e24604b29 100644 --- a/services/spelling/package.json +++ b/services/spelling/package.json @@ -12,6 +12,7 @@ "body-parser": "^1.12.0", "express": "^4.12.1", "logger-sharelatex": "git+https://github.com/sharelatex/logger-sharelatex.git#v1.0.0", + "lru-cache": "^2.5.0", "metrics-sharelatex": "git+https://github.com/sharelatex/metrics-sharelatex.git#v1.0.0", "mongojs": "0.9.11", "node-statsd": "0.0.3",