@open-mercato/cache 0.11.1-develop.8593.1.50784dae35 → 0.11.1-develop.8665.1.2455b2503c
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 +27 -21
- package/README.md +30 -0
- package/dist/codec.js +1 -74
- package/dist/codec.js.map +2 -2
- package/dist/defaults.js +1 -6
- package/dist/defaults.js.map +2 -2
- package/dist/errors.js +1 -12
- package/dist/errors.js.map +2 -2
- package/dist/index.js.map +1 -1
- package/dist/patterns.js +1 -35
- package/dist/patterns.js.map +2 -2
- package/dist/provider.js +440 -0
- package/dist/provider.js.map +7 -0
- package/dist/redisConnection.js +2 -0
- package/dist/redisConnection.js.map +7 -0
- package/dist/service.js +320 -80
- package/dist/service.js.map +3 -3
- package/dist/strategies/jsonfile.js +1 -186
- package/dist/strategies/jsonfile.js.map +3 -3
- package/dist/strategies/memory.js +1 -196
- package/dist/strategies/memory.js.map +3 -3
- package/dist/strategies/redis.js +1 -443
- package/dist/strategies/redis.js.map +3 -3
- package/dist/strategies/sqlite.js +1 -196
- package/dist/strategies/sqlite.js.map +3 -3
- package/dist/testing/conformance.js +448 -0
- package/dist/testing/conformance.js.map +7 -0
- package/dist/testing/index.js +12 -0
- package/dist/testing/index.js.map +7 -0
- package/dist/testing/remote.js +182 -0
- package/dist/testing/remote.js.map +7 -0
- package/fixtures/build-conformance-host.mjs +58 -0
- package/fixtures/cache-provider-fixture/index.d.ts +18 -0
- package/fixtures/cache-provider-fixture/index.js +307 -0
- package/fixtures/cache-provider-fixture/package.json +25 -0
- package/fixtures/conformance-child.mjs +41 -0
- package/jest.config.cjs +3 -1
- package/package.json +10 -2
- package/src/__tests__/cache-di-contract-docs.test.ts +2 -2
- package/src/__tests__/conformance.memory-provider.test.ts +77 -0
- package/src/__tests__/provider-fixture.packed.test.ts +178 -0
- package/src/__tests__/provider.test.ts +469 -0
- package/src/__tests__/service.provider.test.ts +513 -0
- package/src/__tests__/service.test.ts +94 -3
- package/src/codec.ts +1 -94
- package/src/defaults.ts +1 -2
- package/src/errors.ts +1 -14
- package/src/index.ts +4 -0
- package/src/patterns.ts +1 -40
- package/src/provider.ts +641 -0
- package/src/redisConnection.ts +1 -0
- package/src/service.ts +396 -89
- package/src/strategies/jsonfile.ts +1 -242
- package/src/strategies/memory.ts +1 -275
- package/src/strategies/redis.ts +1 -615
- package/src/strategies/sqlite.ts +1 -292
- package/src/testing/conformance.ts +569 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/remote.ts +240 -0
- package/src/types.ts +8 -106
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
import { inspect } from 'node:util'
|
|
2
|
+
import {
|
|
3
|
+
CacheService,
|
|
4
|
+
createCacheService,
|
|
5
|
+
describeCacheSelection,
|
|
6
|
+
purgeConfiguredCachePatternsAcrossTenantScopes,
|
|
7
|
+
} from '../service'
|
|
8
|
+
import {
|
|
9
|
+
CacheProviderError,
|
|
10
|
+
defineCacheProvider,
|
|
11
|
+
defineCacheProviderRegistration,
|
|
12
|
+
prepareCacheProviderSelection,
|
|
13
|
+
resetCacheProviderSelectionForTests,
|
|
14
|
+
setCacheProviderRegistrations,
|
|
15
|
+
type CacheProviderErrorCode,
|
|
16
|
+
type CacheProviderHostContext,
|
|
17
|
+
type ResolvedCacheProvider,
|
|
18
|
+
} from '../provider'
|
|
19
|
+
import { createMemoryStrategy } from '../strategies/memory'
|
|
20
|
+
import { runWithCacheTenant } from '../tenantContext'
|
|
21
|
+
import type { CacheStrategy } from '../types'
|
|
22
|
+
|
|
23
|
+
const SECRET = 'provider-secret-token-value'
|
|
24
|
+
|
|
25
|
+
type ProviderConfig = { token: string }
|
|
26
|
+
|
|
27
|
+
type RecordingStrategy = CacheStrategy & {
|
|
28
|
+
healthcheck: jest.Mock<Promise<void>, []>
|
|
29
|
+
close: jest.Mock<Promise<void>, []>
|
|
30
|
+
setKeys: string[]
|
|
31
|
+
setTags: string[][]
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function recordingStrategy(): RecordingStrategy {
|
|
35
|
+
const base = createMemoryStrategy()
|
|
36
|
+
const setKeys: string[] = []
|
|
37
|
+
const setTags: string[][] = []
|
|
38
|
+
return {
|
|
39
|
+
...base,
|
|
40
|
+
set: async (key, value, options) => {
|
|
41
|
+
setKeys.push(key)
|
|
42
|
+
setTags.push(options?.tags ?? [])
|
|
43
|
+
return base.set(key, value, options)
|
|
44
|
+
},
|
|
45
|
+
healthcheck: jest.fn(async () => {}),
|
|
46
|
+
close: jest.fn(async () => {}),
|
|
47
|
+
setKeys,
|
|
48
|
+
setTags,
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type CreateFn = (config: ProviderConfig, context: CacheProviderHostContext) => CacheStrategy | Promise<CacheStrategy>
|
|
53
|
+
|
|
54
|
+
function resolvedProvider(create: CreateFn, placement: 'local' | 'shared' = 'shared'): ResolvedCacheProvider {
|
|
55
|
+
const definition = defineCacheProvider<ProviderConfig>({
|
|
56
|
+
id: 'acme/test',
|
|
57
|
+
settings: { safeParse: (input) => ({ success: true, data: input as ProviderConfig }) },
|
|
58
|
+
capability: () => ({ placement }),
|
|
59
|
+
create,
|
|
60
|
+
})
|
|
61
|
+
return {
|
|
62
|
+
id: 'acme/test',
|
|
63
|
+
definition: definition as ResolvedCacheProvider['definition'],
|
|
64
|
+
config: { token: SECRET },
|
|
65
|
+
placement,
|
|
66
|
+
namespace: 'deploy-1',
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function expectCode(promise: Promise<unknown>, code: CacheProviderErrorCode): Promise<CacheProviderError> {
|
|
71
|
+
try {
|
|
72
|
+
await promise
|
|
73
|
+
} catch (error) {
|
|
74
|
+
expect(error).toBeInstanceOf(CacheProviderError)
|
|
75
|
+
expect((error as CacheProviderError).code).toBe(code)
|
|
76
|
+
return error as CacheProviderError
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`expected ${code}`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function expectSyncCode(fn: () => unknown, code: CacheProviderErrorCode) {
|
|
82
|
+
try {
|
|
83
|
+
fn()
|
|
84
|
+
} catch (error) {
|
|
85
|
+
expect(error).toBeInstanceOf(CacheProviderError)
|
|
86
|
+
expect((error as CacheProviderError).code).toBe(code)
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
throw new Error(`expected ${code}`)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const flush = () => new Promise((resolve) => setImmediate(resolve))
|
|
93
|
+
|
|
94
|
+
describe('cache service provider selection', () => {
|
|
95
|
+
const originalEnv = { ...process.env }
|
|
96
|
+
|
|
97
|
+
beforeEach(() => {
|
|
98
|
+
delete process.env.CACHE_PROVIDER
|
|
99
|
+
delete process.env.CACHE_PROVIDER_NAMESPACE
|
|
100
|
+
delete process.env.CACHE_PROVIDER_CONNECT_TIMEOUT_MS
|
|
101
|
+
delete process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS
|
|
102
|
+
delete process.env.CACHE_STRATEGY
|
|
103
|
+
resetCacheProviderSelectionForTests()
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
afterEach(() => {
|
|
107
|
+
process.env = { ...originalEnv }
|
|
108
|
+
resetCacheProviderSelectionForTests()
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
describe('precedence', () => {
|
|
112
|
+
it('keeps stock selection when CACHE_PROVIDER is unset or empty', () => {
|
|
113
|
+
expect(describeCacheSelection()).toEqual({ kind: 'stock', strategy: 'memory', placement: 'local' })
|
|
114
|
+
process.env.CACHE_PROVIDER = ''
|
|
115
|
+
process.env.CACHE_STRATEGY = 'redis'
|
|
116
|
+
expect(describeCacheSelection()).toEqual({ kind: 'stock', strategy: 'redis', placement: 'shared' })
|
|
117
|
+
process.env.CACHE_STRATEGY = 'bogus'
|
|
118
|
+
expect(describeCacheSelection()).toEqual({ kind: 'stock', strategy: 'memory', placement: 'local' })
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
it('reports stock placements', () => {
|
|
122
|
+
expect(describeCacheSelection({ strategy: 'sqlite' }).placement).toBe('local')
|
|
123
|
+
expect(describeCacheSelection({ strategy: 'jsonfile' }).placement).toBe('local')
|
|
124
|
+
expect(describeCacheSelection({ strategy: 'redis' }).placement).toBe('shared')
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('rejects an explicit strategy combined with an explicit provider', () => {
|
|
128
|
+
const provider = resolvedProvider(() => recordingStrategy())
|
|
129
|
+
expectSyncCode(() => createCacheService({ strategy: 'memory', provider }), 'conflicting_selection')
|
|
130
|
+
expectSyncCode(() => describeCacheSelection({ strategy: 'memory', provider }), 'conflicting_selection')
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('lets an explicit stock strategy win over the ambient provider', async () => {
|
|
134
|
+
process.env.CACHE_PROVIDER = 'acme/test'
|
|
135
|
+
const cache = createCacheService({ strategy: 'memory' })
|
|
136
|
+
await cache.set('k', 'v')
|
|
137
|
+
expect(await cache.get('k')).toBe('v')
|
|
138
|
+
expect(describeCacheSelection({ strategy: 'memory' }).kind).toBe('stock')
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
it('uses an explicit provider', async () => {
|
|
142
|
+
const strategy = recordingStrategy()
|
|
143
|
+
const provider = resolvedProvider(() => strategy, 'local')
|
|
144
|
+
expect(describeCacheSelection({ provider })).toEqual({ kind: 'provider', id: 'acme/test', placement: 'local' })
|
|
145
|
+
const cache = createCacheService({ provider })
|
|
146
|
+
await cache.set('k', 'v')
|
|
147
|
+
expect(await cache.get('k')).toBe('v')
|
|
148
|
+
expect(strategy.setKeys).toHaveLength(1)
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it('throws not_resolved instead of substituting memory when the ambient provider is not prepared', () => {
|
|
152
|
+
process.env.CACHE_PROVIDER = 'acme/test'
|
|
153
|
+
process.env.CACHE_STRATEGY = 'memory'
|
|
154
|
+
expectSyncCode(() => createCacheService(), 'not_resolved')
|
|
155
|
+
expectSyncCode(() => new CacheService(), 'not_resolved')
|
|
156
|
+
expectSyncCode(() => describeCacheSelection(), 'not_resolved')
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
it('uses the prepared ambient provider over CACHE_STRATEGY', async () => {
|
|
160
|
+
const strategy = recordingStrategy()
|
|
161
|
+
const create = jest.fn(() => strategy)
|
|
162
|
+
process.env.CACHE_PROVIDER = 'acme/test'
|
|
163
|
+
process.env.CACHE_PROVIDER_NAMESPACE = 'deploy-1'
|
|
164
|
+
process.env.CACHE_STRATEGY = 'sqlite'
|
|
165
|
+
setCacheProviderRegistrations([
|
|
166
|
+
defineCacheProviderRegistration({
|
|
167
|
+
id: 'acme/test',
|
|
168
|
+
load: async () => resolvedProvider(create).definition,
|
|
169
|
+
settings: () => ({ token: SECRET }),
|
|
170
|
+
}),
|
|
171
|
+
])
|
|
172
|
+
await prepareCacheProviderSelection()
|
|
173
|
+
expect(describeCacheSelection()).toEqual({ kind: 'provider', id: 'acme/test', placement: 'shared' })
|
|
174
|
+
const cache = new CacheService()
|
|
175
|
+
await cache.set('k', 'v')
|
|
176
|
+
expect(await cache.get('k')).toBe('v')
|
|
177
|
+
expect(create).toHaveBeenCalledTimes(1)
|
|
178
|
+
})
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
describe('lazy strategy handle', () => {
|
|
182
|
+
it('does not create the provider strategy on construction', () => {
|
|
183
|
+
const create = jest.fn(() => recordingStrategy())
|
|
184
|
+
createCacheService({ provider: resolvedProvider(create) })
|
|
185
|
+
expect(create).not.toHaveBeenCalled()
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
it('passes a host context with namespace, ttl and codec', async () => {
|
|
189
|
+
let captured: CacheProviderHostContext | null = null
|
|
190
|
+
const cache = createCacheService({
|
|
191
|
+
provider: resolvedProvider((_config, context) => {
|
|
192
|
+
captured = context
|
|
193
|
+
return recordingStrategy()
|
|
194
|
+
}),
|
|
195
|
+
defaultTtl: 1234,
|
|
196
|
+
compression: 'gzip',
|
|
197
|
+
})
|
|
198
|
+
await cache.has('k')
|
|
199
|
+
expect(captured).not.toBeNull()
|
|
200
|
+
const context = captured as unknown as CacheProviderHostContext
|
|
201
|
+
expect(context.namespace).toBe('deploy-1')
|
|
202
|
+
expect(context.defaultTtl).toBe(1234)
|
|
203
|
+
expect(context.codec.compression).toBe('gzip')
|
|
204
|
+
expect(typeof context.helpers.encode).toBe('function')
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
it('shares one in-flight create across concurrent operations', async () => {
|
|
208
|
+
let release: (() => void) | null = null
|
|
209
|
+
const strategy = recordingStrategy()
|
|
210
|
+
const create = jest.fn(() => new Promise<CacheStrategy>((resolve) => {
|
|
211
|
+
release = () => resolve(strategy)
|
|
212
|
+
}))
|
|
213
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
214
|
+
const operations = Promise.all([cache.get('a'), cache.has('b'), cache.set('c', 1), cache.keys()])
|
|
215
|
+
await flush()
|
|
216
|
+
expect(create).toHaveBeenCalledTimes(1)
|
|
217
|
+
release!()
|
|
218
|
+
await operations
|
|
219
|
+
await cache.get('a')
|
|
220
|
+
expect(create).toHaveBeenCalledTimes(1)
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
it('times out a slow create and closes the late strategy', async () => {
|
|
224
|
+
process.env.CACHE_PROVIDER_CONNECT_TIMEOUT_MS = '20'
|
|
225
|
+
const late = recordingStrategy()
|
|
226
|
+
let release: (() => void) | null = null
|
|
227
|
+
const create = jest.fn(() => new Promise<CacheStrategy>((resolve) => {
|
|
228
|
+
release = () => resolve(late)
|
|
229
|
+
}))
|
|
230
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
231
|
+
const error = await expectCode(cache.get('k'), 'timeout')
|
|
232
|
+
expect(error.providerId).toBe('acme/test')
|
|
233
|
+
release!()
|
|
234
|
+
await flush()
|
|
235
|
+
expect(late.close).toHaveBeenCalledTimes(1)
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
it('closes a partially created strategy that lacks required methods and retries on the next operation', async () => {
|
|
239
|
+
const partialClose = jest.fn(async () => {})
|
|
240
|
+
const good = recordingStrategy()
|
|
241
|
+
const create = jest.fn<CacheStrategy, []>()
|
|
242
|
+
.mockImplementationOnce(() => ({ ...createMemoryStrategy(), close: partialClose }))
|
|
243
|
+
.mockImplementationOnce(() => good)
|
|
244
|
+
process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS = '0'
|
|
245
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
246
|
+
await expectCode(cache.get('k'), 'invalid_registration')
|
|
247
|
+
expect(partialClose).toHaveBeenCalledTimes(1)
|
|
248
|
+
await cache.set('k', 'v')
|
|
249
|
+
expect(await cache.get('k')).toBe('v')
|
|
250
|
+
expect(create).toHaveBeenCalledTimes(2)
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
it('rejects an invalid strategy and retries while its cleanup is still pending', async () => {
|
|
254
|
+
const partialClose = jest.fn(() => new Promise<void>(() => {}))
|
|
255
|
+
const create = jest.fn<CacheStrategy, []>()
|
|
256
|
+
.mockReturnValueOnce({ ...createMemoryStrategy(), close: partialClose })
|
|
257
|
+
.mockReturnValueOnce(recordingStrategy())
|
|
258
|
+
process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS = '0'
|
|
259
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
260
|
+
|
|
261
|
+
const first = expectCode(cache.get('k'), 'invalid_registration')
|
|
262
|
+
await expect(Promise.race([first, flush().then(() => 'pending')])).resolves.toBeInstanceOf(CacheProviderError)
|
|
263
|
+
expect(partialClose).toHaveBeenCalledTimes(1)
|
|
264
|
+
await cache.set('k', 'recovered')
|
|
265
|
+
await expect(cache.get('k')).resolves.toBe('recovered')
|
|
266
|
+
expect(create).toHaveBeenCalledTimes(2)
|
|
267
|
+
})
|
|
268
|
+
|
|
269
|
+
it('reports a sanitized unavailable error, never falls back to memory, and retries', async () => {
|
|
270
|
+
const good = recordingStrategy()
|
|
271
|
+
const create = jest.fn<CacheStrategy, []>()
|
|
272
|
+
.mockImplementationOnce(() => { throw new Error(`ECONNREFUSED token=${SECRET}`) })
|
|
273
|
+
.mockImplementationOnce(() => good)
|
|
274
|
+
process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS = '0'
|
|
275
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
276
|
+
const error = await expectCode(cache.set('k', 'v'), 'unavailable')
|
|
277
|
+
expect(error.message).not.toContain(SECRET)
|
|
278
|
+
expect(JSON.stringify(error)).not.toContain(SECRET)
|
|
279
|
+
expect(await cache.get('k')).toBeNull()
|
|
280
|
+
expect(create).toHaveBeenCalledTimes(2)
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
it('reuses the last init failure during the retry cooldown, then retries', async () => {
|
|
284
|
+
const now = jest.spyOn(Date, 'now').mockReturnValue(1_000_000)
|
|
285
|
+
try {
|
|
286
|
+
const good = recordingStrategy()
|
|
287
|
+
const create = jest.fn<CacheStrategy, []>()
|
|
288
|
+
.mockImplementationOnce(() => { throw new Error('ECONNREFUSED') })
|
|
289
|
+
.mockImplementationOnce(() => good)
|
|
290
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
291
|
+
const first = await expectCode(cache.get('k'), 'unavailable')
|
|
292
|
+
now.mockReturnValue(1_000_500)
|
|
293
|
+
await expect(cache.has('k')).rejects.toBe(first)
|
|
294
|
+
await expect(cache.set('k', 'v')).rejects.toBe(first)
|
|
295
|
+
expect(create).toHaveBeenCalledTimes(1)
|
|
296
|
+
now.mockReturnValue(1_001_000)
|
|
297
|
+
expect(await cache.get('k')).toBeNull()
|
|
298
|
+
expect(create).toHaveBeenCalledTimes(2)
|
|
299
|
+
} finally {
|
|
300
|
+
now.mockRestore()
|
|
301
|
+
}
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
it('honours a custom retry cooldown', async () => {
|
|
305
|
+
process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS = '5000'
|
|
306
|
+
const now = jest.spyOn(Date, 'now').mockReturnValue(2_000_000)
|
|
307
|
+
try {
|
|
308
|
+
const create = jest.fn<CacheStrategy, []>(() => { throw new Error('down') })
|
|
309
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
310
|
+
await expectCode(cache.get('k'), 'unavailable')
|
|
311
|
+
now.mockReturnValue(2_004_999)
|
|
312
|
+
await expectCode(cache.get('k'), 'unavailable')
|
|
313
|
+
expect(create).toHaveBeenCalledTimes(1)
|
|
314
|
+
now.mockReturnValue(2_005_000)
|
|
315
|
+
await expectCode(cache.get('k'), 'unavailable')
|
|
316
|
+
expect(create).toHaveBeenCalledTimes(2)
|
|
317
|
+
} finally {
|
|
318
|
+
now.mockRestore()
|
|
319
|
+
}
|
|
320
|
+
})
|
|
321
|
+
|
|
322
|
+
it('closes idempotently and only once', async () => {
|
|
323
|
+
const strategy = recordingStrategy()
|
|
324
|
+
const cache = createCacheService({ provider: resolvedProvider(() => strategy) })
|
|
325
|
+
await cache.set('k', 'v')
|
|
326
|
+
await Promise.all([cache.close?.(), cache.close?.()])
|
|
327
|
+
await cache.close?.()
|
|
328
|
+
expect(strategy.close).toHaveBeenCalledTimes(1)
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
it('rejects every operation with unavailable once closed and never reconnects', async () => {
|
|
332
|
+
const create = jest.fn(() => recordingStrategy())
|
|
333
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
334
|
+
await cache.set('k', 'v')
|
|
335
|
+
await cache.close?.()
|
|
336
|
+
const error = await expectCode(cache.get('k'), 'unavailable')
|
|
337
|
+
expect(error.message).toContain('closed')
|
|
338
|
+
await expectCode(cache.set('k', 'v'), 'unavailable')
|
|
339
|
+
await expectCode(cache.healthcheck!(), 'unavailable')
|
|
340
|
+
await expectCode(cache.cleanup!(), 'unavailable')
|
|
341
|
+
expect(create).toHaveBeenCalledTimes(1)
|
|
342
|
+
})
|
|
343
|
+
|
|
344
|
+
it('does not create a strategy just to close it', async () => {
|
|
345
|
+
const create = jest.fn(() => recordingStrategy())
|
|
346
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
347
|
+
await cache.close?.()
|
|
348
|
+
expect(create).not.toHaveBeenCalled()
|
|
349
|
+
})
|
|
350
|
+
|
|
351
|
+
it('closes a strategy whose create resolves after close was requested', async () => {
|
|
352
|
+
const strategy = recordingStrategy()
|
|
353
|
+
let release: (() => void) | null = null
|
|
354
|
+
const cache = createCacheService({
|
|
355
|
+
provider: resolvedProvider(() => new Promise<CacheStrategy>((resolve) => {
|
|
356
|
+
release = () => resolve(strategy)
|
|
357
|
+
})),
|
|
358
|
+
})
|
|
359
|
+
const pendingRead = cache.get('k')
|
|
360
|
+
await flush()
|
|
361
|
+
const closing = cache.close?.()
|
|
362
|
+
release!()
|
|
363
|
+
await closing
|
|
364
|
+
await expectCode(pendingRead, 'unavailable')
|
|
365
|
+
expect(strategy.close).toHaveBeenCalledTimes(1)
|
|
366
|
+
})
|
|
367
|
+
|
|
368
|
+
it('sanitizes runtime operation errors so provider messages never leak', async () => {
|
|
369
|
+
const leaky = new Error(`READONLY redis://user:${SECRET}@cache.internal`)
|
|
370
|
+
const strategy = recordingStrategy()
|
|
371
|
+
strategy.get = async () => { throw leaky }
|
|
372
|
+
strategy.healthcheck.mockImplementation(async () => { throw leaky })
|
|
373
|
+
strategy.close.mockImplementation(async () => { throw leaky })
|
|
374
|
+
const cache = createCacheService({ provider: resolvedProvider(() => strategy) })
|
|
375
|
+
const errors = [
|
|
376
|
+
await expectCode(cache.get('k'), 'unavailable'),
|
|
377
|
+
await expectCode(cache.healthcheck!(), 'unavailable'),
|
|
378
|
+
await expectCode(cache.close!(), 'unavailable'),
|
|
379
|
+
]
|
|
380
|
+
for (const error of errors) {
|
|
381
|
+
expect(error.providerId).toBe('acme/test')
|
|
382
|
+
expect(error.originalError).toBe(leaky)
|
|
383
|
+
expect(Object.keys(error)).not.toContain('originalError')
|
|
384
|
+
expect(error.message).not.toContain(SECRET)
|
|
385
|
+
expect(JSON.stringify(error)).not.toContain(SECRET)
|
|
386
|
+
expect(inspect(error, { depth: 10 })).not.toContain(SECRET)
|
|
387
|
+
}
|
|
388
|
+
expect(errors[0].message).toBe('Cache provider "acme/test" get failed')
|
|
389
|
+
})
|
|
390
|
+
|
|
391
|
+
it('passes real CacheProviderError instances from operations through unchanged', async () => {
|
|
392
|
+
const own = new CacheProviderError('timeout', 'Cache provider "acme/test" get timed out', { providerId: 'acme/test' })
|
|
393
|
+
const strategy = recordingStrategy()
|
|
394
|
+
strategy.get = async () => { throw own }
|
|
395
|
+
const cache = createCacheService({ provider: resolvedProvider(() => strategy) })
|
|
396
|
+
await expect(cache.get('k')).rejects.toBe(own)
|
|
397
|
+
})
|
|
398
|
+
|
|
399
|
+
it('re-wraps a create error that only looks like a CacheProviderError', async () => {
|
|
400
|
+
const lookalike = Object.assign(new Error(`invalid token ${SECRET}`), { name: 'CacheProviderError', code: 'invalid_settings' })
|
|
401
|
+
const unknownCode = Object.assign(new Error(`boom ${SECRET}`), { name: 'CacheProviderError', code: 'bogus' })
|
|
402
|
+
const create = jest.fn<CacheStrategy, []>()
|
|
403
|
+
.mockImplementationOnce(() => { throw lookalike })
|
|
404
|
+
.mockImplementationOnce(() => { throw unknownCode })
|
|
405
|
+
process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS = '0'
|
|
406
|
+
const cache = createCacheService({ provider: resolvedProvider(create) })
|
|
407
|
+
const first = await expectCode(cache.get('k'), 'invalid_settings')
|
|
408
|
+
expect(first).not.toBe(lookalike)
|
|
409
|
+
expect(first.message).not.toContain(SECRET)
|
|
410
|
+
expect(first.originalError).toBe(lookalike)
|
|
411
|
+
const second = await expectCode(cache.get('k'), 'unavailable')
|
|
412
|
+
expect(second.message).not.toContain(SECRET)
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
it('delegates healthcheck to the provider strategy', async () => {
|
|
416
|
+
const strategy = recordingStrategy()
|
|
417
|
+
const cache = createCacheService({ provider: resolvedProvider(() => strategy) })
|
|
418
|
+
await cache.healthcheck?.()
|
|
419
|
+
expect(strategy.healthcheck).toHaveBeenCalledTimes(1)
|
|
420
|
+
})
|
|
421
|
+
})
|
|
422
|
+
|
|
423
|
+
describe('tenant scoping', () => {
|
|
424
|
+
it('applies the tenant wrapper exactly once', async () => {
|
|
425
|
+
const strategy = recordingStrategy()
|
|
426
|
+
const cache = createCacheService({ provider: resolvedProvider(() => strategy) })
|
|
427
|
+
await runWithCacheTenant('tenant-a', () => cache.set('item', 'v', { tags: ['t1'] }))
|
|
428
|
+
expect(strategy.setKeys).toHaveLength(1)
|
|
429
|
+
for (const key of strategy.setKeys) {
|
|
430
|
+
expect(key.startsWith('tenant:tenant-a:key:')).toBe(true)
|
|
431
|
+
expect(key.match(/tenant:/g)).toHaveLength(1)
|
|
432
|
+
}
|
|
433
|
+
for (const tag of strategy.setTags[0]) {
|
|
434
|
+
expect(tag.startsWith('tenant:tenant-a:tag:')).toBe(true)
|
|
435
|
+
expect(tag.match(/tenant:/g)).toHaveLength(1)
|
|
436
|
+
}
|
|
437
|
+
expect(await runWithCacheTenant('tenant-b', () => cache.get('item'))).toBeNull()
|
|
438
|
+
expect(await runWithCacheTenant('tenant-a', () => cache.get('item'))).toBe('v')
|
|
439
|
+
expect(await runWithCacheTenant('tenant-a', () => cache.deleteByTags(['t1']))).toBe(1)
|
|
440
|
+
expect(await runWithCacheTenant('tenant-a', () => cache.stats())).toEqual({ size: 0, expired: 0 })
|
|
441
|
+
})
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
describe('maintenance purge', () => {
|
|
445
|
+
it('keeps a newer concurrent write discoverable when an earlier write fails', async () => {
|
|
446
|
+
const store = recordingStrategy()
|
|
447
|
+
const write = store.set
|
|
448
|
+
let rejectFirst: (error: Error) => void = () => {}
|
|
449
|
+
const firstWrite = new Promise<void>((_resolve, reject) => {
|
|
450
|
+
rejectFirst = reject
|
|
451
|
+
})
|
|
452
|
+
store.set = jest.fn(write).mockReturnValueOnce(firstWrite)
|
|
453
|
+
const provider = resolvedProvider(() => store)
|
|
454
|
+
const firstCache = createCacheService({ provider })
|
|
455
|
+
const secondCache = createCacheService({ provider })
|
|
456
|
+
const inTenant = (operation: () => Promise<unknown>) => runWithCacheTenant('t1', operation)
|
|
457
|
+
const failure = expectCode(inTenant(() => firstCache.set('nav:sidebar', 'older', { tags: ['old'] })), 'unavailable')
|
|
458
|
+
|
|
459
|
+
await flush()
|
|
460
|
+
await expect(inTenant(() => secondCache.get('nav:sidebar'))).resolves.toBeNull()
|
|
461
|
+
await expect(inTenant(() => secondCache.keys('nav:*'))).resolves.toEqual([])
|
|
462
|
+
await inTenant(() => secondCache.set('nav:sidebar', 'newer', { tags: ['new'] }))
|
|
463
|
+
rejectFirst(new Error('write failed'))
|
|
464
|
+
await failure
|
|
465
|
+
|
|
466
|
+
await expect(inTenant(() => firstCache.get('nav:sidebar'))).resolves.toBe('newer')
|
|
467
|
+
await expect(inTenant(() => firstCache.deleteByTags(['old']))).resolves.toBe(0)
|
|
468
|
+
await expect(inTenant(() => firstCache.keys('nav:*'))).resolves.toEqual(['nav:sidebar'])
|
|
469
|
+
await expect(purgeConfiguredCachePatternsAcrossTenantScopes(['nav:*'], { provider })).resolves.toBe(1)
|
|
470
|
+
await expect(inTenant(() => firstCache.get('nav:sidebar'))).resolves.toBeNull()
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
it('keeps a committed value discoverable if the provider loses the write acknowledgement', async () => {
|
|
474
|
+
const store = recordingStrategy()
|
|
475
|
+
const write = store.set
|
|
476
|
+
store.set = async (key, value, options) => {
|
|
477
|
+
await write(key, value, options)
|
|
478
|
+
throw new Error('write acknowledgement lost')
|
|
479
|
+
}
|
|
480
|
+
const provider = resolvedProvider(() => store)
|
|
481
|
+
const cache = createCacheService({ provider })
|
|
482
|
+
|
|
483
|
+
await expectCode(cache.set('nav:sidebar', 'cached', { tags: ['nav'] }), 'unavailable')
|
|
484
|
+
await expect(cache.keys('nav:*')).resolves.toEqual(['nav:sidebar'])
|
|
485
|
+
await expect(purgeConfiguredCachePatternsAcrossTenantScopes(['nav:*'], { provider })).resolves.toBe(1)
|
|
486
|
+
await expect(cache.get('nav:sidebar')).resolves.toBeNull()
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
it('purges matching keys across tenant scopes through the provider and closes it', async () => {
|
|
490
|
+
const store = recordingStrategy()
|
|
491
|
+
const cache = createCacheService({ provider: resolvedProvider(() => store) })
|
|
492
|
+
await runWithCacheTenant('t1', () => cache.set('nav:a', 1))
|
|
493
|
+
await runWithCacheTenant('t2', () => cache.set('nav:b', 2))
|
|
494
|
+
await runWithCacheTenant('t2', () => cache.set('other', 3))
|
|
495
|
+
|
|
496
|
+
const closeSpy = jest.fn(async () => {})
|
|
497
|
+
const purgeProvider = resolvedProvider(() => ({ ...store, close: closeSpy }))
|
|
498
|
+
const removed = await purgeConfiguredCachePatternsAcrossTenantScopes(['nav:*'], { provider: purgeProvider })
|
|
499
|
+
expect(removed).toBe(2)
|
|
500
|
+
expect(closeSpy).toHaveBeenCalledTimes(1)
|
|
501
|
+
expect(await runWithCacheTenant('t2', () => cache.get('other'))).toBe(3)
|
|
502
|
+
})
|
|
503
|
+
|
|
504
|
+
it('still short-circuits for stock memory', async () => {
|
|
505
|
+
expect(await purgeConfiguredCachePatternsAcrossTenantScopes(['*'], { strategy: 'memory' })).toBe(0)
|
|
506
|
+
})
|
|
507
|
+
|
|
508
|
+
it('fails instead of purging memory when the ambient provider is not prepared', async () => {
|
|
509
|
+
process.env.CACHE_PROVIDER = 'acme/test'
|
|
510
|
+
await expectCode(purgeConfiguredCachePatternsAcrossTenantScopes(['*']), 'not_resolved')
|
|
511
|
+
})
|
|
512
|
+
})
|
|
513
|
+
})
|
|
@@ -6,10 +6,12 @@ import {
|
|
|
6
6
|
import fs from 'node:fs'
|
|
7
7
|
import path from 'node:path'
|
|
8
8
|
import { DEFAULT_JSON_FILE_CACHE_PATH, DEFAULT_SQLITE_CACHE_PATH } from '../defaults'
|
|
9
|
-
import type { CacheStrategy } from '../types'
|
|
9
|
+
import type { CacheServiceOptions, CacheStrategy } from '../types'
|
|
10
10
|
import { runWithCacheTenant } from '../tenantContext'
|
|
11
|
-
import * as memoryStrategyModule from '
|
|
12
|
-
import * as sqliteStrategyModule from '
|
|
11
|
+
import * as memoryStrategyModule from '@open-mercato/cache-provider-memory'
|
|
12
|
+
import * as sqliteStrategyModule from '@open-mercato/cache-provider-sqlite'
|
|
13
|
+
import * as redisStrategyModule from '@open-mercato/cache-provider-redis-legacy'
|
|
14
|
+
import * as jsonFileStrategyModule from '@open-mercato/cache-provider-jsonfile'
|
|
13
15
|
|
|
14
16
|
describe('Cache Service', () => {
|
|
15
17
|
afterEach(() => {
|
|
@@ -452,3 +454,92 @@ describe('Cache Service compression resolution (CACHE_COMPRESSION)', () => {
|
|
|
452
454
|
expect(spy.mock.calls[0][1]).toMatchObject({ compression: 'off', compressionMinBytes: undefined })
|
|
453
455
|
})
|
|
454
456
|
})
|
|
457
|
+
|
|
458
|
+
describe('Cache Service stock selection characterization', () => {
|
|
459
|
+
const originalStrategy = process.env.CACHE_STRATEGY
|
|
460
|
+
const createRealMemoryStrategy = memoryStrategyModule.createMemoryStrategy
|
|
461
|
+
|
|
462
|
+
afterEach(() => {
|
|
463
|
+
if (originalStrategy === undefined) delete process.env.CACHE_STRATEGY
|
|
464
|
+
else process.env.CACHE_STRATEGY = originalStrategy
|
|
465
|
+
jest.restoreAllMocks()
|
|
466
|
+
})
|
|
467
|
+
|
|
468
|
+
const spyOnStockFactories = () => {
|
|
469
|
+
const memory = jest.spyOn(memoryStrategyModule, 'createMemoryStrategy')
|
|
470
|
+
const sqlite = jest
|
|
471
|
+
.spyOn(sqliteStrategyModule, 'createSqliteStrategy')
|
|
472
|
+
.mockImplementation(() => createRealMemoryStrategy())
|
|
473
|
+
const redis = jest
|
|
474
|
+
.spyOn(redisStrategyModule, 'createRedisStrategy')
|
|
475
|
+
.mockImplementation(() => createRealMemoryStrategy())
|
|
476
|
+
const jsonfile = jest
|
|
477
|
+
.spyOn(jsonFileStrategyModule, 'createJsonFileStrategy')
|
|
478
|
+
.mockImplementation(() => createRealMemoryStrategy())
|
|
479
|
+
return { memory, sqlite, redis, jsonfile }
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
it('falls back to the memory strategy for an unknown CACHE_STRATEGY value', async () => {
|
|
483
|
+
process.env.CACHE_STRATEGY = 'memcached-characterization'
|
|
484
|
+
const factories = spyOnStockFactories()
|
|
485
|
+
|
|
486
|
+
const cache = createCacheService()
|
|
487
|
+
await cache.set('unknown-strategy', 'value')
|
|
488
|
+
|
|
489
|
+
expect(factories.memory).toHaveBeenCalledTimes(1)
|
|
490
|
+
expect(factories.sqlite).not.toHaveBeenCalled()
|
|
491
|
+
expect(factories.redis).not.toHaveBeenCalled()
|
|
492
|
+
expect(factories.jsonfile).not.toHaveBeenCalled()
|
|
493
|
+
await expect(cache.get('unknown-strategy')).resolves.toBe('value')
|
|
494
|
+
})
|
|
495
|
+
|
|
496
|
+
it.each(['constructor', '__proto__'])('keeps the memory fallback for an unknown JS strategy %s', async (strategy) => {
|
|
497
|
+
const cache = createCacheService({ strategy: strategy as CacheServiceOptions['strategy'] })
|
|
498
|
+
await cache.set('unknown-strategy', 'value')
|
|
499
|
+
await expect(cache.get('unknown-strategy')).resolves.toBe('value')
|
|
500
|
+
})
|
|
501
|
+
|
|
502
|
+
it('lets an explicit options.strategy win over CACHE_STRATEGY', () => {
|
|
503
|
+
process.env.CACHE_STRATEGY = 'sqlite'
|
|
504
|
+
const factories = spyOnStockFactories()
|
|
505
|
+
|
|
506
|
+
createCacheService({ strategy: 'memory' })
|
|
507
|
+
|
|
508
|
+
expect(factories.memory).toHaveBeenCalledTimes(1)
|
|
509
|
+
expect(factories.sqlite).not.toHaveBeenCalled()
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
it('uses CACHE_STRATEGY when no explicit strategy is passed', () => {
|
|
513
|
+
process.env.CACHE_STRATEGY = 'redis'
|
|
514
|
+
const factories = spyOnStockFactories()
|
|
515
|
+
|
|
516
|
+
createCacheService()
|
|
517
|
+
|
|
518
|
+
expect(factories.redis).toHaveBeenCalledTimes(1)
|
|
519
|
+
expect(factories.memory).not.toHaveBeenCalled()
|
|
520
|
+
})
|
|
521
|
+
|
|
522
|
+
it('returns 0 and constructs no strategy when purging an env-default memory cache', async () => {
|
|
523
|
+
delete process.env.CACHE_STRATEGY
|
|
524
|
+
const factories = spyOnStockFactories()
|
|
525
|
+
|
|
526
|
+
await expect(purgeConfiguredCachePatternsAcrossTenantScopes(['nav:*'])).resolves.toBe(0)
|
|
527
|
+
|
|
528
|
+
expect(factories.memory).not.toHaveBeenCalled()
|
|
529
|
+
expect(factories.sqlite).not.toHaveBeenCalled()
|
|
530
|
+
expect(factories.redis).not.toHaveBeenCalled()
|
|
531
|
+
expect(factories.jsonfile).not.toHaveBeenCalled()
|
|
532
|
+
})
|
|
533
|
+
|
|
534
|
+
it('returns 0 and constructs no strategy when purging with an unknown CACHE_STRATEGY', async () => {
|
|
535
|
+
process.env.CACHE_STRATEGY = 'memcached-characterization'
|
|
536
|
+
const factories = spyOnStockFactories()
|
|
537
|
+
|
|
538
|
+
await expect(purgeConfiguredCachePatternsAcrossTenantScopes(['nav:*'])).resolves.toBe(0)
|
|
539
|
+
|
|
540
|
+
expect(factories.memory).not.toHaveBeenCalled()
|
|
541
|
+
expect(factories.sqlite).not.toHaveBeenCalled()
|
|
542
|
+
expect(factories.redis).not.toHaveBeenCalled()
|
|
543
|
+
expect(factories.jsonfile).not.toHaveBeenCalled()
|
|
544
|
+
})
|
|
545
|
+
})
|