@open-mercato/cache 0.11.1-develop.8593.1.50784dae35 → 0.11.1-develop.8687.1.adb16f62b3

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.
Files changed (61) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +27 -21
  3. package/README.md +30 -0
  4. package/dist/codec.js +1 -74
  5. package/dist/codec.js.map +2 -2
  6. package/dist/defaults.js +1 -6
  7. package/dist/defaults.js.map +2 -2
  8. package/dist/errors.js +1 -12
  9. package/dist/errors.js.map +2 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/patterns.js +1 -35
  12. package/dist/patterns.js.map +2 -2
  13. package/dist/provider.js +440 -0
  14. package/dist/provider.js.map +7 -0
  15. package/dist/redisConnection.js +2 -0
  16. package/dist/redisConnection.js.map +7 -0
  17. package/dist/service.js +320 -80
  18. package/dist/service.js.map +3 -3
  19. package/dist/strategies/jsonfile.js +1 -186
  20. package/dist/strategies/jsonfile.js.map +3 -3
  21. package/dist/strategies/memory.js +1 -196
  22. package/dist/strategies/memory.js.map +3 -3
  23. package/dist/strategies/redis.js +1 -443
  24. package/dist/strategies/redis.js.map +3 -3
  25. package/dist/strategies/sqlite.js +1 -196
  26. package/dist/strategies/sqlite.js.map +3 -3
  27. package/dist/testing/conformance.js +448 -0
  28. package/dist/testing/conformance.js.map +7 -0
  29. package/dist/testing/index.js +12 -0
  30. package/dist/testing/index.js.map +7 -0
  31. package/dist/testing/remote.js +182 -0
  32. package/dist/testing/remote.js.map +7 -0
  33. package/fixtures/build-conformance-host.mjs +58 -0
  34. package/fixtures/cache-provider-fixture/index.d.ts +18 -0
  35. package/fixtures/cache-provider-fixture/index.js +307 -0
  36. package/fixtures/cache-provider-fixture/package.json +25 -0
  37. package/fixtures/conformance-child.mjs +41 -0
  38. package/jest.config.cjs +3 -1
  39. package/package.json +10 -2
  40. package/src/__tests__/cache-di-contract-docs.test.ts +2 -2
  41. package/src/__tests__/conformance.memory-provider.test.ts +77 -0
  42. package/src/__tests__/provider-fixture.packed.test.ts +178 -0
  43. package/src/__tests__/provider.test.ts +469 -0
  44. package/src/__tests__/service.provider.test.ts +513 -0
  45. package/src/__tests__/service.test.ts +94 -3
  46. package/src/codec.ts +1 -94
  47. package/src/defaults.ts +1 -2
  48. package/src/errors.ts +1 -14
  49. package/src/index.ts +4 -0
  50. package/src/patterns.ts +1 -40
  51. package/src/provider.ts +641 -0
  52. package/src/redisConnection.ts +1 -0
  53. package/src/service.ts +396 -89
  54. package/src/strategies/jsonfile.ts +1 -242
  55. package/src/strategies/memory.ts +1 -275
  56. package/src/strategies/redis.ts +1 -615
  57. package/src/strategies/sqlite.ts +1 -292
  58. package/src/testing/conformance.ts +569 -0
  59. package/src/testing/index.ts +11 -0
  60. package/src/testing/remote.ts +240 -0
  61. package/src/types.ts +8 -106
package/dist/service.js CHANGED
@@ -7,6 +7,13 @@ import { createHash } from "node:crypto";
7
7
  import { CacheDependencyUnavailableError } from "./errors.js";
8
8
  import { matchCacheKeyPattern } from "./patterns.js";
9
9
  import { parseCacheCompression, parseCacheCompressionMinBytes } from "./codec.js";
