@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.
- package/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +10 -0
- package/ENV.md +26 -0
- package/dist/codec.js +75 -0
- package/dist/codec.js.map +7 -0
- package/dist/service.js +9 -4
- package/dist/service.js.map +2 -2
- package/dist/strategies/redis.js +164 -71
- package/dist/strategies/redis.js.map +3 -3
- package/dist/strategies/sqlite.js +4 -2
- package/dist/strategies/sqlite.js.map +2 -2
- package/jest.config.cjs +1 -1
- package/package.json +2 -3
- package/src/__tests__/codec.test.ts +162 -0
- package/src/__tests__/redis.compatibility.live.test.ts +225 -0
- package/src/__tests__/redis.compression.live.test.ts +41 -0
- package/src/__tests__/redis.performance.live.test.ts +113 -0
- package/src/__tests__/redis.strategy.test.ts +754 -46
- package/src/__tests__/service.test.ts +66 -6
- package/src/__tests__/sqlite.strategy.test.ts +53 -2
- package/src/codec.ts +94 -0
- package/src/service.ts +13 -4
- package/src/strategies/redis.ts +214 -114
- package/src/strategies/sqlite.ts +7 -4
- package/src/types.ts +11 -0
package/src/strategies/redis.ts
CHANGED
|
@@ -3,27 +3,36 @@ import { CacheDependencyUnavailableError } from '../errors'
|
|
|
3
3
|
import { getRedisUrlOrThrow, REDIS_WIRE_PROTOCOL } from '@open-mercato/shared/lib/redis/connection'
|
|
4
4
|
import type { RedisProtocolVersion } from '@open-mercato/shared/lib/redis/connection'
|
|
5
5
|
import { matchCacheKeyPattern } from '../patterns'
|
|
6
|
+
import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from '../codec'
|
|
7
|
+
import type { CacheCodecOptions } from '../codec'
|
|
6
8
|
|
|
7
9
|
type RedisPipeline = {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
getBuffer(key: string): RedisPipeline
|
|
11
|
+
smembers(key: string): RedisPipeline
|
|
12
|
+
set(key: string, value: string | Buffer): RedisPipeline
|
|
13
|
+
setex(key: string, ttlSeconds: number, value: string | Buffer): RedisPipeline
|
|
10
14
|
sadd(key: string, value: string): RedisPipeline
|
|
11
|
-
srem(key: string,
|
|
12
|
-
del(
|
|
13
|
-
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
|
|
14
18
|
exec(): Promise<unknown>
|
|
15
19
|
}
|
|
16
20
|
|
|
17
21
|
type RedisClient = {
|
|
18
22
|
ping(): Promise<string>
|
|
19
23
|
get(key: string): Promise<string | null>
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
getBuffer(key: string): Promise<Buffer | null>
|
|
25
|
+
set(key: string, value: string | Buffer): Promise<unknown>
|
|
26
|
+
setex(key: string, ttlSeconds: number, value: string | Buffer): Promise<unknown>
|
|
27
|
+
del(...keys: string[]): Promise<number>
|
|
23
28
|
exists(key: string): Promise<number>
|
|
24
|
-
|
|
29
|
+
scan(cursor: string, match: 'MATCH', pattern: string, count: 'COUNT', limit: number): Promise<[string, string[]]>
|
|
25
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>
|
|
26
34
|
pipeline(): RedisPipeline
|
|
35
|
+
multi(): RedisPipeline
|
|
27
36
|
quit(): Promise<void>
|
|
28
37
|
once?(event: 'end', listener: () => void): void
|
|
29
38
|
}
|
|
@@ -61,7 +70,22 @@ end
|
|
|
61
70
|
return removed
|
|
62
71
|
`
|
|
63
72
|
|
|
64
|
-
|
|
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. */
|
|
65
89
|
const REAP_CHUNK_SIZE = 256
|
|
66
90
|
|
|
67
91
|
/**
|
|
@@ -102,8 +126,18 @@ function loadRedisModuleViaRequire(): PossibleRedisModule | null {
|
|
|
102
126
|
}
|
|
103
127
|
}
|
|
104
128
|
|
|
105
|
-
function pickRedisConstructor(mod: PossibleRedisModule): RedisConstructor | null {
|
|
106
|
-
|
|
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
|
+
]
|
|
107
141
|
const seen = new Set<unknown>()
|
|
108
142
|
while (queue.length) {
|
|
109
143
|
const current = queue.shift()
|
|
@@ -186,8 +220,9 @@ async function releaseRedisEntry(key: string, entry: RedisRegistryEntry): Promis
|
|
|
186
220
|
}
|
|
187
221
|
}
|
|
188
222
|
|
|
189
|
-
export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?: number }): CacheStrategy {
|
|
223
|
+
export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?: number } & CacheCodecOptions): CacheStrategy {
|
|
190
224
|
const defaultTtl = options?.defaultTtl
|
|
225
|
+
const codec = resolveCacheCodecConfig(options)
|
|
191
226
|
const keyPrefix = 'cache:'
|
|
192
227
|
const tagPrefix = 'tag:'
|
|
193
228
|
const connectionUrl = redisUrl || getRedisUrlOrThrow('CACHE')
|
|
@@ -209,6 +244,20 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
209
244
|
return `${tagPrefix}${tag}`
|
|
210
245
|
}
|
|
211
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
|
+
|
|
212
261
|
function isExpired(entry: CacheEntry): boolean {
|
|
213
262
|
if (entry.expiresAt === null) return false
|
|
214
263
|
return Date.now() > entry.expiresAt
|
|
@@ -217,12 +266,12 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
217
266
|
const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {
|
|
218
267
|
const client = await getRedisClient()
|
|
219
268
|
const cacheKey = getCacheKey(key)
|
|
220
|
-
const data = await client.
|
|
269
|
+
const data = await client.getBuffer(cacheKey)
|
|
221
270
|
|
|
222
271
|
if (!data) return null
|
|
223
272
|
|
|
224
273
|
try {
|
|
225
|
-
const entry: CacheEntry = JSON.parse(data)
|
|
274
|
+
const entry: CacheEntry = JSON.parse(decodeCacheText(data))
|
|
226
275
|
|
|
227
276
|
if (isExpired(entry)) {
|
|
228
277
|
if (options?.returnExpired) {
|
|
@@ -245,22 +294,6 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
245
294
|
const client = await getRedisClient()
|
|
246
295
|
const cacheKey = getCacheKey(key)
|
|
247
296
|
|
|
248
|
-
// Remove old entry from tag index if it exists
|
|
249
|
-
const oldData = await client.get(cacheKey)
|
|
250
|
-
if (oldData) {
|
|
251
|
-
try {
|
|
252
|
-
const oldEntry: CacheEntry = JSON.parse(oldData)
|
|
253
|
-
// Remove from old tags
|
|
254
|
-
const pipeline = client.pipeline()
|
|
255
|
-
for (const tag of oldEntry.tags) {
|
|
256
|
-
pipeline.srem(getTagKey(tag), key)
|
|
257
|
-
}
|
|
258
|
-
await pipeline.exec()
|
|
259
|
-
} catch {
|
|
260
|
-
// Ignore parse errors
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
|
|
264
297
|
const ttl = options?.ttl ?? defaultTtl
|
|
265
298
|
const tags = options?.tags || []
|
|
266
299
|
const expiresAt = ttl ? Date.now() + ttl : null
|
|
@@ -273,10 +306,12 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
273
306
|
createdAt: Date.now(),
|
|
274
307
|
}
|
|
275
308
|
|
|
276
|
-
|
|
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()
|
|
277
312
|
|
|
278
313
|
// Store the entry
|
|
279
|
-
const serialized = JSON.stringify(entry)
|
|
314
|
+
const serialized = encodeCacheText(JSON.stringify(entry), codec)
|
|
280
315
|
if (ttl) {
|
|
281
316
|
pipeline.setex(cacheKey, Math.ceil(ttl / 1000), serialized)
|
|
282
317
|
} else {
|
|
@@ -288,7 +323,7 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
288
323
|
pipeline.sadd(getTagKey(tag), key)
|
|
289
324
|
}
|
|
290
325
|
|
|
291
|
-
await pipeline
|
|
326
|
+
await executePipeline(pipeline)
|
|
292
327
|
}
|
|
293
328
|
|
|
294
329
|
const has = async (key: string): Promise<boolean> => {
|
|
@@ -299,11 +334,11 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
299
334
|
if (!exists) return false
|
|
300
335
|
|
|
301
336
|
// Check if expired
|
|
302
|
-
const data = await client.
|
|
337
|
+
const data = await client.getBuffer(cacheKey)
|
|
303
338
|
if (!data) return false
|
|
304
339
|
|
|
305
340
|
try {
|
|
306
|
-
const entry: CacheEntry = JSON.parse(data)
|
|
341
|
+
const entry: CacheEntry = JSON.parse(decodeCacheText(data))
|
|
307
342
|
if (isExpired(entry)) {
|
|
308
343
|
await deleteKey(key)
|
|
309
344
|
return false
|
|
@@ -319,11 +354,11 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
319
354
|
const cacheKey = getCacheKey(key)
|
|
320
355
|
|
|
321
356
|
// Get entry to remove from tag index
|
|
322
|
-
const data = await client.
|
|
357
|
+
const data = await client.getBuffer(cacheKey)
|
|
323
358
|
if (!data) return false
|
|
324
359
|
|
|
325
360
|
try {
|
|
326
|
-
const entry: CacheEntry = JSON.parse(data)
|
|
361
|
+
const entry: CacheEntry = JSON.parse(decodeCacheText(data))
|
|
327
362
|
const pipeline = client.pipeline()
|
|
328
363
|
|
|
329
364
|
// Remove from tag index
|
|
@@ -343,64 +378,133 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
343
378
|
}
|
|
344
379
|
}
|
|
345
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
|
+
|
|
346
477
|
const deleteByTags = async (tags: string[]): Promise<number> => {
|
|
347
478
|
const client = await getRedisClient()
|
|
479
|
+
const requestedTags = new Set(tags)
|
|
348
480
|
const keysToDelete = new Set<string>()
|
|
349
|
-
// Keep
|
|
350
|
-
//
|
|
351
|
-
const
|
|
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[]>()
|
|
352
484
|
|
|
353
485
|
// Collect all keys that have any of the specified tags
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
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])
|
|
358
493
|
for (const key of keys) {
|
|
359
494
|
keysToDelete.add(key)
|
|
495
|
+
const memberTags = tagsByMember.get(key) ?? []
|
|
496
|
+
memberTags.push(tagKey)
|
|
497
|
+
tagsByMember.set(key, memberTags)
|
|
360
498
|
}
|
|
361
499
|
}
|
|
362
500
|
|
|
363
501
|
// Delete all collected keys
|
|
364
502
|
let deleted = 0
|
|
365
|
-
const
|
|
366
|
-
for (
|
|
367
|
-
const
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// A key whose value has already expired leaves its name behind in every tag
|
|
373
|
-
// set it was added to: `set()` only prunes tags when it overwrites a live
|
|
374
|
-
// key, `deleteKey` only prunes when it finds one, and `cleanup()` scans
|
|
375
|
-
// value keys rather than tag sets. Nothing else reaps them, so the sets grow
|
|
376
|
-
// without bound whenever TTL'd entries also rotate their key names — and
|
|
377
|
-
// every later invalidation pays a GET per orphan. Reap what we just walked.
|
|
378
|
-
//
|
|
379
|
-
// `deleteKey` reported these missing some time ago — the walk above is one
|
|
380
|
-
// round trip per member — so a concurrent request may have rebuilt any of
|
|
381
|
-
// them since. Re-check each value key atomically with the removal rather
|
|
382
|
-
// than trusting that stale read: dropping a live key from the index would
|
|
383
|
-
// silently exempt it from every future invalidation of this tag.
|
|
384
|
-
//
|
|
385
|
-
// Reap per tag, over that tag's own members, so the work stays linear in the
|
|
386
|
-
// memberships `smembers` actually returned. Each script is capped at
|
|
387
|
-
// REAP_CHUNK_SIZE members, so no single atomic call can stall the server for
|
|
388
|
-
// longer than a fixed bound however many tags were requested. The calls are
|
|
389
|
-
// pipelined into one round trip, but stay separate scripts so Redis can
|
|
390
|
-
// serve other clients between them.
|
|
391
|
-
if (orphans.size > 0) {
|
|
392
|
-
const pipeline = client.pipeline()
|
|
393
|
-
let queued = 0
|
|
394
|
-
for (const [tagKey, members] of membersByTagKey) {
|
|
395
|
-
const tagOrphans = members.filter((member) => orphans.has(member))
|
|
396
|
-
for (let offset = 0; offset < tagOrphans.length; offset += REAP_CHUNK_SIZE) {
|
|
397
|
-
const chunk = tagOrphans.slice(offset, offset + REAP_CHUNK_SIZE)
|
|
398
|
-
const keys = [tagKey, ...chunk.map(getCacheKey)]
|
|
399
|
-
pipeline.eval(REAP_ORPHANED_TAG_MEMBERS, keys.length, ...keys, ...chunk)
|
|
400
|
-
queued++
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
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)
|
|
404
508
|
}
|
|
405
509
|
|
|
406
510
|
return deleted
|
|
@@ -410,17 +514,18 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
410
514
|
const client = await getRedisClient()
|
|
411
515
|
|
|
412
516
|
// Get all cache keys
|
|
413
|
-
const cacheKeys = await
|
|
414
|
-
const tagKeys = await
|
|
517
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`)
|
|
518
|
+
const tagKeys = await scanKeys(`${tagPrefix}*`)
|
|
415
519
|
|
|
416
520
|
if (cacheKeys.length === 0 && tagKeys.length === 0) return 0
|
|
417
521
|
|
|
418
|
-
const
|
|
419
|
-
for (
|
|
420
|
-
|
|
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)
|
|
421
528
|
}
|
|
422
|
-
|
|
423
|
-
await pipeline.exec()
|
|
424
529
|
return cacheKeys.length
|
|
425
530
|
}
|
|
426
531
|
|
|
@@ -430,7 +535,7 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
430
535
|
? `${keyPrefix}${pattern}`
|
|
431
536
|
: `${keyPrefix}*`
|
|
432
537
|
|
|
433
|
-
const cacheKeys = await
|
|
538
|
+
const cacheKeys = await scanKeys(searchPattern)
|
|
434
539
|
|
|
435
540
|
// Remove prefix from keys
|
|
436
541
|
const result = cacheKeys.map((key: string) => key.substring(keyPrefix.length))
|
|
@@ -443,20 +548,15 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
443
548
|
|
|
444
549
|
const stats = async (): Promise<{ size: number; expired: number }> => {
|
|
445
550
|
const client = await getRedisClient()
|
|
446
|
-
const cacheKeys = await
|
|
551
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`)
|
|
447
552
|
|
|
448
553
|
let expired = 0
|
|
449
|
-
for (
|
|
450
|
-
const data = await client.
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
expired++
|
|
456
|
-
}
|
|
457
|
-
} catch {
|
|
458
|
-
// Ignore parse errors
|
|
459
|
-
}
|
|
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. */ }
|
|
460
560
|
}
|
|
461
561
|
}
|
|
462
562
|
|
|
@@ -465,22 +565,22 @@ export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?:
|
|
|
465
565
|
|
|
466
566
|
const cleanup = async (): Promise<number> => {
|
|
467
567
|
const client = await getRedisClient()
|
|
468
|
-
const cacheKeys = await
|
|
568
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`)
|
|
469
569
|
|
|
470
570
|
let removed = 0
|
|
471
|
-
for (
|
|
472
|
-
const
|
|
473
|
-
|
|
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
|
|
474
577
|
try {
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
const key = cacheKey.substring(keyPrefix.length)
|
|
478
|
-
await deleteKey(key)
|
|
578
|
+
if (isExpired(JSON.parse(decodeCacheText(buffer)))) {
|
|
579
|
+
await deleteKey(chunk[index].substring(keyPrefix.length))
|
|
479
580
|
removed++
|
|
480
581
|
}
|
|
481
582
|
} catch {
|
|
482
|
-
|
|
483
|
-
await client.del(cacheKey)
|
|
583
|
+
await client.del(chunk[index])
|
|
484
584
|
removed++
|
|
485
585
|
}
|
|
486
586
|
}
|
package/src/strategies/sqlite.ts
CHANGED
|
@@ -5,6 +5,8 @@ import path from 'node:path'
|
|
|
5
5
|
import { CacheDependencyUnavailableError } from '../errors'
|
|
6
6
|
import { DEFAULT_SQLITE_CACHE_PATH } from '../defaults'
|
|
7
7
|
import { matchCacheKeyPattern } from '../patterns'
|
|
8
|
+
import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from '../codec'
|
|
9
|
+
import type { CacheCodecOptions } from '../codec'
|
|
8
10
|
|
|
9
11
|
type SqliteStatement<TResult = unknown> = {
|
|
10
12
|
get(...args: unknown[]): TResult | undefined
|
|
@@ -23,7 +25,7 @@ type SqliteDatabase = {
|
|
|
23
25
|
|
|
24
26
|
type SqliteConstructor = new (file: string) => SqliteDatabase
|
|
25
27
|
type SqliteModule = SqliteConstructor | { default: SqliteConstructor }
|
|
26
|
-
type SqliteStrategyOptions = { defaultTtl?: number; databaseConstructor?: SqliteConstructor }
|
|
28
|
+
type SqliteStrategyOptions = { defaultTtl?: number; databaseConstructor?: SqliteConstructor } & CacheCodecOptions
|
|
27
29
|
|
|
28
30
|
const sqliteRequire = createRequire(path.join(process.cwd(), 'package.json'))
|
|
29
31
|
|
|
@@ -38,6 +40,7 @@ const sqliteRequire = createRequire(path.join(process.cwd(), 'package.json'))
|
|
|
38
40
|
export function createSqliteStrategy(dbPath?: string, options?: SqliteStrategyOptions): CacheStrategy {
|
|
39
41
|
let db: SqliteDatabase | null = null
|
|
40
42
|
const defaultTtl = options?.defaultTtl
|
|
43
|
+
const codec = resolveCacheCodecConfig(options)
|
|
41
44
|
const filePath = dbPath || process.env.CACHE_SQLITE_PATH || DEFAULT_SQLITE_CACHE_PATH
|
|
42
45
|
|
|
43
46
|
async function getDb(): Promise<SqliteDatabase> {
|
|
@@ -93,7 +96,7 @@ export function createSqliteStrategy(dbPath?: string, options?: SqliteStrategyOp
|
|
|
93
96
|
return Date.now() > expiresAt
|
|
94
97
|
}
|
|
95
98
|
|
|
96
|
-
type EntryRow = { value: string; expires_at: number | null }
|
|
99
|
+
type EntryRow = { value: string | Buffer; expires_at: number | null }
|
|
97
100
|
type ExpiresRow = { expires_at: number | null }
|
|
98
101
|
type CountRow = { count: number }
|
|
99
102
|
type KeyRow = { key: string }
|
|
@@ -107,7 +110,7 @@ export function createSqliteStrategy(dbPath?: string, options?: SqliteStrategyOp
|
|
|
107
110
|
if (!row) return null
|
|
108
111
|
|
|
109
112
|
try {
|
|
110
|
-
const value = JSON.parse(row.value) as CacheValue
|
|
113
|
+
const value = JSON.parse(decodeCacheText(row.value)) as CacheValue
|
|
111
114
|
const expiresAt = row.expires_at
|
|
112
115
|
|
|
113
116
|
if (isExpired(expiresAt)) {
|
|
@@ -134,7 +137,7 @@ export function createSqliteStrategy(dbPath?: string, options?: SqliteStrategyOp
|
|
|
134
137
|
const expiresAt = ttl ? Date.now() + ttl : null
|
|
135
138
|
const createdAt = Date.now()
|
|
136
139
|
|
|
137
|
-
const serialized = JSON.stringify(value)
|
|
140
|
+
const serialized = encodeCacheText(JSON.stringify(value), codec)
|
|
138
141
|
|
|
139
142
|
database.transaction(() => {
|
|
140
143
|
// Delete old tags
|
package/src/types.ts
CHANGED
|
@@ -120,4 +120,15 @@ export type CacheServiceOptions = {
|
|
|
120
120
|
* disables the cap.
|
|
121
121
|
*/
|
|
122
122
|
maxEntries?: number
|
|
123
|
+
/**
|
|
124
|
+
* Value compression for the redis and sqlite strategies. Falls back to
|
|
125
|
+
* `CACHE_COMPRESSION`, then `off`. Reads detect the stored format, so
|
|
126
|
+
* entries written under any setting stay readable.
|
|
127
|
+
*/
|
|
128
|
+
compression?: 'off' | 'zstd' | 'gzip'
|
|
129
|
+
/**
|
|
130
|
+
* Smallest serialized entry, in bytes, that gets compressed. Falls back to
|
|
131
|
+
* `CACHE_COMPRESSION_MIN_BYTES`, then 1024.
|
|
132
|
+
*/
|
|
133
|
+
compressionMinBytes?: number
|
|
123
134
|
}
|