@open-mercato/cache 0.9.1-develop.7574.1.837288eec1 → 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.
@@ -46,16 +46,22 @@ describe('Cache Service', () => {
46
46
  })
47
47
 
48
48
  it('should respect defaultTtl option', async () => {
49
+ const initialTime = 1_000_000
50
+ const now = jest.spyOn(Date, 'now').mockReturnValue(initialTime)
49
51
  const cache = createCacheService({
50
52
  strategy: 'memory',
51
53
  defaultTtl: 100
52
54
  })
53
-
54
- await cache.set('test', 'value') // Should use default TTL
55
- expect(await cache.get('test')).toBe('value')
56
-
57
- await new Promise((resolve) => setTimeout(resolve, 150))
58
- expect(await cache.get('test')).toBeNull()
55
+
56
+ try {
57
+ await cache.set('test', 'value') // Should use default TTL
58
+ expect(await cache.get('test')).toBe('value')
59
+
60
+ now.mockReturnValue(initialTime + 101)
61
+ expect(await cache.get('test')).toBeNull()
62
+ } finally {
63
+ now.mockRestore()
64
+ }
59
65
  })
60
66
 
61
67
  it('should keep file-backed cache defaults under .mercato', async () => {
@@ -7,12 +7,14 @@ import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from '../co
7
7
  import type { CacheCodecOptions } from '../codec'
8
8
 
9
9
  type RedisPipeline = {
10
+ getBuffer(key: string): RedisPipeline
11
+ smembers(key: string): RedisPipeline
10
12
  set(key: string, value: string | Buffer): RedisPipeline
11
13
  setex(key: string, ttlSeconds: number, value: string | Buffer): RedisPipeline
12
14
  sadd(key: string, value: string): RedisPipeline
13
- srem(key: string, member: string): RedisPipeline
14
- del(key: string): RedisPipeline
15
- eval(script: string, numKeys: number, ...args: (string | number)[]): RedisPipeline
15
+ srem(key: string, ...members: string[]): RedisPipeline
16
+ del(...keys: string[]): RedisPipeline
17
+ eval(script: string, numKeys: number, ...args: (string | number | Buffer)[]): RedisPipeline
16
18
  exec(): Promise<unknown>
17
19
  }
18
20
 
@@ -22,11 +24,15 @@ type RedisClient = {
22
24
  getBuffer(key: string): Promise<Buffer | null>
23
25
  set(key: string, value: string | Buffer): Promise<unknown>
24
26
  setex(key: string, ttlSeconds: number, value: string | Buffer): Promise<unknown>
25
- del(key: string): Promise<unknown>
27
+ del(...keys: string[]): Promise<number>
26
28
  exists(key: string): Promise<number>
27
- keys(pattern: string): Promise<string[]>
29
+ scan(cursor: string, match: 'MATCH', pattern: string, count: 'COUNT', limit: number): Promise<[string, string[]]>
28
30
  smembers(key: string): Promise<string[]>
31
+ mgetBuffer(...keys: string[]): Promise<(Buffer | null)[]>
32
+ srem(key: string, ...members: string[]): Promise<number>
33
+ eval(script: string, numKeys: number, ...args: (string | number | Buffer)[]): Promise<unknown>
29
34
  pipeline(): RedisPipeline
35
+ multi(): RedisPipeline
30
36
  quit(): Promise<void>
31
37
  once?(event: 'end', listener: () => void): void
32
38
  }
@@ -64,7 +70,22 @@ end
64
70
  return removed
65
71
  `
66
72
 
67
- /** Bounds a single script's blocking time on the server, and the request size. */
73
+ // The application decoded these observed buffers and found that their current
74
+ // tags exclude this index. Compare bytes atomically before removing membership:
75
+ // a concurrent retag may have made the index valid again. Compression stays opaque.
76
+ // ARGV contains (member, observed buffer) pairs aligned with KEYS[2..].
77
+ const REAP_STALE_TAG_MEMBERS = `
78
+ local removed = 0
79
+ for i = 2, #KEYS do
80
+ local current = redis.call('GET', KEYS[i])
81
+ if not current or current == ARGV[(i - 2) * 2 + 2] then
82
+ removed = removed + redis.call('SREM', KEYS[1], ARGV[(i - 2) * 2 + 1])
83
+ end
84
+ end
85
+ return removed
86
+ `
87
+
88
+ /** Bounds members per script; payload bytes and execution time remain workload dependent. */
68
89
  const REAP_CHUNK_SIZE = 256
69
90
 
70
91
  /**
@@ -105,8 +126,18 @@ function loadRedisModuleViaRequire(): PossibleRedisModule | null {
105
126
  }
106
127
  }
107
128
 
108
- function pickRedisConstructor(mod: PossibleRedisModule): RedisConstructor | null {
109
- const queue: unknown[] = [mod]
129
+ export function pickRedisConstructor(mod: PossibleRedisModule): RedisConstructor | null {
130
+ // `mod` goes last: a bundler-wrapped ESM namespace for a CJS module (e.g.
131
+ // Turbopack's `createNS`) can itself be a callable-but-not-constructible
132
+ // wrapper around the real class, while `.default`/`.Redis` still point at
133
+ // the real class. Checking them first costs nothing for a plain CJS
134
+ // `require()` or a real Node ESM namespace, where they already agree with
135
+ // `mod`.
136
+ const queue: unknown[] = [
137
+ (mod as { default?: unknown } | null | undefined)?.default,
138
+ (mod as { Redis?: unknown } | null | undefined)?.Redis,
139
+ mod,
140
+ ]
110
141
  const seen = new Set<unknown>()
111
142
  while (queue.length) {
112
143
  const current = queue.shift()
@@ -213,6 +244,20 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
213
244
  return `${tagPrefix}${tag}`
214
245
  }
215
246
 
247
+ // SCAN may return duplicate keys and empty pages before the cursor reaches 0.
248
+ // COUNT is a work hint, not a strict page-size or latency bound.
249
+ async function scanKeys(pattern: string): Promise<string[]> {
250
+ const client = await getRedisClient()
251
+ const keys = new Set<string>()
252
+ let cursor = '0'
253
+ do {
254
+ const [next, page] = await client.scan(cursor, 'MATCH', pattern, 'COUNT', 256)
255
+ cursor = next
256
+ for (const key of page) keys.add(key)
257
+ } while (cursor !== '0')
258
+ return [...keys]
259
+ }
260
+
216
261
  function isExpired(entry: CacheEntry): boolean {
217
262
  if (entry.expiresAt === null) return false
218
263
  return Date.now() > entry.expiresAt
@@ -249,22 +294,6 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
249
294
  const client = await getRedisClient()
250
295
  const cacheKey = getCacheKey(key)
251
296
 
252
- // Remove old entry from tag index if it exists
253
- const oldData = await client.getBuffer(cacheKey)
254
- if (oldData) {
255
- try {
256
- const oldEntry: CacheEntry = JSON.parse(decodeCacheText(oldData))
257
- // Remove from old tags
258
- const pipeline = client.pipeline()
259
- for (const tag of oldEntry.tags) {
260
- pipeline.srem(getTagKey(tag), key)
261
- }
262
- await pipeline.exec()
263
- } catch {
264
- // Ignore parse errors
265
- }
266
- }
267
-
268
297
  const ttl = options?.ttl ?? defaultTtl
269
298
  const tags = options?.tags || []
270
299
  const expiresAt = ttl ? Date.now() + ttl : null
@@ -277,7 +306,9 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
277
306
  createdAt: Date.now(),
278
307
  }
279
308
 
280
- const pipeline = client.pipeline()
309
+ // Old memberships are reconciled by deleteByTags using current entry tags.
310
+ // ioredis sends MULTI, the commands and EXEC together, without a pre-read.
311
+ const pipeline = client.multi()
281
312
 
282
313
  // Store the entry
283
314
  const serialized = encodeCacheText(JSON.stringify(entry), codec)
@@ -292,7 +323,7 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
292
323
  pipeline.sadd(getTagKey(tag), key)
293
324
  }
294
325
 
295
- await pipeline.exec()
326
+ await executePipeline(pipeline)
296
327
  }
297
328
 
298
329
  const has = async (key: string): Promise<boolean> => {
@@ -347,64 +378,133 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
347
378
  }
348
379
  }
349
380
 
381
+
382
+ // Experimental entry-count bound; reply bytes and tag fanout remain workload dependent.
383
+ const batchSize = 256
384
+
385
+ async function executePipeline(pipeline: RedisPipeline): Promise<[Error | null, unknown][]> {
386
+ const result = await pipeline.exec() as [Error | null, unknown][] | null
387
+ if (!result) throw new Error('[internal] Redis pipeline aborted')
388
+ for (const [error] of result) if (error) throw error
389
+ return result
390
+ }
391
+
392
+ async function readBuffers(client: RedisClient, keys: string[]): Promise<(Buffer | null)[]> {
393
+ const values = await client.mgetBuffer(...keys)
394
+ if (values.length !== keys.length || values.some((value) => value !== null && !Buffer.isBuffer(value))) {
395
+ throw new Error('[internal] Unexpected binary Redis batch reply')
396
+ }
397
+ const missingKeys = keys.filter((_, index) => values[index] === null)
398
+ if (missingKeys.length > 0) {
399
+ // Detect WRONGTYPE without consuming a value rebuilt after the original MISS.
400
+ const validation = client.pipeline()
401
+ for (const key of missingKeys) validation.getBuffer(key)
402
+ await executePipeline(validation)
403
+ }
404
+ return values as (Buffer | null)[]
405
+ }
406
+
407
+ async function removeEntries(
408
+ client: RedisClient,
409
+ members: string[],
410
+ data: (Buffer | null)[],
411
+ requestedTags: Set<string>,
412
+ tagsByMember: Map<string, string[]>,
413
+ ): Promise<number> {
414
+ const valueKeys: string[] = []
415
+ const groups = new Map<string, string[]>()
416
+ const orphans = new Map<string, string[]>()
417
+ const stale = new Map<string, { member: string; buffer: Buffer }[]>()
418
+ for (let index = 0; index < members.length; index++) {
419
+ const buffer = data[index]
420
+ const member = members[index]
421
+ const memberTags = tagsByMember.get(member) ?? []
422
+ if (!buffer) {
423
+ for (const tagKey of memberTags) {
424
+ const list = orphans.get(tagKey) ?? []
425
+ list.push(member)
426
+ orphans.set(tagKey, list)
427
+ }
428
+ continue
429
+ }
430
+
431
+ let entryTags: Set<string> | undefined
432
+ try {
433
+ const entry: CacheEntry = JSON.parse(decodeCacheText(buffer))
434
+ if (Array.isArray(entry.tags) && entry.tags.every((tag) => typeof tag === 'string')) {
435
+ entryTags = new Set(entry.tags)
436
+ }
437
+ } catch { /* Corrupt entries are deleted, as with deleteKey(). */ }
438
+ if (entryTags) {
439
+ for (const tagKey of memberTags) {
440
+ if (entryTags.has(tagKey.slice(tagPrefix.length))) continue
441
+ const list = stale.get(tagKey) ?? []
442
+ list.push({ member, buffer })
443
+ stale.set(tagKey, list)
444
+ }
445
+ if (![...entryTags].some((tag) => requestedTags.has(tag))) continue
446
+ for (const tag of entryTags) {
447
+ const tagKey = getTagKey(tag)
448
+ const list = groups.get(tagKey) ?? []
449
+ list.push(member)
450
+ groups.set(tagKey, list)
451
+ }
452
+ }
453
+ valueKeys.push(getCacheKey(member))
454
+ }
455
+ if (!valueKeys.length && !orphans.size && !stale.size) return 0
456
+ const pipeline = client.pipeline()
457
+ for (const [tagKey, list] of groups) pipeline.srem(tagKey, ...list)
458
+ if (valueKeys.length) pipeline.del(...valueKeys)
459
+ for (const [tagKey, list] of orphans) {
460
+ for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {
461
+ const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE)
462
+ const keys = [tagKey, ...chunk.map(getCacheKey)]
463
+ pipeline.eval(REAP_ORPHANED_TAG_MEMBERS, keys.length, ...keys, ...chunk)
464
+ }
465
+ }
466
+ for (const [tagKey, list] of stale) {
467
+ for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {
468
+ const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE)
469
+ const keys = [tagKey, ...chunk.map(({ member }) => getCacheKey(member))]
470
+ pipeline.eval(REAP_STALE_TAG_MEMBERS, keys.length, ...keys, ...chunk.flatMap(({ member, buffer }) => [member, buffer]))
471
+ }
472
+ }
473
+ await executePipeline(pipeline)
474
+ return valueKeys.length
475
+ }
476
+
350
477
  const deleteByTags = async (tags: string[]): Promise<number> => {
351
478
  const client = await getRedisClient()
479
+ const requestedTags = new Set(tags)
352
480
  const keysToDelete = new Set<string>()
353
- // Keep which tag each key came from. Reaping needs it to stay linear in the
354
- // memberships that actually exist rather than in tags x keys.
355
- const membersByTagKey = new Map<string, string[]>()
481
+ // Keep only actual memberships. Each read batch reconciles its indexes so
482
+ // observed value buffers are released before reading the next batch.
483
+ const tagsByMember = new Map<string, string[]>()
356
484
 
357
485
  // Collect all keys that have any of the specified tags
358
- for (const tag of tags) {
359
- const tagKey = getTagKey(tag)
360
- const keys = await client.smembers(tagKey)
361
- membersByTagKey.set(tagKey, keys)
486
+ const tagPipeline = client.pipeline()
487
+ const uniqueTags = [...requestedTags]
488
+ for (const tag of uniqueTags) tagPipeline.smembers(getTagKey(tag))
489
+ const tagReplies = uniqueTags.length ? await executePipeline(tagPipeline) : []
490
+ for (let index = 0; index < uniqueTags.length; index++) {
491
+ const keys = tagReplies[index][1] as string[]
492
+ const tagKey = getTagKey(uniqueTags[index])
362
493
  for (const key of keys) {
363
494
  keysToDelete.add(key)
495
+ const memberTags = tagsByMember.get(key) ?? []
496
+ memberTags.push(tagKey)
497
+ tagsByMember.set(key, memberTags)
364
498
  }
365
499
  }
366
500
 
367
501
  // Delete all collected keys
368
502
  let deleted = 0
369
- const orphans = new Set<string>()
370
- for (const key of keysToDelete) {
371
- const success = await deleteKey(key)
372
- if (success) deleted++
373
- else orphans.add(key)
374
- }
375
-
376
- // A key whose value has already expired leaves its name behind in every tag
377
- // set it was added to: `set()` only prunes tags when it overwrites a live
378
- // key, `deleteKey` only prunes when it finds one, and `cleanup()` scans
379
- // value keys rather than tag sets. Nothing else reaps them, so the sets grow
380
- // without bound whenever TTL'd entries also rotate their key names — and
381
- // every later invalidation pays a GET per orphan. Reap what we just walked.
382
- //
383
- // `deleteKey` reported these missing some time ago — the walk above is one
384
- // round trip per member — so a concurrent request may have rebuilt any of
385
- // them since. Re-check each value key atomically with the removal rather
386
- // than trusting that stale read: dropping a live key from the index would
387
- // silently exempt it from every future invalidation of this tag.
388
- //
389
- // Reap per tag, over that tag's own members, so the work stays linear in the
390
- // memberships `smembers` actually returned. Each script is capped at
391
- // REAP_CHUNK_SIZE members, so no single atomic call can stall the server for
392
- // longer than a fixed bound however many tags were requested. The calls are
393
- // pipelined into one round trip, but stay separate scripts so Redis can
394
- // serve other clients between them.
395
- if (orphans.size > 0) {
396
- const pipeline = client.pipeline()
397
- let queued = 0
398
- for (const [tagKey, members] of membersByTagKey) {
399
- const tagOrphans = members.filter((member) => orphans.has(member))
400
- for (let offset = 0; offset < tagOrphans.length; offset += REAP_CHUNK_SIZE) {
401
- const chunk = tagOrphans.slice(offset, offset + REAP_CHUNK_SIZE)
402
- const keys = [tagKey, ...chunk.map(getCacheKey)]
403
- pipeline.eval(REAP_ORPHANED_TAG_MEMBERS, keys.length, ...keys, ...chunk)
404
- queued++
405
- }
406
- }
407
- if (queued > 0) await pipeline.exec()
503
+ const members = [...keysToDelete]
504
+ for (let offset = 0; offset < members.length; offset += batchSize) {
505
+ const chunk = members.slice(offset, offset + batchSize)
506
+ const data = await readBuffers(client, chunk.map(getCacheKey))
507
+ deleted += await removeEntries(client, chunk, data, requestedTags, tagsByMember)
408
508
  }
409
509
 
410
510
  return deleted
@@ -414,17 +514,18 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
414
514
  const client = await getRedisClient()
415
515
 
416
516
  // Get all cache keys
417
- const cacheKeys = await client.keys(`${keyPrefix}*`)
418
- const tagKeys = await client.keys(`${tagPrefix}*`)
517
+ const cacheKeys = await scanKeys(`${keyPrefix}*`)
518
+ const tagKeys = await scanKeys(`${tagPrefix}*`)
419
519
 
420
520
  if (cacheKeys.length === 0 && tagKeys.length === 0) return 0
421
521
 
422
- const pipeline = client.pipeline()
423
- for (const key of [...cacheKeys, ...tagKeys]) {
424
- pipeline.del(key)
522
+ const physicalKeys = [...cacheKeys, ...tagKeys]
523
+ for (let offset = 0; offset < physicalKeys.length; offset += batchSize) {
524
+ const chunk = physicalKeys.slice(offset, offset + batchSize)
525
+ const pipeline = client.pipeline()
526
+ for (const key of chunk) pipeline.del(key)
527
+ await executePipeline(pipeline)
425
528
  }
426
-
427
- await pipeline.exec()
428
529
  return cacheKeys.length
429
530
  }
430
531
 
@@ -434,7 +535,7 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
434
535
  ? `${keyPrefix}${pattern}`
435
536
  : `${keyPrefix}*`
436
537
 
437
- const cacheKeys = await client.keys(searchPattern)
538
+ const cacheKeys = await scanKeys(searchPattern)
438
539
 
439
540
  // Remove prefix from keys
440
541
  const result = cacheKeys.map((key: string) => key.substring(keyPrefix.length))
@@ -447,20 +548,15 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
447
548
 
448
549
  const stats = async (): Promise<{ size: number; expired: number }> => {
449
550
  const client = await getRedisClient()
450
- const cacheKeys = await client.keys(`${keyPrefix}*`)
551
+ const cacheKeys = await scanKeys(`${keyPrefix}*`)
451
552
 
452
553
  let expired = 0
453
- for (const cacheKey of cacheKeys) {
454
- const data = await client.getBuffer(cacheKey)
455
- if (data) {
456
- try {
457
- const entry: CacheEntry = JSON.parse(decodeCacheText(data))
458
- if (isExpired(entry)) {
459
- expired++
460
- }
461
- } catch {
462
- // Ignore parse errors
463
- }
554
+ for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {
555
+ const data = await readBuffers(client, cacheKeys.slice(offset, offset + batchSize))
556
+ for (const buffer of data) {
557
+ if (!buffer) continue
558
+ try { if (isExpired(JSON.parse(decodeCacheText(buffer)))) expired++ }
559
+ catch { /* stats ignores corrupt entries, as before. */ }
464
560
  }
465
561
  }
466
562
 
@@ -469,22 +565,22 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
469
565
 
470
566
  const cleanup = async (): Promise<number> => {
471
567
  const client = await getRedisClient()
472
- const cacheKeys = await client.keys(`${keyPrefix}*`)
568
+ const cacheKeys = await scanKeys(`${keyPrefix}*`)
473
569
 
474
570
  let removed = 0
475
- for (const cacheKey of cacheKeys) {
476
- const data = await client.getBuffer(cacheKey)
477
- if (data) {
571
+ for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {
572
+ const chunk = cacheKeys.slice(offset, offset + batchSize)
573
+ const data = await readBuffers(client, chunk)
574
+ for (let index = 0; index < chunk.length; index++) {
575
+ const buffer = data[index]
576
+ if (!buffer) continue
478
577
  try {
479
- const entry: CacheEntry = JSON.parse(decodeCacheText(data))
480
- if (isExpired(entry)) {
481
- const key = cacheKey.substring(keyPrefix.length)
482
- await deleteKey(key)
578
+ if (isExpired(JSON.parse(decodeCacheText(buffer)))) {
579
+ await deleteKey(chunk[index].substring(keyPrefix.length))
483
580
  removed++
484
581
  }
485
582
  } catch {
486
- // Remove invalid entries
487
- await client.del(cacheKey)
583
+ await client.del(chunk[index])
488
584
  removed++
489
585
  }
490
586
  }