@open-mercato/cache 0.10.1-develop.8181.1.91f97e988f → 0.10.1-develop.8190.1.cce1779b4a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/strategies/redis.js +148 -62
- package/dist/strategies/redis.js.map +3 -3
- package/package.json +1 -1
- package/src/__tests__/redis.compatibility.live.test.ts +225 -0
- package/src/__tests__/redis.performance.live.test.ts +113 -0
- package/src/__tests__/redis.strategy.test.ts +595 -39
- package/src/strategies/redis.ts +186 -100
|
@@ -2,13 +2,24 @@
|
|
|
2
2
|
import type { CacheStrategy } from '../types'
|
|
3
3
|
import { createRedisStrategy, pickRedisConstructor } from '../strategies/redis'
|
|
4
4
|
|
|
5
|
-
type PipelineOp = () =>
|
|
5
|
+
type PipelineOp = () => unknown | Promise<unknown>
|
|
6
|
+
type RedisArgument = string | number | Buffer
|
|
6
7
|
|
|
7
8
|
class FakeRedis {
|
|
8
9
|
values = new Map<string, string | Buffer>()
|
|
9
10
|
sets = new Map<string, Set<string>>()
|
|
11
|
+
scanCalls: { cursor: string; pattern: string; count: number }[] = []
|
|
12
|
+
scriptedScanPages = new Map<string, [string, string[]][]>()
|
|
13
|
+
private scanSnapshots = new Map<string, string[]>()
|
|
14
|
+
|
|
15
|
+
private matches(key: string, pattern: string): boolean {
|
|
16
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
17
|
+
const expression = escaped.replace(/\*/g, '.*').replace(/\?/g, '.')
|
|
18
|
+
return new RegExp(`^${expression}$`).test(key)
|
|
19
|
+
}
|
|
10
20
|
/** Records the shape of each reap script call so tests can assert its cost. */
|
|
11
|
-
evalCalls: { numKeys: number; memberCount: number }[] = []
|
|
21
|
+
evalCalls: { kind: 'orphan' | 'stale'; tagKey: string; numKeys: number; memberCount: number }[] = []
|
|
22
|
+
multiExecCalls = 0
|
|
12
23
|
|
|
13
24
|
async ping(): Promise<string> {
|
|
14
25
|
return 'PONG'
|
|
@@ -36,34 +47,117 @@ class FakeRedis {
|
|
|
36
47
|
return 'OK'
|
|
37
48
|
}
|
|
38
49
|
|
|
39
|
-
async del(
|
|
40
|
-
|
|
50
|
+
async del(...keys: string[]): Promise<number> {
|
|
51
|
+
let deleted = 0
|
|
52
|
+
for (const key of keys) {
|
|
53
|
+
const existed = this.values.delete(key)
|
|
54
|
+
const setExisted = this.sets.delete(key)
|
|
55
|
+
if (existed || setExisted) deleted++
|
|
56
|
+
}
|
|
57
|
+
return deleted
|
|
41
58
|
}
|
|
42
59
|
|
|
43
60
|
async exists(key: string): Promise<number> {
|
|
44
|
-
return this.values.has(key) ? 1 : 0
|
|
61
|
+
return this.values.has(key) || this.sets.has(key) ? 1 : 0
|
|
45
62
|
}
|
|
46
63
|
|
|
47
64
|
async keys(pattern: string): Promise<string[]> {
|
|
48
|
-
|
|
49
|
-
|
|
65
|
+
return [...new Set([...this.values.keys(), ...this.sets.keys()])].filter((key) => this.matches(key, pattern))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async scan(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]> {
|
|
69
|
+
const matchIndex = args.findIndex((value) => String(value).toUpperCase() === 'MATCH')
|
|
70
|
+
const countIndex = args.findIndex((value) => String(value).toUpperCase() === 'COUNT')
|
|
71
|
+
const pattern = matchIndex < 0 ? '*' : String(args[matchIndex + 1])
|
|
72
|
+
const count = countIndex < 0 ? 10 : Number(args[countIndex + 1])
|
|
73
|
+
this.scanCalls.push({ cursor: String(cursor), pattern, count })
|
|
74
|
+
const scripted = this.scriptedScanPages.get(pattern)
|
|
75
|
+
if (scripted) {
|
|
76
|
+
const next = scripted.shift()
|
|
77
|
+
if (!next) throw new Error(`Unexpected extra SCAN for ${pattern}`)
|
|
78
|
+
return next
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Stable keys model a cursor walk while clear/cleanup delete earlier pages.
|
|
82
|
+
if (String(cursor) === '0') {
|
|
83
|
+
const allKeys = [...new Set([...this.values.keys(), ...this.sets.keys()])]
|
|
84
|
+
this.scanSnapshots.set(pattern, allKeys.filter((key) => this.matches(key, pattern)))
|
|
85
|
+
}
|
|
86
|
+
const snapshot = this.scanSnapshots.get(pattern) ?? []
|
|
87
|
+
const offset = Number(cursor)
|
|
88
|
+
// COUNT is a hint. Small pages force callers to visit the complete cursor.
|
|
89
|
+
const end = Math.min(offset + Math.min(count, 2), snapshot.length)
|
|
90
|
+
return [end >= snapshot.length ? '0' : String(end), snapshot.slice(offset, end)]
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async mgetBuffer(...keys: string[]): Promise<(Buffer | null)[]> {
|
|
94
|
+
// Preserve getBuffer hooks used to land concurrent writes in a read window.
|
|
95
|
+
return Promise.all(keys.map((key) => this.getBuffer(key)))
|
|
50
96
|
}
|
|
51
97
|
|
|
52
98
|
async smembers(key: string): Promise<string[]> {
|
|
53
99
|
return [...(this.sets.get(key) ?? [])]
|
|
54
100
|
}
|
|
55
101
|
|
|
102
|
+
async sadd(key: string, ...members: string[]): Promise<number> {
|
|
103
|
+
const existing = this.sets.get(key) ?? new Set<string>()
|
|
104
|
+
const oldSize = existing.size
|
|
105
|
+
for (const member of members) existing.add(member)
|
|
106
|
+
if (existing.size) this.sets.set(key, existing)
|
|
107
|
+
return existing.size - oldSize
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async srem(key: string, ...members: string[]): Promise<number> {
|
|
111
|
+
const existing = this.sets.get(key)
|
|
112
|
+
if (!existing) return 0
|
|
113
|
+
let removed = 0
|
|
114
|
+
for (const member of members) if (existing.delete(member)) removed++
|
|
115
|
+
if (!existing.size) this.sets.delete(key)
|
|
116
|
+
return removed
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async eval(script: string, numKeys: number, ...args: RedisArgument[]): Promise<unknown> {
|
|
120
|
+
const stale = args.slice(numKeys).some(Buffer.isBuffer)
|
|
121
|
+
this.evalCalls.push({
|
|
122
|
+
kind: stale ? 'stale' : 'orphan', tagKey: String(args[0]), numKeys,
|
|
123
|
+
memberCount: (args.length - numKeys) / (stale ? 2 : 1),
|
|
124
|
+
})
|
|
125
|
+
return this.runEval(script, numKeys, ...args)
|
|
126
|
+
}
|
|
127
|
+
|
|
56
128
|
/**
|
|
57
|
-
* Mirrors the reap
|
|
129
|
+
* Mirrors the reap scripts' KEYS/ARGV contracts rather than interpreting Lua —
|
|
58
130
|
* there is no Lua runtime here, and pulling one in for a single script is not
|
|
59
131
|
* worth the dependency. What this pins down is the strategy's side of the
|
|
60
132
|
* contract (key ordering, member alignment, chunking) and the exists-guarded
|
|
61
|
-
* semantics. The script
|
|
133
|
+
* semantics and byte-guarded stale-member removal. The script bodies are not
|
|
134
|
+
* covered; verify them against a real Redis
|
|
62
135
|
* when changing it.
|
|
63
136
|
*/
|
|
64
|
-
runEval(
|
|
65
|
-
const
|
|
66
|
-
const
|
|
137
|
+
async runEval(script: string, numKeys: number, ...args: RedisArgument[]): Promise<unknown> {
|
|
138
|
+
const keys = args.slice(0, numKeys).map(String)
|
|
139
|
+
const [tagKey, ...valueKeys] = keys
|
|
140
|
+
const argv = args.slice(numKeys)
|
|
141
|
+
const stale = argv.some(Buffer.isBuffer)
|
|
142
|
+
if (stale) {
|
|
143
|
+
if (argv.length !== valueKeys.length * 2) throw new Error('[internal] stale eval argument alignment')
|
|
144
|
+
let removed = 0
|
|
145
|
+
for (let index = 0; index < valueKeys.length; index++) {
|
|
146
|
+
const member = String(argv[index * 2])
|
|
147
|
+
const observed = argv[index * 2 + 1]
|
|
148
|
+
if (!Buffer.isBuffer(observed) || valueKeys[index] !== `cache:${member}`) {
|
|
149
|
+
throw new Error('[internal] stale eval member/value/buffer alignment')
|
|
150
|
+
}
|
|
151
|
+
// Model Redis's byte comparison without routing the atomic script read
|
|
152
|
+
// through a client-side hook used to inject concurrent set() calls.
|
|
153
|
+
const stored = this.values.get(valueKeys[index])
|
|
154
|
+
const current = stored === undefined ? null : Buffer.isBuffer(stored) ? stored : Buffer.from(stored)
|
|
155
|
+
if (current !== null && !current.equals(observed)) continue
|
|
156
|
+
removed += await this.srem(tagKey, member)
|
|
157
|
+
}
|
|
158
|
+
return removed
|
|
159
|
+
}
|
|
160
|
+
const members = argv.map(String)
|
|
67
161
|
|
|
68
162
|
if (valueKeys.length !== members.length) {
|
|
69
163
|
throw new Error(`[internal] eval contract: ${valueKeys.length} value keys vs ${members.length} members`)
|
|
@@ -84,49 +178,65 @@ class FakeRedis {
|
|
|
84
178
|
const ops: PipelineOp[] = []
|
|
85
179
|
const chain = {
|
|
86
180
|
set: (key: string, value: string | Buffer) => {
|
|
87
|
-
ops.push(() =>
|
|
181
|
+
ops.push(() => this.set(key, value))
|
|
182
|
+
return chain
|
|
183
|
+
},
|
|
184
|
+
setex: (key: string, ttlSeconds: number, value: string | Buffer) => {
|
|
185
|
+
ops.push(() => this.setex(key, ttlSeconds, value))
|
|
186
|
+
return chain
|
|
187
|
+
},
|
|
188
|
+
getBuffer: (key: string) => {
|
|
189
|
+
ops.push(() => this.getBuffer(key))
|
|
88
190
|
return chain
|
|
89
191
|
},
|
|
90
|
-
|
|
91
|
-
ops.push(() =>
|
|
192
|
+
smembers: (key: string) => {
|
|
193
|
+
ops.push(() => this.smembers(key))
|
|
92
194
|
return chain
|
|
93
195
|
},
|
|
94
|
-
sadd: (key: string,
|
|
95
|
-
ops.push(() =>
|
|
96
|
-
const members = this.sets.get(key) ?? new Set<string>()
|
|
97
|
-
members.add(member)
|
|
98
|
-
this.sets.set(key, members)
|
|
99
|
-
})
|
|
196
|
+
sadd: (key: string, ...members: string[]) => {
|
|
197
|
+
ops.push(() => this.sadd(key, ...members))
|
|
100
198
|
return chain
|
|
101
199
|
},
|
|
102
|
-
srem: (key: string,
|
|
103
|
-
ops.push(() =>
|
|
104
|
-
const members = this.sets.get(key)
|
|
105
|
-
if (!members) return
|
|
106
|
-
members.delete(member)
|
|
107
|
-
// Redis drops a set once its last member is removed.
|
|
108
|
-
if (members.size === 0) this.sets.delete(key)
|
|
109
|
-
})
|
|
200
|
+
srem: (key: string, ...members: string[]) => {
|
|
201
|
+
ops.push(() => this.srem(key, ...members))
|
|
110
202
|
return chain
|
|
111
203
|
},
|
|
112
|
-
del: (
|
|
113
|
-
ops.push(() =>
|
|
204
|
+
del: (...keys: string[]) => {
|
|
205
|
+
ops.push(() => this.del(...keys))
|
|
114
206
|
return chain
|
|
115
207
|
},
|
|
116
|
-
eval: (script: string, numKeys: number, ...args:
|
|
117
|
-
|
|
118
|
-
ops.push(() => void this.runEval(script, numKeys, ...args))
|
|
208
|
+
eval: (script: string, numKeys: number, ...args: RedisArgument[]) => {
|
|
209
|
+
ops.push(() => this.eval(script, numKeys, ...args))
|
|
119
210
|
return chain
|
|
120
211
|
},
|
|
121
|
-
exec: async () => {
|
|
122
|
-
|
|
212
|
+
exec: async (): Promise<[Error | null, unknown][]> => {
|
|
213
|
+
const results: [Error | null, unknown][] = []
|
|
214
|
+
for (const op of ops) {
|
|
215
|
+
try {
|
|
216
|
+
results.push([null, await op()])
|
|
217
|
+
} catch (error) {
|
|
218
|
+
results.push([error instanceof Error ? error : new Error(String(error)), null])
|
|
219
|
+
}
|
|
220
|
+
}
|
|
123
221
|
ops.length = 0
|
|
124
|
-
return
|
|
222
|
+
return results
|
|
125
223
|
},
|
|
126
224
|
}
|
|
127
225
|
return chain
|
|
128
226
|
}
|
|
129
227
|
|
|
228
|
+
multi() {
|
|
229
|
+
// Shares the command-result model with pipeline. This fake does not prove
|
|
230
|
+
// server transaction isolation; the live Redis suite covers the wire path.
|
|
231
|
+
const transaction = this.pipeline()
|
|
232
|
+
const execute = transaction.exec
|
|
233
|
+
transaction.exec = async () => {
|
|
234
|
+
this.multiExecCalls++
|
|
235
|
+
return execute()
|
|
236
|
+
}
|
|
237
|
+
return transaction
|
|
238
|
+
}
|
|
239
|
+
|
|
130
240
|
async quit(): Promise<void> {}
|
|
131
241
|
|
|
132
242
|
/** Simulate a TTL firing: Redis expiry deletes the value key and nothing else. */
|
|
@@ -285,6 +395,449 @@ describe('redis strategy tag index', () => {
|
|
|
285
395
|
})
|
|
286
396
|
})
|
|
287
397
|
|
|
398
|
+
describe('redis strategy transaction writes and lazy tag memberships', () => {
|
|
399
|
+
let strategy: CacheStrategy
|
|
400
|
+
let urlCounter = 0
|
|
401
|
+
|
|
402
|
+
beforeEach(() => {
|
|
403
|
+
currentRedis = new FakeRedis()
|
|
404
|
+
urlCounter += 1
|
|
405
|
+
strategy = createRedisStrategy(`redis://cache-lazy-tags-${urlCounter}`)
|
|
406
|
+
})
|
|
407
|
+
|
|
408
|
+
afterEach(async () => {
|
|
409
|
+
await strategy.close?.()
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
it.each([
|
|
413
|
+
{ name: 'new TTL entry', overwrite: false, ttl: 1501, tags: ['products'] },
|
|
414
|
+
{ name: 'overwritten TTL entry', overwrite: true, ttl: 60_000, tags: ['new-products'] },
|
|
415
|
+
{ name: 'tagless overwrite without TTL', overwrite: true, ttl: 0, tags: [] },
|
|
416
|
+
{ name: 'new tagless entry without TTL', overwrite: false, ttl: 0, tags: [] },
|
|
417
|
+
])('writes $name in one checked transaction without reading the previous value', async ({ overwrite, ttl, tags }) => {
|
|
418
|
+
if (overwrite) await strategy.set('product', 'old', { tags: ['old-products'] })
|
|
419
|
+
const read = jest.spyOn(currentRedis, 'getBuffer').mockRejectedValue(new Error('set must not read'))
|
|
420
|
+
const readText = jest.spyOn(currentRedis, 'get').mockRejectedValue(new Error('set must not read'))
|
|
421
|
+
const transaction = jest.spyOn(currentRedis, 'multi')
|
|
422
|
+
const set = jest.spyOn(currentRedis, 'set')
|
|
423
|
+
const setex = jest.spyOn(currentRedis, 'setex')
|
|
424
|
+
currentRedis.multiExecCalls = 0
|
|
425
|
+
|
|
426
|
+
await strategy.set('product', 'fresh', { ttl, tags })
|
|
427
|
+
|
|
428
|
+
expect(read).not.toHaveBeenCalled()
|
|
429
|
+
expect(readText).not.toHaveBeenCalled()
|
|
430
|
+
expect(transaction).toHaveBeenCalledTimes(1)
|
|
431
|
+
expect(currentRedis.multiExecCalls).toBe(1)
|
|
432
|
+
const stored = JSON.parse(String(currentRedis.values.get('cache:product')))
|
|
433
|
+
expect(stored).toMatchObject({ key: 'product', value: 'fresh', tags })
|
|
434
|
+
if (ttl) {
|
|
435
|
+
expect(setex).toHaveBeenCalledWith('cache:product', Math.ceil(ttl / 1000), expect.any(String))
|
|
436
|
+
expect(set).not.toHaveBeenCalled()
|
|
437
|
+
expect(stored.expiresAt).toBeGreaterThan(stored.createdAt)
|
|
438
|
+
} else {
|
|
439
|
+
expect(set).toHaveBeenCalledTimes(1)
|
|
440
|
+
expect(setex).not.toHaveBeenCalled()
|
|
441
|
+
expect(stored.expiresAt).toBeNull()
|
|
442
|
+
}
|
|
443
|
+
for (const tag of tags) expect(await currentRedis.smembers(`tag:${tag}`)).toEqual(['product'])
|
|
444
|
+
})
|
|
445
|
+
|
|
446
|
+
it('keeps the live retagged entry when invalidating its previous tag', async () => {
|
|
447
|
+
await strategy.set('product', 'old', { tags: ['old-products'] })
|
|
448
|
+
await strategy.set('product', 'fresh', { tags: ['new-products'] })
|
|
449
|
+
expect(await currentRedis.smembers('tag:old-products')).toEqual(['product'])
|
|
450
|
+
|
|
451
|
+
expect(await strategy.deleteByTags(['old-products'])).toBe(0)
|
|
452
|
+
expect(await strategy.get('product')).toBe('fresh')
|
|
453
|
+
expect(await currentRedis.smembers('tag:old-products')).toEqual([])
|
|
454
|
+
expect(await currentRedis.smembers('tag:new-products')).toEqual(['product'])
|
|
455
|
+
expect(await strategy.deleteByTags(['new-products'])).toBe(1)
|
|
456
|
+
expect(await strategy.get('product')).toBeNull()
|
|
457
|
+
})
|
|
458
|
+
|
|
459
|
+
it('deduplicates overlapping requested old and current tags and cleans both memberships', async () => {
|
|
460
|
+
await strategy.set('product', 'old', { tags: ['old-products'] })
|
|
461
|
+
await strategy.set('product', 'fresh', { tags: ['new-products'] })
|
|
462
|
+
|
|
463
|
+
expect(await strategy.deleteByTags(['old-products', 'new-products', 'old-products'])).toBe(1)
|
|
464
|
+
expect(await strategy.get('product')).toBeNull()
|
|
465
|
+
expect(await currentRedis.smembers('tag:old-products')).toEqual([])
|
|
466
|
+
expect(await currentRedis.smembers('tag:new-products')).toEqual([])
|
|
467
|
+
expect(await strategy.deleteByTags(['old-products', 'new-products'])).toBe(0)
|
|
468
|
+
})
|
|
469
|
+
|
|
470
|
+
it('retains an entry rewritten with no tags when invalidating its previous tag', async () => {
|
|
471
|
+
await strategy.set('product', 'old', { tags: ['products'] })
|
|
472
|
+
await strategy.set('product', 'fresh', { tags: [] })
|
|
473
|
+
|
|
474
|
+
expect(await strategy.deleteByTags(['products'])).toBe(0)
|
|
475
|
+
expect(await strategy.get('product')).toBe('fresh')
|
|
476
|
+
expect(await currentRedis.smembers('tag:products')).toEqual([])
|
|
477
|
+
expect(await strategy.delete('product')).toBe(true)
|
|
478
|
+
})
|
|
479
|
+
|
|
480
|
+
it('does not reap a tag reintroduced after the invalidation snapshot', async () => {
|
|
481
|
+
await strategy.set('product', 'old', { tags: ['products'] })
|
|
482
|
+
await strategy.set('product', 'retagged', { tags: ['other-products'] })
|
|
483
|
+
const read = currentRedis.getBuffer.bind(currentRedis)
|
|
484
|
+
let rewritten = false
|
|
485
|
+
currentRedis.getBuffer = async (key) => {
|
|
486
|
+
const observed = await read(key)
|
|
487
|
+
if (!rewritten && key === 'cache:product' && observed !== null) {
|
|
488
|
+
rewritten = true
|
|
489
|
+
await strategy.set('product', 'reintroduced', { tags: ['products'] })
|
|
490
|
+
}
|
|
491
|
+
return observed
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
expect(await strategy.deleteByTags(['products'])).toBe(0)
|
|
495
|
+
expect(rewritten).toBe(true)
|
|
496
|
+
expect(await strategy.get('product')).toBe('reintroduced')
|
|
497
|
+
expect(await currentRedis.smembers('tag:products')).toEqual(['product'])
|
|
498
|
+
expect(await strategy.deleteByTags(['products'])).toBe(1)
|
|
499
|
+
})
|
|
500
|
+
|
|
501
|
+
it('passes compressed snapshots to stale reaping as exact binary bytes', async () => {
|
|
502
|
+
const compressed = createRedisStrategy(`redis://cache-lazy-binary-${++urlCounter}`, { compression: 'gzip' })
|
|
503
|
+
const value = { detail: 'Agram frozen vegetables and fruit '.repeat(300) }
|
|
504
|
+
try {
|
|
505
|
+
await compressed.set('product', value, { tags: ['old-products'] })
|
|
506
|
+
await compressed.set('product', value, { tags: ['new-products'] })
|
|
507
|
+
const observed = currentRedis.values.get('cache:product')
|
|
508
|
+
expect(Buffer.isBuffer(observed)).toBe(true)
|
|
509
|
+
const evaluate = jest.spyOn(currentRedis, 'eval')
|
|
510
|
+
|
|
511
|
+
expect(await compressed.deleteByTags(['old-products'])).toBe(0)
|
|
512
|
+
const binaryArguments = evaluate.mock.calls.flatMap((call) => call.slice(2)).filter(Buffer.isBuffer)
|
|
513
|
+
expect(binaryArguments).toHaveLength(1)
|
|
514
|
+
expect(binaryArguments[0]).toEqual(observed)
|
|
515
|
+
expect(await compressed.get('product')).toEqual(value)
|
|
516
|
+
expect(await currentRedis.smembers('tag:old-products')).toEqual([])
|
|
517
|
+
expect(await currentRedis.smembers('tag:new-products')).toEqual(['product'])
|
|
518
|
+
} finally {
|
|
519
|
+
await compressed.close?.()
|
|
520
|
+
}
|
|
521
|
+
})
|
|
522
|
+
|
|
523
|
+
it('keeps stale reaping linear in actual memberships and bounded across disjoint tags', async () => {
|
|
524
|
+
const perTag = 300
|
|
525
|
+
for (let tag = 0; tag < 2; tag++) {
|
|
526
|
+
for (let index = 0; index < perTag; index++) {
|
|
527
|
+
const key = `group-${tag}-product-${index}`
|
|
528
|
+
await strategy.set(key, 'old', { tags: [`old-group-${tag}`] })
|
|
529
|
+
await strategy.set(key, 'fresh', { tags: [`new-group-${tag}`] })
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
currentRedis.evalCalls = []
|
|
533
|
+
|
|
534
|
+
expect(await strategy.deleteByTags(['old-group-0', 'old-group-1'])).toBe(0)
|
|
535
|
+
const staleCalls = currentRedis.evalCalls.filter(({ kind }) => kind === 'stale')
|
|
536
|
+
expect(staleCalls.reduce((sum, call) => sum + call.memberCount, 0)).toBe(perTag * 2)
|
|
537
|
+
for (const call of staleCalls) {
|
|
538
|
+
expect(call.memberCount).toBeGreaterThan(0)
|
|
539
|
+
expect(call.memberCount).toBeLessThanOrEqual(256)
|
|
540
|
+
expect(call.numKeys).toBe(call.memberCount + 1)
|
|
541
|
+
}
|
|
542
|
+
for (let tag = 0; tag < 2; tag++) {
|
|
543
|
+
expect(staleCalls.filter(({ tagKey }) => tagKey === `tag:old-group-${tag}`)
|
|
544
|
+
.reduce((sum, call) => sum + call.memberCount, 0)).toBe(perTag)
|
|
545
|
+
expect(await currentRedis.smembers(`tag:old-group-${tag}`)).toEqual([])
|
|
546
|
+
expect(await currentRedis.smembers(`tag:new-group-${tag}`)).toHaveLength(perTag)
|
|
547
|
+
expect(await strategy.get(`group-${tag}-product-${perTag - 1}`)).toBe('fresh')
|
|
548
|
+
}
|
|
549
|
+
})
|
|
550
|
+
|
|
551
|
+
it('still deletes corrupt values reachable through a requested tag', async () => {
|
|
552
|
+
await strategy.set('product', 'old', { tags: ['products'] })
|
|
553
|
+
currentRedis.values.set('cache:product', '{invalid JSON')
|
|
554
|
+
|
|
555
|
+
expect(await strategy.deleteByTags(['products'])).toBe(1)
|
|
556
|
+
expect(currentRedis.values.has('cache:product')).toBe(false)
|
|
557
|
+
})
|
|
558
|
+
|
|
559
|
+
it.each(['setex', 'sadd'] as const)('propagates a %s error from the write transaction', async (command) => {
|
|
560
|
+
jest.spyOn(currentRedis, command).mockRejectedValueOnce(new Error(`injected ${command} failure`))
|
|
561
|
+
|
|
562
|
+
await expect(strategy.set('product', 'fresh', { ttl: 60_000, tags: ['products'] }))
|
|
563
|
+
.rejects.toThrow(`injected ${command} failure`)
|
|
564
|
+
expect(currentRedis.multiExecCalls).toBe(1)
|
|
565
|
+
})
|
|
566
|
+
|
|
567
|
+
it('propagates a stale-reaping pipeline error', async () => {
|
|
568
|
+
await strategy.set('product', 'old', { tags: ['old-products'] })
|
|
569
|
+
await strategy.set('product', 'fresh', { tags: ['new-products'] })
|
|
570
|
+
jest.spyOn(currentRedis, 'eval').mockRejectedValueOnce(new Error('injected stale reap failure'))
|
|
571
|
+
|
|
572
|
+
await expect(strategy.deleteByTags(['old-products'])).rejects.toThrow('injected stale reap failure')
|
|
573
|
+
expect(await strategy.get('product')).toBe('fresh')
|
|
574
|
+
expect(await currentRedis.smembers('tag:new-products')).toEqual(['product'])
|
|
575
|
+
})
|
|
576
|
+
})
|
|
577
|
+
|
|
578
|
+
describe('redis strategy concurrent deletion compatibility', () => {
|
|
579
|
+
let strategy: CacheStrategy
|
|
580
|
+
let urlCounter = 0
|
|
581
|
+
|
|
582
|
+
beforeEach(() => {
|
|
583
|
+
currentRedis = new FakeRedis()
|
|
584
|
+
urlCounter += 1
|
|
585
|
+
strategy = createRedisStrategy(`redis://cache-deletion-compatibility-${urlCounter}`)
|
|
586
|
+
})
|
|
587
|
+
|
|
588
|
+
afterEach(async () => {
|
|
589
|
+
await strategy.close?.()
|
|
590
|
+
})
|
|
591
|
+
|
|
592
|
+
function makeExpired(key: string): void {
|
|
593
|
+
const physicalKey = `cache:${key}`
|
|
594
|
+
const entry = JSON.parse(String(currentRedis.values.get(physicalKey)))
|
|
595
|
+
currentRedis.values.set(physicalKey, JSON.stringify({ ...entry, expiresAt: Date.now() - 100 }))
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
it('counts an invalidated value found before a concurrent deletion even when DEL returns zero', async () => {
|
|
599
|
+
await strategy.set('race', 'old', { tags: ['products'] })
|
|
600
|
+
const read = currentRedis.getBuffer.bind(currentRedis)
|
|
601
|
+
let removed = false
|
|
602
|
+
currentRedis.getBuffer = async (key) => {
|
|
603
|
+
const snapshot = await read(key)
|
|
604
|
+
if (!removed && key === 'cache:race' && snapshot !== null) {
|
|
605
|
+
removed = true
|
|
606
|
+
currentRedis.expire(key)
|
|
607
|
+
}
|
|
608
|
+
return snapshot
|
|
609
|
+
}
|
|
610
|
+
const remove = jest.spyOn(currentRedis, 'del')
|
|
611
|
+
|
|
612
|
+
expect(await strategy.deleteByTags(['products'])).toBe(1)
|
|
613
|
+
expect(removed).toBe(true)
|
|
614
|
+
expect(remove).toHaveReturned()
|
|
615
|
+
expect(await remove.mock.results[0].value).toBe(0)
|
|
616
|
+
expect(currentRedis.values.has('cache:race')).toBe(false)
|
|
617
|
+
expect(await currentRedis.smembers('tag:products')).toEqual([])
|
|
618
|
+
})
|
|
619
|
+
|
|
620
|
+
it('counts an expired entry recognized by cleanup even when the deletion read finds it missing', async () => {
|
|
621
|
+
await strategy.set('race', 'old', { tags: ['products'] })
|
|
622
|
+
makeExpired('race')
|
|
623
|
+
const read = currentRedis.getBuffer.bind(currentRedis)
|
|
624
|
+
let removed = false
|
|
625
|
+
currentRedis.getBuffer = async (key) => {
|
|
626
|
+
const snapshot = await read(key)
|
|
627
|
+
if (!removed && key === 'cache:race' && snapshot !== null) {
|
|
628
|
+
removed = true
|
|
629
|
+
currentRedis.expire(key)
|
|
630
|
+
}
|
|
631
|
+
return snapshot
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
expect(await strategy.cleanup?.()).toBe(1)
|
|
635
|
+
expect(removed).toBe(true)
|
|
636
|
+
expect(currentRedis.values.has('cache:race')).toBe(false)
|
|
637
|
+
// The previous implementation's second read returns a miss, so it leaves
|
|
638
|
+
// the expired value's membership for the existing orphan reaper.
|
|
639
|
+
expect(await currentRedis.smembers('tag:products')).toEqual(['race'])
|
|
640
|
+
expect(await strategy.deleteByTags(['products'])).toBe(0)
|
|
641
|
+
expect(await currentRedis.smembers('tag:products')).toEqual([])
|
|
642
|
+
})
|
|
643
|
+
|
|
644
|
+
it('uses the deletion read tag snapshot after an expired entry is rewritten with new tags', async () => {
|
|
645
|
+
await strategy.set('race', 'old', { tags: ['old-products'] })
|
|
646
|
+
makeExpired('race')
|
|
647
|
+
const read = currentRedis.getBuffer.bind(currentRedis)
|
|
648
|
+
let rewritten = false
|
|
649
|
+
currentRedis.getBuffer = async (key) => {
|
|
650
|
+
const snapshot = await read(key)
|
|
651
|
+
if (!rewritten && key === 'cache:race' && snapshot !== null) {
|
|
652
|
+
rewritten = true
|
|
653
|
+
await strategy.set('race', 'fresh', { tags: ['new-products'] })
|
|
654
|
+
}
|
|
655
|
+
return snapshot
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
expect(await strategy.cleanup?.()).toBe(1)
|
|
659
|
+
expect(rewritten).toBe(true)
|
|
660
|
+
// Preserve the previous implementation's behavior: cleanup still deletes
|
|
661
|
+
// the fresh value, but deleteKey reads and removes its current tags.
|
|
662
|
+
expect(currentRedis.values.has('cache:race')).toBe(false)
|
|
663
|
+
expect(await currentRedis.smembers('tag:new-products')).toEqual([])
|
|
664
|
+
// Lazy set retains the old membership; the existing orphan reaper removes
|
|
665
|
+
// it on the next invalidation after cleanup has deleted the current value.
|
|
666
|
+
expect(await currentRedis.smembers('tag:old-products')).toEqual(['race'])
|
|
667
|
+
expect(await strategy.deleteByTags(['old-products'])).toBe(0)
|
|
668
|
+
expect(await currentRedis.smembers('tag:old-products')).toEqual([])
|
|
669
|
+
})
|
|
670
|
+
|
|
671
|
+
it('keeps the raw-delete behavior when a corrupt snapshot is rewritten before cleanup deletes it', async () => {
|
|
672
|
+
await strategy.set('race', 'old', { tags: ['old-products'] })
|
|
673
|
+
currentRedis.values.set('cache:race', '{invalid JSON')
|
|
674
|
+
const read = currentRedis.getBuffer.bind(currentRedis)
|
|
675
|
+
let rewritten = false
|
|
676
|
+
currentRedis.getBuffer = async (key) => {
|
|
677
|
+
const snapshot = await read(key)
|
|
678
|
+
if (!rewritten && key === 'cache:race' && snapshot !== null) {
|
|
679
|
+
rewritten = true
|
|
680
|
+
await strategy.set('race', 'fresh', { tags: ['new-products'] })
|
|
681
|
+
}
|
|
682
|
+
return snapshot
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
expect(await strategy.cleanup?.()).toBe(1)
|
|
686
|
+
expect(rewritten).toBe(true)
|
|
687
|
+
expect(currentRedis.values.has('cache:race')).toBe(false)
|
|
688
|
+
// A corrupt initial snapshot takes raw DEL, without a second tag read.
|
|
689
|
+
// Repairing these inherited orphan memberships is outside this change.
|
|
690
|
+
expect(await currentRedis.smembers('tag:new-products')).toEqual(['race'])
|
|
691
|
+
})
|
|
692
|
+
|
|
693
|
+
it('counts a corrupt cleanup candidate even if it disappears before raw DEL', async () => {
|
|
694
|
+
currentRedis.values.set('cache:race', '{invalid JSON')
|
|
695
|
+
const read = currentRedis.getBuffer.bind(currentRedis)
|
|
696
|
+
let removed = false
|
|
697
|
+
currentRedis.getBuffer = async (key) => {
|
|
698
|
+
const snapshot = await read(key)
|
|
699
|
+
if (!removed && key === 'cache:race' && snapshot !== null) {
|
|
700
|
+
removed = true
|
|
701
|
+
currentRedis.expire(key)
|
|
702
|
+
}
|
|
703
|
+
return snapshot
|
|
704
|
+
}
|
|
705
|
+
const remove = jest.spyOn(currentRedis, 'del')
|
|
706
|
+
|
|
707
|
+
expect(await strategy.cleanup?.()).toBe(1)
|
|
708
|
+
expect(removed).toBe(true)
|
|
709
|
+
expect(await remove.mock.results[0].value).toBe(0)
|
|
710
|
+
expect(currentRedis.values.has('cache:race')).toBe(false)
|
|
711
|
+
})
|
|
712
|
+
|
|
713
|
+
it('preserves cleanup raw-delete fallback when the second read rejects', async () => {
|
|
714
|
+
await strategy.set('race', 'old', { tags: ['products'] })
|
|
715
|
+
makeExpired('race')
|
|
716
|
+
const read = currentRedis.getBuffer.bind(currentRedis)
|
|
717
|
+
let reads = 0
|
|
718
|
+
currentRedis.getBuffer = async (key) => {
|
|
719
|
+
if (key === 'cache:race' && ++reads === 2) {
|
|
720
|
+
throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value')
|
|
721
|
+
}
|
|
722
|
+
return read(key)
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
expect(await strategy.cleanup?.()).toBe(1)
|
|
726
|
+
expect(reads).toBe(2)
|
|
727
|
+
expect(currentRedis.values.has('cache:race')).toBe(false)
|
|
728
|
+
expect(await currentRedis.smembers('tag:products')).toEqual(['race'])
|
|
729
|
+
})
|
|
730
|
+
})
|
|
731
|
+
|
|
732
|
+
describe('redis strategy cursor walks', () => {
|
|
733
|
+
let strategy: CacheStrategy
|
|
734
|
+
let urlCounter = 0
|
|
735
|
+
|
|
736
|
+
beforeEach(() => {
|
|
737
|
+
currentRedis = new FakeRedis()
|
|
738
|
+
urlCounter += 1
|
|
739
|
+
strategy = createRedisStrategy(`redis://cache-scan-test-${urlCounter}`)
|
|
740
|
+
// A regression to a blocking KEYS call must fail, even for tiny fixtures.
|
|
741
|
+
jest.spyOn(currentRedis, 'keys').mockRejectedValue(new Error('Use SCAN, not KEYS'))
|
|
742
|
+
})
|
|
743
|
+
|
|
744
|
+
afterEach(async () => {
|
|
745
|
+
await strategy.close?.()
|
|
746
|
+
})
|
|
747
|
+
|
|
748
|
+
it('continues after an empty page and returns duplicate scan keys only once', async () => {
|
|
749
|
+
currentRedis.scriptedScanPages.set('cache:*', [
|
|
750
|
+
['17', []],
|
|
751
|
+
['23', ['cache:alpha', 'cache:beta']],
|
|
752
|
+
['0', ['cache:beta', 'cache:gamma']],
|
|
753
|
+
])
|
|
754
|
+
|
|
755
|
+
expect(await strategy.keys()).toEqual(['alpha', 'beta', 'gamma'])
|
|
756
|
+
expect(currentRedis.scanCalls.map(({ cursor }) => cursor)).toEqual(['0', '17', '23'])
|
|
757
|
+
expect(currentRedis.scanCalls.every(({ count }) => count > 0)).toBe(true)
|
|
758
|
+
})
|
|
759
|
+
|
|
760
|
+
it('walks every page when filtering by a wildcard pattern', async () => {
|
|
761
|
+
for (const key of ['item:a', 'item:b', 'item:c', 'item:d', 'item:e', 'other:x']) {
|
|
762
|
+
await strategy.set(key, key)
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
expect(await strategy.keys('item:?')).toEqual(['item:a', 'item:b', 'item:c', 'item:d', 'item:e'])
|
|
766
|
+
expect(currentRedis.scanCalls).toHaveLength(3)
|
|
767
|
+
expect(currentRedis.scanCalls.every(({ pattern }) => pattern === 'cache:item:?')).toBe(true)
|
|
768
|
+
})
|
|
769
|
+
|
|
770
|
+
it('counts each scanned entry once in stats, including expired entries', async () => {
|
|
771
|
+
await strategy.set('live', { value: 1 }, { tags: ['shared'] })
|
|
772
|
+
await strategy.set('expired', { value: 2 }, { tags: ['shared'] })
|
|
773
|
+
const stored = JSON.parse(String(currentRedis.values.get('cache:expired')))
|
|
774
|
+
currentRedis.values.set('cache:expired', JSON.stringify({ ...stored, expiresAt: Date.now() - 1 }))
|
|
775
|
+
currentRedis.scriptedScanPages.set('cache:*', [
|
|
776
|
+
['8', []],
|
|
777
|
+
['11', ['cache:expired']],
|
|
778
|
+
['0', ['cache:live', 'cache:expired']],
|
|
779
|
+
])
|
|
780
|
+
const read = jest.spyOn(currentRedis, 'getBuffer')
|
|
781
|
+
|
|
782
|
+
expect(await strategy.stats()).toEqual({ size: 2, expired: 1 })
|
|
783
|
+
expect(read.mock.calls.filter(([key]) => key === 'cache:expired')).toHaveLength(1)
|
|
784
|
+
expect(currentRedis.scanCalls.map(({ cursor }) => cursor)).toEqual(['0', '8', '11'])
|
|
785
|
+
})
|
|
786
|
+
|
|
787
|
+
it('cleans expired and corrupt values across pages without losing live tag memberships', async () => {
|
|
788
|
+
await strategy.set('expired', { value: 1 }, { tags: ['shared'] })
|
|
789
|
+
await strategy.set('live', { value: 2 }, { tags: ['shared'] })
|
|
790
|
+
const stored = JSON.parse(String(currentRedis.values.get('cache:expired')))
|
|
791
|
+
currentRedis.values.set('cache:expired', JSON.stringify({ ...stored, expiresAt: Date.now() - 1 }))
|
|
792
|
+
currentRedis.values.set('cache:broken', '{invalid JSON')
|
|
793
|
+
currentRedis.values.set('unrelated:value', 'keep')
|
|
794
|
+
currentRedis.scriptedScanPages.set('cache:*', [
|
|
795
|
+
['9', []],
|
|
796
|
+
['21', ['cache:expired', 'cache:broken']],
|
|
797
|
+
['0', ['cache:live', 'cache:broken']],
|
|
798
|
+
])
|
|
799
|
+
const read = jest.spyOn(currentRedis, 'getBuffer')
|
|
800
|
+
|
|
801
|
+
expect(await strategy.cleanup?.()).toBe(2)
|
|
802
|
+
expect(await strategy.get('live')).toEqual({ value: 2 })
|
|
803
|
+
expect(currentRedis.values.has('cache:expired')).toBe(false)
|
|
804
|
+
expect(currentRedis.values.has('cache:broken')).toBe(false)
|
|
805
|
+
expect(currentRedis.values.get('unrelated:value')).toBe('keep')
|
|
806
|
+
expect(await currentRedis.smembers('tag:shared')).toEqual(['live'])
|
|
807
|
+
expect(read.mock.calls.filter(([key]) => key === 'cache:broken')).toHaveLength(1)
|
|
808
|
+
expect(currentRedis.scanCalls.map(({ cursor }) => cursor)).toEqual(['0', '9', '21'])
|
|
809
|
+
})
|
|
810
|
+
|
|
811
|
+
it('clears every cache and tag page, deduplicating keys and preserving other namespaces', async () => {
|
|
812
|
+
for (const key of ['one', 'two', 'three']) {
|
|
813
|
+
await strategy.set(key, key, { tags: [`group-${key}`] })
|
|
814
|
+
}
|
|
815
|
+
currentRedis.values.set('unrelated:value', 'keep')
|
|
816
|
+
currentRedis.sets.set('unrelated:set', new Set(['keep']))
|
|
817
|
+
currentRedis.scriptedScanPages.set('cache:*', [
|
|
818
|
+
['7', []],
|
|
819
|
+
['16', ['cache:one', 'cache:two']],
|
|
820
|
+
['0', ['cache:two', 'cache:three']],
|
|
821
|
+
])
|
|
822
|
+
currentRedis.scriptedScanPages.set('tag:*', [
|
|
823
|
+
['2', ['tag:group-one']],
|
|
824
|
+
['4', []],
|
|
825
|
+
['0', ['tag:group-two', 'tag:group-three', 'tag:group-one']],
|
|
826
|
+
])
|
|
827
|
+
const remove = jest.spyOn(currentRedis, 'del')
|
|
828
|
+
|
|
829
|
+
expect(await strategy.clear()).toBe(3)
|
|
830
|
+
expect([...currentRedis.values.keys()]).toEqual(['unrelated:value'])
|
|
831
|
+
expect([...currentRedis.sets.keys()]).toEqual(['unrelated:set'])
|
|
832
|
+
expect(remove.mock.calls.flat().filter((key) => key === 'cache:two')).toHaveLength(1)
|
|
833
|
+
expect(remove.mock.calls.flat().filter((key) => key === 'tag:group-one')).toHaveLength(1)
|
|
834
|
+
expect(currentRedis.scanCalls.filter(({ pattern }) => pattern === 'cache:*').map(({ cursor }) => cursor))
|
|
835
|
+
.toEqual(['0', '7', '16'])
|
|
836
|
+
expect(currentRedis.scanCalls.filter(({ pattern }) => pattern === 'tag:*').map(({ cursor }) => cursor))
|
|
837
|
+
.toEqual(['0', '2', '4'])
|
|
838
|
+
})
|
|
839
|
+
})
|
|
840
|
+
|
|
288
841
|
describe('redis strategy value compression', () => {
|
|
289
842
|
let urlCounter = 0
|
|
290
843
|
const largeValue = {
|
|
@@ -339,14 +892,17 @@ describe('redis strategy value compression', () => {
|
|
|
339
892
|
await compressed.close?.()
|
|
340
893
|
})
|
|
341
894
|
|
|
342
|
-
it('
|
|
895
|
+
it('lazily removes old tag memberships without invalidating a compressed overwrite', async () => {
|
|
343
896
|
const strategy = createStrategy('zstd')
|
|
344
897
|
|
|
345
898
|
await strategy.set('list', largeValue, { tags: ['old-tag'] })
|
|
346
899
|
await strategy.set('list', largeValue, { tags: ['new-tag'] })
|
|
347
900
|
|
|
348
|
-
expect(await currentRedis.smembers('tag:old-tag')).toEqual([])
|
|
901
|
+
expect(await currentRedis.smembers('tag:old-tag')).toEqual(['list'])
|
|
349
902
|
expect(await currentRedis.smembers('tag:new-tag')).toEqual(['list'])
|
|
903
|
+
expect(await strategy.deleteByTags(['old-tag'])).toBe(0)
|
|
904
|
+
expect(await strategy.get('list')).toEqual(largeValue)
|
|
905
|
+
expect(await currentRedis.smembers('tag:old-tag')).toEqual([])
|
|
350
906
|
expect(await strategy.deleteByTags(['new-tag'])).toBe(1)
|
|
351
907
|
expect(currentRedis.values.has('cache:list')).toBe(false)
|
|
352
908
|
expect(await currentRedis.smembers('tag:new-tag')).toEqual([])
|