@open-mercato/cache 0.9.1-develop.7575.1.8480826a9b → 0.10.0

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.
@@ -1,61 +1,163 @@
1
1
  /** @jest-environment node */
2
2
  import type { CacheStrategy } from '../types'
3
- import { createRedisStrategy } from '../strategies/redis'
3
+ import { createRedisStrategy, pickRedisConstructor } from '../strategies/redis'
4
4
 
5
- type PipelineOp = () => void
5
+ type PipelineOp = () => unknown | Promise<unknown>
6
+ type RedisArgument = string | number | Buffer
6
7
 
7
8
  class FakeRedis {
8
- values = new Map<string, string>()
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'
15
26
  }
16
27
 
17
28
  async get(key: string): Promise<string | null> {
18
- return this.values.get(key) ?? null
29
+ const value = this.values.get(key)
30
+ if (value === undefined) return null
31
+ return Buffer.isBuffer(value) ? value.toString('utf8') : value
32
+ }
33
+
34
+ async getBuffer(key: string): Promise<Buffer | null> {
35
+ const value = this.values.get(key)
36
+ if (value === undefined) return null
37
+ return Buffer.isBuffer(value) ? value : Buffer.from(value, 'utf8')
19
38
  }
20
39
 
21
- async set(key: string, value: string): Promise<unknown> {
40
+ async set(key: string, value: string | Buffer): Promise<unknown> {
22
41
  this.values.set(key, value)
23
42
  return 'OK'
24
43
  }
25
44
 
26
- async setex(key: string, _ttlSeconds: number, value: string): Promise<unknown> {
45
+ async setex(key: string, _ttlSeconds: number, value: string | Buffer): Promise<unknown> {
27
46
  this.values.set(key, value)
28
47
  return 'OK'
29
48
  }
30
49
 
31
- async del(key: string): Promise<unknown> {
32
- return this.values.delete(key) ? 1 : 0
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
33
58
  }
34
59
 
35
60
  async exists(key: string): Promise<number> {
36
- return this.values.has(key) ? 1 : 0
61
+ return this.values.has(key) || this.sets.has(key) ? 1 : 0
37
62
  }
38
63
 
39
64
  async keys(pattern: string): Promise<string[]> {
40
- const prefix = pattern.endsWith('*') ? pattern.slice(0, -1) : pattern
41
- return [...this.values.keys()].filter((key) => key.startsWith(prefix))
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)))
42
96
  }
43
97
 
44
98
  async smembers(key: string): Promise<string[]> {
45
99
  return [...(this.sets.get(key) ?? [])]
46
100
  }
47
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
+
48
128
  /**
49
- * Mirrors the reap script's KEYS/ARGV contract rather than interpreting Lua —
129
+ * Mirrors the reap scripts' KEYS/ARGV contracts rather than interpreting Lua —
50
130
  * there is no Lua runtime here, and pulling one in for a single script is not
51
131
  * worth the dependency. What this pins down is the strategy's side of the
52
132
  * contract (key ordering, member alignment, chunking) and the exists-guarded
53
- * semantics. The script *body* is not covered; verify it against a real Redis
133
+ * semantics and byte-guarded stale-member removal. The script bodies are not
134
+ * covered; verify them against a real Redis
54
135
  * when changing it.
55
136
  */
56
- runEval(_script: string, numKeys: number, ...args: (string | number)[]): number {
57
- const [tagKey, ...valueKeys] = args.slice(0, numKeys) as string[]
58
- const members = args.slice(numKeys).map(String)
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)
59
161
 
