@nathapp/nestjs-cache 2.0.4 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CLAUDE.md +149 -0
  2. package/MIGRATION.md +263 -0
  3. package/README.md +486 -1
  4. package/TODO.md +56 -0
  5. package/dist/enum/strategy.enum.d.ts +6 -0
  6. package/dist/enum/strategy.enum.js +8 -1
  7. package/dist/enum/strategy.enum.js.map +1 -1
  8. package/dist/index.d.ts +3 -1
  9. package/dist/index.js +3 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/inteceptor/index.d.ts +1 -2
  12. package/dist/inteceptor/index.js +1 -2
  13. package/dist/inteceptor/index.js.map +1 -1
  14. package/dist/interceptor/cache-invalidate.interceptor.js.map +1 -0
  15. package/dist/{inteceptor → interceptor}/cache.interceptor.js +9 -3
  16. package/dist/interceptor/cache.interceptor.js.map +1 -0
  17. package/dist/interceptor/index.d.ts +2 -0
  18. package/dist/interceptor/index.js +19 -0
  19. package/dist/interceptor/index.js.map +1 -0
  20. package/dist/interface/cache-invalidate.interface.d.ts +8 -0
  21. package/dist/interface/enhanced-cache-options.interface.d.ts +45 -0
  22. package/dist/interface/enhanced-cache-options.interface.js +3 -0
  23. package/dist/interface/enhanced-cache-options.interface.js.map +1 -0
  24. package/dist/interface/health.interface.d.ts +19 -0
  25. package/dist/interface/health.interface.js +3 -0
  26. package/dist/interface/health.interface.js.map +1 -0
  27. package/dist/interface/index.d.ts +3 -0
  28. package/dist/interface/index.js +3 -0
  29. package/dist/interface/index.js.map +1 -1
  30. package/dist/interface/metrics.interface.d.ts +17 -0
  31. package/dist/interface/metrics.interface.js +3 -0
  32. package/dist/interface/metrics.interface.js.map +1 -0
  33. package/dist/module/cache-invalidate.provider.js +5 -0
  34. package/dist/module/cache-invalidate.provider.js.map +1 -1
  35. package/dist/module/cache-module.interface.d.ts +3 -1
  36. package/dist/module/cache.module.d.ts +2 -1
  37. package/dist/module/cache.module.js +39 -4
  38. package/dist/module/cache.module.js.map +1 -1
  39. package/dist/module/cache.provider.js +72 -3
  40. package/dist/module/cache.provider.js.map +1 -1
  41. package/dist/provider/cacheable.provider.d.ts +11 -0
  42. package/dist/provider/cacheable.provider.js +213 -0
  43. package/dist/provider/cacheable.provider.js.map +1 -0
  44. package/dist/provider/index.d.ts +1 -0
  45. package/dist/provider/index.js +18 -0
  46. package/dist/provider/index.js.map +1 -0
  47. package/dist/service/cache-invalidate.factory.js.map +1 -1
  48. package/dist/service/cache-invalidate.manager.d.ts +4 -3
  49. package/dist/service/cache-invalidate.manager.js +8 -5
  50. package/dist/service/cache-invalidate.manager.js.map +1 -1
  51. package/dist/service/cache-manager.d.ts +42 -6
  52. package/dist/service/cache-manager.js +622 -45
  53. package/dist/service/cache-manager.js.map +1 -1
  54. package/dist/service/cache-provider.js +3 -6
  55. package/dist/service/cache-provider.js.map +1 -1
  56. package/dist/service/cache-tag-registry.d.ts +30 -0
  57. package/dist/service/cache-tag-registry.js +100 -0
  58. package/dist/service/cache-tag-registry.js.map +1 -0
  59. package/dist/service/index.d.ts +2 -0
  60. package/dist/service/index.js +2 -0
  61. package/dist/service/index.js.map +1 -1
  62. package/dist/service/redis-cache-invalidate.manager.d.ts +9 -1
  63. package/dist/service/redis-cache-invalidate.manager.js +107 -55
  64. package/dist/service/redis-cache-invalidate.manager.js.map +1 -1
  65. package/dist/service/redis-pattern-invalidation.d.ts +11 -0
  66. package/dist/service/redis-pattern-invalidation.js +107 -0
  67. package/dist/service/redis-pattern-invalidation.js.map +1 -0
  68. package/dist/utils/cache-key.utils.d.ts +3 -0
  69. package/dist/utils/cache-key.utils.js +34 -2
  70. package/dist/utils/cache-key.utils.js.map +1 -1
  71. package/dist/utils/config-validation.d.ts +2 -0
  72. package/dist/utils/config-validation.js +57 -0
  73. package/dist/utils/config-validation.js.map +1 -0
  74. package/dist/utils/deprecation.d.ts +3 -0
  75. package/dist/utils/deprecation.js +33 -0
  76. package/dist/utils/deprecation.js.map +1 -0
  77. package/dist/utils/index.d.ts +4 -0
  78. package/dist/utils/index.js +4 -0
  79. package/dist/utils/index.js.map +1 -1
  80. package/dist/utils/redis-uri.utils.d.ts +9 -0
  81. package/dist/utils/redis-uri.utils.js +62 -0
  82. package/dist/utils/redis-uri.utils.js.map +1 -0
  83. package/dist/utils/validation.d.ts +10 -0
  84. package/dist/utils/validation.js +39 -0
  85. package/dist/utils/validation.js.map +1 -0
  86. package/docker-compose.e2e.yml +16 -0
  87. package/docs/CACHEOBLESYNC-MIGRATION-PLAN.md +55 -0
  88. package/docs/CODE-REVIEW-2026-02-10-v2.md +134 -0
  89. package/docs/CODE-REVIEW-2026-02-10.md +142 -0
  90. package/docs/CODE_REVIEW.md +356 -0
  91. package/docs/FINAL-CODE-REVIEW-2026-02-10.md +312 -0
  92. package/docs/IMPLEMENTATION_PLAN.md +1045 -0
  93. package/docs/IMPLEMENTATION_PLAN_V2.md +201 -0
  94. package/docs/IMPLEMENTATION_PLAN_V3.md +169 -0
  95. package/docs/IMPLEMENTATION_TASKS.md +1090 -0
  96. package/docs/PHASE3_COVERAGE_TASKS.md +266 -0
  97. package/docs/TAG-BASED-INVALIDATION-PLAN.md +367 -0
  98. package/docs/UNIFIED-INVALIDATE-PLAN.md +229 -0
  99. package/package.json +27 -2
  100. package/dist/inteceptor/cache-invalidate.interceptor.js.map +0 -1
  101. package/dist/inteceptor/cache.interceptor.js.map +0 -1
  102. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.d.ts +0 -0
  103. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.js +0 -0
  104. /package/dist/{inteceptor → interceptor}/cache.interceptor.d.ts +0 -0
