@open-mercato/cache 0.10.1-develop.8182.1.0acd6a564c → 0.10.1-develop.8191.1.2563ac3bfc
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/dist/strategies/redis.js +148 -62
- package/dist/strategies/redis.js.map +3 -3
- package/package.json +1 -1
- package/src/__tests__/redis.compatibility.live.test.ts +225 -0
- package/src/__tests__/redis.performance.live.test.ts +113 -0
- package/src/__tests__/redis.strategy.test.ts +595 -39
- package/src/strategies/redis.ts +186 -100
|
@@ -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,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
|
+
})
|