@nathapp/nestjs-cache 2.1.0-rc.0 → 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 (95) hide show
  1. package/CLAUDE.md +149 -0
  2. package/README.md +330 -420
  3. package/TODO.md +56 -0
  4. package/dist/enum/strategy.enum.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/inteceptor/index.d.ts +1 -2
  9. package/dist/inteceptor/index.js +1 -2
  10. package/dist/inteceptor/index.js.map +1 -1
  11. package/dist/interceptor/cache-invalidate.interceptor.js.map +1 -0
  12. package/dist/{inteceptor → interceptor}/cache.interceptor.js +9 -3
  13. package/dist/interceptor/cache.interceptor.js.map +1 -0
  14. package/dist/interceptor/index.d.ts +2 -0
  15. package/dist/interceptor/index.js +19 -0
  16. package/dist/interceptor/index.js.map +1 -0
  17. package/dist/interface/cache-invalidate.interface.d.ts +8 -0
  18. package/dist/interface/enhanced-cache-options.interface.d.ts +16 -0
  19. package/dist/interface/health.interface.d.ts +19 -0
  20. package/dist/interface/health.interface.js +3 -0
  21. package/dist/interface/health.interface.js.map +1 -0
  22. package/dist/interface/index.d.ts +2 -0
  23. package/dist/interface/index.js +2 -0
  24. package/dist/interface/index.js.map +1 -1
  25. package/dist/interface/metrics.interface.d.ts +17 -0
  26. package/dist/interface/metrics.interface.js +3 -0
  27. package/dist/interface/metrics.interface.js.map +1 -0
  28. package/dist/module/cache-invalidate.provider.js +5 -0
  29. package/dist/module/cache-invalidate.provider.js.map +1 -1
  30. package/dist/module/cache-module.interface.d.ts +1 -0
  31. package/dist/module/cache.module.d.ts +2 -1
  32. package/dist/module/cache.module.js +7 -3
  33. package/dist/module/cache.module.js.map +1 -1
  34. package/dist/module/cache.provider.js +69 -1
  35. package/dist/module/cache.provider.js.map +1 -1
  36. package/dist/provider/cacheable.provider.d.ts +3 -0
  37. package/dist/provider/cacheable.provider.js +120 -35
  38. package/dist/provider/cacheable.provider.js.map +1 -1
  39. package/dist/service/cache-invalidate.factory.js.map +1 -1
  40. package/dist/service/cache-invalidate.manager.d.ts +4 -3
  41. package/dist/service/cache-invalidate.manager.js +8 -5
  42. package/dist/service/cache-invalidate.manager.js.map +1 -1
  43. package/dist/service/cache-manager.d.ts +39 -8
  44. package/dist/service/cache-manager.js +579 -71
  45. package/dist/service/cache-manager.js.map +1 -1
  46. package/dist/service/cache-provider.js +3 -6
  47. package/dist/service/cache-provider.js.map +1 -1
  48. package/dist/service/cache-tag-registry.d.ts +30 -0
  49. package/dist/service/cache-tag-registry.js +100 -0
  50. package/dist/service/cache-tag-registry.js.map +1 -0
  51. package/dist/service/index.d.ts +1 -0
  52. package/dist/service/index.js +1 -0
  53. package/dist/service/index.js.map +1 -1
  54. package/dist/service/redis-cache-invalidate.manager.d.ts +9 -1
  55. package/dist/service/redis-cache-invalidate.manager.js +107 -55
  56. package/dist/service/redis-cache-invalidate.manager.js.map +1 -1
  57. package/dist/service/redis-pattern-invalidation.js +4 -0
  58. package/dist/service/redis-pattern-invalidation.js.map +1 -1
  59. package/dist/utils/cache-key.utils.d.ts +3 -0
  60. package/dist/utils/cache-key.utils.js +34 -2
  61. package/dist/utils/cache-key.utils.js.map +1 -1
  62. package/dist/utils/config-validation.d.ts +2 -0
  63. package/dist/utils/config-validation.js +57 -0
  64. package/dist/utils/config-validation.js.map +1 -0
  65. package/dist/utils/deprecation.d.ts +1 -0
  66. package/dist/utils/deprecation.js +13 -2
  67. package/dist/utils/deprecation.js.map +1 -1
  68. package/dist/utils/index.d.ts +3 -0
  69. package/dist/utils/index.js +3 -0
  70. package/dist/utils/index.js.map +1 -1
  71. package/dist/utils/redis-uri.utils.d.ts +9 -0
  72. package/dist/utils/redis-uri.utils.js +62 -0
  73. package/dist/utils/redis-uri.utils.js.map +1 -0
  74. package/dist/utils/validation.d.ts +10 -0
  75. package/dist/utils/validation.js +39 -0
  76. package/dist/utils/validation.js.map +1 -0
  77. package/docker-compose.e2e.yml +16 -0
  78. package/docs/CACHEOBLESYNC-MIGRATION-PLAN.md +55 -0
  79. package/docs/CODE-REVIEW-2026-02-10-v2.md +134 -0
  80. package/docs/CODE-REVIEW-2026-02-10.md +142 -0
  81. package/docs/CODE_REVIEW.md +356 -0
  82. package/docs/FINAL-CODE-REVIEW-2026-02-10.md +312 -0
  83. package/docs/IMPLEMENTATION_PLAN.md +1045 -0
  84. package/docs/IMPLEMENTATION_PLAN_V2.md +201 -0
  85. package/docs/IMPLEMENTATION_PLAN_V3.md +169 -0
  86. package/docs/IMPLEMENTATION_TASKS.md +1090 -0
  87. package/docs/PHASE3_COVERAGE_TASKS.md +266 -0
  88. package/docs/TAG-BASED-INVALIDATION-PLAN.md +367 -0
  89. package/docs/UNIFIED-INVALIDATE-PLAN.md +229 -0
  90. package/package.json +11 -4
  91. package/dist/inteceptor/cache-invalidate.interceptor.js.map +0 -1
  92. package/dist/inteceptor/cache.interceptor.js.map +0 -1
  93. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.d.ts +0 -0
  94. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.js +0 -0
  95. /package/dist/{inteceptor → interceptor}/cache.interceptor.d.ts +0 -0