@@ -3,87 +3,398 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CacheManager = void 0;
4
4
  const common_1 = require("@nestjs/common");
5
5
  const enum_1 = require("../enum");
6
+ const utils_1 = require("../utils");
7
+ const redis_pattern_invalidation_1 = require("./redis-pattern-invalidation");
6
8
  class CacheManager {
7
- constructor(invalidateOptions, cacheProvider, cacheInvalidateManager) {
9
+ constructor(invalidateOptions, cacheProvider, cacheInvalidateManager, cacheable, metrics, strategy, fallbackToMemory, tagRegistry) {
8
10
  this.invalidateOptions = invalidateOptions;
9
11
  this.cacheProvider = cacheProvider;
10
12
  this.cacheInvalidateManager = cacheInvalidateManager;
13
+ this.cacheable = cacheable;
11
14
  this.logger = new common_1.Logger(CacheManager.name);
12
15
  this.invalidateOptions = Object.assign({}, { strategy: enum_1.InvalidateStrategy.DIRECT }, invalidateOptions);
16
+ this.useCacheable = !!cacheable;
17
+ this.metrics = metrics;
18
+ this.strategy = strategy;
19
+ this.fallbackToMemory = fallbackToMemory;
20
+ this.tagRegistry = tagRegistry;
21
+ if (this.useCacheable && this.cacheable) {
22
+ this.patternInvalidator = new redis_pattern_invalidation_1.RedisPatternInvalidation(this.cacheable);
23
+ }
24
+ }
25
+ emitMetric(hookName, context) {
26
+ if (!this.metrics || !this.metrics[hookName]) {
27
+ return;
28
+ }
29
+ try {
30
+ const hook = this.metrics[hookName];
31
+ const result = hook(context);
32
+ if (result && typeof result.then === 'function') {
33
+ result.catch((error) => {
34
+ this.logger.warn(`Metrics hook ${hookName} failed:`, error.message);
35
+ });
36
+ }
37
+ }
38
+ catch (error) {
39
+ this.logger.warn(`Metrics hook ${hookName} failed:`, error.message);
40
+ }
41
+ }
42
+ createContext(key, durationMs) {
43
+ return {
44
+ key,
45
+ durationMs,
46
+ strategy: this.strategy,
47
+ };
13
48
  }
14
- async get(keys, resultResolver, expirationMs = 300000) {
15
- return this.cacheProvider.get(keys, resultResolver, expirationMs);
49
+ handleCacheError(error, operation, key, durationMs) {
50
+ const context = this.createContext(key, durationMs);
51
+ this.emitMetric('onCacheError', { ...context, error });
52
+ if (!this.fallbackToMemory) {
53
+ this.logger.error(`Cache ${operation} failed for key ${key}:`, error.message);
54
+ return false;
55
+ }
56
+ if (this.strategy === enum_1.CacheStrategy.MULTI_TIER) {
57
+ this.logger.warn(`Redis ${operation} failed for key ${key}, continuing with L1 (memory) cache:`, error.message);
58
+ return true;
59
+ }
60
+ else if (this.strategy === enum_1.CacheStrategy.DISTRIBUTED) {
61
+ this.logger.warn(`Redis ${operation} failed for key ${key}, acting as no-op cache:`, error.message);
62
+ return true;
63
+ }
64
+ this.logger.error(`Cache ${operation} failed for key ${key}:`, error.message);
65
+ return false;
66
+ }
67
+ async get(keys, resultResolver, expirationOrOptions, maybeOptions) {
68
+ var _a;
69
+ const cacheKey = (0, utils_1.resolveCacheKey)(keys);
70
+ const startTime = Date.now();
71
+ let expirationMs = 300000;
72
+ let options;
73
+ if (typeof expirationOrOptions === 'number') {
74
+ expirationMs = expirationOrOptions;
75
+ options = maybeOptions;
76
+ }
77
+ else if (typeof expirationOrOptions === 'object') {
78
+ options = expirationOrOptions;
79
+ }
80
+ try {
81
+ let result = null;
82
+ if (this.useCacheable && this.cacheable) {
83
+ result = await this.cacheable.get(cacheKey);
84
+ if (result === undefined) {
85
+ result = null;
86
+ }
87
+ if (result === null && resultResolver) {
88
+ result = await resultResolver();
89
+ if (result !== null && result !== undefined) {
90
+ await this.set(keys, result, expirationMs, options);
91
+ }
92
+ return result;
93
+ }
94
+ }
95
+ else {
96
+ result = await this.cacheProvider.get(keys, resultResolver, expirationMs);
97
+ if (result !== null && result !== undefined && resultResolver && ((_a = options === null || options === void 0 ? void 0 : options.tags) === null || _a === void 0 ? void 0 : _a.length) && this.tagRegistry) {
98
+ try {
99
+ await this.tagRegistry.registerTags(cacheKey, options.tags);
100
+ }
101
+ catch (tagError) {
102
+ this.logger.warn(`Tag registration failed for key "${cacheKey}":`, tagError.message);
103
+ }
104
+ }
105
+ }
106
+ const durationMs = Date.now() - startTime;
107
+ if (result !== null && result !== undefined) {
108
+ this.emitMetric('onCacheHit', this.createContext(cacheKey, durationMs));
109
+ }
110
+ else {
111
+ this.emitMetric('onCacheMiss', this.createContext(cacheKey, durationMs));
112
+ }
113
+ return result;
114
+ }
115
+ catch (error) {
116
+ const durationMs = Date.now() - startTime;
117
+ if (this.handleCacheError(error, 'get', cacheKey, durationMs)) {
118
+ return null;
119
+ }
120
+ throw error;
121
+ }
16
122
  }
17
123
  async getOnly(keys) {
18
- return await this.cacheProvider.getOnly(keys);
124
+ const cacheKey = (0, utils_1.resolveCacheKey)(keys);
125
+ const startTime = Date.now();
126
+ try {
127
+ let result = null;
128
+ if (this.useCacheable && this.cacheable) {
129
+ result = await this.cacheable.get(cacheKey);
130
+ if (result === undefined) {
131
+ result = null;
132
+ }
133
+ }
134
+ else {
135
+ result = await this.cacheProvider.getOnly(keys);
136
+ }
137
+ const durationMs = Date.now() - startTime;
138
+ if (result !== null && result !== undefined) {
139
+ this.emitMetric('onCacheHit', this.createContext(cacheKey, durationMs));
140
+ }
141
+ else {
142
+ this.emitMetric('onCacheMiss', this.createContext(cacheKey, durationMs));
143
+ }
144
+ return result;
145
+ }
146
+ catch (error) {
147
+ const durationMs = Date.now() - startTime;
148
+ if (this.handleCacheError(error, 'getOnly', cacheKey, durationMs)) {
149
+ return null;
150
+ }
151
+ throw error;
152
+ }
19
153
  }
20
- getRaw(keys) {
21
- return this.cacheProvider.getRaw(keys);
154
+ async getRaw(keys) {
155
+ const cacheKey = (0, utils_1.resolveCacheKey)(keys);
156
+ try {
157
+ if (this.useCacheable && this.cacheable) {
158
+ const result = await this.cacheable.get(cacheKey);
159
+ return result === undefined ? null : result;
160
+ }
161
+ const result = await this.cacheProvider.getRaw(keys);
162
+ return result === undefined ? null : result;
163
+ }
164
+ catch (error) {
165
+ if (this.handleCacheError(error, 'getRaw', cacheKey)) {
166
+ return null;
167
+ }
168
+ throw error;
169
+ }
22
170
  }
23
- async set(keys, value, expirationMs = 300000) {
24
- await this.cacheProvider.set(keys, value, expirationMs);
171
+ async set(keys, value, expirationMs = 300000, options) {
172
+ var _a;
173
+ const cacheKey = (0, utils_1.resolveCacheKey)(keys);
174
+ const startTime = Date.now();
175
+ try {
176
+ if (this.useCacheable && this.cacheable) {
177
+ await this.cacheable.set(cacheKey, value, expirationMs);
178
+ }
179
+ else {
180
+ await this.cacheProvider.set(keys, value, expirationMs);
181
+ }
182
+ if (((_a = options === null || options === void 0 ? void 0 : options.tags) === null || _a === void 0 ? void 0 : _a.length) && this.tagRegistry) {
183
+ try {
184
+ await this.tagRegistry.registerTags(cacheKey, options.tags);
185
+ }
186
+ catch (tagError) {
187
+ this.logger.warn(`Tag registration failed for key "${cacheKey}":`, tagError.message);
188
+ }
189
+ }
190
+ const durationMs = Date.now() - startTime;
191
+ this.emitMetric('onCacheSet', { ...this.createContext(cacheKey, durationMs), ttl: expirationMs });
192
+ }
193
+ catch (error) {
194
+ const durationMs = Date.now() - startTime;
195
+ if (this.handleCacheError(error, 'set', cacheKey, durationMs)) {
196
+ return;
197
+ }
198
+ throw error;
199
+ }
25
200
  }
26
- setRaw(keys, value, ttl) {
27
- return this.cacheProvider.set(keys, value, ttl);
201
+ async setRaw(keys, value, ttl) {
202
+ const cacheKey = (0, utils_1.resolveCacheKey)(keys);
203
+ try {
204
+ if (this.useCacheable && this.cacheable) {
205
+ await this.cacheable.set(cacheKey, value, ttl);
206
+ }
207
+ else {
208
+ await this.cacheProvider.set(keys, value, ttl);
209
+ }
210
+ }
211
+ catch (error) {
212
+ if (this.handleCacheError(error, 'setRaw', cacheKey)) {
213
+ return;
214
+ }
215
+ throw error;
216
+ }
28
217
  }
29
218
  async mset(list) {
219
+ if (this.useCacheable && this.cacheable) {
220
+ await Promise.all(list.map(async ({ key, value, ttl, tags }) => {
221
+ const cacheKey = (0, utils_1.resolveCacheKey)(key);
222
+ await this.cacheable.set(cacheKey, value, ttl);
223
+ if ((tags === null || tags === void 0 ? void 0 : tags.length) && this.tagRegistry) {
224
+ try {
225
+ await this.tagRegistry.registerTags(cacheKey, tags);
226
+ }
227
+ catch (tagError) {
228
+ this.logger.warn(`Tag registration failed for key "${cacheKey}":`, tagError.message);
229
+ }
230
+ }
231
+ }));
232
+ return;
233
+ }
234
+ if (list.some(item => { var _a; return (_a = item.tags) === null || _a === void 0 ? void 0 : _a.length; })) {
235
+ this.logger.warn('Tags are not supported in legacy mode. Consider upgrading to enhanced mode.');
236
+ }
30
237
  return this.cacheProvider.mset(list);
31
238
  }
32
239
  async mget(keys) {
240
+ if (this.useCacheable && this.cacheable) {
241
+ return Promise.all(keys.map(key => this.cacheable.get(key)));
242
+ }
33
243
  return await this.cacheProvider.mget(keys);
34
244
  }
35
245
  async reset() {
36
- await this.cacheProvider.reset();
246
+ const startTime = Date.now();
247
+ try {
248
+ if (this.useCacheable && this.cacheable) {
249
+ await this.cacheable.clear();
250
+ }
251
+ else {
252
+ await this.cacheProvider.reset();
253
+ }
254
+ const durationMs = Date.now() - startTime;
255
+ this.emitMetric('onCacheDelete', this.createContext('*', durationMs));
256
+ }
257
+ catch (error) {
258
+ const durationMs = Date.now() - startTime;
259
+ if (this.handleCacheError(error, 'reset', '*', durationMs)) {
260
+ return;
261
+ }
262
+ throw error;
263
+ }
37
264
  }
38
265
  async keys() {
266
+ if (this.useCacheable && this.cacheable) {
267
+ this.logger.warn('keys() method is not supported in enhanced mode. Consider using legacy mode for this operation.');
268
+ return [];
269
+ }
39
270
  return await this.cacheProvider.keys();
40
271
  }
41
272
  resolveKey(keyParts) {
42
- return this.cacheProvider.resolveKey(keyParts);
273
+ return (0, utils_1.resolveCacheKey)(keyParts);
43
274
  }
44
- async mInvalidate(list) {
45
- const mdelKeys = [];
46
- const mdelGroupKeys = [];
47
- for (const { cacheKeysParts, group } of list) {
48
- if (this.isCacheInvalidateMessage(cacheKeysParts)) {
49
- if (cacheKeysParts.group) {
50
- mdelGroupKeys.push(cacheKeysParts.cacheKey);
275
+ async invalidate(key, optionsOrGroup) {
276
+ let mode = 'key';
277
+ let actualKey;
278
+ let isGroup = false;
279
+ if (this.isCacheInvalidateMessage(key)) {
280
+ mode = key.group ? 'tag' : 'key';
281
+ actualKey = key.cacheKey;
282
+ isGroup = key.group || false;
283
+ }
284
+ else {
285
+ actualKey = key;
286
+ if (typeof optionsOrGroup === 'boolean') {
287
+ mode = optionsOrGroup ? 'tag' : 'key';
288
+ isGroup = optionsOrGroup;
289
+ }
290
+ else if (optionsOrGroup && typeof optionsOrGroup === 'object') {
291
+ mode = optionsOrGroup.mode;
292
+ isGroup = mode === 'tag' || mode === 'pattern';
293
+ }
294
+ }
295
+ if (this.invalidateOptions.strategy === enum_1.InvalidateStrategy.BROKER) {
296
+ return this.invalidateWithBroker(this.isCacheInvalidateMessage(key) ? key : actualKey, isGroup);
297
+ }
298
+ switch (mode) {
299
+ case 'tag':
300
+ if (this.tagRegistry) {
301
+ await this.invalidateByTag((0, utils_1.resolveCacheKey)(actualKey));
51
302
  }
52
303
  else {
53
- mdelKeys.push(cacheKeysParts.cacheKey);
304
+ await this.invalidateWithDirect(actualKey, true);
54
305
  }
55
- }
56
- else {
57
- if (group) {
58
- mdelGroupKeys.push(cacheKeysParts);
306
+ break;
307
+ case 'pattern':
308
+ if (this.tagRegistry) {
309
+ this.logger.warn('Pattern invalidation is deprecated. Using tag-based invalidation instead.');
310
+ await this.invalidateByTag((0, utils_1.resolveCacheKey)(actualKey));
59
311
  }
60
312
  else {
61
- mdelKeys.push(cacheKeysParts);
313
+ await this.invalidateWithDirect(actualKey, true);
314
+ }
315
+ break;
316
+ case 'key':
317
+ default: {
318
+ if (this.useCacheable && this.cacheable) {
319
+ const resolvedKey = (0, utils_1.resolveCacheKey)(actualKey);
320
+ if (typeof this.cacheable.delete === 'function') {
321
+ await this.cacheable.delete(resolvedKey);
322
+ }
323
+ else if (typeof this.cacheable.deleteMany === 'function') {
324
+ await this.cacheable.deleteMany([resolvedKey]);
325
+ }
326
+ else {
327
+ await this.invalidateWithDirect(actualKey, false);
328
+ }
329
+ break;
62
330
  }
331
+ await this.invalidateWithDirect(actualKey, false);
332
+ break;
63
333
  }
64
334
  }
65
- if (this.invalidateOptions.strategy === enum_1.InvalidateStrategy.BROKER) {
66
- if (mdelKeys.length > 0) {
67
- await this.mInvalidateWithBroker(mdelKeys, false);
335
+ }
336
+ async mInvalidate(list) {
337
+ const keyDeletes = [];
338
+ const patternDeletes = [];
339
+ const tagDeletes = [];
340
+ for (const item of list) {
341
+ if (item.cacheKey !== undefined) {
342
+ const mode = item.mode || 'key';
343
+ switch (mode) {
344
+ case 'tag':
345
+ tagDeletes.push((0, utils_1.resolveCacheKey)(item.cacheKey));
346
+ break;
347
+ case 'pattern':
348
+ if (this.tagRegistry) {
349
+ tagDeletes.push((0, utils_1.resolveCacheKey)(item.cacheKey));
350
+ }
351
+ else {
352
+ patternDeletes.push(item.cacheKey);
353
+ }
354
+ break;
355
+ case 'key':
356
+ default:
357
+ keyDeletes.push(item.cacheKey);
358
+ break;
359
+ }
360
+ continue;
68
361
  }
69
- if (mdelGroupKeys.length > 0) {
70
- await this.mInvalidateWithBroker(mdelGroupKeys, true);
362
+ if (item.cacheKeysParts !== undefined) {
363
+ if (this.isCacheInvalidateMessage(item.cacheKeysParts)) {
364
+ if (item.cacheKeysParts.group) {
365
+ tagDeletes.push((0, utils_1.resolveCacheKey)(item.cacheKeysParts.cacheKey));
366
+ }
367
+ else {
368
+ keyDeletes.push(item.cacheKeysParts.cacheKey);
369
+ }
370
+ }
371
+ else {
372
+ if (item.group) {
373
+ tagDeletes.push((0, utils_1.resolveCacheKey)(item.cacheKeysParts));
374
+ }
375
+ else {
376
+ keyDeletes.push(item.cacheKeysParts);
377
+ }
378
+ }
71
379
  }
72
380
  }
73
- else {
74
- if (mdelKeys.length > 0) {
75
- await this.cacheProvider.mdel(mdelKeys);
381
+ const promises = [];
382
+ if (keyDeletes.length > 0) {
383
+ if (this.useCacheable && this.cacheable) {
384
+ const resolvedKeys = keyDeletes.map(k => (0, utils_1.resolveCacheKey)(k));
385
+ promises.push(this.cacheable.deleteMany(resolvedKeys));
76
386
  }
77
- if (mdelGroupKeys.length > 0) {
78
- await this.cacheProvider.mdelByPattern(mdelGroupKeys);
387
+ else {
388
+ promises.push(this.cacheProvider.mdel(keyDeletes));
79
389
  }
80
390
  }
81
- }
82
- async invalidate(cacheKeyParts, group = false) {
83
- if (this.invalidateOptions.strategy === enum_1.InvalidateStrategy.BROKER) {
84
- return this.invalidateWithBroker(cacheKeyParts, group);
391
+ if (patternDeletes.length > 0) {
392
+ promises.push(this.cacheProvider.mdelByPattern(patternDeletes));
85
393
  }
86
- return this.invalidateWithDirect(cacheKeyParts, group);
394
+ if (tagDeletes.length > 0 && this.tagRegistry) {
395
+ promises.push(this.invalidateByTags(tagDeletes).then(() => { }));
396
+ }
397
+ await Promise.all(promises);
87
398
  }
88
399
  invalidateWithBroker(cacheKeyParts, group = false) {
89
400
  if (typeof cacheKeyParts === 'string' || Array.isArray(cacheKeyParts)) {
@@ -94,7 +405,7 @@ class CacheManager {
94
405
  mInvalidateWithBroker(cacheKeys, group = false) {
95
406
  return this.cacheInvalidateManager.publish({ cacheKeys, group });
96
407
  }
97
- invalidateWithDirect(cacheKeyParts, group = false) {
408
+ async invalidateWithDirect(cacheKeyParts, group = false) {
98
409
  let cacheKey;
99
410
  let deleteByPattern = false;
100
411
  if (this.isCacheInvalidateMessage(cacheKeyParts)) {
@@ -105,13 +416,279 @@ class CacheManager {
105
416
  cacheKey = cacheKeyParts;
106
417
  deleteByPattern = group;
107
418
  }
108
- if (deleteByPattern) {
109
- return this.cacheProvider.delByPattern(cacheKey);
419
+ const resolvedKey = (0, utils_1.resolveCacheKey)(cacheKey);
420
+ const startTime = Date.now();
421
+ try {
422
+ if (deleteByPattern) {
423
+ await this.cacheProvider.delByPattern(cacheKey);
424
+ }
425
+ else {
426
+ await this.cacheProvider.del(cacheKey);
427
+ }
428
+ const durationMs = Date.now() - startTime;
429
+ this.emitMetric('onCacheDelete', this.createContext(resolvedKey, durationMs));
430
+ }
431
+ catch (error) {
432
+ const durationMs = Date.now() - startTime;
433
+ if (this.handleCacheError(error, 'invalidate', resolvedKey, durationMs)) {
434
+ return;
435
+ }
436
+ throw error;
110
437
  }
111
- return this.cacheProvider.del(cacheKey);
112
438
  }
113
439
  isCacheInvalidateMessage(cacheKeyParts) {
114
- return cacheKeyParts.cacheKey !== undefined;
440
+ return typeof cacheKeyParts === 'object' && cacheKeyParts !== null && !Array.isArray(cacheKeyParts) && 'cacheKey' in cacheKeyParts;
441
+ }
442
+ async getStats() {
443
+ if (this.useCacheable && this.cacheable && this.cacheable.getStats) {
444
+ return this.cacheable.getStats();
445
+ }
446
+ return null;
447
+ }
448
+ isEnhancedMode() {
449
+ return this.useCacheable;
450
+ }
451
+ async invalidateByPattern(pattern) {
452
+ if (this.tagRegistry) {
453
+ this.logger.warn(`invalidateByPattern("${pattern}") is deprecated. ` +
454
+ `Use invalidate(key, { mode: 'tag' }) for O(m) performance. ` +
455
+ `Falling back to tag-based invalidation.`);
456
+ await this.invalidateByTag(pattern);
457
+ return;
458
+ }
459
+ if (this.useCacheable && this.patternInvalidator) {
460
+ try {
461
+ await this.patternInvalidator.deleteByPattern(pattern);
462
+ }
463
+ catch (error) {
464
+ this.logger.error(`Pattern invalidation failed for pattern ${pattern}:`, error);
465
+ throw error;
466
+ }
467
+ return;
468
+ }
469
+ await this.cacheProvider.delByPatternRaw([pattern]);
470
+ }
471
+ async invalidateByTag(tag) {
472
+ if (!this.tagRegistry) {
473
+ throw new Error('Tag-based invalidation is not available. ' +
474
+ 'Tags require Redis (DISTRIBUTED or MULTI_TIER strategy).');
475
+ }
476
+ const startTime = Date.now();
477
+ try {
478
+ const keys = await this.tagRegistry.consumeTag(tag);
479
+ if (keys.length === 0) {
480
+ this.logger.debug(`No keys found for tag "${tag}"`);
481
+ return 0;
482
+ }
483
+ if (this.useCacheable && this.cacheable) {
484
+ await this.cacheable.deleteMany(keys);
485
+ }
486
+ else {
487
+ await Promise.all(keys.map(key => this.cacheProvider.del([key])));
488
+ }
489
+ const durationMs = Date.now() - startTime;
490
+ this.emitMetric('onCacheDelete', this.createContext(`tag:${tag}`, durationMs));
491
+ this.logger.debug(`Invalidated ${keys.length} keys for tag "${tag}"`);
492
+ return keys.length;
493
+ }
494
+ catch (error) {
495
+ const durationMs = Date.now() - startTime;
496
+ this.emitMetric('onCacheError', { ...this.createContext(`tag:${tag}`, durationMs), error });
497
+ this.logger.error(`Tag invalidation failed for tag "${tag}":`, error.message);
498
+ throw error;
499
+ }
500
+ }
501
+ async invalidateByTags(tags) {
502
+ if (!this.tagRegistry) {
503
+ throw new Error('Tag-based invalidation is not available. ' +
504
+ 'Tags require Redis (DISTRIBUTED or MULTI_TIER strategy).');
505
+ }
506
+ if (!tags || tags.length === 0) {
507
+ return 0;
508
+ }
509
+ const startTime = Date.now();
510
+ try {
511
+ const keys = await this.tagRegistry.consumeTags(tags);
512
+ if (keys.length === 0) {
513
+ this.logger.debug(`No keys found for tags: ${tags.join(', ')}`);
514
+ return 0;
515
+ }
516
+ if (this.useCacheable && this.cacheable) {
517
+ await this.cacheable.deleteMany(keys);
518
+ }
519
+ else {
520
+ await Promise.all(keys.map(key => this.cacheProvider.del([key])));
521
+ }
522
+ const durationMs = Date.now() - startTime;
523
+ this.emitMetric('onCacheDelete', this.createContext(`tags:[${tags.join(',')}]`, durationMs));
524
+ this.logger.debug(`Invalidated ${keys.length} keys for ${tags.length} tags`);
525
+ return keys.length;
526
+ }
527
+ catch (error) {
528
+ const durationMs = Date.now() - startTime;
529
+ this.emitMetric('onCacheError', { ...this.createContext(`tags:[${tags.join(',')}]`, durationMs), error });
530
+ this.logger.error(`Tag invalidation failed for tags [${tags.join(', ')}]:`, error.message);
531
+ throw error;
532
+ }
533
+ }
534
+ async isHealthy() {
535
+ var _a;
536
+ const connections = [];
537
+ let healthy = true;
538
+ if (this.useCacheable && this.cacheable) {
539
+ if (this.cacheable.primary) {
540
+ connections.push({
541
+ name: 'memory',
542
+ status: 'connected',
543
+ });
544
+ }
545
+ if ((_a = this.cacheable.secondary) === null || _a === void 0 ? void 0 : _a.client) {
546
+ try {
547
+ const start = Date.now();
548
+ await this.cacheable.secondary.client.ping();
549
+ connections.push({
550
+ name: 'redis',
551
+ status: 'connected',
552
+ latencyMs: Date.now() - start,
553
+ });
554
+ }
555
+ catch (error) {
556
+ healthy = false;
557
+ connections.push({
558
+ name: 'redis',
559
+ status: 'error',
560
+ error: error.message,
561
+ });
562
+ }
563
+ }
564
+ }
565
+ else {
566
+ connections.push({
567
+ name: 'cache-manager',
568
+ status: 'connected',
569
+ });
570
+ }
571
+ return {
572
+ healthy,
573
+ timestamp: new Date(),
574
+ connections,
575
+ stats: await this.getStats(),
576
+ };
577
+ }
578
+ async touch(keys, ttlMs) {
579
+ const cacheKey = (0, utils_1.resolveCacheKey)(keys);
580
+ const ttl = ttlMs !== null && ttlMs !== void 0 ? ttlMs : 300000;
581
+ const startTime = Date.now();
582
+ try {
583
+ if (this.useCacheable && this.cacheable) {
584
+ if (typeof this.cacheable.touch === 'function') {
585
+ await this.cacheable.touch(cacheKey, ttl);
586
+ const durationMs = Date.now() - startTime;
587
+ this.emitMetric('onCacheSet', { ...this.createContext(cacheKey, durationMs), ttl });
588
+ return true;
589
+ }
590
+ if (typeof this.cacheable.expire === 'function') {
591
+ const success = await this.cacheable.expire(cacheKey, ttl);
592
+ if (success) {
593
+ const durationMs = Date.now() - startTime;
594
+ this.emitMetric('onCacheSet', { ...this.createContext(cacheKey, durationMs), ttl });
595
+ return true;
596
+ }
597
+ }
598
+ const value = await this.cacheable.get(cacheKey);
599
+ if (value !== null && value !== undefined) {
600
+ await this.cacheable.set(cacheKey, value, ttl);
601
+ const durationMs = Date.now() - startTime;
602
+ this.emitMetric('onCacheSet', { ...this.createContext(cacheKey, durationMs), ttl });
603
+ return true;
604
+ }
605
+ return false;
606
+ }
607
+ const value = await this.cacheProvider.getRaw(keys);
608
+ if (value !== null && value !== undefined) {
609
+ await this.cacheProvider.setRaw(keys, value, ttl);
610
+ const durationMs = Date.now() - startTime;
611
+ this.emitMetric('onCacheSet', { ...this.createContext(cacheKey, durationMs), ttl });
612
+ return true;
613
+ }
614
+ return false;
615
+ }
616
+ catch (error) {
617
+ const durationMs = Date.now() - startTime;
618
+ this.emitMetric('onCacheError', { ...this.createContext(cacheKey, durationMs), error });
619
+ this.logger.warn(`Touch operation failed for key ${cacheKey}:`, error.message);
620
+ return false;
621
+ }
622
+ }
623
+ namespace(name) {
624
+ const namespacePrefix = name.toUpperCase();
625
+ return {
626
+ get: async (key, resultResolver, ttlOrOptions, maybeOptions) => {
627
+ const namespacedKey = Array.isArray(key) ? [namespacePrefix, ...key] : [namespacePrefix, key];
628
+ let ttl;
629
+ let options;
630
+ if (typeof ttlOrOptions === 'number') {
631
+ ttl = ttlOrOptions;
632
+ options = maybeOptions;
633
+ }
634
+ else if (typeof ttlOrOptions === 'object') {
635
+ options = ttlOrOptions;
636
+ }
637
+ const namespacedOptions = (options === null || options === void 0 ? void 0 : options.tags)
638
+ ? { ...options, tags: options.tags.map(t => `${namespacePrefix}:${t}`) }
639
+ : options;
640
+ if (ttl !== undefined && namespacedOptions) {
641
+ return this.get(namespacedKey, resultResolver, ttl, namespacedOptions);
642
+ }
643
+ else if (ttl !== undefined) {
644
+ return this.get(namespacedKey, resultResolver, ttl);
645
+ }
646
+ else if (namespacedOptions) {
647
+ return this.get(namespacedKey, resultResolver, namespacedOptions);
648
+ }
649
+ else {
650
+ return this.get(namespacedKey, resultResolver);
651
+ }
652
+ },
653
+ getOnly: async (key) => {
654
+ const namespacedKey = Array.isArray(key) ? [namespacePrefix, ...key] : [namespacePrefix, key];
655
+ return this.getOnly(namespacedKey);
656
+ },
657
+ set: async (key, value, ttl, options) => {
658
+ const namespacedKey = Array.isArray(key) ? [namespacePrefix, ...key] : [namespacePrefix, key];
659
+ const namespacedOptions = (options === null || options === void 0 ? void 0 : options.tags)
660
+ ? { ...options, tags: options.tags.map(t => `${namespacePrefix}:${t}`) }
661
+ : options;
662
+ return this.set(namespacedKey, value, ttl, namespacedOptions);
663
+ },
664
+ invalidate: async (key, optionsOrGroup) => {
665
+ const namespacedKey = Array.isArray(key) ? [namespacePrefix, ...key] : [namespacePrefix, key];
666
+ if (typeof optionsOrGroup === 'object' && optionsOrGroup.mode === 'tag') {
667
+ const tag = `${namespacePrefix}:${(0, utils_1.resolveCacheKey)(key)}`;
668
+ await this.invalidateByTag(tag);
669
+ return;
670
+ }
671
+ if (optionsOrGroup !== undefined) {
672
+ return this.invalidate(namespacedKey, optionsOrGroup);
673
+ }
674
+ return this.invalidate(namespacedKey);
675
+ },
676
+ invalidateByTag: async (tag) => {
677
+ const namespacedTag = `${namespacePrefix}:${tag}`;
678
+ return this.invalidateByTag(namespacedTag);
679
+ },
680
+ invalidateByTags: async (tags) => {
681
+ const namespacedTags = tags.map(t => `${namespacePrefix}:${t}`);
682
+ return this.invalidateByTags(namespacedTags);
683
+ },
684
+ invalidateAll: async () => {
685
+ const namespacePattern = `${namespacePrefix}:*`;
686
+ if (this.useCacheable && this.patternInvalidator) {
687
+ return this.invalidateByPattern(namespacePattern);
688
+ }
689
+ return this.cacheProvider.delByPatternRaw([`${namespacePrefix.toUpperCase()}:`]);
690
+ },
691
+ };
115
692
  }
116
693
  }
117
694
  exports.CacheManager = CacheManager;