@nathapp/nestjs-cache 2.1.0-rc.0 → 2.1.1

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 +13 -6
  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
@@ -0,0 +1,1090 @@
1
+ # @nathapp/nestjs-cache Implementation Tasks
2
+
3
+ **For**: Lower-model coordination (Gemini Flash, GPT-4o-mini, Haiku)
4
+ **Created**: 2026-02-09
5
+ **Branch**: `cache-cacheable-migration`
6
+
7
+ ---
8
+
9
+ ## Instructions for Implementer
10
+
11
+ 1. Complete tasks in order (Phase 0 → 1 → 2 → 3 → 4)
12
+ 2. Run tests after each task: `npm test`
13
+ 3. Commit after each completed task
14
+ 4. Do NOT modify legacy mode behavior
15
+ 5. All new code must have tests
16
+
17
+ ---
18
+
19
+ ## Phase 0: Fix Jest Coverage Configuration
20
+
21
+ ### Task 0.1: Update Jest Config
22
+
23
+ **File**: `test/jest-test.json`
24
+
25
+ **Current (broken)**:
26
+ ```json
27
+ "collectCoverageFrom": [
28
+ "src/**/*.ts",
29
+ "!**/node_modules/**"
30
+ ]
31
+ ```
32
+
33
+ **Replace with**:
34
+ ```json
35
+ "collectCoverageFrom": [
36
+ "lib/**/*.ts",
37
+ "!lib/**/index.ts",
38
+ "!**/node_modules/**"
39
+ ],
40
+ "coverageDirectory": "./coverage",
41
+ "coverageThreshold": {
42
+ "global": {
43
+ "branches": 70,
44
+ "functions": 80,
45
+ "lines": 80,
46
+ "statements": 80
47
+ }
48
+ }
49
+ ```
50
+
51
+ **Verify**: Run `npm run test:cov` - should show coverage for `lib/` files.
52
+
53
+ **Commit**: `fix(test): correct Jest coverage configuration`
54
+
55
+ ---
56
+
57
+ ## Phase 1: Memory Leak Fixes
58
+
59
+ ### Task 1.1: Add Max Size to Deprecation Warnings
60
+
61
+ **File**: `lib/utils/deprecation.ts`
62
+
63
+ **Replace entire file with**:
64
+
65
+ ```typescript
66
+ import { Logger } from '@nestjs/common';
67
+
68
+ const logger = new Logger('DeprecationWarning');
69
+ const MAX_WARNED_FEATURES = 100;
70
+ const warnedFeatures = new Map<string, number>();
71
+
72
+ /**
73
+ * Emit a deprecation warning once per feature (with LRU eviction)
74
+ */
75
+ export function warnDeprecation(
76
+ feature: string,
77
+ message: string,
78
+ alternative?: string,
79
+ ): void {
80
+ if (warnedFeatures.has(feature)) {
81
+ return;
82
+ }
83
+
84
+ // LRU eviction when at capacity
85
+ if (warnedFeatures.size >= MAX_WARNED_FEATURES) {
86
+ const oldestKey = warnedFeatures.keys().next().value;
87
+ if (oldestKey) {
88
+ warnedFeatures.delete(oldestKey);
89
+ }
90
+ }
91
+
92
+ warnedFeatures.set(feature, Date.now());
93
+
94
+ let warning = `DEPRECATED: ${feature} - ${message}`;
95
+ if (alternative) {
96
+ warning += `\nPlease use: ${alternative}`;
97
+ }
98
+
99
+ logger.warn(warning);
100
+ }
101
+
102
+ /**
103
+ * Clear all deprecation warnings (useful for testing)
104
+ */
105
+ export function clearDeprecationWarnings(): void {
106
+ warnedFeatures.clear();
107
+ }
108
+
109
+ /**
110
+ * Get count of warned features (for monitoring)
111
+ */
112
+ export function getWarnedFeaturesCount(): number {
113
+ return warnedFeatures.size;
114
+ }
115
+ ```
116
+
117
+ **Create test file**: `test/utils/deprecation.spec.ts`
118
+
119
+ ```typescript
120
+ import { describe, it, expect, beforeEach } from '@jest/globals';
121
+ import {
122
+ warnDeprecation,
123
+ clearDeprecationWarnings,
124
+ getWarnedFeaturesCount
125
+ } from '../../lib/utils/deprecation';
126
+
127
+ describe('deprecation warnings', () => {
128
+ beforeEach(() => {
129
+ clearDeprecationWarnings();
130
+ });
131
+
132
+ it('should only warn once per feature', () => {
133
+ warnDeprecation('feature1', 'deprecated');
134
+ warnDeprecation('feature1', 'deprecated');
135
+ expect(getWarnedFeaturesCount()).toBe(1);
136
+ });
137
+
138
+ it('should allow different features', () => {
139
+ warnDeprecation('feature1', 'deprecated');
140
+ warnDeprecation('feature2', 'deprecated');
141
+ expect(getWarnedFeaturesCount()).toBe(2);
142
+ });
143
+
144
+ it('should evict oldest when at capacity', () => {
145
+ for (let i = 0; i < 100; i++) {
146
+ warnDeprecation(`feature-${i}`, 'deprecated');
147
+ }
148
+ expect(getWarnedFeaturesCount()).toBe(100);
149
+
150
+ warnDeprecation('feature-100', 'deprecated');
151
+ expect(getWarnedFeaturesCount()).toBe(100);
152
+ });
153
+
154
+ it('should clear all warnings', () => {
155
+ warnDeprecation('feature1', 'deprecated');
156
+ clearDeprecationWarnings();
157
+ expect(getWarnedFeaturesCount()).toBe(0);
158
+ });
159
+
160
+ it('should include alternative in warning', () => {
161
+ // Just verify it doesn't throw
162
+ expect(() => {
163
+ warnDeprecation('old-api', 'deprecated', 'Use new-api instead');
164
+ }).not.toThrow();
165
+ });
166
+ });
167
+ ```
168
+
169
+ **Verify**: `npm test -- test/utils/deprecation.spec.ts`
170
+
171
+ **Commit**: `fix(utils): add max size limit to deprecation warnings set`
172
+
173
+ ---
174
+
175
+ ### Task 1.2: Cache RedisPatternInvalidation Instance
176
+
177
+ **File**: `lib/service/cache-manager.ts`
178
+
179
+ **Step 1**: Add import at top of file:
180
+ ```typescript
181
+ import { RedisPatternInvalidation } from './redis-pattern-invalidation';
182
+ ```
183
+
184
+ **Step 2**: Add property after `useCacheable`:
185
+ ```typescript
186
+ private patternInvalidator?: RedisPatternInvalidation;
187
+ ```
188
+
189
+ **Step 3**: Initialize in constructor (after `this.useCacheable = !!cacheable;`):
190
+ ```typescript
191
+ if (this.useCacheable && this.cacheable) {
192
+ this.patternInvalidator = new RedisPatternInvalidation(this.cacheable);
193
+ }
194
+ ```
195
+
196
+ **Step 4**: Replace `invalidateByPattern` method:
197
+ ```typescript
198
+ /**
199
+ * Invalidate cache keys matching a pattern (enhanced mode)
200
+ * This method uses efficient Redis SCAN for pattern-based invalidation
201
+ * @param pattern Pattern to match (e.g., 'user:*', 'session:123:*')
202
+ */
203
+ async invalidateByPattern(pattern: string): Promise<void> {
204
+ if (this.useCacheable && this.patternInvalidator) {
205
+ try {
206
+ await this.patternInvalidator.deleteByPattern(pattern);
207
+ } catch (error) {
208
+ this.logger.error(`Pattern invalidation failed for pattern ${pattern}:`, error);
209
+ throw error;
210
+ }
211
+ return;
212
+ }
213
+
214
+ // Legacy mode - use existing pattern deletion
215
+ await this.cacheProvider.delByPatternRaw([pattern]);
216
+ }
217
+ ```
218
+
219
+ **Verify**: `npm test`
220
+
221
+ **Commit**: `fix(cache-manager): cache RedisPatternInvalidation instance`
222
+
223
+ ---
224
+
225
+ ### Task 1.3: Fix Redis Connection Cleanup
226
+
227
+ **File**: `lib/service/redis-cache-invalidate.manager.ts`
228
+
229
+ **Step 1**: Add property after `protected protectedKeys`:
230
+ ```typescript
231
+ private messageHandler?: (channel: string, message: string) => Promise<void>;
232
+ ```
233
+
234
+ **Step 2**: Refactor `subscribe()` method - extract message handling to separate methods:
235
+
236
+ ```typescript
237
+ async subscribe(): Promise<void> {
238
+ const errorHandler = (err: { message: any }, count: any) => {
239
+ if (err) {
240
+ this.logger.error(`Failed to subscribe: ${err.message}`);
241
+ } else {
242
+ this.logger.log(`Subscribed successfully! This client is currently subscribed to ${count} channels.`);
243
+ }
244
+ };
245
+
246
+ this.subClient.subscribe(this.extraOptions.channel, errorHandler);
247
+ this.subClient.subscribe(this.extraOptions.mchannel, errorHandler);
248
+
249
+ // Store reference to handler for cleanup
250
+ this.messageHandler = async (channel: string, message: string) => {
251
+ if (channel === this.extraOptions.channel) {
252
+ await this.handleSingleInvalidate(message);
253
+ } else if (channel === this.extraOptions.mchannel) {
254
+ await this.handleMultiInvalidate(message);
255
+ }
256
+ };
257
+
258
+ this.subClient.on('message', this.messageHandler);
259
+ }
260
+
261
+ private async handleSingleInvalidate(message: string): Promise<void> {
262
+ try {
263
+ const { cacheKey, group } = JSON.parse(message);
264
+
265
+ if (isProtectedKey(cacheKey, this.protectedKeys) ||
266
+ isProtectedKeyPrefix(cacheKey, this.protectedKeys, ':')) {
267
+ this.logger.warn(`Protected key is not allowed to be invalidated`);
268
+ return;
269
+ }
270
+
271
+ if (group) {
272
+ await this.cacheProvider.delByPattern(cacheKey);
273
+ } else {
274
+ await this.cacheProvider.del(cacheKey);
275
+ }
276
+ } catch (err) {
277
+ this.logger.error(`Failed to parse invalidate message`);
278
+ }
279
+ }
280
+
281
+ private async handleMultiInvalidate(message: string): Promise<void> {
282
+ try {
283
+ const { cacheKeys, group } = JSON.parse(message);
284
+
285
+ if (!Array.isArray(cacheKeys)) {
286
+ this.logger.error(`Invalid cacheKeys format - expected array`);
287
+ return;
288
+ }
289
+
290
+ const safeCacheKeys = cacheKeys.filter(
291
+ (key) => !isProtectedKey(key, this.protectedKeys) &&
292
+ !isProtectedKeyPrefix(key, this.protectedKeys, ':')
293
+ );
294
+
295
+ if (safeCacheKeys.length !== cacheKeys.length) {
296
+ this.logger.warn(`Some protected keys excluded from invalidation`);
297
+ }
298
+
299
+ if (group) {
300
+ await this.cacheProvider.mdelByPattern(safeCacheKeys);
301
+ } else {
302
+ await this.cacheProvider.mdel(safeCacheKeys);
303
+ }
304
+ } catch (err) {
305
+ this.logger.error(`Failed to parse multi-invalidate message`);
306
+ }
307
+ }
308
+ ```
309
+
310
+ **Step 3**: Replace `close()` method:
311
+
312
+ ```typescript
313
+ public async close(): Promise<void> {
314
+ this.isExplicitlyTerminated = true;
315
+
316
+ const closePromises: Promise<void>[] = [];
317
+
318
+ if (this.subClient) {
319
+ // Remove message handler before closing
320
+ if (this.messageHandler) {
321
+ this.subClient.removeListener('message', this.messageHandler);
322
+ this.messageHandler = undefined;
323
+ }
324
+
325
+ closePromises.push(
326
+ Promise.race([
327
+ this.subClient.quit().catch((err: Error) => {
328
+ this.logger.warn(`Error closing subscriber: ${err.message}`);
329
+ }),
330
+ new Promise<void>((resolve) => setTimeout(resolve, 5000)),
331
+ ])
332
+ );
333
+ }
334
+
335
+ if (this.pubClient) {
336
+ closePromises.push(
337
+ Promise.race([
338
+ this.pubClient.quit().catch((err: Error) => {
339
+ this.logger.warn(`Error closing publisher: ${err.message}`);
340
+ }),
341
+ new Promise<void>((resolve) => setTimeout(resolve, 5000)),
342
+ ])
343
+ );
344
+ }
345
+
346
+ await Promise.all(closePromises);
347
+
348
+ this.pubClient = null;
349
+ this.subClient = null;
350
+ }
351
+ ```
352
+
353
+ **Verify**: `npm test`
354
+
355
+ **Commit**: `fix(redis-invalidate): proper connection cleanup with error handling`
356
+
357
+ ---
358
+
359
+ ## Phase 2: Security Hardening
360
+
361
+ ### Task 2.1: Add Cache Key Sanitization
362
+
363
+ **File**: `lib/utils/cache-key.utils.ts`
364
+
365
+ **Replace entire file with**:
366
+
367
+ ```typescript
368
+ import { CacheKey } from "../interface";
369
+
370
+ const MAX_KEY_LENGTH = 256;
371
+
372
+ /**
373
+ * Sanitize a single cache key part
374
+ * Removes potentially dangerous characters
375
+ */
376
+ export function sanitizeCacheKeyPart(part: string): string {
377
+ if (!part || typeof part !== 'string') {
378
+ throw new Error('Cache key part must be a non-empty string');
379
+ }
380
+
381
+ // Replace disallowed characters with underscores
382
+ const sanitized = part.replace(/[^a-zA-Z0-9:_\-\.]/g, '_');
383
+
384
+ // Collapse multiple underscores
385
+ return sanitized.replace(/_+/g, '_');
386
+ }
387
+
388
+ /**
389
+ * Validate cache key length
390
+ */
391
+ export function validateCacheKeyLength(key: string): void {
392
+ if (key.length > MAX_KEY_LENGTH) {
393
+ throw new Error(`Cache key exceeds maximum length of ${MAX_KEY_LENGTH} characters`);
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Resolve cache key from parts with sanitization
399
+ */
400
+ export const resolveCacheKey = (cacheKeyParts: CacheKey): string => {
401
+ let key: string;
402
+
403
+ if (Array.isArray(cacheKeyParts)) {
404
+ key = cacheKeyParts
405
+ .map(k => sanitizeCacheKeyPart(k).toUpperCase())
406
+ .join(':');
407
+ } else {
408
+ key = sanitizeCacheKeyPart(cacheKeyParts).toUpperCase();
409
+ }
410
+
411
+ validateCacheKeyLength(key);
412
+ return key;
413
+ };
414
+
415
+ export const isProtectedKey = (key: string, protectedKeys: string[]): boolean => {
416
+ return protectedKeys.includes(key);
417
+ };
418
+
419
+ export const isProtectedKeyPrefix = (key: string, protectedKeys: string[], separator = ''): boolean => {
420
+ return protectedKeys.some(k => key.startsWith(`${k}${separator}`));
421
+ };
422
+ ```
423
+
424
+ **Update test file**: `test/util/cache-keys.utils.spec.ts`
425
+
426
+ Add these tests:
427
+
428
+ ```typescript
429
+ describe('cache key sanitization', () => {
430
+ it('should sanitize special characters', () => {
431
+ expect(resolveCacheKey('user<script>')).toBe('USER_SCRIPT_');
432
+ });
433
+
434
+ it('should collapse multiple underscores', () => {
435
+ expect(resolveCacheKey('test!!!key')).toBe('TEST_KEY');
436
+ });
437
+
438
+ it('should reject empty keys', () => {
439
+ expect(() => resolveCacheKey('')).toThrow('non-empty string');
440
+ });
441
+
442
+ it('should reject null/undefined keys', () => {
443
+ expect(() => resolveCacheKey(null as any)).toThrow('non-empty string');
444
+ expect(() => resolveCacheKey(undefined as any)).toThrow('non-empty string');
445
+ });
446
+
447
+ it('should reject keys exceeding max length', () => {
448
+ const longKey = 'a'.repeat(300);
449
+ expect(() => resolveCacheKey(longKey)).toThrow('exceeds maximum length');
450
+ });
451
+
452
+ it('should accept keys at max length', () => {
453
+ const maxKey = 'a'.repeat(256);
454
+ expect(() => resolveCacheKey(maxKey)).not.toThrow();
455
+ });
456
+
457
+ it('should sanitize array keys', () => {
458
+ expect(resolveCacheKey(['user', '../etc'])).toBe('USER:_.._ETC');
459
+ });
460
+
461
+ it('should preserve allowed characters', () => {
462
+ expect(resolveCacheKey('user-123_test.key')).toBe('USER-123_TEST.KEY');
463
+ });
464
+ });
465
+ ```
466
+
467
+ **Verify**: `npm test`
468
+
469
+ **Commit**: `fix(security): add cache key sanitization`
470
+
471
+ ---
472
+
473
+ ### Task 2.2: Add Message Validation
474
+
475
+ **Create new file**: `lib/utils/validation.ts`
476
+
477
+ ```typescript
478
+ /**
479
+ * Validate cache invalidate message structure
480
+ */
481
+ export function validateInvalidateMessage(data: unknown): asserts data is {
482
+ cacheKey?: string;
483
+ cacheKeys?: string[];
484
+ group?: boolean
485
+ } {
486
+ if (!data || typeof data !== 'object') {
487
+ throw new Error('Invalid message: must be an object');
488
+ }
489
+
490
+ const msg = data as Record<string, unknown>;
491
+
492
+ if (msg.cacheKey !== undefined && typeof msg.cacheKey !== 'string') {
493
+ throw new Error('Invalid message: cacheKey must be a string');
494
+ }
495
+
496
+ if (msg.cacheKeys !== undefined) {
497
+ if (!Array.isArray(msg.cacheKeys)) {
498
+ throw new Error('Invalid message: cacheKeys must be an array');
499
+ }
500
+ if (!msg.cacheKeys.every((k: unknown) => typeof k === 'string')) {
501
+ throw new Error('Invalid message: all cacheKeys must be strings');
502
+ }
503
+ }
504
+
505
+ if (msg.group !== undefined && typeof msg.group !== 'boolean') {
506
+ throw new Error('Invalid message: group must be a boolean');
507
+ }
508
+
509
+ if (!msg.cacheKey && !msg.cacheKeys) {
510
+ throw new Error('Invalid message: must have cacheKey or cacheKeys');
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Safely parse JSON with validation
516
+ */
517
+ export function parseInvalidateMessage(json: string): {
518
+ cacheKey?: string;
519
+ cacheKeys?: string[];
520
+ group?: boolean
521
+ } {
522
+ let data: unknown;
523
+
524
+ try {
525
+ data = JSON.parse(json);
526
+ } catch {
527
+ throw new Error('Invalid JSON format');
528
+ }
529
+
530
+ validateInvalidateMessage(data);
531
+ return data;
532
+ }
533
+ ```
534
+
535
+ **Update**: `lib/utils/index.ts` - add export:
536
+
537
+ ```typescript
538
+ export * from './validation';
539
+ ```
540
+
541
+ **Create test file**: `test/utils/validation.spec.ts`
542
+
543
+ ```typescript
544
+ import { describe, it, expect } from '@jest/globals';
545
+ import { validateInvalidateMessage, parseInvalidateMessage } from '../../lib/utils/validation';
546
+
547
+ describe('validateInvalidateMessage', () => {
548
+ it('should accept valid single key message', () => {
549
+ expect(() => validateInvalidateMessage({ cacheKey: 'test', group: false })).not.toThrow();
550
+ });
551
+
552
+ it('should accept valid multi key message', () => {
553
+ expect(() => validateInvalidateMessage({ cacheKeys: ['a', 'b'], group: true })).not.toThrow();
554
+ });
555
+
556
+ it('should reject non-object', () => {
557
+ expect(() => validateInvalidateMessage('string')).toThrow('must be an object');
558
+ expect(() => validateInvalidateMessage(null)).toThrow('must be an object');
559
+ });
560
+
561
+ it('should reject invalid cacheKey type', () => {
562
+ expect(() => validateInvalidateMessage({ cacheKey: 123 })).toThrow('cacheKey must be a string');
563
+ });
564
+
565
+ it('should reject invalid cacheKeys type', () => {
566
+ expect(() => validateInvalidateMessage({ cacheKeys: 'not-array' })).toThrow('must be an array');
567
+ });
568
+
569
+ it('should reject non-string items in cacheKeys', () => {
570
+ expect(() => validateInvalidateMessage({ cacheKeys: ['a', 123] })).toThrow('must be strings');
571
+ });
572
+
573
+ it('should reject missing both cacheKey and cacheKeys', () => {
574
+ expect(() => validateInvalidateMessage({ group: true })).toThrow('must have cacheKey or cacheKeys');
575
+ });
576
+ });
577
+
578
+ describe('parseInvalidateMessage', () => {
579
+ it('should parse valid JSON', () => {
580
+ const result = parseInvalidateMessage('{"cacheKey": "test"}');
581
+ expect(result).toEqual({ cacheKey: 'test' });
582
+ });
583
+
584
+ it('should reject invalid JSON', () => {
585
+ expect(() => parseInvalidateMessage('not json')).toThrow('Invalid JSON');
586
+ });
587
+
588
+ it('should validate after parsing', () => {
589
+ expect(() => parseInvalidateMessage('{"invalid": true}')).toThrow('must have cacheKey');
590
+ });
591
+ });
592
+ ```
593
+
594
+ **Verify**: `npm test`
595
+
596
+ **Commit**: `fix(security): add message validation for Redis pub/sub`
597
+
598
+ ---
599
+
600
+ ### Task 2.3: Mask Passwords in Logs
601
+
602
+ **File**: `lib/provider/cacheable.provider.ts`
603
+
604
+ **Add new function after `buildRedisUrl`**:
605
+
606
+ ```typescript
607
+ /**
608
+ * Build Redis URL with masked password for logging
609
+ */
610
+ export function buildRedisUrlForLogging(options: DistributedCacheOptions): string {
611
+ if (options.url) {
612
+ // Mask password in existing URL
613
+ return options.url.replace(/:([^@]+)@/, ':***@');
614
+ }
615
+
616
+ const host = options.host || 'localhost';
617
+ const port = options.port || 6379;
618
+ const db = options.db || 0;
619
+
620
+ let url = 'redis://';
621
+ if (options.password) {
622
+ url += ':***@';
623
+ }
624
+ url += `${host}:${port}/${db}`;
625
+
626
+ return url;
627
+ }
628
+ ```
629
+
630
+ **Add test to** `test/cacheable-multi-tier.spec.ts`:
631
+
632
+ ```typescript
633
+ describe('buildRedisUrlForLogging', () => {
634
+ it('should mask password in URL', () => {
635
+ const options: DistributedCacheOptions = {
636
+ host: 'localhost',
637
+ password: 'supersecret',
638
+ };
639
+ expect(buildRedisUrlForLogging(options)).toBe('redis://:***@localhost:6379/0');
640
+ });
641
+
642
+ it('should mask password in existing URL', () => {
643
+ const options: DistributedCacheOptions = {
644
+ url: 'redis://:mypassword@redis.example.com:6379/0',
645
+ };
646
+ expect(buildRedisUrlForLogging(options)).toBe('redis://:***@redis.example.com:6379/0');
647
+ });
648
+
649
+ it('should not add mask when no password', () => {
650
+ const options: DistributedCacheOptions = {
651
+ host: 'localhost',
652
+ };
653
+ expect(buildRedisUrlForLogging(options)).toBe('redis://localhost:6379/0');
654
+ });
655
+ });
656
+ ```
657
+
658
+ **Verify**: `npm test`
659
+
660
+ **Commit**: `fix(security): mask Redis password in logs`
661
+
662
+ ---
663
+
664
+ ## Phase 3: Test Coverage
665
+
666
+ ### Task 3.1: CacheProvider Unit Tests
667
+
668
+ **Create file**: `test/service/cache-provider.spec.ts`
669
+
670
+ ```typescript
671
+ import { describe, it, expect, beforeEach, jest } from '@jest/globals';
672
+ import { CacheProvider } from '../../lib/service/cache-provider';
673
+ import { createMock } from '@golevelup/ts-jest';
674
+ import { Cache } from 'cache-manager';
675
+
676
+ describe('CacheProvider', () => {
677
+ let cacheProvider: CacheProvider;
678
+ let mockCacheManager: jest.Mocked<Cache>;
679
+
680
+ beforeEach(() => {
681
+ mockCacheManager = createMock<Cache>();
682
+ mockCacheManager.stores = [];
683
+ cacheProvider = new CacheProvider(mockCacheManager);
684
+ });
685
+
686
+ describe('get', () => {
687
+ it('should return cached value when exists', async () => {
688
+ mockCacheManager.get.mockResolvedValue('cached-value');
689
+
690
+ const result = await cacheProvider.get('test-key');
691
+
692
+ expect(result).toBe('cached-value');
693
+ expect(mockCacheManager.get).toHaveBeenCalledWith('TEST-KEY');
694
+ });
695
+
696
+ it('should return null when no cache and no resolver', async () => {
697
+ mockCacheManager.get.mockResolvedValue(null);
698
+
699
+ const result = await cacheProvider.get('test-key');
700
+
701
+ expect(result).toBeNull();
702
+ });
703
+
704
+ it('should call resolver and cache result on miss', async () => {
705
+ mockCacheManager.get.mockResolvedValue(null);
706
+ mockCacheManager.set.mockResolvedValue(undefined);
707
+ const resolver = jest.fn().mockResolvedValue('fresh-value');
708
+
709
+ const result = await cacheProvider.get('test-key', resolver, 5000);
710
+
711
+ expect(resolver).toHaveBeenCalled();
712
+ expect(mockCacheManager.set).toHaveBeenCalledWith('TEST-KEY', 'fresh-value', 5000);
713
+ expect(result).toBe('fresh-value');
714
+ });
715
+
716
+ it('should not cache null resolver results', async () => {
717
+ mockCacheManager.get.mockResolvedValue(null);
718
+ const resolver = jest.fn().mockResolvedValue(null);
719
+
720
+ await cacheProvider.get('test-key', resolver);
721
+
722
+ expect(mockCacheManager.set).not.toHaveBeenCalled();
723
+ });
724
+
725
+ it('should not cache undefined resolver results', async () => {
726
+ mockCacheManager.get.mockResolvedValue(null);
727
+ const resolver = jest.fn().mockResolvedValue(undefined);
728
+
729
+ await cacheProvider.get('test-key', resolver);
730
+
731
+ expect(mockCacheManager.set).not.toHaveBeenCalled();
732
+ });
733
+ });
734
+
735
+ describe('getOnly', () => {
736
+ it('should return cached value without resolver', async () => {
737
+ mockCacheManager.get.mockResolvedValue('value');
738
+
739
+ const result = await cacheProvider.getOnly('key');
740
+
741
+ expect(result).toBe('value');
742
+ });
743
+ });
744
+
745
+ describe('set', () => {
746
+ it('should set value with TTL', async () => {
747
+ await cacheProvider.set('key', 'value', 5000);
748
+
749
+ expect(mockCacheManager.set).toHaveBeenCalledWith('KEY', 'value', 5000);
750
+ });
751
+
752
+ it('should use default TTL', async () => {
753
+ await cacheProvider.set('key', 'value');
754
+
755
+ expect(mockCacheManager.set).toHaveBeenCalledWith('KEY', 'value', 300000);
756
+ });
757
+ });
758
+
759
+ describe('mset', () => {
760
+ it('should set multiple values', async () => {
761
+ const list = [
762
+ { key: 'key1', value: 'v1', ttl: 1000 },
763
+ { key: 'key2', value: 'v2', ttl: 2000 },
764
+ ];
765
+ mockCacheManager.mset.mockResolvedValue(undefined);
766
+
767
+ await cacheProvider.mset(list);
768
+
769
+ expect(mockCacheManager.mset).toHaveBeenCalledWith([
770
+ { key: 'KEY1', value: 'v1', ttl: 1000 },
771
+ { key: 'KEY2', value: 'v2', ttl: 2000 },
772
+ ]);
773
+ });
774
+ });
775
+
776
+ describe('del', () => {
777
+ it('should delete key', async () => {
778
+ await cacheProvider.del('key');
779
+
780
+ expect(mockCacheManager.del).toHaveBeenCalledWith('KEY');
781
+ });
782
+ });
783
+
784
+ describe('mdel', () => {
785
+ it('should delete multiple keys', async () => {
786
+ await cacheProvider.mdel(['key1', 'key2']);
787
+
788
+ expect(mockCacheManager.mdel).toHaveBeenCalledWith(['KEY1', 'KEY2']);
789
+ });
790
+
791
+ it('should handle array keys', async () => {
792
+ await cacheProvider.mdel([['a', 'b'], ['c', 'd']]);
793
+
794
+ expect(mockCacheManager.mdel).toHaveBeenCalledWith(['A:B', 'C:D']);
795
+ });
796
+ });
797
+
798
+ describe('mget', () => {
799
+ it('should get multiple values', async () => {
800
+ mockCacheManager.mget.mockResolvedValue(['v1', 'v2']);
801
+
802
+ const result = await cacheProvider.mget(['key1', 'key2']);
803
+
804
+ expect(result).toEqual(['v1', 'v2']);
805
+ });
806
+ });
807
+
808
+ describe('reset', () => {
809
+ it('should clear cache', async () => {
810
+ mockCacheManager.clear.mockResolvedValue(true);
811
+
812
+ const result = await cacheProvider.reset();
813
+
814
+ expect(result).toBe(true);
815
+ expect(mockCacheManager.clear).toHaveBeenCalled();
816
+ });
817
+ });
818
+
819
+ describe('keys', () => {
820
+ it('should return empty array when no stores', async () => {
821
+ mockCacheManager.stores = [];
822
+
823
+ const keys = await cacheProvider.keys();
824
+
825
+ expect(keys).toEqual([]);
826
+ });
827
+
828
+ it('should iterate over stores with iterator', async () => {
829
+ const mockIterator = async function* () {
830
+ yield ['key1', 'v1'];
831
+ yield ['key2', 'v2'];
832
+ };
833
+ mockCacheManager.stores = [{ iterator: mockIterator }, {}];
834
+
835
+ const keys = await cacheProvider.keys();
836
+
837
+ expect(keys).toEqual(['key1', 'key2']);
838
+ });
839
+
840
+ it('should deduplicate keys', async () => {
841
+ const mockIterator1 = async function* () {
842
+ yield ['key1', 'v1'];
843
+ };
844
+ const mockIterator2 = async function* () {
845
+ yield ['key1', 'v2'];
846
+ };
847
+ mockCacheManager.stores = [
848
+ { iterator: mockIterator1 },
849
+ { iterator: mockIterator2 },
850
+ {},
851
+ ];
852
+
853
+ const keys = await cacheProvider.keys();
854
+
855
+ expect(keys).toEqual(['key1']);
856
+ });
857
+ });
858
+
859
+ describe('delByPatternRaw', () => {
860
+ it('should delete keys matching pattern', async () => {
861
+ const mockIterator = async function* () {
862
+ yield ['user:1', 'v1'];
863
+ yield ['user:2', 'v2'];
864
+ yield ['session:1', 'v3'];
865
+ };
866
+ mockCacheManager.stores = [{ iterator: mockIterator }, {}];
867
+
868
+ await cacheProvider.delByPatternRaw(['user:']);
869
+
870
+ expect(mockCacheManager.mdel).toHaveBeenCalledWith(['user:1', 'user:2']);
871
+ });
872
+
873
+ it('should handle multiple patterns', async () => {
874
+ const mockIterator = async function* () {
875
+ yield ['user:1', 'v1'];
876
+ yield ['session:1', 'v2'];
877
+ yield ['other:1', 'v3'];
878
+ };
879
+ mockCacheManager.stores = [{ iterator: mockIterator }, {}];
880
+
881
+ await cacheProvider.delByPatternRaw(['user:', 'session:']);
882
+
883
+ expect(mockCacheManager.mdel).toHaveBeenCalledWith(['user:1', 'session:1']);
884
+ });
885
+ });
886
+ });
887
+ ```
888
+
889
+ **Verify**: `npm test`
890
+
891
+ **Commit**: `test(cache-provider): add comprehensive unit tests`
892
+
893
+ ---
894
+
895
+ ### Task 3.2: Health Check Interface
896
+
897
+ **Create file**: `lib/interface/health.interface.ts`
898
+
899
+ ```typescript
900
+ export interface CacheConnectionHealth {
901
+ name: string;
902
+ status: 'connected' | 'disconnected' | 'connecting' | 'error';
903
+ latencyMs?: number;
904
+ error?: string;
905
+ }
906
+
907
+ export interface CacheHealthResult {
908
+ healthy: boolean;
909
+ timestamp: Date;
910
+ connections: CacheConnectionHealth[];
911
+ stats?: {
912
+ hits?: number;
913
+ misses?: number;
914
+ keys?: number;
915
+ };
916
+ }
917
+
918
+ export interface CacheHealthCheck {
919
+ /**
920
+ * Check health of all cache connections
921
+ */
922
+ isHealthy(): Promise<CacheHealthResult>;
923
+ }
924
+ ```
925
+
926
+ **Update**: `lib/interface/index.ts` - add export:
927
+ ```typescript
928
+ export * from './health.interface';
929
+ ```
930
+
931
+ **Update**: `lib/service/cache-manager.ts` - implement health check:
932
+
933
+ Add import:
934
+ ```typescript
935
+ import { CacheHealthCheck, CacheHealthResult, CacheConnectionHealth } from '../interface/health.interface';
936
+ ```
937
+
938
+ Add `implements CacheHealthCheck` to class declaration.
939
+
940
+ Add method:
941
+ ```typescript
942
+ /**
943
+ * Check health of cache connections
944
+ */
945
+ async isHealthy(): Promise<CacheHealthResult> {
946
+ const connections: CacheConnectionHealth[] = [];
947
+ let healthy = true;
948
+
949
+ if (this.useCacheable && this.cacheable) {
950
+ // Check primary (memory) cache
951
+ if (this.cacheable.primary) {
952
+ connections.push({
953
+ name: 'memory',
954
+ status: 'connected',
955
+ });
956
+ }
957
+
958
+ // Check secondary (Redis) cache
959
+ if (this.cacheable.secondary?.client) {
960
+ try {
961
+ const start = Date.now();
962
+ await this.cacheable.secondary.client.ping();
963
+ connections.push({
964
+ name: 'redis',
965
+ status: 'connected',
966
+ latencyMs: Date.now() - start,
967
+ });
968
+ } catch (error: any) {
969
+ healthy = false;
970
+ connections.push({
971
+ name: 'redis',
972
+ status: 'error',
973
+ error: error.message,
974
+ });
975
+ }
976
+ }
977
+ } else {
978
+ // Legacy mode
979
+ connections.push({
980
+ name: 'cache-manager',
981
+ status: 'connected',
982
+ });
983
+ }
984
+
985
+ return {
986
+ healthy,
987
+ timestamp: new Date(),
988
+ connections,
989
+ stats: await this.getStats(),
990
+ };
991
+ }
992
+ ```
993
+
994
+ **Create test in**: `test/service/cache-manager.spec.ts` - add:
995
+
996
+ ```typescript
997
+ describe('isHealthy', () => {
998
+ it('should return healthy for legacy mode', async () => {
999
+ cacheManager = new CacheManager(
1000
+ { strategy: InvalidateStrategy.DIRECT },
1001
+ cache,
1002
+ cacheInvalidateManager,
1003
+ null
1004
+ );
1005
+
1006
+ const result = await cacheManager.isHealthy();
1007
+
1008
+ expect(result.healthy).toBe(true);
1009
+ expect(result.connections).toHaveLength(1);
1010
+ expect(result.connections[0].name).toBe('cache-manager');
1011
+ });
1012
+
1013
+ it('should check redis connection in enhanced mode', async () => {
1014
+ const mockCacheable = {
1015
+ primary: {},
1016
+ secondary: {
1017
+ client: {
1018
+ ping: jest.fn().mockResolvedValue('PONG'),
1019
+ },
1020
+ },
1021
+ getStats: jest.fn().mockReturnValue(null),
1022
+ };
1023
+
1024
+ cacheManager = new CacheManager(
1025
+ { strategy: InvalidateStrategy.DIRECT },
1026
+ cache,
1027
+ cacheInvalidateManager,
1028
+ mockCacheable
1029
+ );
1030
+
1031
+ const result = await cacheManager.isHealthy();
1032
+
1033
+ expect(result.healthy).toBe(true);
1034
+ expect(result.connections).toHaveLength(2);
1035
+ expect(result.connections[1].name).toBe('redis');
1036
+ expect(result.connections[1].latencyMs).toBeDefined();
1037
+ });
1038
+
1039
+ it('should report unhealthy when redis fails', async () => {
1040
+ const mockCacheable = {
1041
+ primary: {},
1042
+ secondary: {
1043
+ client: {
1044
+ ping: jest.fn().mockRejectedValue(new Error('Connection refused')),
1045
+ },
1046
+ },
1047
+ getStats: jest.fn().mockReturnValue(null),
1048
+ };
1049
+
1050
+ cacheManager = new CacheManager(
1051
+ { strategy: InvalidateStrategy.DIRECT },
1052
+ cache,
1053
+ cacheInvalidateManager,
1054
+ mockCacheable
1055
+ );
1056
+
1057
+ const result = await cacheManager.isHealthy();
1058
+
1059
+ expect(result.healthy).toBe(false);
1060
+ expect(result.connections[1].status).toBe('error');
1061
+ expect(result.connections[1].error).toBe('Connection refused');
1062
+ });
1063
+ });
1064
+ ```
1065
+
1066
+ **Verify**: `npm test`
1067
+
1068
+ **Commit**: `feat(health): add health check interface for cache connections`
1069
+
1070
+ ---
1071
+
1072
+ ## Completion Checklist
1073
+
1074
+ After all tasks:
1075
+
1076
+ 1. [ ] Run full test suite: `npm test`
1077
+ 2. [ ] Run coverage: `npm run test:cov` (target: 80%)
1078
+ 3. [ ] Build package: `npm run build`
1079
+ 4. [ ] Final commit: `chore: complete cache enhancements phase 1-3`
1080
+ 5. [ ] Push to branch: `git push origin cache-cacheable-migration`
1081
+
1082
+ ---
1083
+
1084
+ ## Notes for Implementer
1085
+
1086
+ - Always run `npm test` after each task
1087
+ - If a test fails, fix it before moving on
1088
+ - Do NOT skip tasks or combine them
1089
+ - Commit messages should match the format provided
1090
+ - If stuck, check the CODE_REVIEW.md for context