@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
package/src/service.ts
CHANGED
|
@@ -9,6 +9,14 @@ import { CacheDependencyUnavailableError } from './errors'
|
|
|
9
9
|
import { matchCacheKeyPattern } from './patterns'
|
|
10
10
|
import { parseCacheCompression, parseCacheCompressionMinBytes } from './codec'
|
|
11
11
|
import type { CacheCodecOptions } from './codec'
|
|
12
|
+
import type { CacheProviderHostContext, CacheProviderPlacement, ResolvedCacheProvider } from './provider'
|
|
13
|
+
import {
|
|
14
|
+
CacheProviderError,
|
|
15
|
+
createCacheProviderHostContext,
|
|
16
|
+
getPreparedCacheProvider,
|
|
17
|
+
readSelectedCacheProviderId,
|
|
18
|
+
toSanitizedCacheProviderError,
|
|
19
|
+
} from './provider'
|
|
12
20
|
|
|
13
21
|
function normalizeTenantKey(raw: string | null | undefined): string {
|
|
14
22
|
const value = typeof raw === 'string' ? raw.trim() : ''
|
|
@@ -41,9 +49,13 @@ function isCacheMetadata(value: CacheValue | null): value is CacheMetadata {
|
|
|
41
49
|
return hasValidKey && hasValidExpiresAt
|
|
42
50
|
}
|
|
43
51
|
|
|
52
|
+
type CacheProviderEntry = CacheMetadata & { value: CacheValue }
|
|
53
|
+
type CacheRecordLayout =
|
|
54
|
+
| { kind: 'stock'; reportsBoundedCounters: boolean }
|
|
55
|
+
| { kind: 'provider'; defaultTtl?: number }
|
|
56
|
+
|
|
44
57
|
type CacheStrategyName = NonNullable<CacheServiceOptions['strategy']>
|
|
45
|
-
const
|
|
46
|
-
const TENANT_META_KEY_PATTERN = 'tenant:*:key:meta:*'
|
|
58
|
+
const PROVIDER_ENTRY_PREFIX = 'entry:v1:'
|
|
47
59
|
const TENANT_META_KEY_MARKER = ':key:meta:'
|
|
48
60
|
|
|
49
61
|
type TenantAwareCacheStrategy = CacheStrategy & {
|
|
@@ -52,7 +64,7 @@ type TenantAwareCacheStrategy = CacheStrategy & {
|
|
|
52
64
|
|
|
53
65
|
function isCacheStrategyName(value: string | undefined): value is CacheStrategyName {
|
|
54
66
|
if (!value) return false
|
|
55
|
-
return
|
|
67
|
+
return Object.hasOwn(stockProviderFactories, value)
|
|
56
68
|
}
|
|
57
69
|
|
|
58
70
|
function resolveConfiguredStrategyType(options?: CacheServiceOptions): CacheStrategyName {
|
|
@@ -80,10 +92,27 @@ function storageKey(originalKey: string, prefixes: TenantPrefixes): string {
|
|
|
80
92
|
return `${prefixes.keyPrefix}k:${hashIdentifier(originalKey)}`
|
|
81
93
|
}
|
|
82
94
|
|
|
95
|
+
function providerEntryKey(originalKey: string, keyPrefix: string): string {
|
|
96
|
+
return `${keyPrefix}${PROVIDER_ENTRY_PREFIX}${hashIdentifier(originalKey)}`
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function isCacheProviderEntry(value: CacheValue | null): value is CacheProviderEntry {
|
|
100
|
+
return isCacheMetadata(value) && Object.hasOwn(value, 'value')
|
|
101
|
+
}
|
|
102
|
+
|
|
83
103
|
function metaKey(originalKey: string, prefixes: TenantPrefixes): string {
|
|
84
104
|
return `${prefixes.keyPrefix}meta:${hashIdentifier(originalKey)}`
|
|
85
105
|
}
|
|
86
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Physical key under which the tenant-aware wrapper stores a logical key's value
|
|
109
|
+
* record. Providers receive these already-scoped keys; exposed so provider
|
|
110
|
+
* conformance tooling can target a specific record without copying the layout.
|
|
111
|
+
*/
|
|
112
|
+
export function resolvePhysicalCacheValueKey(originalKey: string, tenantId: string | null): string {
|
|
113
|
+
return providerEntryKey(originalKey, `tenant:${normalizeTenantKey(tenantId)}:key:`)
|
|
114
|
+
}
|
|
115
|
+
|
|
87
116
|
function hashedTag(tag: string, prefixes: TenantPrefixes): string {
|
|
88
117
|
return `${prefixes.tagPrefix}t:${hashIdentifier(tag)}`
|
|
89
118
|
}
|
|
@@ -99,42 +128,59 @@ function buildTagSet(tags: string[] | undefined, prefixes: TenantPrefixes, inclu
|
|
|
99
128
|
return Array.from(scoped)
|
|
100
129
|
}
|
|
101
130
|
|
|
102
|
-
function createTenantAwareWrapper(base: CacheStrategy,
|
|
131
|
+
function createTenantAwareWrapper(base: CacheStrategy, layout: CacheRecordLayout): TenantAwareCacheStrategy {
|
|
132
|
+
const recordPrefix = layout.kind === 'provider' ? PROVIDER_ENTRY_PREFIX : 'meta:'
|
|
133
|
+
|
|
134
|
+
function valueKey(key: string, prefixes: TenantPrefixes) {
|
|
135
|
+
return layout.kind === 'provider' ? providerEntryKey(key, prefixes.keyPrefix) : storageKey(key, prefixes)
|
|
136
|
+
}
|
|
137
|
+
|
|
103
138
|
function normalizeDeletionCount(raw: number): number {
|
|
104
|
-
if (!raw) return raw
|
|
105
|
-
if (!Number.isFinite(raw)) return raw
|
|
139
|
+
if (layout.kind === 'provider' || !raw || !Number.isFinite(raw)) return raw
|
|
106
140
|
return Math.ceil(raw / 2)
|
|
107
141
|
}
|
|
108
142
|
|
|
143
|
+
async function* scanRecords(keyPrefix: string) {
|
|
144
|
+
for (const physicalKey of await base.keys(`${keyPrefix}${recordPrefix}*`)) {
|
|
145
|
+
const record = await base.get(physicalKey, { returnExpired: true })
|
|
146
|
+
if (layout.kind === 'stock' && typeof record === 'string') {
|
|
147
|
+
yield { physicalKey, key: record, expiresAt: null }
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
if (!isCacheMetadata(record) || (layout.kind === 'provider' && !isCacheProviderEntry(record))) continue
|
|
151
|
+
yield { physicalKey, key: record.key, expiresAt: record.expiresAt ?? null }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
109
155
|
const get = async (key: string, options?: CacheGetOptions) => {
|
|
110
|
-
const
|
|
111
|
-
|
|
156
|
+
const record = await base.get(valueKey(key, resolveTenantPrefixes()), options)
|
|
157
|
+
if (layout.kind === 'stock') return record
|
|
158
|
+
return isCacheProviderEntry(record) ? record.value : null
|
|
112
159
|
}
|
|
113
160
|
|
|
114
161
|
const set = async (key: string, value: CacheValue, options?: CacheSetOptions) => {
|
|
115
162
|
const prefixes = resolveTenantPrefixes()
|
|
116
|
-
const
|
|
163
|
+
const tags = buildTagSet(options?.tags, prefixes, true)
|
|
164
|
+
const nextOptions: CacheSetOptions = { ...options, tags }
|
|
165
|
+
if (layout.kind === 'provider') {
|
|
166
|
+
const ttl = options?.ttl ?? layout.defaultTtl
|
|
167
|
+
const entry: CacheProviderEntry = { key, value, expiresAt: ttl && ttl > 0 ? Date.now() + ttl : null }
|
|
168
|
+
await base.set(valueKey(key, prefixes), entry, nextOptions)
|
|
169
|
+
return
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
await base.set(valueKey(key, prefixes), value, nextOptions)
|
|
117
173
|
const ttl = options?.ttl ?? undefined
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
: { tags: hashedTags }
|
|
121
|
-
await base.set(storageKey(key, prefixes), value, nextOptions)
|
|
122
|
-
const metaPayload: CacheMetadata = { key, expiresAt: ttl ? Date.now() + ttl : null }
|
|
123
|
-
await base.set(metaKey(key, prefixes), metaPayload, {
|
|
124
|
-
ttl,
|
|
125
|
-
tags: hashedTags,
|
|
126
|
-
})
|
|
174
|
+
const metadata: CacheMetadata = { key, expiresAt: ttl ? Date.now() + ttl : null }
|
|
175
|
+
await base.set(metaKey(key, prefixes), metadata, { ttl, tags })
|
|
127
176
|
}
|
|
128
177
|
|
|
129
|
-
const has = async (key: string) =>
|
|
130
|
-
const prefixes = resolveTenantPrefixes()
|
|
131
|
-
return base.has(storageKey(key, prefixes))
|
|
132
|
-
}
|
|
178
|
+
const has = async (key: string) => base.has(valueKey(key, resolveTenantPrefixes()))
|
|
133
179
|
|
|
134
180
|
const del = async (key: string) => {
|
|
135
181
|
const prefixes = resolveTenantPrefixes()
|
|
136
|
-
const primary = await base.delete(
|
|
137
|
-
await base.delete(metaKey(key, prefixes))
|
|
182
|
+
const primary = await base.delete(valueKey(key, prefixes))
|
|
183
|
+
if (layout.kind === 'stock') await base.delete(metaKey(key, prefixes))
|
|
138
184
|
return primary
|
|
139
185
|
}
|
|
140
186
|
|
|
@@ -153,18 +199,11 @@ function createTenantAwareWrapper(base: CacheStrategy, reportsBoundedCounters: b
|
|
|
153
199
|
}
|
|
154
200
|
|
|
155
201
|
const keys = async (pattern?: string) => {
|
|
156
|
-
const prefixes = resolveTenantPrefixes()
|
|
157
|
-
const metaPattern = `${prefixes.keyPrefix}meta:*`
|
|
158
|
-
const metaKeys = await base.keys(metaPattern)
|
|
159
202
|
const originals: string[] = []
|
|
160
|
-
for (const
|
|
161
|
-
|
|
162
|
-
if (!
|
|
163
|
-
|
|
164
|
-
const original = typeof metaValue === 'string' ? metaValue : metadata?.key
|
|
165
|
-
if (!original) continue
|
|
166
|
-
if (pattern && !matchCacheKeyPattern(original, pattern)) continue
|
|
167
|
-
originals.push(original)
|
|
203
|
+
for await (const { key } of scanRecords(resolveTenantPrefixes().keyPrefix)) {
|
|
204
|
+
if (layout.kind === 'stock' && !key) continue
|
|
205
|
+
if (pattern && !matchCacheKeyPattern(key, pattern)) continue
|
|
206
|
+
originals.push(key)
|
|
168
207
|
}
|
|
169
208
|
return originals
|
|
170
209
|
}
|
|
@@ -173,51 +212,34 @@ function createTenantAwareWrapper(base: CacheStrategy, reportsBoundedCounters: b
|
|
|
173
212
|
const normalizedPatterns = Array.from(new Set(patterns.map((pattern) => pattern.trim()).filter(Boolean)))
|
|
174
213
|
if (normalizedPatterns.length === 0) return 0
|
|
175
214
|
|
|
176
|
-
const metaKeys = await base.keys(TENANT_META_KEY_PATTERN)
|
|
177
215
|
let deleted = 0
|
|
178
|
-
for (const
|
|
179
|
-
|
|
180
|
-
if (!
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
: (isCacheMetadata(metadataValue) ? metadataValue : null)
|
|
184
|
-
const originalKey = typeof metadataValue === 'string' ? metadataValue : metadata?.key
|
|
185
|
-
if (!originalKey || !normalizedPatterns.some((pattern) => matchCacheKeyPattern(originalKey, pattern))) {
|
|
216
|
+
for await (const { physicalKey, key } of scanRecords('tenant:*:key:')) {
|
|
217
|
+
if (layout.kind === 'stock' && !key) continue
|
|
218
|
+
if (!normalizedPatterns.some((pattern) => matchCacheKeyPattern(key, pattern))) continue
|
|
219
|
+
if (layout.kind === 'provider') {
|
|
220
|
+
if (await base.delete(physicalKey)) deleted += 1
|
|
186
221
|
continue
|
|
187
222
|
}
|
|
188
223
|
|
|
189
|
-
const markerIndex =
|
|
224
|
+
const markerIndex = physicalKey.lastIndexOf(TENANT_META_KEY_MARKER)
|
|
190
225
|
if (markerIndex < 0) continue
|
|
191
|
-
const primaryKey = `${
|
|
226
|
+
const primaryKey = `${physicalKey.slice(0, markerIndex)}:key:k:${physicalKey.slice(markerIndex + TENANT_META_KEY_MARKER.length)}`
|
|
192
227
|
if (await base.delete(primaryKey)) deleted += 1
|
|
193
|
-
await base.delete(
|
|
228
|
+
await base.delete(physicalKey)
|
|
194
229
|
}
|
|
195
230
|
return deleted
|
|
196
231
|
}
|
|
197
232
|
|
|
198
233
|
const stats = async () => {
|
|
199
|
-
const prefixes = resolveTenantPrefixes()
|
|
200
|
-
const metaKeys = await base.keys(`${prefixes.keyPrefix}meta:*`)
|
|
201
234
|
let size = 0
|
|
202
235
|
let expired = 0
|
|
203
236
|
const now = Date.now()
|
|
204
|
-
for (const
|
|
205
|
-
|
|
206
|
-
if (!metaValue) continue
|
|
207
|
-
const metadata = typeof metaValue === 'string' ? null : (isCacheMetadata(metaValue) ? metaValue : null)
|
|
208
|
-
const original = typeof metaValue === 'string' ? metaValue : metadata?.key
|
|
209
|
-
if (!original) continue
|
|
237
|
+
for await (const { key, expiresAt } of scanRecords(resolveTenantPrefixes().keyPrefix)) {
|
|
238
|
+
if (layout.kind === 'stock' && !key) continue
|
|
210
239
|
size++
|
|
211
|
-
const expiresAt = metadata?.expiresAt ?? null
|
|
212
240
|
if (expiresAt !== null && expiresAt <= now) expired++
|
|
213
241
|
}
|
|
214
|
-
|
|
215
|
-
// Only memory-backed strategies track the process-global bound counters, so
|
|
216
|
-
// skip the extra base.stats() round-trip for redis/sqlite/jsonfile and omit
|
|
217
|
-
// the optional fields (the stats() contract marks them optional). Keyed off
|
|
218
|
-
// the configured strategy: a backend degraded to the memory fallback
|
|
219
|
-
// intentionally does not surface these diagnostics.
|
|
220
|
-
if (!reportsBoundedCounters) {
|
|
242
|
+
if (layout.kind !== 'stock' || !layout.reportsBoundedCounters) {
|
|
221
243
|
return { size, expired }
|
|
222
244
|
}
|
|
223
245
|
const { evictions, sweeps, lastSweepReclaimed } = await base.stats()
|
|
@@ -251,27 +273,310 @@ function createTenantAwareWrapper(base: CacheStrategy, reportsBoundedCounters: b
|
|
|
251
273
|
}
|
|
252
274
|
}
|
|
253
275
|
|
|
254
|
-
|
|
255
|
-
|
|
276
|
+
export type CacheSelection =
|
|
277
|
+
| { kind: 'stock'; strategy: CacheStrategyName; placement: CacheProviderPlacement }
|
|
278
|
+
| { kind: 'provider'; id: string; placement: CacheProviderPlacement }
|
|
279
|
+
|
|
280
|
+
type EffectiveCacheSelection =
|
|
281
|
+
| { kind: 'stock'; strategy: CacheStrategyName }
|
|
282
|
+
| { kind: 'provider'; provider: ResolvedCacheProvider }
|
|
283
|
+
|
|
284
|
+
const DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS = 10_000
|
|
285
|
+
const DEFAULT_PROVIDER_RETRY_COOLDOWN_MS = 1_000
|
|
286
|
+
const REQUIRED_PROVIDER_STRATEGY_METHODS = [
|
|
287
|
+
'get',
|
|
288
|
+
'set',
|
|
289
|
+
'has',
|
|
290
|
+
'delete',
|
|
291
|
+
'deleteByTags',
|
|
292
|
+
'clear',
|
|
293
|
+
'keys',
|
|
294
|
+
'stats',
|
|
295
|
+
'healthcheck',
|
|
296
|
+
'close',
|
|
297
|
+
] as const
|
|
298
|
+
|
|
299
|
+
type ProviderStrategy = CacheStrategy & {
|
|
300
|
+
healthcheck(): Promise<void>
|
|
301
|
+
close(): Promise<void>
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function resolveEffectiveSelection(options?: CacheServiceOptions): EffectiveCacheSelection {
|
|
305
|
+
if (options?.strategy && options?.provider) {
|
|
306
|
+
throw new CacheProviderError(
|
|
307
|
+
'conflicting_selection',
|
|
308
|
+
'Cache service options must not combine an explicit stock strategy with an explicit cache provider',
|
|
309
|
+
{ providerId: options.provider.id },
|
|
310
|
+
)
|
|
311
|
+
}
|
|
312
|
+
if (options?.strategy) return { kind: 'stock', strategy: resolveConfiguredStrategyType(options) }
|
|
313
|
+
if (options?.provider) return { kind: 'provider', provider: options.provider }
|
|
314
|
+
if (readSelectedCacheProviderId(process.env)) {
|
|
315
|
+
const prepared = getPreparedCacheProvider(process.env)
|
|
316
|
+
if (prepared) return { kind: 'provider', provider: prepared }
|
|
317
|
+
}
|
|
318
|
+
return { kind: 'stock', strategy: resolveConfiguredStrategyType(options) }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Describe the effective cache selection (stock strategy or registered provider)
|
|
323
|
+
* without constructing a backend. Throws a `CacheProviderError` when a provider
|
|
324
|
+
* is selected but invalid or not yet prepared.
|
|
325
|
+
*/
|
|
326
|
+
export function describeCacheSelection(options?: CacheServiceOptions): CacheSelection {
|
|
327
|
+
const selection = resolveEffectiveSelection(options)
|
|
328
|
+
if (selection.kind === 'provider') {
|
|
329
|
+
return { kind: 'provider', id: selection.provider.id, placement: selection.provider.placement }
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
kind: 'stock',
|
|
333
|
+
strategy: selection.strategy,
|
|
334
|
+
placement: selection.strategy === 'redis' ? 'shared' : 'local',
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function resolveProviderConnectTimeoutMs(): number {
|
|
339
|
+
const raw = process.env.CACHE_PROVIDER_CONNECT_TIMEOUT_MS
|
|
340
|
+
const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN
|
|
341
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function resolveProviderRetryCooldownMs(): number {
|
|
345
|
+
const raw = process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS
|
|
346
|
+
const parsed = raw !== undefined && raw.trim().length > 0 ? Number(raw) : Number.NaN
|
|
347
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_PROVIDER_RETRY_COOLDOWN_MS
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function isProviderStrategy(value: unknown): value is ProviderStrategy {
|
|
351
|
+
if (typeof value !== 'object' || value === null) return false
|
|
352
|
+
const record = value as Record<string, unknown>
|
|
353
|
+
return REQUIRED_PROVIDER_STRATEGY_METHODS.every((method) => typeof record[method] === 'function')
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function closeQuietly(value: unknown): Promise<void> {
|
|
357
|
+
if (typeof value !== 'object' || value === null) return
|
|
358
|
+
try {
|
|
359
|
+
const close = (value as { close?: unknown }).close
|
|
360
|
+
if (typeof close === 'function') await close.call(value)
|
|
361
|
+
} catch {
|
|
362
|
+
return
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function connectProviderStrategy(
|
|
367
|
+
provider: ResolvedCacheProvider,
|
|
368
|
+
context: CacheProviderHostContext,
|
|
369
|
+
timeoutMs: number,
|
|
370
|
+
): Promise<ProviderStrategy> {
|
|
371
|
+
return new Promise<ProviderStrategy>((resolve, reject) => {
|
|
372
|
+
let settled = false
|
|
373
|
+
const timer = setTimeout(() => {
|
|
374
|
+
if (settled) return
|
|
375
|
+
settled = true
|
|
376
|
+
reject(new CacheProviderError(
|
|
377
|
+
'timeout',
|
|
378
|
+
`Cache provider "${provider.id}" did not initialize within ${timeoutMs}ms`,
|
|
379
|
+
{ providerId: provider.id },
|
|
380
|
+
))
|
|
381
|
+
}, timeoutMs)
|
|
382
|
+
if (typeof timer === 'object' && typeof timer.unref === 'function') timer.unref()
|
|
383
|
+
|
|
384
|
+
Promise.resolve()
|
|
385
|
+
.then(() => provider.definition.create(provider.config, context))
|
|
386
|
+
.then(
|
|
387
|
+
(strategy) => {
|
|
388
|
+
if (settled) {
|
|
389
|
+
void closeQuietly(strategy)
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
clearTimeout(timer)
|
|
393
|
+
settled = true
|
|
394
|
+
try {
|
|
395
|
+
if (!isProviderStrategy(strategy)) {
|
|
396
|
+
throw new CacheProviderError(
|
|
397
|
+
'invalid_registration',
|
|
398
|
+
`Cache provider "${provider.id}" create() must return a cache strategy implementing ${REQUIRED_PROVIDER_STRATEGY_METHODS.join(', ')}`,
|
|
399
|
+
{ providerId: provider.id },
|
|
400
|
+
)
|
|
401
|
+
}
|
|
402
|
+
resolve(strategy)
|
|
403
|
+
} catch (error) {
|
|
404
|
+
void closeQuietly(strategy)
|
|
405
|
+
reject(toSanitizedCacheProviderError(error, {
|
|
406
|
+
message: `Cache provider "${provider.id}" failed to initialize`,
|
|
407
|
+
providerId: provider.id,
|
|
408
|
+
}))
|
|
409
|
+
}
|
|
410
|
+
},
|
|
411
|
+
(error: unknown) => {
|
|
412
|
+
if (settled) return
|
|
413
|
+
clearTimeout(timer)
|
|
414
|
+
settled = true
|
|
415
|
+
reject(toSanitizedCacheProviderError(error, {
|
|
416
|
+
message: `Cache provider "${provider.id}" failed to initialize`,
|
|
417
|
+
providerId: provider.id,
|
|
418
|
+
}))
|
|
419
|
+
},
|
|
420
|
+
)
|
|
421
|
+
})
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
type ProviderOperation = 'get' | 'set' | 'has' | 'delete' | 'deleteByTags' | 'clear' | 'keys' | 'stats' | 'healthcheck' | 'cleanup' | 'close'
|
|
425
|
+
|
|
426
|
+
function createLazyProviderStrategy(
|
|
427
|
+
provider: ResolvedCacheProvider,
|
|
428
|
+
context: CacheProviderHostContext,
|
|
429
|
+
timeoutMs: number,
|
|
430
|
+
retryCooldownMs: number,
|
|
431
|
+
): ProviderStrategy {
|
|
432
|
+
let active: ProviderStrategy | null = null
|
|
433
|
+
let pending: Promise<ProviderStrategy> | null = null
|
|
434
|
+
let closing: Promise<void> | null = null
|
|
435
|
+
let closed = false
|
|
436
|
+
let lastFailure: { error: CacheProviderError; at: number } | null = null
|
|
437
|
+
let generation = 0
|
|
438
|
+
|
|
439
|
+
const sanitize = (error: unknown, operation: ProviderOperation): CacheProviderError =>
|
|
440
|
+
toSanitizedCacheProviderError(error, {
|
|
441
|
+
message: `Cache provider "${provider.id}" ${operation} failed`,
|
|
442
|
+
providerId: provider.id,
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
const ensure = async (operation: ProviderOperation): Promise<ProviderStrategy> => {
|
|
446
|
+
if (closed) {
|
|
447
|
+
throw new CacheProviderError('unavailable', `Cache provider "${provider.id}" is closed`, { providerId: provider.id })
|
|
448
|
+
}
|
|
449
|
+
if (active) return active
|
|
450
|
+
if (!pending) {
|
|
451
|
+
if (lastFailure && Date.now() - lastFailure.at < retryCooldownMs) throw lastFailure.error
|
|
452
|
+
const attemptGeneration = generation
|
|
453
|
+
const attempt: Promise<ProviderStrategy> = connectProviderStrategy(provider, context, timeoutMs).then(
|
|
454
|
+
async (strategy) => {
|
|
455
|
+
if (attemptGeneration !== generation) {
|
|
456
|
+
await closeQuietly(strategy)
|
|
457
|
+
throw new CacheProviderError('unavailable', `Cache provider "${provider.id}" was closed during initialization`, { providerId: provider.id })
|
|
458
|
+
}
|
|
459
|
+
active = strategy
|
|
460
|
+
lastFailure = null
|
|
461
|
+
if (pending === attempt) pending = null
|
|
462
|
+
return strategy
|
|
463
|
+
},
|
|
464
|
+
(error: unknown) => {
|
|
465
|
+
if (pending === attempt) pending = null
|
|
466
|
+
if (attemptGeneration === generation) {
|
|
467
|
+
lastFailure = { error: sanitize(error, operation), at: Date.now() }
|
|
468
|
+
}
|
|
469
|
+
throw error
|
|
470
|
+
},
|
|
471
|
+
)
|
|
472
|
+
pending = attempt
|
|
473
|
+
}
|
|
474
|
+
try {
|
|
475
|
+
return await pending
|
|
476
|
+
} catch (error) {
|
|
477
|
+
throw sanitize(error, operation)
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const run = async <T>(operation: ProviderOperation, call: (strategy: ProviderStrategy) => Promise<T> | T): Promise<T> => {
|
|
482
|
+
const strategy = await ensure(operation)
|
|
483
|
+
try {
|
|
484
|
+
return await call(strategy)
|
|
485
|
+
} catch (error) {
|
|
486
|
+
throw sanitize(error, operation)
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const close = async (): Promise<void> => {
|
|
491
|
+
if (!closing) {
|
|
492
|
+
const current = active
|
|
493
|
+
const inflight = pending
|
|
494
|
+
closed = true
|
|
495
|
+
active = null
|
|
496
|
+
pending = null
|
|
497
|
+
lastFailure = null
|
|
498
|
+
generation += 1
|
|
499
|
+
closing = (async () => {
|
|
500
|
+
if (inflight) await inflight.catch(() => undefined)
|
|
501
|
+
if (current) {
|
|
502
|
+
try {
|
|
503
|
+
await current.close()
|
|
504
|
+
} catch (error) {
|
|
505
|
+
throw sanitize(error, 'close')
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
})()
|
|
509
|
+
}
|
|
510
|
+
return closing
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
return {
|
|
514
|
+
get: (key, options) => run('get', (strategy) => strategy.get(key, options)),
|
|
515
|
+
set: (key, value, options) => run('set', (strategy) => strategy.set(key, value, options)),
|
|
516
|
+
has: (key) => run('has', (strategy) => strategy.has(key)),
|
|
517
|
+
delete: (key) => run('delete', (strategy) => strategy.delete(key)),
|
|
518
|
+
deleteByTags: (tags) => run('deleteByTags', (strategy) => strategy.deleteByTags(tags)),
|
|
519
|
+
clear: () => run('clear', (strategy) => strategy.clear()),
|
|
520
|
+
keys: (pattern) => run('keys', (strategy) => strategy.keys(pattern)),
|
|
521
|
+
stats: () => run('stats', (strategy) => strategy.stats()),
|
|
522
|
+
healthcheck: () => run('healthcheck', (strategy) => strategy.healthcheck()),
|
|
523
|
+
cleanup: () => run('cleanup', (strategy) => (strategy.cleanup ? strategy.cleanup() : 0)),
|
|
524
|
+
close,
|
|
525
|
+
}
|
|
526
|
+
}
|
|
256
527
|
|
|
528
|
+
function resolveDefaultTtl(options?: CacheServiceOptions): number | undefined {
|
|
257
529
|
const envTtl = process.env.CACHE_TTL
|
|
258
530
|
const parsedEnvTtl = envTtl ? Number.parseInt(envTtl, 10) : undefined
|
|
259
|
-
|
|
531
|
+
return options?.defaultTtl ?? (typeof parsedEnvTtl === 'number' && Number.isFinite(parsedEnvTtl) ? parsedEnvTtl : undefined)
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function resolveCodecOptions(options?: CacheServiceOptions): CacheCodecOptions {
|
|
535
|
+
return {
|
|
536
|
+
compression: options?.compression ?? parseCacheCompression(process.env.CACHE_COMPRESSION),
|
|
537
|
+
compressionMinBytes: options?.compressionMinBytes ?? parseCacheCompressionMinBytes(process.env.CACHE_COMPRESSION_MIN_BYTES),
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function createProviderTenantAwareStrategy(provider: ResolvedCacheProvider, options?: CacheServiceOptions): TenantAwareCacheStrategy {
|
|
542
|
+
const context = createCacheProviderHostContext(provider, {
|
|
543
|
+
defaultTtl: resolveDefaultTtl(options),
|
|
544
|
+
codec: resolveCodecOptions(options),
|
|
545
|
+
})
|
|
546
|
+
const lazyStrategy = createLazyProviderStrategy(
|
|
547
|
+
provider,
|
|
548
|
+
context,
|
|
549
|
+
resolveProviderConnectTimeoutMs(),
|
|
550
|
+
resolveProviderRetryCooldownMs(),
|
|
551
|
+
)
|
|
552
|
+
return createTenantAwareWrapper(lazyStrategy, { kind: 'provider', defaultTtl: context.defaultTtl })
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function createTenantAwareStrategyForSelection(
|
|
556
|
+
selection: EffectiveCacheSelection,
|
|
557
|
+
options?: CacheServiceOptions,
|
|
558
|
+
): TenantAwareCacheStrategy {
|
|
559
|
+
if (selection.kind === 'provider') return createProviderTenantAwareStrategy(selection.provider, options)
|
|
560
|
+
return createStockTenantAwareStrategy(selection.strategy, options)
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function createConfiguredTenantAwareStrategy(options?: CacheServiceOptions): TenantAwareCacheStrategy {
|
|
564
|
+
return createTenantAwareStrategyForSelection(resolveEffectiveSelection(options), options)
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function createStockTenantAwareStrategy(strategyType: CacheStrategyName, options?: CacheServiceOptions): TenantAwareCacheStrategy {
|
|
568
|
+
const defaultTtl = resolveDefaultTtl(options)
|
|
260
569
|
|
|
261
570
|
const envMaxEntries = process.env.CACHE_MEMORY_MAX_ENTRIES
|
|
262
571
|
const parsedEnvMaxEntries = envMaxEntries ? Number.parseInt(envMaxEntries, 10) : undefined
|
|
263
572
|
const maxEntries = options?.maxEntries ?? (typeof parsedEnvMaxEntries === 'number' && Number.isFinite(parsedEnvMaxEntries) ? parsedEnvMaxEntries : undefined)
|
|
264
573
|
|
|
265
|
-
const codecOptions
|
|
266
|
-
compression: options?.compression ?? parseCacheCompression(process.env.CACHE_COMPRESSION),
|
|
267
|
-
compressionMinBytes: options?.compressionMinBytes ?? parseCacheCompressionMinBytes(process.env.CACHE_COMPRESSION_MIN_BYTES),
|
|
268
|
-
}
|
|
574
|
+
const codecOptions = resolveCodecOptions(options)
|
|
269
575
|
|
|
270
|
-
const
|
|
576
|
+
const createStrategy = isCacheStrategyName(strategyType) ? stockProviderFactories[strategyType] : stockProviderFactories.memory
|
|
577
|
+
const baseStrategy = createStrategy({ options, defaultTtl, maxEntries, codecOptions })
|
|
271
578
|
const resilientStrategy = withDependencyFallback(baseStrategy, strategyType, defaultTtl, maxEntries)
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
return createTenantAwareWrapper(resilientStrategy, reportsBoundedCounters)
|
|
579
|
+
return createTenantAwareWrapper(resilientStrategy, { kind: 'stock', reportsBoundedCounters: strategyType === 'memory' })
|
|
275
580
|
}
|
|
276
581
|
|
|
277
582
|
/**
|
|
@@ -309,9 +614,10 @@ export async function purgeConfiguredCachePatternsAcrossTenantScopes(
|
|
|
309
614
|
// A newly-created memory strategy cannot reach the running app's process-local
|
|
310
615
|
// cache, so constructing one here would only allocate and immediately discard
|
|
311
616
|
// an empty store. Persistent stock backends remain cross-process maintainable.
|
|
312
|
-
|
|
617
|
+
const selection = resolveEffectiveSelection(options)
|
|
618
|
+
if (selection.kind === 'stock' && selection.strategy === 'memory') return 0
|
|
313
619
|
|
|
314
|
-
const cache =
|
|
620
|
+
const cache = createTenantAwareStrategyForSelection(selection, options)
|
|
315
621
|
try {
|
|
316
622
|
return await cache.deleteByPatternsAcrossScopes(patterns)
|
|
317
623
|
} finally {
|
|
@@ -382,18 +688,19 @@ export class CacheService implements CacheStrategy {
|
|
|
382
688
|
}
|
|
383
689
|
}
|
|
384
690
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
}
|
|
691
|
+
type StockFactoryOptions = {
|
|
692
|
+
defaultTtl?: number
|
|
693
|
+
maxEntries?: number
|
|
694
|
+
codecOptions: CacheCodecOptions
|
|
695
|
+
options?: CacheServiceOptions
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** Stock npm factories are available even to synchronous pre-bootstrap callers. */
|
|
699
|
+
const stockProviderFactories: Record<CacheStrategyName, (config: StockFactoryOptions) => CacheStrategy> = {
|
|
700
|
+
memory: ({ defaultTtl, maxEntries }) => createMemoryStrategy({ defaultTtl, maxEntries }),
|
|
701
|
+
redis: ({ defaultTtl, codecOptions, options }) => createRedisStrategy(options?.redisUrl, { defaultTtl, ...codecOptions }),
|
|
702
|
+
sqlite: ({ defaultTtl, codecOptions, options }) => createSqliteStrategy(options?.sqlitePath, { defaultTtl, ...codecOptions }),
|
|
703
|
+
jsonfile: ({ defaultTtl, options }) => createJsonFileStrategy(options?.jsonFilePath, { defaultTtl }),
|
|
397
704
|
}
|
|
398
705
|
|
|
399
706
|
function describeDependencyFailure(error: CacheDependencyUnavailableError): string {
|
|
@@ -427,7 +734,7 @@ function withDependencyFallback(strategy: CacheStrategy, strategyType: CacheStra
|
|
|
427
734
|
|
|
428
735
|
const ensureFallback = (error: CacheDependencyUnavailableError) => {
|
|
429
736
|
if (!fallbackStrategy) {
|
|
430
|
-
fallbackStrategy =
|
|
737
|
+
fallbackStrategy = stockProviderFactories.memory({ defaultTtl, maxEntries, codecOptions: {} })
|
|
431
738
|
}
|
|
432
739
|
if (!warned) {
|
|
433
740
|
const dependencyMessage = error.dependency
|