@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.
@@ -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
  /**
@@ -223,6 +244,20 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
223
244
  return `${tagPrefix}${tag}`
224
245
  }
225
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
+
226
261
  function isExpired(entry: CacheEntry): boolean {
227
262
  if (entry.expiresAt === null) return false
228
263
  return Date.now() > entry.expiresAt
@@ -259,22 +294,6 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
259
294
  const client = await getRedisClient()
260
295
  const cacheKey = getCacheKey(key)
261
296
 
262
- // Remove old entry from tag index if it exists
263
- const oldData = await client.getBuffer(cacheKey)
264
- if (oldData) {
265
- try {
266
- const oldEntry: CacheEntry = JSON.parse(decodeCacheText(oldData))
267
- // Remove from old tags
268
- const pipeline = client.pipeline()
269
- for (const tag of oldEntry.tags) {
270
- pipeline.srem(getTagKey(tag), key)
271
- }
272
- await pipeline.exec()
273
- } catch {
274
- // Ignore parse errors
275
- }
276
- }
277
-
278
297
  const ttl = options?.ttl ?? defaultTtl
279
298
  const tags = options?.tags || []
280
299
  const expiresAt = ttl ? Date.now() + ttl : null
@@ -287,7 +306,9 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
287
306
  createdAt: Date.now(),
288
307
  }
289
308
 
290
- 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()
291
312
 
292
313
  // Store the entry
293
314
  const serialized = encodeCacheText(JSON.stringify(entry), codec)
@@ -302,7 +323,7 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
302
323
  pipeline.sadd(getTagKey(tag), key)
303
324
  }
304
325
 
305
- await pipeline.exec()
326
+ await executePipeline(pipeline)
306
327
  }
307
328
 
308
329
  const has = async (key: string): Promise<boolean> => {
@@ -357,64 +378,133 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
357
378
  }
358
379
  }
359
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
+
360
477
  const deleteByTags = async (tags: string[]): Promise<number> => {
361
478
  const client = await getRedisClient()
479
+ const requestedTags = new Set(tags)
362
480
  const keysToDelete = new Set<string>()
363
- // Keep which tag each key came from. Reaping needs it to stay linear in the
364
- // memberships that actually exist rather than in tags x keys.
365
- 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[]>()
366
484
 
367
485
  // Collect all keys that have any of the specified tags
368
- for (const tag of tags) {
369
- const tagKey = getTagKey(tag)
370
- const keys = await client.smembers(tagKey)
371
- 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])
372
493
  for (const key of keys) {
373
494
  keysToDelete.add(key)
495
+ const memberTags = tagsByMember.get(key) ?? []
496
+ memberTags.push(tagKey)
497
+ tagsByMember.set(key, memberTags)
374
498
  }
375
499
  }
376
500
 
377
501
  // Delete all collected keys
378
502
  let deleted = 0
379
- const orphans = new Set<string>()
380
- for (const key of keysToDelete) {
381
- const success = await deleteKey(key)
382
- if (success) deleted++
383
- else orphans.add(key)
384
- }
385
-
386
- // A key whose value has already expired leaves its name behind in every tag
387
- // set it was added to: `set()` only prunes tags when it overwrites a live
388
- // key, `deleteKey` only prunes when it finds one, and `cleanup()` scans
389
- // value keys rather than tag sets. Nothing else reaps them, so the sets grow
390
- // without bound whenever TTL'd entries also rotate their key names — and
391
- // every later invalidation pays a GET per orphan. Reap what we just walked.
392
- //
393
- // `deleteKey` reported these missing some time ago — the walk above is one
394
- // round trip per member — so a concurrent request may have rebuilt any of
395
- // them since. Re-check each value key atomically with the removal rather
396
- // than trusting that stale read: dropping a live key from the index would
397
- // silently exempt it from every future invalidation of this tag.
398
- //
399
- // Reap per tag, over that tag's own members, so the work stays linear in the
400
- // memberships `smembers` actually returned. Each script is capped at
401
- // REAP_CHUNK_SIZE members, so no single atomic call can stall the server for
402
- // longer than a fixed bound however many tags were requested. The calls are
403
- // pipelined into one round trip, but stay separate scripts so Redis can
404
- // serve other clients between them.
405
- if (orphans.size > 0) {
406
- const pipeline = client.pipeline()
407
- let queued = 0
408
- for (const [tagKey, members] of membersByTagKey) {
409
- const tagOrphans = members.filter((member) => orphans.has(member))
410
- for (let offset = 0; offset < tagOrphans.length; offset += REAP_CHUNK_SIZE) {
411
- const chunk = tagOrphans.slice(offset, offset + REAP_CHUNK_SIZE)
412
- const keys = [tagKey, ...chunk.map(getCacheKey)]
413
- pipeline.eval(REAP_ORPHANED_TAG_MEMBERS, keys.length, ...keys, ...chunk)
414
- queued++
415
- }
416
- }
417
- 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)
418
508
  }
419
509
 
420
510
  return deleted
@@ -424,17 +514,18 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
424
514
  const client = await getRedisClient()
425
515
 
426
516
  // Get all cache keys
427
- const cacheKeys = await client.keys(`${keyPrefix}*`)
428
- const tagKeys = await client.keys(`${tagPrefix}*`)
517
+ const cacheKeys = await scanKeys(`${keyPrefix}*`)
518
+ const tagKeys = await scanKeys(`${tagPrefix}*`)
429
519
 
430
520
  if (cacheKeys.length === 0 && tagKeys.length === 0) return 0
431
521
 
432
- const pipeline = client.pipeline()
433
- for (const key of [...cacheKeys, ...tagKeys]) {
434
- 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)
435
528
  }
436
-
437
- await pipeline.exec()
438
529
  return cacheKeys.length
439
530
  }
440
531
 
@@ -444,7 +535,7 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
444
535
  ? `${keyPrefix}${pattern}`
445
536
  : `${keyPrefix}*`
446
537
 
447
- const cacheKeys = await client.keys(searchPattern)
538
+ const cacheKeys = await scanKeys(searchPattern)
448
539
 
449
540
  // Remove prefix from keys
450
541
  const result = cacheKeys.map((key: string) => key.substring(keyPrefix.length))
@@ -457,20 +548,15 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
457
548
 
458
549
  const stats = async (): Promise<{ size: number; expired: number }> => {
459
550
  const client = await getRedisClient()
460
- const cacheKeys = await client.keys(`${keyPrefix}*`)
551
+ const cacheKeys = await scanKeys(`${keyPrefix}*`)
461
552
 
462
553
  let expired = 0
463
- for (const cacheKey of cacheKeys) {
464
- const data = await client.getBuffer(cacheKey)
465
- if (data) {
466
- try {
467
- const entry: CacheEntry = JSON.parse(decodeCacheText(data))
468
- if (isExpired(entry)) {
469
- expired++
470
- }
471
- } catch {
472
- // Ignore parse errors
473
- }
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. */ }
474
560
  }
475
561
  }
476
562
 
@@ -479,22 +565,22 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
479
565
 
480
566
  const cleanup = async (): Promise<number> => {
481
567
  const client = await getRedisClient()
482
- const cacheKeys = await client.keys(`${keyPrefix}*`)
568
+ const cacheKeys = await scanKeys(`${keyPrefix}*`)
483
569
 
484
570
  let removed = 0
485
- for (const cacheKey of cacheKeys) {
486
- const data = await client.getBuffer(cacheKey)
487
- 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
488
577
  try {
489
- const entry: CacheEntry = JSON.parse(decodeCacheText(data))
490
- if (isExpired(entry)) {
491
- const key = cacheKey.substring(keyPrefix.length)
492
- await deleteKey(key)
578
+ if (isExpired(JSON.parse(decodeCacheText(buffer)))) {
579
+ await deleteKey(chunk[index].substring(keyPrefix.length))
493
580
  removed++
494
581
  }
495
582
  } catch {
496
- // Remove invalid entries
497
- await client.del(cacheKey)
583
+ await client.del(chunk[index])
498
584
  removed++
499
585
  }
500
586
  }