60
162
  if (valueKeys.length !== members.length) {
61
163
  throw new Error(`[internal] eval contract: ${valueKeys.length} value keys vs ${members.length} members`)
@@ -75,50 +177,66 @@ class FakeRedis {
75
177
  pipeline() {
76
178
  const ops: PipelineOp[] = []
77
179
  const chain = {
78
- set: (key: string, value: string) => {
79
- ops.push(() => void this.values.set(key, value))
180
+ set: (key: string, value: string | Buffer) => {
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))
80
186
  return chain
81
187
  },
82
- setex: (key: string, _ttlSeconds: number, value: string) => {
83
- ops.push(() => void this.values.set(key, value))
188
+ getBuffer: (key: string) => {
189
+ ops.push(() => this.getBuffer(key))
84
190
  return chain
85
191
  },
86
- sadd: (key: string, member: string) => {
87
- ops.push(() => {
88
- const members = this.sets.get(key) ?? new Set<string>()
89
- members.add(member)
90
- this.sets.set(key, members)
91
- })
192
+ smembers: (key: string) => {
193
+ ops.push(() => this.smembers(key))
92
194
  return chain
93
195
  },
94
- srem: (key: string, member: string) => {
95
- ops.push(() => {
96
- const members = this.sets.get(key)
97
- if (!members) return
98
- members.delete(member)
99
- // Redis drops a set once its last member is removed.
100
- if (members.size === 0) this.sets.delete(key)
101
- })
196
+ sadd: (key: string, ...members: string[]) => {
197
+ ops.push(() => this.sadd(key, ...members))
102
198
  return chain
103
199
  },
104
- del: (key: string) => {
105
- ops.push(() => void this.values.delete(key))
200
+ srem: (key: string, ...members: string[]) => {
201
+ ops.push(() => this.srem(key, ...members))
106
202
  return chain
107
203
  },
108
- eval: (script: string, numKeys: number, ...args: (string | number)[]) => {
109
- this.evalCalls.push({ numKeys, memberCount: args.length - numKeys })
110
- ops.push(() => void this.runEval(script, numKeys, ...args))
204
+ del: (...keys: string[]) => {
205
+ ops.push(() => this.del(...keys))
111
206
  return chain
112
207
  },
113
- exec: async () => {
114
- for (const op of ops) op()
208
+ eval: (script: string, numKeys: number, ...args: RedisArgument[]) => {
209
+ ops.push(() => this.eval(script, numKeys, ...args))
210
+ return chain
211
+ },
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
+ }
115
221
  ops.length = 0
116
- return []
222
+ return results
117
223
  },
118
224
  }
119
225
  return chain
120
226
  }
121
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
+
122
240
  async quit(): Promise<void> {}
123
241
 
124
242
  /** Simulate a TTL firing: Redis expiry deletes the value key and nothing else. */
@@ -202,9 +320,9 @@ describe('redis strategy tag index', () => {
202
320
  // deleteByTags walks members one round trip at a time, so an entry it read
203
321
  // as missing can be rebuilt before the reap runs. Land that write in the
204
322
  // window by hooking the GET that reports the key absent.
205
- const readValue = currentRedis.get.bind(currentRedis)
323
+ const readValue = currentRedis.getBuffer.bind(currentRedis)
206
324
  let rebuilt = false
207
- currentRedis.get = async (key: string) => {
325
+ currentRedis.getBuffer = async (key: string) => {
208
326
  const result = await readValue(key)
209
327
  if (!rebuilt && key === 'cache:nav:user-1' && result === null) {
210
328
  rebuilt = true
@@ -214,7 +332,7 @@ describe('redis strategy tag index', () => {
214
332
  }
215
333
 
216
334
  await strategy.deleteByTags(['rbac:tenant:t1'])
217
- currentRedis.get = readValue
335
+ currentRedis.getBuffer = readValue
218
336
 
219
337
  // The rebuilt entry must stay in the index, or it silently outlives every
220
338
  // future invalidation of this tag and serves stale data until its TTL.
@@ -276,3 +394,593 @@ describe('redis strategy tag index', () => {
276
394
  expect(await currentRedis.smembers('tag:tag-b')).toEqual(['key-1'])
277
395
  })
278
396
  })
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
+
841
+ describe('redis strategy value compression', () => {
842
+ let urlCounter = 0
843
+ const largeValue = {
844
+ items: Array.from({ length: 100 }, (_, index) => ({ id: `row-${index}`, name: `Contact ${index}`, status: 'active' })),
845
+ }
846
+
847
+ function createStrategy(compression: 'off' | 'zstd' | 'gzip'): CacheStrategy {
848
+ urlCounter += 1
849
+ return createRedisStrategy(`redis://cache-compression-test-${urlCounter}`, { compression })
850
+ }
851
+
852
+ beforeEach(() => {
853
+ currentRedis = new FakeRedis()
854
+ })
855
+
856
+ it.each([
857
+ ['zstd', [0x28, 0xb5, 0x2f, 0xfd]],
858
+ ['gzip', [0x1f, 0x8b]],
859
+ ] as const)('stores large entries as %s frames and reads them back', async (compression, magic) => {
860
+ const strategy = createStrategy(compression)
861
+
862
+ await strategy.set('list:page:1', largeValue, { ttl: 60_000, tags: ['customers'] })
863
+
864
+ const stored = currentRedis.values.get('cache:list:page:1')
865
+ expect(Buffer.isBuffer(stored)).toBe(true)
866
+ expect(magic.every((byte, index) => (stored as Buffer)[index] === byte)).toBe(true)
867
+ expect(await strategy.get('list:page:1')).toEqual(largeValue)
868
+ expect(await strategy.has('list:page:1')).toBe(true)
869
+ await strategy.close?.()
870
+ })
871
+
872
+ it('keeps small entries as plain JSON strings', async () => {
873
+ const strategy = createStrategy('zstd')
874
+
875
+ await strategy.set('small', { id: 1 })
876
+
877
+ expect(typeof currentRedis.values.get('cache:small')).toBe('string')
878
+ expect(await strategy.get('small')).toEqual({ id: 1 })
879
+ await strategy.close?.()
880
+ })
881
+
882
+ it('reads legacy and compressed entries side by side in either direction', async () => {
883
+ const legacy = createStrategy('off')
884
+ await legacy.set('legacy', largeValue)
885
+ const compressed = createStrategy('zstd')
886
+ await compressed.set('compressed', largeValue)
887
+
888
+ expect(typeof currentRedis.values.get('cache:legacy')).toBe('string')
889
+ expect(await compressed.get('legacy')).toEqual(largeValue)
890
+ expect(await legacy.get('compressed')).toEqual(largeValue)
891
+ await legacy.close?.()
892
+ await compressed.close?.()
893
+ })
894
+
895
+ it('lazily removes old tag memberships without invalidating a compressed overwrite', async () => {
896
+ const strategy = createStrategy('zstd')
897
+
898
+ await strategy.set('list', largeValue, { tags: ['old-tag'] })
899
+ await strategy.set('list', largeValue, { tags: ['new-tag'] })
900
+
901
+ expect(await currentRedis.smembers('tag:old-tag')).toEqual(['list'])
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([])
906
+ expect(await strategy.deleteByTags(['new-tag'])).toBe(1)
907
+ expect(currentRedis.values.has('cache:list')).toBe(false)
908
+ expect(await currentRedis.smembers('tag:new-tag')).toEqual([])
909
+ await strategy.close?.()
910
+ })
911
+
912
+ it('counts and cleans up expired compressed entries', async () => {
913
+ const strategy = createStrategy('gzip')
914
+ await strategy.set('fresh', largeValue, { ttl: 60_000, tags: ['t'] })
915
+ await strategy.set('stale', largeValue, { ttl: 1, tags: ['t'] })
916
+ await new Promise((resolve) => setTimeout(resolve, 5))
917
+
918
+ expect(await strategy.stats()).toEqual({ size: 2, expired: 1 })
919
+ expect(await strategy.cleanup?.()).toBe(1)
920
+ expect(currentRedis.values.has('cache:fresh')).toBe(true)
921
+ expect(currentRedis.values.has('cache:stale')).toBe(false)
922
+ expect(await currentRedis.smembers('tag:t')).toEqual(['fresh'])
923
+ await strategy.close?.()
924
+ })
925
+
926
+ it('drops a corrupt frame as a miss', async () => {
927
+ const strategy = createStrategy('zstd')
928
+ currentRedis.values.set('cache:broken', Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0xff, 0xff, 0xff]))
929
+
930
+ expect(await strategy.get('broken')).toBeNull()
931
+ expect(currentRedis.values.has('cache:broken')).toBe(false)
932
+ await strategy.close?.()
933
+ })
934
+ })
935
+
936
+ describe('pickRedisConstructor', () => {
937
+ class RealRedis {
938
+ args: unknown[]
939
+ constructor(...args: unknown[]) {
940
+ this.args = args
941
+ }
942
+ }
943
+
944
+ it('resolves a plain CommonJS require, where module.exports is the class itself', () => {
945
+ const mod = RealRedis as unknown as { default: unknown; Redis: unknown }
946
+ mod.default = RealRedis
947
+ mod.Redis = RealRedis
948
+
949
+ const ctor = pickRedisConstructor(mod)
950
+
951
+ expect(ctor).toBe(RealRedis)
952
+ expect(new ctor!()).toBeInstanceOf(RealRedis)
953
+ })
954
+
955
+ it('resolves a real Node ESM namespace, where .default is the class and the namespace is a plain object', () => {
956
+ const mod = { default: RealRedis, Redis: RealRedis }
957
+
958
+ const ctor = pickRedisConstructor(mod)
959
+
960
+ expect(ctor).toBe(RealRedis)
961
+ expect(new ctor!()).toBeInstanceOf(RealRedis)
962
+ })
963
+
964
+ it('resolves a Turbopack-wrapped callable namespace by preferring .default/.Redis over the wrapper', () => {
965
+ // Mirrors Turbopack's `createNS`: a plain function that forwards to the
966
+ // real class via `.apply`, which is callable but throws when invoked
967
+ // with `new` because `apply` always calls the class as a plain function.
968
+ const wrapper = function (this: unknown, ...args: unknown[]) {
969
+ return RealRedis.apply(this, args)
970
+ } as unknown as { default: unknown; Redis: unknown }
971
+ wrapper.default = RealRedis
972
+ wrapper.Redis = RealRedis
973
+
974
+ const ctor = pickRedisConstructor(wrapper)
975
+
976
+ expect(ctor).toBe(RealRedis)
977
+ expect(new ctor!()).toBeInstanceOf(RealRedis)
978
+ expect(() => new (wrapper as unknown as new () => unknown)()).toThrow(TypeError)
979
+ })
980
+
981
+ it('returns null when nothing usable is found', () => {
982
+ expect(pickRedisConstructor({})).toBeNull()
983
+ expect(pickRedisConstructor(null)).toBeNull()
984
+ expect(pickRedisConstructor(undefined)).toBeNull()
985
+ })
986
+ })