10
+ import {
11
+ CacheProviderError,
12
+ createCacheProviderHostContext,
13
+ getPreparedCacheProvider,
14
+ readSelectedCacheProviderId,
15
+ toSanitizedCacheProviderError
16
+ } from "./provider.js";
10
17
  function normalizeTenantKey(raw) {
11
18
  const value = typeof raw === "string" ? raw.trim() : "";
12
19
  if (!value) return "global";
@@ -21,12 +28,11 @@ function isCacheMetadata(value) {
21
28
  const hasValidExpiresAt = !("expiresAt" in record) || record.expiresAt === null || typeof record.expiresAt === "number";
22
29
  return hasValidKey && hasValidExpiresAt;
23
30
  }
24
- const KNOWN_STRATEGIES = ["memory", "redis", "sqlite", "jsonfile"];
25
- const TENANT_META_KEY_PATTERN = "tenant:*:key:meta:*";
31
+ const PROVIDER_ENTRY_PREFIX = "entry:v1:";
26
32
  const TENANT_META_KEY_MARKER = ":key:meta:";
27
33
  function isCacheStrategyName(value) {
28
34
  if (!value) return false;
29
- return KNOWN_STRATEGIES.includes(value);
35
+ return Object.hasOwn(stockProviderFactories, value);
30
36
  }
31
37
  function resolveConfiguredStrategyType(options) {
32
38
  const envStrategy = isCacheStrategyName(process.env.CACHE_STRATEGY) ? process.env.CACHE_STRATEGY : void 0;
@@ -47,9 +53,18 @@ function hashIdentifier(input) {
47
53
  function storageKey(originalKey, prefixes) {
48
54
  return `${prefixes.keyPrefix}k:${hashIdentifier(originalKey)}`;
49
55
  }
56
+ function providerEntryKey(originalKey, keyPrefix) {
57
+ return `${keyPrefix}${PROVIDER_ENTRY_PREFIX}${hashIdentifier(originalKey)}`;
58
+ }
59
+ function isCacheProviderEntry(value) {
60
+ return isCacheMetadata(value) && Object.hasOwn(value, "value");
61
+ }
50
62
  function metaKey(originalKey, prefixes) {
51
63
  return `${prefixes.keyPrefix}meta:${hashIdentifier(originalKey)}`;
52
64
  }
65
+ function resolvePhysicalCacheValueKey(originalKey, tenantId) {
66
+ return providerEntryKey(originalKey, `tenant:${normalizeTenantKey(tenantId)}:key:`);
67
+ }
53
68
  function hashedTag(tag, prefixes) {
54
69
  return `${prefixes.tagPrefix}t:${hashIdentifier(tag)}`;
55
70
  }
@@ -63,36 +78,51 @@ function buildTagSet(tags, prefixes, includeScope) {
63
78
  }
64
79
  return Array.from(scoped);
65
80
  }
66
- function createTenantAwareWrapper(base, reportsBoundedCounters) {
81
+ function createTenantAwareWrapper(base, layout) {
82
+ const recordPrefix = layout.kind === "provider" ? PROVIDER_ENTRY_PREFIX : "meta:";
83
+ function valueKey(key, prefixes) {
84
+ return layout.kind === "provider" ? providerEntryKey(key, prefixes.keyPrefix) : storageKey(key, prefixes);
85
+ }
67
86
  function normalizeDeletionCount(raw) {
68
- if (!raw) return raw;
69
- if (!Number.isFinite(raw)) return raw;
87
+ if (layout.kind === "provider" || !raw || !Number.isFinite(raw)) return raw;
70
88
  return Math.ceil(raw / 2);
71
89
  }
90
+ async function* scanRecords(keyPrefix) {
91
+ for (const physicalKey of await base.keys(`${keyPrefix}${recordPrefix}*`)) {
92
+ const record = await base.get(physicalKey, { returnExpired: true });
93
+ if (layout.kind === "stock" && typeof record === "string") {
94
+ yield { physicalKey, key: record, expiresAt: null };
95
+ continue;
96
+ }
97
+ if (!isCacheMetadata(record) || layout.kind === "provider" && !isCacheProviderEntry(record)) continue;
98
+ yield { physicalKey, key: record.key, expiresAt: record.expiresAt ?? null };
99
+ }
100
+ }
72
101
  const get = async (key, options) => {
73
- const prefixes = resolveTenantPrefixes();
74
- return base.get(storageKey(key, prefixes), options);
102
+ const record = await base.get(valueKey(key, resolveTenantPrefixes()), options);
103
+ if (layout.kind === "stock") return record;
104
+ return isCacheProviderEntry(record) ? record.value : null;
75
105
  };
76
106
  const set = async (key, value, options) => {
77
107
  const prefixes = resolveTenantPrefixes();
78
- const hashedTags = buildTagSet(options?.tags, prefixes, true);
108
+ const tags = buildTagSet(options?.tags, prefixes, true);
109
+ const nextOptions = { ...options, tags };
110
+ if (layout.kind === "provider") {
111
+ const ttl2 = options?.ttl ?? layout.defaultTtl;
112
+ const entry = { key, value, expiresAt: ttl2 && ttl2 > 0 ? Date.now() + ttl2 : null };
113
+ await base.set(valueKey(key, prefixes), entry, nextOptions);
114
+ return;
115
+ }
116
+ await base.set(valueKey(key, prefixes), value, nextOptions);
79
117
  const ttl = options?.ttl ?? void 0;
80
- const nextOptions = options ? { ...options, tags: hashedTags } : { tags: hashedTags };
81
- await base.set(storageKey(key, prefixes), value, nextOptions);
82
- const metaPayload = { key, expiresAt: ttl ? Date.now() + ttl : null };
83
- await base.set(metaKey(key, prefixes), metaPayload, {
84
- ttl,
85
- tags: hashedTags
86
- });
87
- };
88
- const has = async (key) => {
89
- const prefixes = resolveTenantPrefixes();
90
- return base.has(storageKey(key, prefixes));
118
+ const metadata = { key, expiresAt: ttl ? Date.now() + ttl : null };
119
+ await base.set(metaKey(key, prefixes), metadata, { ttl, tags });
91
120
  };
121
+ const has = async (key) => base.has(valueKey(key, resolveTenantPrefixes()));
92
122
  const del = async (key) => {
93
123
  const prefixes = resolveTenantPrefixes();
94
- const primary = await base.delete(storageKey(key, prefixes));
95
- await base.delete(metaKey(key, prefixes));
124
+ const primary = await base.delete(valueKey(key, prefixes));
125
+ if (layout.kind === "stock") await base.delete(metaKey(key, prefixes));
96
126
  return primary;
97
127
  };
98
128
  const deleteByTags = async (tags) => {
@@ -108,59 +138,43 @@ function createTenantAwareWrapper(base, reportsBoundedCounters) {
108
138
  return normalizeDeletionCount(removed);
109
139
  };
110
140
  const keys = async (pattern) => {
111
- const prefixes = resolveTenantPrefixes();
112
- const metaPattern = `${prefixes.keyPrefix}meta:*`;
113
- const metaKeys = await base.keys(metaPattern);
114
141
  const originals = [];
115
- for (const metaKey2 of metaKeys) {
116
- const metaValue = await base.get(metaKey2, { returnExpired: true });
117
- if (!metaValue) continue;
118
- const metadata = typeof metaValue === "string" ? null : isCacheMetadata(metaValue) ? metaValue : null;
119
- const original = typeof metaValue === "string" ? metaValue : metadata?.key;
120
- if (!original) continue;
121
- if (pattern && !matchCacheKeyPattern(original, pattern)) continue;
122
- originals.push(original);
142
+ for await (const { key } of scanRecords(resolveTenantPrefixes().keyPrefix)) {
143
+ if (layout.kind === "stock" && !key) continue;
144
+ if (pattern && !matchCacheKeyPattern(key, pattern)) continue;
145
+ originals.push(key);
123
146
  }
124
147
  return originals;
125
148
  };
126
149
  const deleteByPatternsAcrossScopes = async (patterns) => {
127
150
  const normalizedPatterns = Array.from(new Set(patterns.map((pattern) => pattern.trim()).filter(Boolean)));
128
151
  if (normalizedPatterns.length === 0) return 0;
129
- const metaKeys = await base.keys(TENANT_META_KEY_PATTERN);
130
152
  let deleted = 0;
131
- for (const metadataKey of metaKeys) {
132
- const metadataValue = await base.get(metadataKey, { returnExpired: true });
133
- if (!metadataValue) continue;
134
- const metadata = typeof metadataValue === "string" ? null : isCacheMetadata(metadataValue) ? metadataValue : null;
135
- const originalKey = typeof metadataValue === "string" ? metadataValue : metadata?.key;
136
- if (!originalKey || !normalizedPatterns.some((pattern) => matchCacheKeyPattern(originalKey, pattern))) {
153
+ for await (const { physicalKey, key } of scanRecords("tenant:*:key:")) {
154
+ if (layout.kind === "stock" && !key) continue;
155
+ if (!normalizedPatterns.some((pattern) => matchCacheKeyPattern(key, pattern))) continue;
156
+ if (layout.kind === "provider") {
157
+ if (await base.delete(physicalKey)) deleted += 1;
137
158
  continue;
138
159
  }
139
- const markerIndex = metadataKey.lastIndexOf(TENANT_META_KEY_MARKER);
160
+ const markerIndex = physicalKey.lastIndexOf(TENANT_META_KEY_MARKER);
140
161
  if (markerIndex < 0) continue;
141
- const primaryKey = `${metadataKey.slice(0, markerIndex)}:key:k:${metadataKey.slice(markerIndex + TENANT_META_KEY_MARKER.length)}`;
162
+ const primaryKey = `${physicalKey.slice(0, markerIndex)}:key:k:${physicalKey.slice(markerIndex + TENANT_META_KEY_MARKER.length)}`;
142
163
  if (await base.delete(primaryKey)) deleted += 1;
143
- await base.delete(metadataKey);
164
+ await base.delete(physicalKey);
144
165
  }
145
166
  return deleted;
146
167
  };
147
168
  const stats = async () => {
148
- const prefixes = resolveTenantPrefixes();
149
- const metaKeys = await base.keys(`${prefixes.keyPrefix}meta:*`);
150
169
  let size = 0;
151
170
  let expired = 0;
152
171
  const now = Date.now();
153
- for (const metaKey2 of metaKeys) {
154
- const metaValue = await base.get(metaKey2, { returnExpired: true });
155
- if (!metaValue) continue;
156
- const metadata = typeof metaValue === "string" ? null : isCacheMetadata(metaValue) ? metaValue : null;
157
- const original = typeof metaValue === "string" ? metaValue : metadata?.key;
158
- if (!original) continue;
172
+ for await (const { key, expiresAt } of scanRecords(resolveTenantPrefixes().keyPrefix)) {
173
+ if (layout.kind === "stock" && !key) continue;
159
174
  size++;
160
- const expiresAt = metadata?.expiresAt ?? null;
161
175
  if (expiresAt !== null && expiresAt <= now) expired++;
162
176
  }
163
- if (!reportsBoundedCounters) {
177
+ if (layout.kind !== "stock" || !layout.reportsBoundedCounters) {
164
178
  return { size, expired };
165
179
  }
166
180
  const { evictions, sweeps, lastSweepReclaimed } = await base.stats();
@@ -184,29 +198,260 @@ function createTenantAwareWrapper(base, reportsBoundedCounters) {
184
198
  deleteByPatternsAcrossScopes
185
199
  };
186
200
  }
187
- function createConfiguredTenantAwareStrategy(options) {
188
- const strategyType = resolveConfiguredStrategyType(options);
201
+ const DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS = 1e4;
202
+ const DEFAULT_PROVIDER_RETRY_COOLDOWN_MS = 1e3;
203
+ const REQUIRED_PROVIDER_STRATEGY_METHODS = [
204
+ "get",
205
+ "set",
206
+ "has",
207
+ "delete",
208
+ "deleteByTags",
209
+ "clear",
210
+ "keys",
211
+ "stats",
212
+ "healthcheck",
213
+ "close"
214
+ ];
215
+ function resolveEffectiveSelection(options) {
216
+ if (options?.strategy && options?.provider) {
217
+ throw new CacheProviderError(
218
+ "conflicting_selection",
219
+ "Cache service options must not combine an explicit stock strategy with an explicit cache provider",
220
+ { providerId: options.provider.id }
221
+ );
222
+ }
223
+ if (options?.strategy) return { kind: "stock", strategy: resolveConfiguredStrategyType(options) };
224
+ if (options?.provider) return { kind: "provider", provider: options.provider };
225
+ if (readSelectedCacheProviderId(process.env)) {
226
+ const prepared = getPreparedCacheProvider(process.env);
227
+ if (prepared) return { kind: "provider", provider: prepared };
228
+ }
229
+ return { kind: "stock", strategy: resolveConfiguredStrategyType(options) };
230
+ }
231
+ function describeCacheSelection(options) {
232
+ const selection = resolveEffectiveSelection(options);
233
+ if (selection.kind === "provider") {
234
+ return { kind: "provider", id: selection.provider.id, placement: selection.provider.placement };
235
+ }
236
+ return {
237
+ kind: "stock",
238
+ strategy: selection.strategy,
239
+ placement: selection.strategy === "redis" ? "shared" : "local"
240
+ };
241
+ }
242
+ function resolveProviderConnectTimeoutMs() {
243
+ const raw = process.env.CACHE_PROVIDER_CONNECT_TIMEOUT_MS;
244
+ const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
245
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS;
246
+ }
247
+ function resolveProviderRetryCooldownMs() {
248
+ const raw = process.env.CACHE_PROVIDER_RETRY_COOLDOWN_MS;
249
+ const parsed = raw !== void 0 && raw.trim().length > 0 ? Number(raw) : Number.NaN;
250
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_PROVIDER_RETRY_COOLDOWN_MS;
251
+ }
252
+ function isProviderStrategy(value) {
253
+ if (typeof value !== "object" || value === null) return false;
254
+ const record = value;
255
+ return REQUIRED_PROVIDER_STRATEGY_METHODS.every((method) => typeof record[method] === "function");
256
+ }
257
+ async function closeQuietly(value) {
258
+ if (typeof value !== "object" || value === null) return;
259
+ try {
260
+ const close = value.close;
261
+ if (typeof close === "function") await close.call(value);
262
+ } catch {
263
+ return;
264
+ }
265
+ }
266
+ function connectProviderStrategy(provider, context, timeoutMs) {
267
+ return new Promise((resolve, reject) => {
268
+ let settled = false;
269
+ const timer = setTimeout(() => {
270
+ if (settled) return;
271
+ settled = true;
272
+ reject(new CacheProviderError(
273
+ "timeout",
274
+ `Cache provider "${provider.id}" did not initialize within ${timeoutMs}ms`,
275
+ { providerId: provider.id }
276
+ ));
277
+ }, timeoutMs);
278
+ if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
279
+ Promise.resolve().then(() => provider.definition.create(provider.config, context)).then(
280
+ (strategy) => {
281
+ if (settled) {
282
+ void closeQuietly(strategy);
283
+ return;
284
+ }
285
+ clearTimeout(timer);
286
+ settled = true;
287
+ try {
288
+ if (!isProviderStrategy(strategy)) {
289
+ throw new CacheProviderError(
290
+ "invalid_registration",
291
+ `Cache provider "${provider.id}" create() must return a cache strategy implementing ${REQUIRED_PROVIDER_STRATEGY_METHODS.join(", ")}`,
292
+ { providerId: provider.id }
293
+ );
294
+ }
295
+ resolve(strategy);
296
+ } catch (error) {
297
+ void closeQuietly(strategy);
298
+ reject(toSanitizedCacheProviderError(error, {
299
+ message: `Cache provider "${provider.id}" failed to initialize`,
300
+ providerId: provider.id
301
+ }));
302
+ }
303
+ },
304
+ (error) => {
305
+ if (settled) return;
306
+ clearTimeout(timer);
307
+ settled = true;
308
+ reject(toSanitizedCacheProviderError(error, {
309
+ message: `Cache provider "${provider.id}" failed to initialize`,
310
+ providerId: provider.id
311
+ }));
312
+ }
313
+ );
314
+ });
315
+ }
316
+ function createLazyProviderStrategy(provider, context, timeoutMs, retryCooldownMs) {
317
+ let active = null;
318
+ let pending = null;
319
+ let closing = null;
320
+ let closed = false;
321
+ let lastFailure = null;
322
+ let generation = 0;
323
+ const sanitize = (error, operation) => toSanitizedCacheProviderError(error, {
324
+ message: `Cache provider "${provider.id}" ${operation} failed`,
325
+ providerId: provider.id
326
+ });
327
+ const ensure = async (operation) => {
328
+ if (closed) {
329
+ throw new CacheProviderError("unavailable", `Cache provider "${provider.id}" is closed`, { providerId: provider.id });
330
+ }
331
+ if (active) return active;
332
+ if (!pending) {
333
+ if (lastFailure && Date.now() - lastFailure.at < retryCooldownMs) throw lastFailure.error;
334
+ const attemptGeneration = generation;
335
+ const attempt = connectProviderStrategy(provider, context, timeoutMs).then(
336
+ async (strategy) => {
337
+ if (attemptGeneration !== generation) {
338
+ await closeQuietly(strategy);
339
+ throw new CacheProviderError("unavailable", `Cache provider "${provider.id}" was closed during initialization`, { providerId: provider.id });
340
+ }
341
+ active = strategy;
342
+ lastFailure = null;
343
+ if (pending === attempt) pending = null;
344
+ return strategy;
345
+ },
346
+ (error) => {
347
+ if (pending === attempt) pending = null;
348
+ if (attemptGeneration === generation) {
349
+ lastFailure = { error: sanitize(error, operation), at: Date.now() };
350
+ }
351
+ throw error;
352
+ }
353
+ );
354
+ pending = attempt;
355
+ }
356
+ try {
357
+ return await pending;
358
+ } catch (error) {
359
+ throw sanitize(error, operation);
360
+ }
361
+ };
362
+ const run = async (operation, call) => {
363
+ const strategy = await ensure(operation);
364
+ try {
365
+ return await call(strategy);
366
+ } catch (error) {
367
+ throw sanitize(error, operation);
368
+ }
369
+ };
370
+ const close = async () => {
371
+ if (!closing) {
372
+ const current = active;
373
+ const inflight = pending;
374
+ closed = true;
375
+ active = null;
376
+ pending = null;
377
+ lastFailure = null;
378
+ generation += 1;
379
+ closing = (async () => {
380
+ if (inflight) await inflight.catch(() => void 0);
381
+ if (current) {
382
+ try {
383
+ await current.close();
384
+ } catch (error) {
385
+ throw sanitize(error, "close");
386
+ }
387
+ }
388
+ })();
389
+ }
390
+ return closing;
391
+ };
392
+ return {
393
+ get: (key, options) => run("get", (strategy) => strategy.get(key, options)),
394
+ set: (key, value, options) => run("set", (strategy) => strategy.set(key, value, options)),
395
+ has: (key) => run("has", (strategy) => strategy.has(key)),
396
+ delete: (key) => run("delete", (strategy) => strategy.delete(key)),
397
+ deleteByTags: (tags) => run("deleteByTags", (strategy) => strategy.deleteByTags(tags)),
398
+ clear: () => run("clear", (strategy) => strategy.clear()),
399
+ keys: (pattern) => run("keys", (strategy) => strategy.keys(pattern)),
400
+ stats: () => run("stats", (strategy) => strategy.stats()),
401
+ healthcheck: () => run("healthcheck", (strategy) => strategy.healthcheck()),
402
+ cleanup: () => run("cleanup", (strategy) => strategy.cleanup ? strategy.cleanup() : 0),
403
+ close
404
+ };
405
+ }
406
+ function resolveDefaultTtl(options) {
189
407
  const envTtl = process.env.CACHE_TTL;
190
408
  const parsedEnvTtl = envTtl ? Number.parseInt(envTtl, 10) : void 0;
191
- const defaultTtl = options?.defaultTtl ?? (typeof parsedEnvTtl === "number" && Number.isFinite(parsedEnvTtl) ? parsedEnvTtl : void 0);
192
- const envMaxEntries = process.env.CACHE_MEMORY_MAX_ENTRIES;
193
- const parsedEnvMaxEntries = envMaxEntries ? Number.parseInt(envMaxEntries, 10) : void 0;
194
- const maxEntries = options?.maxEntries ?? (typeof parsedEnvMaxEntries === "number" && Number.isFinite(parsedEnvMaxEntries) ? parsedEnvMaxEntries : void 0);
195
- const codecOptions = {
409
+ return options?.defaultTtl ?? (typeof parsedEnvTtl === "number" && Number.isFinite(parsedEnvTtl) ? parsedEnvTtl : void 0);
410
+ }
411
+ function resolveCodecOptions(options) {
412
+ return {
196
413
  compression: options?.compression ?? parseCacheCompression(process.env.CACHE_COMPRESSION),
197
414
  compressionMinBytes: options?.compressionMinBytes ?? parseCacheCompressionMinBytes(process.env.CACHE_COMPRESSION_MIN_BYTES)
198
415
  };
199
- const baseStrategy = createStrategyForType(strategyType, options, defaultTtl, maxEntries, codecOptions);
416
+ }
417
+ function createProviderTenantAwareStrategy(provider, options) {
418
+ const context = createCacheProviderHostContext(provider, {
419
+ defaultTtl: resolveDefaultTtl(options),
420
+ codec: resolveCodecOptions(options)
421
+ });
422
+ const lazyStrategy = createLazyProviderStrategy(
423
+ provider,
424
+ context,
425
+ resolveProviderConnectTimeoutMs(),
426
+ resolveProviderRetryCooldownMs()
427
+ );
428
+ return createTenantAwareWrapper(lazyStrategy, { kind: "provider", defaultTtl: context.defaultTtl });
429
+ }
430
+ function createTenantAwareStrategyForSelection(selection, options) {
431
+ if (selection.kind === "provider") return createProviderTenantAwareStrategy(selection.provider, options);
432
+ return createStockTenantAwareStrategy(selection.strategy, options);
433
+ }
434
+ function createConfiguredTenantAwareStrategy(options) {
435
+ return createTenantAwareStrategyForSelection(resolveEffectiveSelection(options), options);
436
+ }
437
+ function createStockTenantAwareStrategy(strategyType, options) {
438
+ const defaultTtl = resolveDefaultTtl(options);
439
+ const envMaxEntries = process.env.CACHE_MEMORY_MAX_ENTRIES;
440
+ const parsedEnvMaxEntries = envMaxEntries ? Number.parseInt(envMaxEntries, 10) : void 0;
441
+ const maxEntries = options?.maxEntries ?? (typeof parsedEnvMaxEntries === "number" && Number.isFinite(parsedEnvMaxEntries) ? parsedEnvMaxEntries : void 0);
442
+ const codecOptions = resolveCodecOptions(options);
443
+ const createStrategy = isCacheStrategyName(strategyType) ? stockProviderFactories[strategyType] : stockProviderFactories.memory;
444
+ const baseStrategy = createStrategy({ options, defaultTtl, maxEntries, codecOptions });
200
445
  const resilientStrategy = withDependencyFallback(baseStrategy, strategyType, defaultTtl, maxEntries);
201
- const reportsBoundedCounters = strategyType === "memory";
202
- return createTenantAwareWrapper(resilientStrategy, reportsBoundedCounters);
446
+ return createTenantAwareWrapper(resilientStrategy, { kind: "stock", reportsBoundedCounters: strategyType === "memory" });
203
447
  }
204
448
  function createCacheService(options) {
205
449
  return createConfiguredTenantAwareStrategy(options);
206
450
  }
207
451
  async function purgeConfiguredCachePatternsAcrossTenantScopes(patterns, options) {
208
- if (resolveConfiguredStrategyType(options) === "memory") return 0;
209
- const cache = createConfiguredTenantAwareStrategy(options);
452
+ const selection = resolveEffectiveSelection(options);
453
+ if (selection.kind === "stock" && selection.strategy === "memory") return 0;
454
+ const cache = createTenantAwareStrategyForSelection(selection, options);
210
455
  try {
211
456
  return await cache.deleteByPatternsAcrossScopes(patterns);
212
457
  } finally {
@@ -253,19 +498,12 @@ class CacheService {
253
498
  }
254
499
  }
255
500
  }
256
- function createStrategyForType(strategyType, options, defaultTtl, maxEntries, codecOptions) {
257
- switch (strategyType) {
258
- case "redis":
259
- return createRedisStrategy(options?.redisUrl, { defaultTtl, ...codecOptions });
260
- case "sqlite":
261
- return createSqliteStrategy(options?.sqlitePath, { defaultTtl, ...codecOptions });
262
- case "jsonfile":
263
- return createJsonFileStrategy(options?.jsonFilePath, { defaultTtl });
264
- case "memory":
265
- default:
266
- return createMemoryStrategy({ defaultTtl, maxEntries });
267
- }
268
- }
501
+ const stockProviderFactories = {
502
+ memory: ({ defaultTtl, maxEntries }) => createMemoryStrategy({ defaultTtl, maxEntries }),
503
+ redis: ({ defaultTtl, codecOptions, options }) => createRedisStrategy(options?.redisUrl, { defaultTtl, ...codecOptions }),
504
+ sqlite: ({ defaultTtl, codecOptions, options }) => createSqliteStrategy(options?.sqlitePath, { defaultTtl, ...codecOptions }),
505
+ jsonfile: ({ defaultTtl, options }) => createJsonFileStrategy(options?.jsonFilePath, { defaultTtl })
506
+ };
269
507
  function describeDependencyFailure(error) {
270
508
  const originalError = error.originalError;
271
509
  if (!(originalError instanceof Error)) {
@@ -290,7 +528,7 @@ function withDependencyFallback(strategy, strategyType, defaultTtl, maxEntries)
290
528
  let warned = false;
291
529
  const ensureFallback = (error) => {
292
530
  if (!fallbackStrategy) {
293
- fallbackStrategy = createMemoryStrategy({ defaultTtl, maxEntries });
531
+ fallbackStrategy = stockProviderFactories.memory({ defaultTtl, maxEntries, codecOptions: {} });
294
532
  }
295
533
  if (!warned) {
296
534
  const dependencyMessage = error.dependency ? ` (${describeDependencyFailure(error)})` : "";
@@ -338,6 +576,8 @@ function withDependencyFallback(strategy, strategyType, defaultTtl, maxEntries)
338
576
  export {
339
577
  CacheService,
340
578
  createCacheService,
341
- purgeConfiguredCachePatternsAcrossTenantScopes
579
+ describeCacheSelection,
580
+ purgeConfiguredCachePatternsAcrossTenantScopes,
581
+ resolvePhysicalCacheValueKey
342
582
  };
343
583
  //# sourceMappingURL=service.js.map