@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.
@@ -0,0 +1,162 @@
1
+ /** @jest-environment node */
2
+ import zlib from 'node:zlib'
3
+ import {
4
+ DEFAULT_COMPRESSION_MIN_BYTES,
5
+ MAX_DECOMPRESSED_BYTES,
6
+ decodeCacheText,
7
+ encodeCacheText,
8
+ parseCacheCompression,
9
+ parseCacheCompressionMinBytes,
10
+ resolveCacheCodecConfig,
11
+ } from '../codec'
12
+ import type { CacheCodecConfig } from '../codec'
13
+
14
+ const ZSTD_MAGIC = [0x28, 0xb5, 0x2f, 0xfd]
15
+ const GZIP_MAGIC = [0x1f, 0x8b]
16
+
17
+ function listPayload(rows: number): string {
18
+ return JSON.stringify({
19
+ items: Array.from({ length: rows }, (_, index) => ({
20
+ id: `00000000-0000-4000-8000-${String(index).padStart(12, '0')}`,
21
+ displayName: `Contact ${index}`,
22
+ primaryEmail: `contact.${index}@example.com`,
23
+ status: index % 2 ? 'active' : 'lead',
24
+ })),
25
+ total: rows,
26
+ })
27
+ }
28
+
29
+ function startsWith(raw: string | Buffer, magic: number[]): boolean {
30
+ return Buffer.isBuffer(raw) && magic.every((byte, index) => raw[index] === byte)
31
+ }
32
+
33
+ describe.each([
34
+ ['zstd', ZSTD_MAGIC],
35
+ ['gzip', GZIP_MAGIC],
36
+ ] as const)('cache codec (%s)', (compression, magic) => {
37
+ const config: CacheCodecConfig = { compression, minBytes: DEFAULT_COMPRESSION_MIN_BYTES }
38
+
39
+ it('round-trips a large entry through a compressed frame', () => {
40
+ const json = listPayload(100)
41
+ const encoded = encodeCacheText(json, config)
42
+
43
+ expect(startsWith(encoded, magic)).toBe(true)
44
+ expect((encoded as Buffer).length).toBeLessThan(Buffer.byteLength(json) / 4)
45
+ expect(decodeCacheText(encoded)).toBe(json)
46
+ })
47
+
48
+ it('keeps entries below the threshold as plain JSON', () => {
49
+ const json = listPayload(2)
50
+ expect(Buffer.byteLength(json)).toBeLessThan(DEFAULT_COMPRESSION_MIN_BYTES)
51
+
52
+ expect(encodeCacheText(json, config)).toBe(json)
53
+ })
54
+
55
+ it('stores the JSON when compression would not shrink it', () => {
56
+ const json = JSON.stringify({ id: 'a1' })
57
+
58
+ expect(encodeCacheText(json, { compression, minBytes: 1 })).toBe(json)
59
+ })
60
+
61
+ it('reads entries written by the other codec and by the off setting', () => {
62
+ const json = listPayload(100)
63
+ const other: CacheCodecConfig = { compression: compression === 'zstd' ? 'gzip' : 'zstd', minBytes: 1024 }
64
+
65
+ expect(decodeCacheText(encodeCacheText(json, other))).toBe(json)
66
+ expect(decodeCacheText(encodeCacheText(json, { compression: 'off', minBytes: 1024 }))).toBe(json)
67
+ })
68
+
69
+ it('rejects a corrupt frame', () => {
70
+ const encoded = encodeCacheText(listPayload(100), config) as Buffer
71
+ const corrupt = Buffer.concat([encoded.subarray(0, magic.length), Buffer.alloc(32, 0xff)])
72
+
73
+ expect(() => decodeCacheText(corrupt)).toThrow()
74
+ })
75
+ })
76
+
77
+ describe('cache codec format detection', () => {
78
+ it('reads legacy JSON stored as a string or as UTF-8 bytes', () => {
79
+ const json = listPayload(100)
80
+
81
+ expect(decodeCacheText(json)).toBe(json)
82
+ expect(decodeCacheText(Buffer.from(json, 'utf8'))).toBe(json)
83
+ })
84
+
85
+ it('never compresses with compression off', () => {
86
+ const json = listPayload(100)
87
+ expect(encodeCacheText(json, { compression: 'off', minBytes: 1 })).toBe(json)
88
+ })
89
+
90
+ it('skips compression above the decode cap so a legitimate entry can always be read back', () => {
91
+ const encodeSpy = jest.spyOn(zlib, 'gzipSync')
92
+ const json = 'x'.repeat(MAX_DECOMPRESSED_BYTES + 1)
93
+
94
+ expect(encodeCacheText(json, { compression: 'gzip', minBytes: 1 })).toBe(json)
95
+ expect(encodeSpy).not.toHaveBeenCalled()
96
+ encodeSpy.mockRestore()
97
+ })
98
+
99
+ it('caps the decompressed size of a hostile frame', () => {
100
+ const bomb = zlib.zstdCompressSync(Buffer.alloc(MAX_DECOMPRESSED_BYTES + 1024, 0x20))
101
+
102
+ expect(() => decodeCacheText(bomb)).toThrow()
103
+ })
104
+ })
105
+
106
+ describe('cache codec configuration', () => {
107
+ afterEach(() => {
108
+ jest.restoreAllMocks()
109
+ })
110
+
111
+ it('parses known compression values case-insensitively', () => {
112
+ expect(parseCacheCompression('zstd')).toBe('zstd')
113
+ expect(parseCacheCompression(' GZIP ')).toBe('gzip')
114
+ expect(parseCacheCompression('off')).toBe('off')
115
+ expect(parseCacheCompression(undefined)).toBe('off')
116
+ expect(parseCacheCompression('')).toBe('off')
117
+ })
118
+
119
+ it('treats an unknown value as off and warns once', () => {
120
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
121
+
122
+ expect(parseCacheCompression('brotli-codec-test')).toBe('off')
123
+ expect(parseCacheCompression('brotli-codec-test')).toBe('off')
124
+
125
+ expect(warn).toHaveBeenCalledTimes(1)
126
+ })
127
+
128
+ it('accepts only a positive min-bytes value', () => {
129
+ expect(parseCacheCompressionMinBytes('2048')).toBe(2048)
130
+ expect(parseCacheCompressionMinBytes('0')).toBeUndefined()
131
+ expect(parseCacheCompressionMinBytes('-5')).toBeUndefined()
132
+ expect(parseCacheCompressionMinBytes('abc')).toBeUndefined()
133
+ expect(parseCacheCompressionMinBytes(undefined)).toBeUndefined()
134
+ })
135
+
136
+ it('defaults to off with a 1 KB threshold', () => {
137
+ expect(resolveCacheCodecConfig()).toEqual({ compression: 'off', minBytes: DEFAULT_COMPRESSION_MIN_BYTES })
138
+ expect(resolveCacheCodecConfig({ compression: 'zstd', compressionMinBytes: 0 })).toEqual({
139
+ compression: 'zstd',
140
+ minBytes: DEFAULT_COMPRESSION_MIN_BYTES,
141
+ })
142
+ })
143
+
144
+ it('falls back to gzip when the runtime has no zstd', () => {
145
+ jest.isolateModules(() => {
146
+ jest.doMock('node:zlib', () => {
147
+ const actual = jest.requireActual<typeof import('node:zlib')>('node:zlib')
148
+ return { ...actual, zstdCompressSync: undefined, zstdDecompressSync: undefined }
149
+ })
150
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
151
+ const isolated = require('../codec') as typeof import('../codec')
152
+
153
+ const config = isolated.resolveCacheCodecConfig({ compression: 'zstd' })
154
+ const encoded = isolated.encodeCacheText(listPayload(100), config)
155
+
156
+ expect(config.compression).toBe('gzip')
157
+ expect(startsWith(encoded, GZIP_MAGIC)).toBe(true)
158
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('zstd is not available'))
159
+ })
160
+ jest.dontMock('node:zlib')
161
+ })
162
+ })
@@ -0,0 +1,225 @@
1
+ /** @jest-environment node */
2
+ import { randomUUID } from 'node:crypto'
3
+ import Redis from 'ioredis'
4
+ import { createRedisStrategy } from '../strategies/redis'
5
+
6
+ const redisUrl = process.env.CACHE_REDIS_TEST_URL
7
+ const describeWithRedis = redisUrl ? describe : describe.skip
8
+
9
+ describeWithRedis('Redis batch compatibility against the real server', () => {
10
+ async function fixture(run: (context: {
11
+ strategy: ReturnType<typeof createRedisStrategy>
12
+ admin: Redis
13
+ key: string
14
+ tag: string
15
+ }) => Promise<void>, compression: 'off' | 'gzip' | 'zstd' = 'off') {
16
+ const prefix = `batch-compat-${randomUUID()}`
17
+ const key = `${prefix}:value`
18
+ const tag = `${prefix}:tag`
19
+ const strategy = createRedisStrategy(redisUrl, { compression, defaultTtl: 60_000 })
20
+ const admin = new Redis(redisUrl!, { protocol: 2, maxRetriesPerRequest: 1 })
21
+ try {
22
+ expect(await admin.dbsize()).toBe(0)
23
+ await strategy.healthcheck?.()
24
+ await run({ strategy, admin, key, tag })
25
+ } finally {
26
+ let cursor = '0'
27
+ const keys = new Set<string>()
28
+ do {
29
+ const [next, page] = await admin.scan(cursor, 'MATCH', `*${prefix}*`, 'COUNT', 256)
30
+ cursor = next
31
+ for (const ownKey of page) keys.add(ownKey)
32
+ } while (cursor !== '0')
33
+ const ownKeys = [...keys]
34
+ for (let offset = 0; offset < ownKeys.length; offset += 256) {
35
+ await admin.del(...ownKeys.slice(offset, offset + 256))
36
+ }
37
+ await admin.quit()
38
+ await strategy.close?.()
39
+ }
40
+ }
41
+
42
+ it.each(['invalidation', 'stats', 'cleanup'] as const)(
43
+ '%s reports WRONGTYPE instead of treating a Redis set as a missing string',
44
+ async (operation) => fixture(async ({ strategy, admin, key, tag }) => {
45
+ await strategy.set(key, { healthy: true }, { tags: [tag] })
46
+ await admin.del(`cache:${key}`)
47
+ await admin.sadd(`cache:${key}`, 'wrong-value-type')
48
+ const result = operation === 'invalidation'
49
+ ? strategy.deleteByTags([tag])
50
+ : operation === 'stats' ? strategy.stats() : strategy.cleanup!()
51
+ await expect(result).rejects.toThrow('WRONGTYPE')
52
+ expect(await admin.type(`cache:${key}`)).toBe('set')
53
+ expect(await admin.sismember(`tag:${tag}`, key)).toBe(1)
54
+ }),
55
+ )
56
+
57
+ it.each(['off', 'gzip'] as const)(
58
+ 'preserves a %s rebuild after the missing MGET reply during validation',
59
+ async (compression) => fixture(async ({ strategy, admin, key, tag }) => {
60
+ await admin.sadd(`tag:${tag}`, key)
61
+ const original = Redis.prototype.mgetBuffer
62
+ let rebuilt = false
63
+ Redis.prototype.mgetBuffer = async function (this: Redis, ...keys: string[]) {
64
+ const buffers = await original.apply(this, keys)
65
+ if (!rebuilt && keys.includes(`cache:${key}`)) {
66
+ expect(buffers[keys.indexOf(`cache:${key}`)]).toBeNull()
67
+ rebuilt = true
68
+ await strategy.set(key, { revision: 'fresh', padding: 'fresh-content '.repeat(256) }, { tags: [tag] })
69
+ }
70
+ return buffers
71
+ } as typeof original
72
+ try {
73
+ expect(await strategy.deleteByTags([tag])).toBe(0)
74
+ expect(rebuilt).toBe(true)
75
+ expect(await strategy.get(key)).toMatchObject({ revision: 'fresh' })
76
+ expect(await admin.sismember(`tag:${tag}`, key)).toBe(1)
77
+ if (compression === 'gzip') {
78
+ expect((await admin.getBuffer(`cache:${key}`))?.subarray(0, 2)).toEqual(Buffer.from([0x1f, 0x8b]))
79
+ }
80
+ expect(await strategy.deleteByTags([tag])).toBe(1)
81
+ } finally {
82
+ Redis.prototype.mgetBuffer = original
83
+ }
84
+ }, compression),
85
+ )
86
+
87
+ it.each(['off', 'gzip', 'zstd'] as const)(
88
+ 'reconciles %s old tags without deleting a retagged or tagless value',
89
+ async (compression) => fixture(async ({ strategy, admin, key, tag }) => {
90
+ const nextTag = `${tag}:next`
91
+ const payload = { revision: 'fresh', padding: 'frozen-products '.repeat(256) }
92
+ await strategy.set(key, 'old', { tags: [tag] })
93
+ await strategy.set(key, payload, { tags: [nextTag] })
94
+ expect(await admin.sismember(`tag:${tag}`, key)).toBe(1)
95
+ expect(await strategy.deleteByTags([tag])).toBe(0)
96
+ expect(await strategy.get(key)).toEqual(payload)
97
+ expect(await admin.scard(`tag:${tag}`)).toBe(0)
98
+ expect(await admin.sismember(`tag:${nextTag}`, key)).toBe(1)
99
+ const ttl = await admin.pttl(`cache:${key}`)
100
+ expect(ttl).toBeGreaterThan(0)
101
+ expect(ttl).toBeLessThanOrEqual(60_000)
102
+
103
+ await strategy.set(key, payload, { tags: [tag] })
104
+ expect(await strategy.deleteByTags([nextTag, tag, tag])).toBe(1)
105
+ expect(await admin.scard(`tag:${nextTag}`)).toBe(0)
106
+ expect(await admin.scard(`tag:${tag}`)).toBe(0)
107
+
108
+ await strategy.set(key, payload, { tags: [tag] })
109
+ await strategy.set(key, payload, { tags: [] })
110
+ expect(await strategy.deleteByTags([tag])).toBe(0)
111
+ expect(await strategy.get(key)).toEqual(payload)
112
+ expect(await admin.scard(`tag:${tag}`)).toBe(0)
113
+ }, compression),
114
+ )
115
+
116
+ it.each(['off', 'gzip'] as const)(
117
+ 'preserves a %s tag reintroduced before stale membership reconciliation',
118
+ async (compression) => fixture(async ({ strategy, admin, key, tag }) => {
119
+ await strategy.set(key, 'old', { tags: [tag] })
120
+ await strategy.set(key, { revision: 'retagged', padding: 'content '.repeat(512) }, { tags: [`${tag}:next`] })
121
+ const original = Redis.prototype.mgetBuffer
122
+ let rebuilt = false
123
+ Redis.prototype.mgetBuffer = async function (this: Redis, ...keys: string[]) {
124
+ const buffers = await original.apply(this, keys)
125
+ if (!rebuilt && keys.includes(`cache:${key}`)) {
126
+ rebuilt = true
127
+ await strategy.set(key, { revision: 'reintroduced', padding: 'new-content '.repeat(512) }, { tags: [tag] })
128
+ }
129
+ return buffers
130
+ } as typeof original
131
+ try {
132
+ expect(await strategy.deleteByTags([tag])).toBe(0)
133
+ expect(rebuilt).toBe(true)
134
+ expect(await strategy.get(key)).toMatchObject({ revision: 'reintroduced' })
135
+ expect(await admin.sismember(`tag:${tag}`, key)).toBe(1)
136
+ expect(await strategy.deleteByTags([tag])).toBe(1)
137
+ } finally {
138
+ Redis.prototype.mgetBuffer = original
139
+ }
140
+ }, compression),
141
+ )
142
+
143
+ it('reaps stale membership when the observed value disappears before reconciliation', async () => fixture(
144
+ async ({ strategy, admin, key, tag }) => {
145
+ await strategy.set(key, 'old', { tags: [tag] })
146
+ await strategy.set(key, 'retagged', { tags: [`${tag}:next`] })
147
+ const original = Redis.prototype.mgetBuffer
148
+ Redis.prototype.mgetBuffer = async function (this: Redis, ...keys: string[]) {
149
+ const buffers = await original.apply(this, keys)
150
+ await admin.del(`cache:${key}`)
151
+ return buffers
152
+ } as typeof original
153
+ try {
154
+ expect(await strategy.deleteByTags([tag])).toBe(0)
155
+ expect(await admin.scard(`tag:${tag}`)).toBe(0)
156
+ } finally {
157
+ Redis.prototype.mgetBuffer = original
158
+ }
159
+ },
160
+ ))
161
+
162
+ it('reports transaction command errors even when the value write succeeds', async () => fixture(
163
+ async ({ strategy, admin, key, tag }) => {
164
+ await admin.set(`tag:${tag}`, 'wrong-tag-type')
165
+ await expect(strategy.set(key, 'new-value', { tags: [tag] })).rejects.toThrow('WRONGTYPE')
166
+ expect(await strategy.get(key)).toBe('new-value')
167
+ expect(await admin.get(`tag:${tag}`)).toBe('wrong-tag-type')
168
+ },
169
+ ))
170
+
171
+ it.each([[42], [null], [{}]])('deletes a JSON entry with malformed tags %j', async (invalidTag) => fixture(
172
+ async ({ strategy, admin, key, tag }) => {
173
+ await strategy.set(key, 'old', { tags: [tag] })
174
+ await admin.set(`cache:${key}`, JSON.stringify({
175
+ key, value: 'malformed', tags: [invalidTag], expiresAt: null, createdAt: Date.now(),
176
+ }))
177
+ expect(await strategy.deleteByTags([tag])).toBe(1)
178
+ expect(await admin.exists(`cache:${key}`)).toBe(0)
179
+ expect(await strategy.deleteByTags([tag])).toBe(0)
180
+ expect(await admin.scard(`tag:${tag}`)).toBe(0)
181
+ },
182
+ ))
183
+
184
+ it('can overwrite a TTL entry with a persistent tagless value', async () => fixture(
185
+ async ({ strategy, admin, key, tag }) => {
186
+ await strategy.set(key, 'old', { tags: [tag], ttl: 60_000 })
187
+ await strategy.set(key, 'persistent', { tags: [], ttl: 0 })
188
+ expect(await admin.pttl(`cache:${key}`)).toBe(-1)
189
+ expect(await strategy.deleteByTags([tag])).toBe(0)
190
+ expect(await strategy.get(key)).toBe('persistent')
191
+ expect(await admin.scard(`tag:${tag}`)).toBe(0)
192
+ },
193
+ ))
194
+
195
+ it('overwrites a non-string old value using Redis SET semantics', async () => fixture(
196
+ async ({ strategy, admin, key, tag }) => {
197
+ await admin.sadd(`cache:${key}`, 'old-non-string-value')
198
+ await strategy.set(key, 'replacement', { tags: [tag] })
199
+ expect(await admin.type(`cache:${key}`)).toBe('string')
200
+ expect(await strategy.get(key)).toBe('replacement')
201
+ expect(await strategy.deleteByTags([tag])).toBe(1)
202
+ },
203
+ ))
204
+
205
+ it('reports WRONGTYPE if a value changes type before stale membership reconciliation', async () => fixture(
206
+ async ({ strategy, admin, key, tag }) => {
207
+ await strategy.set(key, 'old', { tags: [tag] })
208
+ await strategy.set(key, 'retagged', { tags: [`${tag}:next`] })
209
+ const original = Redis.prototype.mgetBuffer
210
+ Redis.prototype.mgetBuffer = async function (this: Redis, ...keys: string[]) {
211
+ const buffers = await original.apply(this, keys)
212
+ await admin.del(`cache:${key}`)
213
+ await admin.sadd(`cache:${key}`, 'changed-type')
214
+ return buffers
215
+ } as typeof original
216
+ try {
217
+ await expect(strategy.deleteByTags([tag])).rejects.toThrow('WRONGTYPE')
218
+ expect(await admin.sismember(`tag:${tag}`, key)).toBe(1)
219
+ expect(await admin.type(`cache:${key}`)).toBe('set')
220
+ } finally {
221
+ Redis.prototype.mgetBuffer = original
222
+ }
223
+ },
224
+ ))
225
+ })
@@ -0,0 +1,41 @@
1
+ /** @jest-environment node */
2
+ import { randomUUID } from 'node:crypto'
3
+ import { createRedisStrategy } from '../strategies/redis'
4
+
5
+ const redisUrl = process.env.CACHE_REDIS_URL
6
+ const describeWithRedis = redisUrl ? describe : describe.skip
7
+
8
+ describeWithRedis('redis strategy value compression against a live Redis', () => {
9
+ const largeValue = {
10
+ items: Array.from({ length: 100 }, (_, index) => ({ id: `row-${index}`, name: `Contact ${index}`, status: 'active' })),
11
+ }
12
+ const runId = randomUUID()
13
+
14
+ it.each(['zstd', 'gzip'] as const)('round-trips %s frames and legacy JSON over the binary-safe path', async (compression) => {
15
+ const legacy = createRedisStrategy(redisUrl, { compression: 'off' })
16
+ const compressed = createRedisStrategy(redisUrl, { compression })
17
+ const legacyKey = `compression-live:${runId}:${compression}:legacy`
18
+ const compressedKey = `compression-live:${runId}:${compression}:compressed`
19
+ const tag = `compression-live:${runId}:${compression}`
20
+
21
+ try {
22
+ await legacy.set(legacyKey, largeValue, { ttl: 60_000, tags: [tag] })
23
+ await compressed.set(compressedKey, largeValue, { ttl: 60_000, tags: [tag] })
24
+
25
+ expect(await compressed.get(legacyKey)).toEqual(largeValue)
26
+ expect(await compressed.get(compressedKey)).toEqual(largeValue)
27
+ expect(await legacy.get(compressedKey)).toEqual(largeValue)
28
+ expect(await compressed.has(compressedKey)).toBe(true)
29
+
30
+ await compressed.set(compressedKey, largeValue, { ttl: 60_000, tags: [`${tag}:next`] })
31
+ expect(await compressed.deleteByTags([tag])).toBe(1)
32
+ expect(await compressed.deleteByTags([`${tag}:next`])).toBe(1)
33
+ expect(await compressed.get(compressedKey)).toBeNull()
34
+ } finally {
35
+ await legacy.delete(legacyKey)
36
+ await compressed.delete(compressedKey)
37
+ await legacy.close?.()
38
+ await compressed.close?.()
39
+ }
40
+ })
41
+ })
@@ -0,0 +1,113 @@
1
+ /** @jest-environment node */
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import Redis from 'ioredis'
4
+ import { createCacheService } from '../service'
5
+ import { createRedisStrategy } from '../strategies/redis'
6
+ import { runWithCacheTenant } from '../tenantContext'
7
+
8
+ const redisUrl = process.env.CACHE_REDIS_URL
9
+ const describeWithRedis = redisUrl ? describe : describe.skip
10
+
11
+ describeWithRedis('redis invalidation batching contracts against a live Redis', () => {
12
+ const value = {
13
+ products: Array.from({ length: 80 }, (_, index) => ({
14
+ sku: `AGRAM-FROZEN-${index}`,
15
+ product: 'Frozen vegetables, fruit and ready meals',
16
+ storage: 'Keep frozen at -18°C',
17
+ })),
18
+ }
19
+
20
+ it.each([
21
+ ['strategy', 'gzip'], ['service', 'gzip'],
22
+ ['strategy', 'off'], ['service', 'off'],
23
+ ] as const)(
24
+ '%s invalidates %s values across multiple batches while preserving unrelated data',
25
+ async (layer, compression) => {
26
+ const runId = `invalidation-live-${randomUUID()}`
27
+ const tenant = `${runId}-selected`
28
+ const otherTenant = `${runId}-other`
29
+ const tags = [`${runId}:products`, `${runId}:frozen`, `${runId}:inventory`]
30
+ const oldTag = `${runId}:previous-category`
31
+ const controlTags = layer === 'service' ? tags : [`${runId}:unrelated`]
32
+ const cache = layer === 'strategy'
33
+ ? createRedisStrategy(redisUrl, { compression })
34
+ : createCacheService({ strategy: 'redis', redisUrl, compression, defaultTtl: 60_000 })
35
+ // A separate client is used only for fixture expiry and physical-storage assertions.
36
+ const admin = new Redis(redisUrl!, { protocol: 2 })
37
+ const count = 513 // More than two 256-key batches; the service stores two physical entries per key.
38
+ const keys = Array.from({ length: count }, (_, index) => `${runId}:product:${index}`)
39
+ const orphan = `${runId}:expired-product`
40
+ const control = `${runId}:control`
41
+ const inTenant = <T>(target: string, action: () => Promise<T>): Promise<T> => (
42
+ layer === 'service' ? runWithCacheTenant(target, action) : action()
43
+ )
44
+ const digest = (input: string) => createHash('sha256').update(input).digest('hex')
45
+ const physicalKeys = (key: string) => layer === 'strategy'
46
+ ? [`cache:${key}`]
47
+ : [`cache:tenant:${tenant}:key:k:${digest(key)}`, `cache:tenant:${tenant}:key:meta:${digest(key)}`]
48
+ const physicalTag = (tag: string) => layer === 'strategy'
49
+ ? `tag:${tag}`
50
+ : `tag:tenant:${tenant}:tag:t:${digest(tag)}`
51
+
52
+ try {
53
+ await cache.healthcheck?.() // A fallback backend must not make this live test pass.
54
+ for (let offset = 0; offset < keys.length; offset += 16) {
55
+ await Promise.all(keys.slice(offset, offset + 16).map((key) => inTenant(
56
+ tenant,
57
+ () => cache.set(key, value, { ttl: 60_000, tags: [oldTag] }),
58
+ )))
59
+ }
60
+ for (let offset = 0; offset < keys.length; offset += 16) {
61
+ await Promise.all(keys.slice(offset, offset + 16).map((key) => inTenant(
62
+ tenant,
63
+ () => cache.set(key, value, { ttl: 60_000, tags }),
64
+ )))
65
+ }
66
+ await inTenant(tenant, () => cache.set(orphan, value, { ttl: 60_000, tags }))
67
+ await inTenant(otherTenant, () => cache.set(control, value, { ttl: 60_000, tags: controlTags }))
68
+
69
+ const stored = await admin.getBuffer(physicalKeys(keys[0])[0])
70
+ if (compression === 'gzip') expect(stored?.subarray(0, 2)).toEqual(Buffer.from([0x1f, 0x8b]))
71
+ else expect(JSON.parse(stored!.toString('utf8')).value).toEqual(value)
72
+ expect(await inTenant(tenant, () => cache.get(keys[count - 1]))).toEqual(value)
73
+ // A stale index is a candidate list: reaping it must preserve all current
74
+ // values, including service metadata, across more than two read batches.
75
+ expect(await admin.scard(physicalTag(oldTag))).toBe(count * (layer === 'service' ? 2 : 1))
76
+ expect(await inTenant(tenant, () => cache.deleteByTags([oldTag]))).toBe(0)
77
+ expect(await admin.scard(physicalTag(oldTag))).toBe(0)
78
+ expect((await admin.mget(...keys.flatMap(physicalKeys))).every((entry) => entry !== null)).toBe(true)
79
+ // Redis expiry removes value keys, leaving the secondary tag memberships.
80
+ await admin.del(...physicalKeys(orphan))
81
+ expect(await admin.scard(physicalTag(tags[0]))).toBe((count + 1) * (layer === 'service' ? 2 : 1))
82
+
83
+ // All three tags overlap completely. Returned counts must deduplicate
84
+ // memberships, exclude already-expired values, and normalize metadata.
85
+ expect(await inTenant(tenant, () => cache.deleteByTags(tags))).toBe(count)
86
+ expect(await inTenant(tenant, () => cache.deleteByTags(tags))).toBe(0)
87
+ expect(await inTenant(otherTenant, () => cache.get(control))).toEqual(value)
88
+ for (const tag of tags) expect(await admin.scard(physicalTag(tag))).toBe(0)
89
+
90
+ const remaining = await admin.mget(...keys.flatMap(physicalKeys))
91
+ expect(remaining.every((entry) => entry === null)).toBe(true)
92
+ expect(await inTenant(otherTenant, () => cache.deleteByTags(controlTags))).toBe(1)
93
+ } finally {
94
+ // Clean only this run's namespace, including residual indexes after a failure.
95
+ // Collect before deleting so cleanup itself does not perturb the cursor walk.
96
+ let cursor = '0'
97
+ const ownKeys = new Set<string>()
98
+ do {
99
+ const [next, page] = await admin.scan(cursor, 'MATCH', `*${runId}*`, 'COUNT', 256)
100
+ cursor = next
101
+ for (const key of page) ownKeys.add(key)
102
+ } while (cursor !== '0')
103
+ const cleanupKeys = [...ownKeys]
104
+ for (let offset = 0; offset < cleanupKeys.length; offset += 256) {
105
+ await admin.del(...cleanupKeys.slice(offset, offset + 256))
106
+ }
107
+ await admin.quit()
108
+ await cache.close?.()
109
+ }
110
+ },
111
+ 30_000,
112
+ )
113
+ })