@@ -4,8 +4,9 @@ exports.CacheManager = void 0;
4
4
  const common_1 = require("@nestjs/common");
5
5
  const enum_1 = require("../enum");
6
6
  const utils_1 = require("../utils");
7
+ const redis_pattern_invalidation_1 = require("./redis-pattern-invalidation");
7
8
  class CacheManager {
8
- constructor(invalidateOptions, cacheProvider, cacheInvalidateManager, cacheable) {
9
+ constructor(invalidateOptions, cacheProvider, cacheInvalidateManager, cacheable, metrics, strategy, fallbackToMemory, tagRegistry) {
9
10
  this.invalidateOptions = invalidateOptions;
10
11
  this.cacheProvider = cacheProvider;
11
12
  this.cacheInvalidateManager = cacheInvalidateManager;
@@ -13,54 +14,226 @@ class CacheManager {
13
14
  this.logger = new common_1.Logger(CacheManager.name);
14
15
  this.invalidateOptions = Object.assign({}, { strategy: enum_1.InvalidateStrategy.DIRECT }, invalidateOptions);
15
16
  this.useCacheable = !!cacheable;
16
- }
17
- async get(keys, resultResolver, expirationMs = 300000) {
17
+ this.metrics = metrics;
18
+ this.strategy = strategy;
19
+ this.fallbackToMemory = fallbackToMemory;
20
+ this.tagRegistry = tagRegistry;
18
21
  if (this.useCacheable && this.cacheable) {
19
- const cacheKey = (0, utils_1.resolveCacheKey)(keys);
20
- if (resultResolver) {
21
- return this.cacheable.wrap(cacheKey, resultResolver, { ttl: expirationMs });
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
+ };
48
+ }
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
+ }
22
94
  }
23
- return this.cacheable.get(cacheKey);
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;
24
121
  }
25
- return this.cacheProvider.get(keys, resultResolver, expirationMs);
26
122
  }
27
123
  async getOnly(keys) {
28
- if (this.useCacheable && this.cacheable) {
29
- const cacheKey = (0, utils_1.resolveCacheKey)(keys);
30
- return this.cacheable.get(cacheKey);
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;
31
152
  }
32
- return await this.cacheProvider.getOnly(keys);
33
153
  }
34
- getRaw(keys) {
35
- if (this.useCacheable && this.cacheable) {
36
- const cacheKey = (0, utils_1.resolveCacheKey)(keys);
37
- return this.cacheable.get(cacheKey);
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;
38
169
  }
39
- return this.cacheProvider.getRaw(keys);
40
170
  }
41
- async set(keys, value, expirationMs = 300000) {
42
- if (this.useCacheable && this.cacheable) {
43
- const cacheKey = (0, utils_1.resolveCacheKey)(keys);
44
- await this.cacheable.set(cacheKey, value, expirationMs);
45
- return;
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;
46
199
  }
47
- await this.cacheProvider.set(keys, value, expirationMs);
48
200
  }
