@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,312 @@
1
+ # Final Code Review β€” `@nathapp/nestjs-cache` v2.1.0-rc.0
2
+
3
+ **Date:** 2026-02-10
4
+ **Branch:** `cache-cacheable-migration`
5
+ **Reviewer:** Subrina (AI)
6
+ **Scope:** Security, memory leaks, enterprise-grade assessment
7
+
8
+ ---
9
+
10
+ ## Overall Verdict: **Aβˆ’** (Enterprise-Ready with Minor Items)
11
+
12
+ The module is in strong shape after the V2/V3 hardening passes. It supports four cache strategies (LEGACY, MEMORY, DISTRIBUTED, MULTI_TIER), has validated pub/sub messaging, rate limiting, graceful degradation, fail-fast config validation, and real Redis E2E tests. Below are the remaining findings.
13
+
14
+ ---
15
+
16
+ ## πŸ”΄ Critical Issues (0)
17
+
18
+ None found.
19
+
20
+ ---
21
+
22
+ ## 🟑 Security Findings
23
+
24
+ ### S1. `buildRedisConnectionUrl()` reconstructs plaintext password in URL (Medium)
25
+
26
+ **File:** `lib/provider/cacheable.provider.ts` β†’ `buildRedisConnectionUrl()`
27
+
28
+ The internal helper inside `createCacheableInstance()` builds a Redis URL with the raw password for `createKeyv()`:
29
+
30
+ ```ts
31
+ const buildRedisConnectionUrl = (distributedOpts) => {
32
+ const connection = resolveRedisConnection(distributedOpts);
33
+ let url = 'redis://';
34
+ if (connection.password) {
35
+ url += `:${connection.password}@`; // ← plaintext password in string
36
+ }
37
+ ...
38
+ };
39
+ ```
40
+
41
+ While this is internal (not exported) and required by `@keyv/redis`'s `createKeyv(url)`, the URL string lives in memory and could appear in stack traces or debug logs. This is an inherent limitation of `@keyv/redis` accepting URL strings.
42
+
43
+ **Risk:** Low (internal only, not logged)
44
+ **Recommendation:** Document this as a known limitation. If `@keyv/redis` adds connection-object support in the future, switch to it.
45
+
46
+ ### S2. `CacheInvalidateInterceptor` logs cache key in error message (Low)
47
+
48
+ **File:** `lib/interceptor/cache-invalidate.interceptor.ts:54`
49
+
50
+ ```ts
51
+ Logger.error(`An error has occurred when delete "key: ${key}"`, err.stack, ...);
52
+ ```
53
+
54
+ Cache keys are logged on error. If keys contain user-identifiable information, this leaks PII to logs.
55
+
56
+ **Recommendation:** Remove key from error log or hash it:
57
+ ```ts
58
+ Logger.error(`Cache invalidation failed for key hash ${hash(key)}`, err.stack, ...);
59
+ ```
60
+
61
+ ### S3. `CacheInterceptor` logs cache key on set error (Low)
62
+
63
+ **File:** `lib/interceptor/cache.interceptor.ts:77`
64
+
65
+ ```ts
66
+ Logger.error(`An error has occurred when inserting "key: ${key}"`, err);
67
+ ```
68
+
69
+ Same issue as S2.
70
+
71
+ ### S4. `RedisCacheInvalidateManager` β€” `require('ioredis')` in constructor (Low)
72
+
73
+ **File:** `lib/service/redis-cache-invalidate.manager.ts:38`
74
+
75
+ ```ts
76
+ redisPackage = loadPackage('ioredis', 'CacheModule', () => require('ioredis'));
77
+ ```
78
+
79
+ Uses a module-level `let redisPackage` that's shared across all instances. In a multi-tenant scenario (highly unlikely but theoretically possible), this is a shared mutable state concern.
80
+
81
+ **Risk:** Negligible for normal use.
82
+
83
+ ---
84
+
85
+ ## 🟑 Memory Leak Findings
86
+
87
+ ### M1. `RedisPatternInvalidation` holds stale Redis client reference (Medium)
88
+
89
+ **File:** `lib/service/redis-pattern-invalidation.ts`
90
+
91
+ The `RedisPatternInvalidation` class grabs a Redis client reference in the constructor and never updates it:
92
+
93
+ ```ts
94
+ constructor(private readonly cacheable: any) {
95
+ this.initializeRedisClient(); // Captures client reference once
96
+ }
97
+ ```
98
+
99
+ If the underlying Cacheable instance reconnects (e.g., after a Redis failover), the `redisClient` reference becomes stale. There's no reconnection listener or lazy-access pattern.
100
+
101
+ **Recommendation:** Use a getter that accesses `cacheable.secondary.client` (or `primary.client`) lazily each time, rather than caching the reference:
102
+
103
+ ```ts
104
+ private get redisClient(): any {
105
+ return this.cacheable.secondary?.client || this.cacheable.primary?.client || null;
106
+ }
107
+ ```
108
+
109
+ ### M2. `CacheProvider.keys()` loads all keys into memory (Medium)
110
+
111
+ **File:** `lib/service/cache-provider.ts:114-127`
112
+
113
+ ```ts
114
+ async keys(): Promise<string[]> {
115
+ const keys = [];
116
+ for (let i = 0; i < storesLength; i++) {
117
+ for await (const [key] of this.cacheManager.stores[i].iterator({})) {
118
+ if (!keys.includes(key)) {
119
+ keys.push(key);
120
+ }
121
+ }
122
+ }
123
+ return keys;
124
+ }
125
+ ```
126
+
127
+ Two issues:
128
+ 1. **Unbounded memory**: All keys are loaded into a single array. With millions of keys, this causes OOM.
129
+ 2. **O(nΒ²) dedup**: `keys.includes(key)` is O(n) per check, making the whole loop O(nΒ²). Use a `Set`.
130
+
131
+ **Recommendation:**
132
+ ```ts
133
+ async keys(): Promise<string[]> {
134
+ const keysSet = new Set<string>();
135
+ for (let i = 0; i < storesLength; i++) {
136
+ if (this.cacheManager.stores[i]?.iterator) {
137
+ for await (const [key] of this.cacheManager.stores[i].iterator({})) {
138
+ keysSet.add(key);
139
+ }
140
+ }
141
+ }
142
+ return Array.from(keysSet);
143
+ }
144
+ ```
145
+ Also consider adding a `maxKeys` safety limit to prevent runaway scans.
146
+
147
+ ### M3. `delByPatternRaw()` also loads all keys (Medium)
148
+
149
+ **File:** `lib/service/cache-provider.ts:99-108`
150
+
151
+ ```ts
152
+ async delByPatternRaw(patterns: string[]): Promise<void> {
153
+ const keys = await this.keys(); // ← loads ALL keys
154
+ ...
155
+ }
156
+ ```
157
+
158
+ This calls `keys()` internally, inheriting the same unbounded memory issue. In production with a large cache-manager backing store, this is a real risk.
159
+
160
+ **Recommendation:** This is a known limitation documented in the TODO. For legacy mode, consider adding a warning log when the key count exceeds a threshold (e.g., 10,000).
161
+
162
+ ### M4. `RedisCacheInvalidateManager.close()` β€” null assignment after quit (Low)
163
+
164
+ **File:** `lib/service/redis-cache-invalidate.manager.ts:197-198`
165
+
166
+ ```ts
167
+ this.pubClient = null;
168
+ this.subClient = null;
169
+ ```
170
+
171
+ After `close()`, if any pending operations try to use `pubClient` or `subClient`, they'll get a null reference error instead of a graceful "connection closed" error. Consider a `closed` flag check in `dispatch()`.
172
+
173
+ ### M5. `warnedFeatures` Map never cleared in production (Negligible)
174
+
175
+ **File:** `lib/utils/deprecation.ts`
176
+
177
+ The `warnedFeatures` Map has a cap of 100 entries with LRU eviction, so this is well-handled. No leak concern.
178
+
179
+ ---
180
+
181
+ ## 🟑 Robustness / Edge Cases
182
+
183
+ ### R1. `CacheManager.get()` β€” resolver errors are not distinguished from cache errors (Medium)
184
+
185
+ **File:** `lib/service/cache-manager.ts:117-132`
186
+
187
+ In enhanced mode, if the `resultResolver()` throws, the error is caught by the outer `try/catch` and routed through `handleCacheError()`, which may silently swallow it when `fallbackToMemory` is enabled. Resolver errors should propagate β€” they're application errors, not cache infrastructure errors.
188
+
189
+ **Recommendation:** Wrap only cache operations in try/catch, let resolver errors propagate:
190
+
191
+ ```ts
192
+ if (result === null && resultResolver) {
193
+ // Don't catch resolver errors β€” they're application logic
194
+ result = await resultResolver();
195
+ if (result !== null && result !== undefined) {
196
+ try {
197
+ await this.cacheable.set(cacheKey, result, expirationMs);
198
+ } catch (error: any) {
199
+ this.handleCacheError(error, 'set', cacheKey);
200
+ }
201
+ }
202
+ return result;
203
+ }
204
+ ```
205
+
206
+ ### R2. `mset` and `mget` in enhanced mode don't emit metrics (Low)
207
+
208
+ **File:** `lib/service/cache-manager.ts:244-263`
209
+
210
+ Both `mset()` and `mget()` skip metrics hooks entirely. For enterprise monitoring, these should emit per-key or batch-level metrics.
211
+
212
+ ### R3. `CacheManager.reset()` doesn't reset the `patternInvalidator` (Low)
213
+
214
+ **File:** `lib/service/cache-manager.ts:271`
215
+
216
+ After `reset()`, the `patternInvalidator` still holds a reference to the cacheable client, which is fine β€” but it's worth documenting that `reset()` clears data, not connections.
217
+
218
+ ### R4. No timeout on `cacheable.get()` / `cacheable.set()` operations (Low)
219
+
220
+ If Redis hangs (network partition without disconnect), cache operations will hang indefinitely. Consider wrapping enhanced-mode operations with a configurable timeout:
221
+
222
+ ```ts
223
+ await Promise.race([
224
+ this.cacheable.get(cacheKey),
225
+ timeout(this.operationTimeoutMs, 'Cache get timeout'),
226
+ ]);
227
+ ```
228
+
229
+ ### R5. `mget()` doesn't convert `undefined` β†’ `null` in enhanced mode (Low)
230
+
231
+ **File:** `lib/service/cache-manager.ts:260`
232
+
233
+ ```ts
234
+ return Promise.all(keys.map(key => this.cacheable.get(key)));
235
+ ```
236
+
237
+ Unlike `getOnly()` and `getRaw()`, `mget()` doesn't normalize `undefined` to `null`. Inconsistent API behavior.
238
+
239
+ ### R6. `config-validation.ts` uses `console.warn()` instead of `Logger` (Trivial)
240
+
241
+ **File:** `lib/utils/config-validation.ts:77`
242
+
243
+ ```ts
244
+ console.warn(`[CacheModule] Warning: MEMORY strategy detected with "distributed" config...`);
245
+ ```
246
+
247
+ Should use NestJS `Logger` for consistency with the rest of the codebase.
248
+
249
+ ---
250
+
251
+ ## βœ… Enterprise-Grade Strengths
252
+
253
+ | Capability | Status | Notes |
254
+ |---|---|---|
255
+ | **Multi-strategy support** | βœ… | LEGACY, MEMORY, DISTRIBUTED, MULTI_TIER |
256
+ | **Backward compatibility** | βœ… | Legacy mode default, deprecated aliases, re-exports |
257
+ | **Fail-fast validation** | βœ… | Config validated at `onModuleInit()` |
258
+ | **Redis URI parsing** | βœ… | `parseRedisUri()` handles redis:// and rediss:// |
259
+ | **Credential handling** | βœ… | Connection objects instead of URL strings (except `@keyv/redis` limitation) |
260
+ | **Pub/sub invalidation** | βœ… | Validated JSON parsing, protected key blocking |
261
+ | **Rate limiting** | βœ… | Configurable per-second limit on invalidation messages |
262
+ | **Graceful degradation** | βœ… | `fallbackToMemory` for Redis failures |
263
+ | **Metrics hooks** | βœ… | Non-blocking, catches async errors |
264
+ | **Pattern invalidation** | βœ… | Redis SCAN-based (non-blocking), broad pattern blocked |
265
+ | **Health check** | βœ… | `isHealthy()` with Redis ping + latency |
266
+ | **Lifecycle management** | βœ… | Proper `onApplicationShutdown()` cleanup |
267
+ | **Key sanitization** | βœ… | Percent-encoding (collision-safe), legacy compatibility option |
268
+ | **TTL shorthand** | βœ… | `'5m'`, `'1h'`, `'1d'` notation |
269
+ | **Test coverage** | βœ… | 288 unit + 62 E2E, real Redis via Docker Compose |
270
+ | **i18n support** | βœ… | Safe optional loading with try/catch |
271
+ | **Deprecation management** | βœ… | Warn-once with LRU, clear API guidance |
272
+
273
+ ---
274
+
275
+ ## πŸ“‹ Recommended Priority Actions
276
+
277
+ ### High Priority (before GA release)
278
+ 1. **R1** β€” Fix resolver error propagation in `CacheManager.get()` (can silently swallow app errors)
279
+ 2. **M1** β€” Make `RedisPatternInvalidation.redisClient` a lazy getter (stale reference after reconnect)
280
+ 3. **M2** β€” Replace `keys.includes()` with `Set` in `CacheProvider.keys()` (O(nΒ²) β†’ O(n))
281
+
282
+ ### Medium Priority (next sprint)
283
+ 4. **R5** — Normalize `mget()` undefined→null for consistent API
284
+ 5. **S2/S3** β€” Remove raw cache keys from interceptor error logs
285
+ 6. **R4** β€” Add configurable operation timeout for enhanced mode
286
+ 7. **R2** β€” Add metrics emission for `mset`/`mget`
287
+
288
+ ### Low Priority (backlog)
289
+ 8. **M4** β€” Add `closed` flag to `RedisCacheInvalidateManager` for post-close safety
290
+ 9. **R6** β€” Replace `console.warn` with NestJS `Logger` in config validation
291
+ 10. **S1** β€” Document `@keyv/redis` URL limitation
292
+
293
+ ---
294
+
295
+ ## Enterprise-Grade Summary
296
+
297
+ **What "enterprise-grade" means here:**
298
+
299
+ The module meets enterprise standards for:
300
+ - βœ… **Reliability**: Graceful degradation, fail-fast config, proper lifecycle management
301
+ - βœ… **Security**: Protected keys, rate limiting, validated pub/sub, credential-safe connection objects
302
+ - βœ… **Observability**: Metrics hooks, health checks, structured logging
303
+ - βœ… **Scalability**: Multi-tier caching (L1+L2), SCAN-based pattern invalidation
304
+ - βœ… **Maintainability**: 350+ tests, documented APIs, backward compatibility
305
+ - βœ… **Operability**: Docker Compose E2E, environment-based configuration
306
+
307
+ **Gaps to full enterprise-grade (addressed by priority actions above):**
308
+ - ⚠️ Operation timeouts for hung Redis connections
309
+ - ⚠️ Resolver error leakage through cache error handler
310
+ - ⚠️ Memory safety for large key sets in legacy mode
311
+
312
+ After addressing the 3 high-priority items, this module is production-ready for enterprise deployment.