fix(memory): match each cache key independently during invalidation

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
This commit is contained in:
Rudy Celekli committed 2026-10-04 02:13:10 -04:00
1 parent 85ea254193
commit e0fb4ebd74
2 files changed
+36 -1

No files matched your search

@@ -0,0 +1,30 @@
import { afterEach, describe, it, expect } from 'vitest';
import { CacheManager } from './cache-manager.js';
const caches: CacheManager<string>[] = [];
afterEach(() => {
for (const cache of caches.splice(0)) cache.shutdown();
});
describe('stateful cache invalidation patterns', () => {
it.each([/article/g, /article/y])(
'invalidates every matching entry with %s',
(pattern) => {
const cache = new CacheManager<string>();
caches.push(cache);
cache.set('article-one', 'old result one');
cache.set('article-two', 'old result two');
cache.set('article-three', 'old result three');
cache.set('unrelated', 'valid');
expect(cache.invalidatePattern(pattern)).toBe(3);
expect(cache.keys()).toEqual(['unrelated']);
},
);
it('preserves the caller pattern cursor instead of skipping the first key', () => {
const cache = new CacheManager<string>();
caches.push(cache);
cache.set('article-one', 'old');
const pattern = /article/g;
pattern.lastIndex = 4;
expect(cache.invalidatePattern(pattern)).toBe(1);
expect(pattern.lastIndex).toBe(4);
});
});
+6 -1
View File
@@ -296,7 +296,12 @@ export class CacheManager<T = MemoryEntry> extends EventEmitter {
let invalidated = 0;
for (const key of this.cache.keys()) {
if (regex.test(key)) {
// RegExp cursors belong to a single input, not the whole key sequence.
const lastIndex = regex.lastIndex;
regex.lastIndex = 0;
const matches = regex.test(key);
regex.lastIndex = lastIndex;
if (matches) {
this.delete(key);
invalidated++;
}