diff --git a/server/managers/ApiCacheManager.js b/server/managers/ApiCacheManager.js index e34e4c055..556ea4357 100644 --- a/server/managers/ApiCacheManager.js +++ b/server/managers/ApiCacheManager.js @@ -2,6 +2,10 @@ const { LRUCache } = require('lru-cache') const Logger = require('../Logger') const Database = require('../Database') +const PERSONALIZED_URL_PATTERN = /^\/libraries\/[^/]+\/personalized/ +const RECENT_EPISODES_URL_PATTERN = /^\/libraries\/[^/]+\/recent-episodes/ +const ME_URL_PATTERN = /^\/me(\/|\?|$)/ + class ApiCacheManager { defaultCacheOptions = { max: 1000, maxSize: 10 * 1000 * 1000, sizeCalculation: (item) => item.body.length + JSON.stringify(item.headers).length } defaultTtlOptions = { ttl: 30 * 60 * 1000 } @@ -12,6 +16,9 @@ class ApiCacheManager { constructor(cache = new LRUCache(this.defaultCacheOptions), ttlOptions = this.defaultTtlOptions) { this.cache = cache this.ttlOptions = ttlOptions + this.globalVersion = 0 + this.personalizedVersion = 0 + this.meVersion = 0 } init(database = Database) { @@ -20,12 +27,25 @@ class ApiCacheManager { } getModelName(model) { - if (typeof model?.name === 'string') return model.name - if (typeof model?.model?.name === 'string') return model.model.name - if (typeof model?.constructor?.name === 'string' && model.constructor.name !== 'Object') return model.constructor.name + const target = Array.isArray(model) ? model[0] : model + if (typeof target?.constructor?.name === 'string' && target.constructor.name !== 'Object' && target.constructor.name !== 'Function') { + return target.constructor.name + } + if (typeof target?.model?.name === 'string') return target.model.name + if (typeof target?.name === 'string') return target.name return 'unknown' } + getCacheVersion(url) { + if (PERSONALIZED_URL_PATTERN.test(url) || RECENT_EPISODES_URL_PATTERN.test(url)) { + return this.globalVersion + this.personalizedVersion + } + if (ME_URL_PATTERN.test(url)) { + return this.globalVersion + this.meVersion + } + return this.globalVersion + } + clearByUrlPattern(urlPattern) { let removed = 0 for (const key of this.cache.keys()) { @@ -45,10 +65,15 @@ class ApiCacheManager { let removedPersonalized = 0 let removedRecentEpisodes = 0 if (this.modelsInvalidatingPersonalized.has(modelName)) { - removedPersonalized = this.clearByUrlPattern(/^\/libraries\/[^/]+\/personalized/) - removedRecentEpisodes = this.clearByUrlPattern(/^\/libraries\/[^/]+\/recent-episodes/) + this.personalizedVersion++ + removedPersonalized = this.clearByUrlPattern(PERSONALIZED_URL_PATTERN) + removedRecentEpisodes = this.clearByUrlPattern(RECENT_EPISODES_URL_PATTERN) + } + let removedMe = 0 + if (this.modelsInvalidatingMe.has(modelName)) { + this.meVersion++ + removedMe = this.clearByUrlPattern(ME_URL_PATTERN) } - const removedMe = this.modelsInvalidatingMe.has(modelName) ? this.clearByUrlPattern(/^\/me(\/|\?|$)/) : 0 Logger.debug(`[ApiCacheManager] ${modelName}.${hook}: cleared user-progress cache slices (personalized=${removedPersonalized}, recentEpisodes=${removedRecentEpisodes}, me=${removedMe})`) } @@ -60,6 +85,7 @@ class ApiCacheManager { } Logger.debug(`[ApiCacheManager] ${modelName}.${hook}: Clearing cache`) + this.globalVersion++ this.cache.clear() } @@ -70,6 +96,7 @@ class ApiCacheManager { Logger.info(`[ApiCacheManager] Resetting cache`) this.init() + this.globalVersion++ this.cache.clear() } @@ -96,15 +123,20 @@ class ApiCacheManager { res.send(cached.body) return } + const requestCacheVersion = this.getCacheVersion(key.url) res.originalSend = res.send res.send = (body) => { - Logger.debug(`[ApiCacheManager] Cache miss: ${stringifiedKey}`) - const cached = { body, headers: res.getHeaders(), statusCode: res.statusCode } - if (key.url.search(/^\/libraries\/.*?\/personalized/) !== -1) { - Logger.debug(`[ApiCacheManager] Caching with ${this.ttlOptions.ttl} ms TTL`) - this.cache.set(stringifiedKey, cached, this.ttlOptions) + if (this.getCacheVersion(key.url) !== requestCacheVersion) { + Logger.debug(`[ApiCacheManager] Skipping cache set for invalidated in-flight request: ${stringifiedKey}`) } else { - this.cache.set(stringifiedKey, cached) + Logger.debug(`[ApiCacheManager] Cache miss: ${stringifiedKey}`) + const cached = { body, headers: res.getHeaders(), statusCode: res.statusCode } + if (PERSONALIZED_URL_PATTERN.test(key.url)) { + Logger.debug(`[ApiCacheManager] Caching with ${this.ttlOptions.ttl} ms TTL`) + this.cache.set(stringifiedKey, cached, this.ttlOptions) + } else { + this.cache.set(stringifiedKey, cached) + } } res.originalSend(body) } diff --git a/test/server/managers/ApiCacheManager.test.js b/test/server/managers/ApiCacheManager.test.js index 2e9ad5b77..fad363e8e 100644 --- a/test/server/managers/ApiCacheManager.test.js +++ b/test/server/managers/ApiCacheManager.test.js @@ -108,4 +108,82 @@ describe('ApiCacheManager', () => { expect(cache.get(key)).to.be.undefined }) }) + + describe('in-flight invalidation', () => { + it('should not cache response when full clear happens while request is in flight', () => { + const lruCache = new LRUCache({ max: 10 }) + req.url = '/libraries/abc-123/personalized?include=rssfeed,share' + res.getHeaders.returns({ 'content-type': 'application/json' }) + manager = new ApiCacheManager(lruCache) + + manager.middleware(req, res, next) + manager.clear({ name: 'libraryItem' }, 'afterCreate') + res.send('stale personalized data') + + const key = JSON.stringify({ user: req.user.username, url: req.url }) + expect(lruCache.get(key)).to.be.undefined + expect(res.originalSend.calledOnceWith('stale personalized data')).to.be.true + }) + + it('should not cache personalized or recent-episodes response when mediaProgress updates while in flight', () => { + const lruCache = new LRUCache({ max: 10 }) + req.url = '/libraries/abc-123/personalized' + res.getHeaders.returns({ 'content-type': 'application/json' }) + manager = new ApiCacheManager(lruCache) + + manager.middleware(req, res, next) + manager.clear({ name: 'mediaProgress' }, 'afterUpdate') + res.send('stale personalized data') + + const key = JSON.stringify({ user: req.user.username, url: req.url }) + expect(lruCache.get(key)).to.be.undefined + expect(res.originalSend.calledOnceWith('stale personalized data')).to.be.true + }) + + it('should still cache unrelated endpoints when a high-churn slice clears while in flight', () => { + const lruCache = new LRUCache({ max: 10 }) + req.url = '/libraries/abc-123/stats' + res.getHeaders.returns({ 'content-type': 'application/json' }) + manager = new ApiCacheManager(lruCache) + + manager.middleware(req, res, next) + manager.clear({ name: 'session' }, 'afterCreate') + res.send('fresh stats') + + const key = JSON.stringify({ user: req.user.username, url: req.url }) + expect(lruCache.get(key)).to.deep.equal({ + body: 'fresh stats', + headers: { 'content-type': 'application/json' }, + statusCode: 200 + }) + }) + }) + + describe('getModelName', () => { + it('should prefer instance constructor name over name column value', () => { + class author { + constructor(name) { + this.name = name + } + } + const lruCache = new LRUCache({ max: 10 }) + const key = JSON.stringify({ user: 'u', url: '/libraries/abc-123/stats' }) + lruCache.set(key, { body: '{}', headers: {}, statusCode: 200 }) + manager = new ApiCacheManager(lruCache) + + // An author named "session" must still clear the full cache, not be treated as the high-churn session model + const instance = new author('session') + expect(manager.getModelName(instance)).to.equal('author') + manager.clear(instance, 'afterCreate') + expect(lruCache.get(key)).to.be.undefined + }) + + it('should resolve model name from arrays and bulk hook options', () => { + class libraryItem {} + manager = new ApiCacheManager(cache) + + expect(manager.getModelName([new libraryItem()])).to.equal('libraryItem') + expect(manager.getModelName({ model: { name: 'mediaProgress' } })).to.equal('mediaProgress') + }) + }) })