From c25fd40ae5e391ebd75f5f0f524cf8b1d2ae481b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bar=C4=B1=C5=9F=20Soner=20U=C5=9Fakl=C4=B1?= Date: Mon, 9 Dec 2024 18:47:26 -0500 Subject: [PATCH] fix: race condition that results in 2x localReset call the same process --- src/cache/lru.js | 12 +++++++++--- src/cache/ttl.js | 12 +++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/cache/lru.js b/src/cache/lru.js index fc6eb69147..2af778b23d 100644 --- a/src/cache/lru.js +++ b/src/cache/lru.js @@ -2,6 +2,8 @@ module.exports = function (opts) { const { LRUCache } = require('lru-cache'); + const os = require('os'); + const pubsub = require('../pubsub'); // lru-cache@7 deprecations @@ -91,7 +93,9 @@ module.exports = function (opts) { cache.delete = cache.del; cache.reset = function () { - pubsub.publish(`${cache.name}:lruCache:reset`); + pubsub.publish(`${cache.name}:lruCache:reset`, { + id: `${os.hostname()}:${process.pid}`, + }); localReset(); }; cache.clear = cache.reset; @@ -102,8 +106,10 @@ module.exports = function (opts) { cache.misses = 0; } - pubsub.on(`${cache.name}:lruCache:reset`, () => { - localReset(); + pubsub.on(`${cache.name}:lruCache:reset`, ({ id }) => { + if (id !== `${os.hostname()}:${process.pid}`) { + localReset(); + } }); pubsub.on(`${cache.name}:lruCache:del`, (keys) => { diff --git a/src/cache/ttl.js b/src/cache/ttl.js index 292c76fdc7..818289da00 100644 --- a/src/cache/ttl.js +++ b/src/cache/ttl.js @@ -2,6 +2,8 @@ module.exports = function (opts) { const TTLCache = require('@isaacs/ttlcache'); + const os = require('os'); + const pubsub = require('../pubsub'); const ttlCache = new TTLCache(opts); @@ -72,7 +74,9 @@ module.exports = function (opts) { cache.delete = cache.del; cache.reset = function () { - pubsub.publish(`${cache.name}:ttlCache:reset`); + pubsub.publish(`${cache.name}:ttlCache:reset`, { + id: `${os.hostname()}:${process.pid}`, + }); localReset(); }; cache.clear = cache.reset; @@ -83,8 +87,10 @@ module.exports = function (opts) { cache.misses = 0; } - pubsub.on(`${cache.name}:ttlCache:reset`, () => { - localReset(); + pubsub.on(`${cache.name}:ttlCache:reset`, ({ id }) => { + if (id !== `${os.hostname()}:${process.pid}`) { + localReset(); + } }); pubsub.on(`${cache.name}:ttlCache:del`, (keys) => {