49
- setRaw(keys, value, ttl) {
50
- if (this.useCacheable && this.cacheable) {
51
- const cacheKey = (0, utils_1.resolveCacheKey)(keys);
52
- return this.cacheable.set(cacheKey, 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;
53
216
  }
54
- return this.cacheProvider.set(keys, value, ttl);
55
217
  }
56
218
  async mset(list) {
57
219
  if (this.useCacheable && this.cacheable) {
58
- await Promise.all(list.map(({ key, value, ttl }) => {
220
+ await Promise.all(list.map(async ({ key, value, ttl, tags }) => {
59
221
  const cacheKey = (0, utils_1.resolveCacheKey)(key);
60
- return this.cacheable.set(cacheKey, value, ttl);
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
+ }
61
231
  }));
62
232
  return;
63
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
+ }
64
237
  return this.cacheProvider.mset(list);
65
238
  }
66
239
  async mget(keys) {
@@ -70,11 +243,24 @@ class CacheManager {
70
243
  return await this.cacheProvider.mget(keys);
71
244
  }
72
245
  async reset() {
73
- if (this.useCacheable && this.cacheable) {
74
- await this.cacheable.clear();
75
- return;
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;
76
263
  }
77
- await this.cacheProvider.reset();
78
264
  }
79
265
  async keys() {
80
266
  if (this.useCacheable && this.cacheable) {
@@ -86,49 +272,129 @@ class CacheManager {
86
272
  resolveKey(keyParts) {
87
273
  return (0, utils_1.resolveCacheKey)(keyParts);
88
274
  }
89
- async mInvalidate(list) {
90
- const mdelKeys = [];
91
- const mdelGroupKeys = [];
92
- for (const { cacheKeysParts, group } of list) {
93
- if (this.isCacheInvalidateMessage(cacheKeysParts)) {
94
- if (cacheKeysParts.group) {
95
- 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));
96
302
  }
97
303
  else {
98
- mdelKeys.push(cacheKeysParts.cacheKey);
304
+ await this.invalidateWithDirect(actualKey, true);
99
305
  }
100
- }
101
- else {
102
- if (group) {
103
- 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));
104
311
  }
105
312
  else {
106
- 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;
107
330
  }
331
+ await this.invalidateWithDirect(actualKey, false);
332
+ break;
108
333
  }
109
334
  }
110
- if (this.invalidateOptions.strategy === enum_1.InvalidateStrategy.BROKER) {
111
- if (mdelKeys.length > 0) {
112
- 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;
113
361
  }
114
- if (mdelGroupKeys.length > 0) {
115
- 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
+ }
116
379
  }
117
380
  }
118
- else {
119
- if (mdelKeys.length > 0) {
120
- 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));
121
386
  }
122
- if (mdelGroupKeys.length > 0) {
123
- await this.cacheProvider.mdelByPattern(mdelGroupKeys);
387
+ else {
388
+ promises.push(this.cacheProvider.mdel(keyDeletes));
124
389
  }
125
390
  }
126
- }
127
- async invalidate(cacheKeyParts, group = false) {
128
- if (this.invalidateOptions.strategy === enum_1.InvalidateStrategy.BROKER) {
129
- return this.invalidateWithBroker(cacheKeyParts, group);
391
+ if (patternDeletes.length > 0) {
392
+ promises.push(this.cacheProvider.mdelByPattern(patternDeletes));
130
393
  }
131
- 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);
132
398
  }
133
399
  invalidateWithBroker(cacheKeyParts, group = false) {
134
400
  if (typeof cacheKeyParts === 'string' || Array.isArray(cacheKeyParts)) {
@@ -139,7 +405,7 @@ class CacheManager {
139
405
  mInvalidateWithBroker(cacheKeys, group = false) {
140
406
  return this.cacheInvalidateManager.publish({ cacheKeys, group });
141
407
  }
142
- invalidateWithDirect(cacheKeyParts, group = false) {
408
+ async invalidateWithDirect(cacheKeyParts, group = false) {
143
409
  let cacheKey;
144
410
  let deleteByPattern = false;
145
411
  if (this.isCacheInvalidateMessage(cacheKeyParts)) {
@@ -150,13 +416,28 @@ class CacheManager {
150
416
  cacheKey = cacheKeyParts;
151
417
  deleteByPattern = group;
152
418
  }
153
- if (deleteByPattern) {
154
- 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;
155
437
  }
156
- return this.cacheProvider.del(cacheKey);
157
438
  }
158
439
  isCacheInvalidateMessage(cacheKeyParts) {
159
- return cacheKeyParts.cacheKey !== undefined;
440
+ return typeof cacheKeyParts === 'object' && cacheKeyParts !== null && !Array.isArray(cacheKeyParts) && 'cacheKey' in cacheKeyParts;
160
441
  }
161
442
  async getStats() {
162
443
  if (this.useCacheable && this.cacheable && this.cacheable.getStats) {
@@ -168,11 +449,16 @@ class CacheManager {
168
449
  return this.useCacheable;
169
450
  }
170
451
  async invalidateByPattern(pattern) {
171
- if (this.useCacheable && this.cacheable) {
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) {
172
460
  try {
173
- const { RedisPatternInvalidation } = await Promise.resolve().then(() => require('./redis-pattern-invalidation'));
174
- const invalidator = new RedisPatternInvalidation(this.cacheable);
175
- await invalidator.deleteByPattern(pattern);
461
+ await this.patternInvalidator.deleteByPattern(pattern);
176
462
  }
177
463
  catch (error) {
178
464
  this.logger.error(`Pattern invalidation failed for pattern ${pattern}:`, error);
@@ -182,6 +468,228 @@ class CacheManager {
182
468
  }
183
469
  await this.cacheProvider.delByPatternRaw([pattern]);
184
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
+ };
692
+ }
185
693
  }
186
694
  exports.CacheManager = CacheManager;
187
695
  //# sourceMappingURL=cache-manager.js.map