@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.
- package/CLAUDE.md +149 -0
- package/MIGRATION.md +263 -0
- package/README.md +486 -1
- package/TODO.md +56 -0
- package/dist/enum/strategy.enum.d.ts +6 -0
- package/dist/enum/strategy.enum.js +8 -1
- package/dist/enum/strategy.enum.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/inteceptor/index.d.ts +1 -2
- package/dist/inteceptor/index.js +1 -2
- package/dist/inteceptor/index.js.map +1 -1
- package/dist/interceptor/cache-invalidate.interceptor.js.map +1 -0
- package/dist/{inteceptor → interceptor}/cache.interceptor.js +9 -3
- package/dist/interceptor/cache.interceptor.js.map +1 -0
- package/dist/interceptor/index.d.ts +2 -0
- package/dist/interceptor/index.js +19 -0
- package/dist/interceptor/index.js.map +1 -0
- package/dist/interface/cache-invalidate.interface.d.ts +8 -0
- package/dist/interface/enhanced-cache-options.interface.d.ts +45 -0
- package/dist/interface/enhanced-cache-options.interface.js +3 -0
- package/dist/interface/enhanced-cache-options.interface.js.map +1 -0
- package/dist/interface/health.interface.d.ts +19 -0
- package/dist/interface/health.interface.js +3 -0
- package/dist/interface/health.interface.js.map +1 -0
- package/dist/interface/index.d.ts +3 -0
- package/dist/interface/index.js +3 -0
- package/dist/interface/index.js.map +1 -1
- package/dist/interface/metrics.interface.d.ts +17 -0
- package/dist/interface/metrics.interface.js +3 -0
- package/dist/interface/metrics.interface.js.map +1 -0
- package/dist/module/cache-invalidate.provider.js +5 -0
- package/dist/module/cache-invalidate.provider.js.map +1 -1
- package/dist/module/cache-module.interface.d.ts +3 -1
- package/dist/module/cache.module.d.ts +2 -1
- package/dist/module/cache.module.js +39 -4
- package/dist/module/cache.module.js.map +1 -1
- package/dist/module/cache.provider.js +72 -3
- package/dist/module/cache.provider.js.map +1 -1
- package/dist/provider/cacheable.provider.d.ts +11 -0
- package/dist/provider/cacheable.provider.js +213 -0
- package/dist/provider/cacheable.provider.js.map +1 -0
- package/dist/provider/index.d.ts +1 -0
- package/dist/provider/index.js +18 -0
- package/dist/provider/index.js.map +1 -0
- package/dist/service/cache-invalidate.factory.js.map +1 -1
- package/dist/service/cache-invalidate.manager.d.ts +4 -3
- package/dist/service/cache-invalidate.manager.js +8 -5
- package/dist/service/cache-invalidate.manager.js.map +1 -1
- package/dist/service/cache-manager.d.ts +42 -6
- package/dist/service/cache-manager.js +622 -45
- package/dist/service/cache-manager.js.map +1 -1
- package/dist/service/cache-provider.js +3 -6
- package/dist/service/cache-provider.js.map +1 -1
- package/dist/service/cache-tag-registry.d.ts +30 -0
- package/dist/service/cache-tag-registry.js +100 -0
- package/dist/service/cache-tag-registry.js.map +1 -0
- package/dist/service/index.d.ts +2 -0
- package/dist/service/index.js +2 -0
- package/dist/service/index.js.map +1 -1
- package/dist/service/redis-cache-invalidate.manager.d.ts +9 -1
- package/dist/service/redis-cache-invalidate.manager.js +107 -55
- package/dist/service/redis-cache-invalidate.manager.js.map +1 -1
- package/dist/service/redis-pattern-invalidation.d.ts +11 -0
- package/dist/service/redis-pattern-invalidation.js +107 -0
- package/dist/service/redis-pattern-invalidation.js.map +1 -0
- package/dist/utils/cache-key.utils.d.ts +3 -0
- package/dist/utils/cache-key.utils.js +34 -2
- package/dist/utils/cache-key.utils.js.map +1 -1
- package/dist/utils/config-validation.d.ts +2 -0
- package/dist/utils/config-validation.js +57 -0
- package/dist/utils/config-validation.js.map +1 -0
- package/dist/utils/deprecation.d.ts +3 -0
- package/dist/utils/deprecation.js +33 -0
- package/dist/utils/deprecation.js.map +1 -0
- package/dist/utils/index.d.ts +4 -0
- package/dist/utils/index.js +4 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/redis-uri.utils.d.ts +9 -0
- package/dist/utils/redis-uri.utils.js +62 -0
- package/dist/utils/redis-uri.utils.js.map +1 -0
- package/dist/utils/validation.d.ts +10 -0
- package/dist/utils/validation.js +39 -0
- package/dist/utils/validation.js.map +1 -0
- package/docker-compose.e2e.yml +16 -0
- package/docs/CACHEOBLESYNC-MIGRATION-PLAN.md +55 -0
- package/docs/CODE-REVIEW-2026-02-10-v2.md +134 -0
- package/docs/CODE-REVIEW-2026-02-10.md +142 -0
- package/docs/CODE_REVIEW.md +356 -0
- package/docs/FINAL-CODE-REVIEW-2026-02-10.md +312 -0
- package/docs/IMPLEMENTATION_PLAN.md +1045 -0
- package/docs/IMPLEMENTATION_PLAN_V2.md +201 -0
- package/docs/IMPLEMENTATION_PLAN_V3.md +169 -0
- package/docs/IMPLEMENTATION_TASKS.md +1090 -0
- package/docs/PHASE3_COVERAGE_TASKS.md +266 -0
- package/docs/TAG-BASED-INVALIDATION-PLAN.md +367 -0
- package/docs/UNIFIED-INVALIDATE-PLAN.md +229 -0
- package/package.json +27 -2
- package/dist/inteceptor/cache-invalidate.interceptor.js.map +0 -1
- package/dist/inteceptor/cache.interceptor.js.map +0 -1
- /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.d.ts +0 -0
- /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.js +0 -0
- /package/dist/{inteceptor → interceptor}/cache.interceptor.d.ts +0 -0
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
# @nathapp/nestjs-cache Implementation Plan
|
|
2
|
+
|
|
3
|
+
**Created**: 2026-02-09
|
|
4
|
+
**Author**: Subrina
|
|
5
|
+
**Based on**: CODE_REVIEW.md findings
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Overview
|
|
10
|
+
|
|
11
|
+
This plan addresses memory leaks, security issues, test coverage gaps, and enhancements while **preserving full backward compatibility** with legacy mode.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## Phase 0: Configuration Fixes
|
|
16
|
+
|
|
17
|
+
### Task 0.1: Fix Jest Coverage Configuration
|
|
18
|
+
|
|
19
|
+
**File**: `test/jest-test.json`
|
|
20
|
+
|
|
21
|
+
```json
|
|
22
|
+
{
|
|
23
|
+
"moduleFileExtensions": ["js", "json", "ts", "d.ts"],
|
|
24
|
+
"rootDir": "../",
|
|
25
|
+
"testEnvironment": "node",
|
|
26
|
+
"testRegex": ".spec.ts$",
|
|
27
|
+
"transform": {
|
|
28
|
+
"^.+\\.(t)s$": ["ts-jest", { "diagnostics": true, "isolatedModules": true }]
|
|
29
|
+
},
|
|
30
|
+
"collectCoverageFrom": [
|
|
31
|
+
"lib/**/*.ts",
|
|
32
|
+
"!lib/**/index.ts",
|
|
33
|
+
"!**/node_modules/**"
|
|
34
|
+
],
|
|
35
|
+
"coverageDirectory": "./coverage",
|
|
36
|
+
"coverageThreshold": {
|
|
37
|
+
"global": {
|
|
38
|
+
"branches": 70,
|
|
39
|
+
"functions": 80,
|
|
40
|
+
"lines": 80,
|
|
41
|
+
"statements": 80
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**Verification**: Run `npm run test:cov` and confirm coverage is reported.
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Phase 1: Memory Leak Fixes (P0 - Critical)
|
|
52
|
+
|
|
53
|
+
### Task 1.1: Add Max Size to Deprecation Warnings Set
|
|
54
|
+
|
|
55
|
+
**File**: `lib/utils/deprecation.ts`
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
import { Logger } from '@nestjs/common';
|
|
59
|
+
|
|
60
|
+
const logger = new Logger('DeprecationWarning');
|
|
61
|
+
const MAX_WARNED_FEATURES = 100;
|
|
62
|
+
const warnedFeatures = new Map<string, number>(); // Track timestamp
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Emit a deprecation warning once per feature (with LRU eviction)
|
|
66
|
+
*/
|
|
67
|
+
export function warnDeprecation(
|
|
68
|
+
feature: string,
|
|
69
|
+
message: string,
|
|
70
|
+
alternative?: string,
|
|
71
|
+
): void {
|
|
72
|
+
if (warnedFeatures.has(feature)) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// LRU eviction when at capacity
|
|
77
|
+
if (warnedFeatures.size >= MAX_WARNED_FEATURES) {
|
|
78
|
+
// Remove oldest entry
|
|
79
|
+
const oldestKey = warnedFeatures.keys().next().value;
|
|
80
|
+
if (oldestKey) {
|
|
81
|
+
warnedFeatures.delete(oldestKey);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
warnedFeatures.set(feature, Date.now());
|
|
86
|
+
|
|
87
|
+
let warning = `DEPRECATED: ${feature} - ${message}`;
|
|
88
|
+
if (alternative) {
|
|
89
|
+
warning += `\nPlease use: ${alternative}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
logger.warn(warning);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Clear all deprecation warnings (useful for testing)
|
|
97
|
+
*/
|
|
98
|
+
export function clearDeprecationWarnings(): void {
|
|
99
|
+
warnedFeatures.clear();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Get count of warned features (for monitoring)
|
|
104
|
+
*/
|
|
105
|
+
export function getWarnedFeaturesCount(): number {
|
|
106
|
+
return warnedFeatures.size;
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**Tests**: `test/utils/deprecation.spec.ts`
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
import { describe, it, expect, beforeEach } from '@jest/globals';
|
|
114
|
+
import {
|
|
115
|
+
warnDeprecation,
|
|
116
|
+
clearDeprecationWarnings,
|
|
117
|
+
getWarnedFeaturesCount
|
|
118
|
+
} from '../../lib/utils/deprecation';
|
|
119
|
+
|
|
120
|
+
describe('deprecation warnings', () => {
|
|
121
|
+
beforeEach(() => {
|
|
122
|
+
clearDeprecationWarnings();
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it('should only warn once per feature', () => {
|
|
126
|
+
warnDeprecation('feature1', 'deprecated');
|
|
127
|
+
warnDeprecation('feature1', 'deprecated');
|
|
128
|
+
expect(getWarnedFeaturesCount()).toBe(1);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('should evict oldest when at capacity', () => {
|
|
132
|
+
// Add 100 features
|
|
133
|
+
for (let i = 0; i < 100; i++) {
|
|
134
|
+
warnDeprecation(`feature-${i}`, 'deprecated');
|
|
135
|
+
}
|
|
136
|
+
expect(getWarnedFeaturesCount()).toBe(100);
|
|
137
|
+
|
|
138
|
+
// Add one more - should evict oldest
|
|
139
|
+
warnDeprecation('feature-100', 'deprecated');
|
|
140
|
+
expect(getWarnedFeaturesCount()).toBe(100);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('should clear all warnings', () => {
|
|
144
|
+
warnDeprecation('feature1', 'deprecated');
|
|
145
|
+
clearDeprecationWarnings();
|
|
146
|
+
expect(getWarnedFeaturesCount()).toBe(0);
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
### Task 1.2: Cache RedisPatternInvalidation Instance
|
|
154
|
+
|
|
155
|
+
**File**: `lib/service/cache-manager.ts`
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { RedisPatternInvalidation } from './redis-pattern-invalidation';
|
|
159
|
+
|
|
160
|
+
export class CacheManager {
|
|
161
|
+
// ... existing properties ...
|
|
162
|
+
private patternInvalidator?: RedisPatternInvalidation;
|
|
163
|
+
|
|
164
|
+
constructor(
|
|
165
|
+
protected readonly invalidateOptions: ExtraInvalidateOptions,
|
|
166
|
+
protected readonly cacheProvider: CacheProvider,
|
|
167
|
+
protected readonly cacheInvalidateManager: CacheInvalidateManager,
|
|
168
|
+
protected readonly cacheable?: any,
|
|
169
|
+
) {
|
|
170
|
+
this.invalidateOptions = Object.assign({}, { strategy: InvalidateStrategy.DIRECT }, invalidateOptions);
|
|
171
|
+
this.useCacheable = !!cacheable;
|
|
172
|
+
|
|
173
|
+
// Initialize pattern invalidator if using cacheable
|
|
174
|
+
if (this.useCacheable && this.cacheable) {
|
|
175
|
+
this.patternInvalidator = new RedisPatternInvalidation(this.cacheable);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Invalidate cache keys matching a pattern (enhanced mode)
|
|
181
|
+
* This method uses efficient Redis SCAN for pattern-based invalidation
|
|
182
|
+
* @param pattern Pattern to match (e.g., 'user:*', 'session:123:*')
|
|
183
|
+
*/
|
|
184
|
+
async invalidateByPattern(pattern: string): Promise<void> {
|
|
185
|
+
if (this.useCacheable && this.patternInvalidator) {
|
|
186
|
+
try {
|
|
187
|
+
await this.patternInvalidator.deleteByPattern(pattern);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
this.logger.error(`Pattern invalidation failed for pattern ${pattern}:`, error);
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Legacy mode - use existing pattern deletion
|
|
196
|
+
await this.cacheProvider.delByPatternRaw([pattern]);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
### Task 1.3: Fix Redis Connection Cleanup
|
|
204
|
+
|
|
205
|
+
**File**: `lib/service/redis-cache-invalidate.manager.ts`
|
|
206
|
+
|
|
207
|
+
```typescript
|
|
208
|
+
export class RedisCacheInvalidateManager extends BaseCacheInvalidateManager {
|
|
209
|
+
// ... existing properties ...
|
|
210
|
+
private messageHandler?: (channel: string, message: string) => Promise<void>;
|
|
211
|
+
|
|
212
|
+
async subscribe(): Promise<void> {
|
|
213
|
+
const errorHandler = (err: { message: any }, count: any) => {
|
|
214
|
+
if (err) {
|
|
215
|
+
this.logger.error(`Failed to subscribe: ${err.message}`);
|
|
216
|
+
} else {
|
|
217
|
+
this.logger.log(`Subscribed successfully! This client is currently subscribed to ${count} channels.`);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
this.subClient.subscribe(this.extraOptions.channel, errorHandler);
|
|
222
|
+
this.subClient.subscribe(this.extraOptions.mchannel, errorHandler);
|
|
223
|
+
|
|
224
|
+
// Store reference to handler for cleanup
|
|
225
|
+
this.messageHandler = async (channel: string, message: string) => {
|
|
226
|
+
await this.handleMessage(channel, message);
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
this.subClient.on('message', this.messageHandler);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private async handleMessage(channel: string, message: string): Promise<void> {
|
|
233
|
+
if (channel === this.extraOptions.channel) {
|
|
234
|
+
await this.handleSingleInvalidate(message);
|
|
235
|
+
} else if (channel === this.extraOptions.mchannel) {
|
|
236
|
+
await this.handleMultiInvalidate(message);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private async handleSingleInvalidate(message: string): Promise<void> {
|
|
241
|
+
try {
|
|
242
|
+
const { cacheKey, group } = JSON.parse(message);
|
|
243
|
+
|
|
244
|
+
if (isProtectedKey(cacheKey, this.protectedKeys) ||
|
|
245
|
+
isProtectedKeyPrefix(cacheKey, this.protectedKeys, ':')) {
|
|
246
|
+
this.logger.warn(`Protected key is not allowed to be invalidated`);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (group) {
|
|
251
|
+
await this.cacheProvider.delByPattern(cacheKey);
|
|
252
|
+
} else {
|
|
253
|
+
await this.cacheProvider.del(cacheKey);
|
|
254
|
+
}
|
|
255
|
+
} catch (err) {
|
|
256
|
+
this.logger.error(`Failed to parse invalidate message`);
|
|
257
|
+
this.logger.debug(`Parse error details:`, err);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private async handleMultiInvalidate(message: string): Promise<void> {
|
|
262
|
+
try {
|
|
263
|
+
const { cacheKeys, group } = JSON.parse(message);
|
|
264
|
+
|
|
265
|
+
if (!Array.isArray(cacheKeys)) {
|
|
266
|
+
this.logger.error(`Invalid cacheKeys format - expected array`);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const safeCacheKeys = cacheKeys.filter(
|
|
271
|
+
(key) => !isProtectedKey(key, this.protectedKeys) &&
|
|
272
|
+
!isProtectedKeyPrefix(key, this.protectedKeys, ':')
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
if (safeCacheKeys.length !== cacheKeys.length) {
|
|
276
|
+
this.logger.warn(`Some protected keys excluded from invalidation`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (group) {
|
|
280
|
+
await this.cacheProvider.mdelByPattern(safeCacheKeys);
|
|
281
|
+
} else {
|
|
282
|
+
await this.cacheProvider.mdel(safeCacheKeys);
|
|
283
|
+
}
|
|
284
|
+
} catch (err) {
|
|
285
|
+
this.logger.error(`Failed to parse multi-invalidate message`);
|
|
286
|
+
this.logger.debug(`Parse error details:`, err);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
public async close(): Promise<void> {
|
|
291
|
+
this.isExplicitlyTerminated = true;
|
|
292
|
+
|
|
293
|
+
const closePromises: Promise<void>[] = [];
|
|
294
|
+
|
|
295
|
+
if (this.subClient) {
|
|
296
|
+
// Remove message handler before closing
|
|
297
|
+
if (this.messageHandler) {
|
|
298
|
+
this.subClient.removeListener('message', this.messageHandler);
|
|
299
|
+
this.messageHandler = undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
closePromises.push(
|
|
303
|
+
Promise.race([
|
|
304
|
+
this.subClient.quit().catch((err: Error) => {
|
|
305
|
+
this.logger.warn(`Error closing subscriber: ${err.message}`);
|
|
306
|
+
}),
|
|
307
|
+
new Promise<void>((resolve) => setTimeout(resolve, 5000)), // 5s timeout
|
|
308
|
+
])
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (this.pubClient) {
|
|
313
|
+
closePromises.push(
|
|
314
|
+
Promise.race([
|
|
315
|
+
this.pubClient.quit().catch((err: Error) => {
|
|
316
|
+
this.logger.warn(`Error closing publisher: ${err.message}`);
|
|
317
|
+
}),
|
|
318
|
+
new Promise<void>((resolve) => setTimeout(resolve, 5000)), // 5s timeout
|
|
319
|
+
])
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
await Promise.all(closePromises);
|
|
324
|
+
|
|
325
|
+
this.pubClient = null;
|
|
326
|
+
this.subClient = null;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
## Phase 2: Security Hardening (P1)
|
|
334
|
+
|
|
335
|
+
### Task 2.1: Add Cache Key Sanitization
|
|
336
|
+
|
|
337
|
+
**File**: `lib/utils/cache-key.utils.ts`
|
|
338
|
+
|
|
339
|
+
```typescript
|
|
340
|
+
import { CacheKey } from "../interface";
|
|
341
|
+
|
|
342
|
+
// Characters allowed in cache keys
|
|
343
|
+
const ALLOWED_CHARS = /^[a-zA-Z0-9:_\-\.]+$/;
|
|
344
|
+
const MAX_KEY_LENGTH = 256;
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Sanitize a single cache key part
|
|
348
|
+
*/
|
|
349
|
+
export function sanitizeCacheKeyPart(part: string): string {
|
|
350
|
+
if (!part || typeof part !== 'string') {
|
|
351
|
+
throw new Error('Cache key part must be a non-empty string');
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Replace disallowed characters with underscores
|
|
355
|
+
const sanitized = part.replace(/[^a-zA-Z0-9:_\-\.]/g, '_');
|
|
356
|
+
|
|
357
|
+
// Collapse multiple underscores
|
|
358
|
+
return sanitized.replace(/_+/g, '_');
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Validate cache key length
|
|
363
|
+
*/
|
|
364
|
+
export function validateCacheKeyLength(key: string): void {
|
|
365
|
+
if (key.length > MAX_KEY_LENGTH) {
|
|
366
|
+
throw new Error(`Cache key exceeds maximum length of ${MAX_KEY_LENGTH} characters`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Resolve cache key from parts with sanitization
|
|
372
|
+
*/
|
|
373
|
+
export const resolveCacheKey = (cacheKeyParts: CacheKey): string => {
|
|
374
|
+
let key: string;
|
|
375
|
+
|
|
376
|
+
if (Array.isArray(cacheKeyParts)) {
|
|
377
|
+
key = cacheKeyParts
|
|
378
|
+
.map(k => sanitizeCacheKeyPart(k).toUpperCase())
|
|
379
|
+
.join(':');
|
|
380
|
+
} else {
|
|
381
|
+
key = sanitizeCacheKeyPart(cacheKeyParts).toUpperCase();
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
validateCacheKeyLength(key);
|
|
385
|
+
return key;
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
export const isProtectedKey = (key: string, protectedKeys: string[]): boolean => {
|
|
389
|
+
return protectedKeys.includes(key);
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
export const isProtectedKeyPrefix = (key: string, protectedKeys: string[], separator = ''): boolean => {
|
|
393
|
+
return protectedKeys.some(k => key.startsWith(`${k}${separator}`));
|
|
394
|
+
};
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
**Tests**: `test/utils/cache-key.utils.spec.ts` (extend existing)
|
|
398
|
+
|
|
399
|
+
```typescript
|
|
400
|
+
describe('cache key sanitization', () => {
|
|
401
|
+
it('should sanitize special characters', () => {
|
|
402
|
+
expect(resolveCacheKey('user<script>')).toBe('USER_SCRIPT_');
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
it('should reject empty keys', () => {
|
|
406
|
+
expect(() => resolveCacheKey('')).toThrow('non-empty string');
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
it('should reject keys exceeding max length', () => {
|
|
410
|
+
const longKey = 'a'.repeat(300);
|
|
411
|
+
expect(() => resolveCacheKey(longKey)).toThrow('exceeds maximum length');
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it('should sanitize array keys', () => {
|
|
415
|
+
expect(resolveCacheKey(['user', '../../../etc'])).toBe('USER:_.._.._.._ETC');
|
|
416
|
+
});
|
|
417
|
+
});
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
### Task 2.2: Add Message Validation
|
|
423
|
+
|
|
424
|
+
**File**: `lib/utils/validation.ts` (new file)
|
|
425
|
+
|
|
426
|
+
```typescript
|
|
427
|
+
import { CacheInvalidateMessage } from '../interface';
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Validate cache invalidate message structure
|
|
431
|
+
*/
|
|
432
|
+
export function validateInvalidateMessage(data: unknown): asserts data is { cacheKey?: string; cacheKeys?: string[]; group?: boolean } {
|
|
433
|
+
if (!data || typeof data !== 'object') {
|
|
434
|
+
throw new Error('Invalid message: must be an object');
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const msg = data as Record<string, unknown>;
|
|
438
|
+
|
|
439
|
+
if (msg.cacheKey !== undefined && typeof msg.cacheKey !== 'string') {
|
|
440
|
+
throw new Error('Invalid message: cacheKey must be a string');
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (msg.cacheKeys !== undefined) {
|
|
444
|
+
if (!Array.isArray(msg.cacheKeys)) {
|
|
445
|
+
throw new Error('Invalid message: cacheKeys must be an array');
|
|
446
|
+
}
|
|
447
|
+
if (!msg.cacheKeys.every((k: unknown) => typeof k === 'string')) {
|
|
448
|
+
throw new Error('Invalid message: all cacheKeys must be strings');
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (msg.group !== undefined && typeof msg.group !== 'boolean') {
|
|
453
|
+
throw new Error('Invalid message: group must be a boolean');
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (!msg.cacheKey && !msg.cacheKeys) {
|
|
457
|
+
throw new Error('Invalid message: must have cacheKey or cacheKeys');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Safely parse JSON with validation
|
|
463
|
+
*/
|
|
464
|
+
export function parseInvalidateMessage(json: string): { cacheKey?: string; cacheKeys?: string[]; group?: boolean } {
|
|
465
|
+
let data: unknown;
|
|
466
|
+
|
|
467
|
+
try {
|
|
468
|
+
data = JSON.parse(json);
|
|
469
|
+
} catch {
|
|
470
|
+
throw new Error('Invalid JSON format');
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
validateInvalidateMessage(data);
|
|
474
|
+
return data;
|
|
475
|
+
}
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
---
|
|
479
|
+
|
|
480
|
+
### Task 2.3: Mask Passwords in Logs
|
|
481
|
+
|
|
482
|
+
**File**: `lib/provider/cacheable.provider.ts`
|
|
483
|
+
|
|
484
|
+
```typescript
|
|
485
|
+
/**
|
|
486
|
+
* Build Redis URL from connection options (for internal use)
|
|
487
|
+
* Use buildRedisUrlForLogging() for log output
|
|
488
|
+
*/
|
|
489
|
+
export function buildRedisUrl(options: DistributedCacheOptions): string {
|
|
490
|
+
if (options.url) {
|
|
491
|
+
return options.url;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
const host = options.host || 'localhost';
|
|
495
|
+
const port = options.port || 6379;
|
|
496
|
+
const password = options.password;
|
|
497
|
+
const db = options.db || 0;
|
|
498
|
+
|
|
499
|
+
let url = 'redis://';
|
|
500
|
+
if (password) {
|
|
501
|
+
url += `:${password}@`;
|
|
502
|
+
}
|
|
503
|
+
url += `${host}:${port}/${db}`;
|
|
504
|
+
|
|
505
|
+
return url;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Build Redis URL with masked password for logging
|
|
510
|
+
*/
|
|
511
|
+
export function buildRedisUrlForLogging(options: DistributedCacheOptions): string {
|
|
512
|
+
if (options.url) {
|
|
513
|
+
// Mask password in existing URL
|
|
514
|
+
return options.url.replace(/:([^@]+)@/, ':***@');
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const host = options.host || 'localhost';
|
|
518
|
+
const port = options.port || 6379;
|
|
519
|
+
const db = options.db || 0;
|
|
520
|
+
|
|
521
|
+
let url = 'redis://';
|
|
522
|
+
if (options.password) {
|
|
523
|
+
url += `:***@`;
|
|
524
|
+
}
|
|
525
|
+
url += `${host}:${port}/${db}`;
|
|
526
|
+
|
|
527
|
+
return url;
|
|
528
|
+
}
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
---
|
|
532
|
+
|
|
533
|
+
## Phase 3: Test Coverage (P2)
|
|
534
|
+
|
|
535
|
+
### Task 3.1: CacheProvider Tests
|
|
536
|
+
|
|
537
|
+
**File**: `test/service/cache-provider.spec.ts` (new file)
|
|
538
|
+
|
|
539
|
+
```typescript
|
|
540
|
+
import { describe, it, expect, beforeEach, jest } from '@jest/globals';
|
|
541
|
+
import { CacheProvider } from '../../lib/service/cache-provider';
|
|
542
|
+
import { createMock } from '@golevelup/ts-jest';
|
|
543
|
+
import { Cache } from 'cache-manager';
|
|
544
|
+
|
|
545
|
+
describe('CacheProvider', () => {
|
|
546
|
+
let cacheProvider: CacheProvider;
|
|
547
|
+
let mockCacheManager: jest.Mocked<Cache>;
|
|
548
|
+
|
|
549
|
+
beforeEach(() => {
|
|
550
|
+
mockCacheManager = createMock<Cache>();
|
|
551
|
+
cacheProvider = new CacheProvider(mockCacheManager);
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
describe('get', () => {
|
|
555
|
+
it('should return cached value when exists', async () => {
|
|
556
|
+
mockCacheManager.get.mockResolvedValue('cached-value');
|
|
557
|
+
|
|
558
|
+
const result = await cacheProvider.get('test-key');
|
|
559
|
+
|
|
560
|
+
expect(result).toBe('cached-value');
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
it('should call resolver and cache when miss', async () => {
|
|
564
|
+
mockCacheManager.get.mockResolvedValue(null);
|
|
565
|
+
mockCacheManager.set.mockResolvedValue(undefined);
|
|
566
|
+
const resolver = jest.fn().mockResolvedValue('fresh-value');
|
|
567
|
+
|
|
568
|
+
const result = await cacheProvider.get('test-key', resolver, 5000);
|
|
569
|
+
|
|
570
|
+
expect(resolver).toHaveBeenCalled();
|
|
571
|
+
expect(mockCacheManager.set).toHaveBeenCalledWith('TEST-KEY', 'fresh-value', 5000);
|
|
572
|
+
expect(result).toBe('fresh-value');
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
it('should not cache null/undefined resolver results', async () => {
|
|
576
|
+
mockCacheManager.get.mockResolvedValue(null);
|
|
577
|
+
const resolver = jest.fn().mockResolvedValue(null);
|
|
578
|
+
|
|
579
|
+
await cacheProvider.get('test-key', resolver);
|
|
580
|
+
|
|
581
|
+
expect(mockCacheManager.set).not.toHaveBeenCalled();
|
|
582
|
+
});
|
|
583
|
+
});
|
|
584
|
+
|
|
585
|
+
describe('keys', () => {
|
|
586
|
+
it('should iterate over all stores', async () => {
|
|
587
|
+
const mockStore = {
|
|
588
|
+
iterator: jest.fn().mockImplementation(function* () {
|
|
589
|
+
yield ['key1', 'value1'];
|
|
590
|
+
yield ['key2', 'value2'];
|
|
591
|
+
}),
|
|
592
|
+
};
|
|
593
|
+
mockCacheManager.stores = [mockStore, {}];
|
|
594
|
+
|
|
595
|
+
const keys = await cacheProvider.keys();
|
|
596
|
+
|
|
597
|
+
expect(keys).toEqual(['key1', 'key2']);
|
|
598
|
+
});
|
|
599
|
+
|
|
600
|
+
it('should handle stores without iterator', async () => {
|
|
601
|
+
mockCacheManager.stores = [{}, {}];
|
|
602
|
+
|
|
603
|
+
const keys = await cacheProvider.keys();
|
|
604
|
+
|
|
605
|
+
expect(keys).toEqual([]);
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
it('should deduplicate keys across stores', async () => {
|
|
609
|
+
const mockStore1 = {
|
|
610
|
+
iterator: jest.fn().mockImplementation(function* () {
|
|
611
|
+
yield ['key1', 'value1'];
|
|
612
|
+
}),
|
|
613
|
+
};
|
|
614
|
+
const mockStore2 = {
|
|
615
|
+
iterator: jest.fn().mockImplementation(function* () {
|
|
616
|
+
yield ['key1', 'value2']; // Duplicate key
|
|
617
|
+
}),
|
|
618
|
+
};
|
|
619
|
+
mockCacheManager.stores = [mockStore1, mockStore2, {}];
|
|
620
|
+
|
|
621
|
+
const keys = await cacheProvider.keys();
|
|
622
|
+
|
|
623
|
+
expect(keys).toEqual(['key1']);
|
|
624
|
+
});
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
describe('delByPatternRaw', () => {
|
|
628
|
+
it('should delete keys matching patterns', async () => {
|
|
629
|
+
const mockStore = {
|
|
630
|
+
iterator: jest.fn().mockImplementation(function* () {
|
|
631
|
+
yield ['user:1', 'v1'];
|
|
632
|
+
yield ['user:2', 'v2'];
|
|
633
|
+
yield ['session:1', 'v3'];
|
|
634
|
+
}),
|
|
635
|
+
};
|
|
636
|
+
mockCacheManager.stores = [mockStore, {}];
|
|
637
|
+
mockCacheManager.mdel.mockResolvedValue(undefined);
|
|
638
|
+
|
|
639
|
+
await cacheProvider.delByPatternRaw(['user:']);
|
|
640
|
+
|
|
641
|
+
expect(mockCacheManager.mdel).toHaveBeenCalledWith(['user:1', 'user:2']);
|
|
642
|
+
});
|
|
643
|
+
});
|
|
644
|
+
});
|
|
645
|
+
```
|
|
646
|
+
|
|
647
|
+
### Task 3.2: Redis Cache Invalidate Manager Tests
|
|
648
|
+
|
|
649
|
+
**File**: `test/service/redis-cache-invalidate.manager.spec.ts` (new file)
|
|
650
|
+
|
|
651
|
+
```typescript
|
|
652
|
+
import { describe, it, expect, beforeEach, jest } from '@jest/globals';
|
|
653
|
+
import { RedisCacheInvalidateManager } from '../../lib/service/redis-cache-invalidate.manager';
|
|
654
|
+
import { CacheProvider } from '../../lib/service/cache-provider';
|
|
655
|
+
import { createMock } from '@golevelup/ts-jest';
|
|
656
|
+
|
|
657
|
+
// Mock ioredis
|
|
658
|
+
jest.mock('ioredis', () => {
|
|
659
|
+
return jest.fn().mockImplementation(() => ({
|
|
660
|
+
subscribe: jest.fn((channel: string, cb: Function) => cb(null, 1)),
|
|
661
|
+
on: jest.fn(),
|
|
662
|
+
removeListener: jest.fn(),
|
|
663
|
+
publish: jest.fn().mockResolvedValue(1),
|
|
664
|
+
quit: jest.fn().mockResolvedValue('OK'),
|
|
665
|
+
}));
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
describe('RedisCacheInvalidateManager', () => {
|
|
669
|
+
let manager: RedisCacheInvalidateManager;
|
|
670
|
+
let mockCacheProvider: jest.Mocked<CacheProvider>;
|
|
671
|
+
|
|
672
|
+
beforeEach(() => {
|
|
673
|
+
mockCacheProvider = createMock<CacheProvider>();
|
|
674
|
+
manager = new RedisCacheInvalidateManager(
|
|
675
|
+
{ host: 'localhost', port: 6379 },
|
|
676
|
+
mockCacheProvider,
|
|
677
|
+
{ protectedKeys: ['protected-key'] }
|
|
678
|
+
);
|
|
679
|
+
});
|
|
680
|
+
|
|
681
|
+
describe('subscribe', () => {
|
|
682
|
+
it('should subscribe to invalidate channels', async () => {
|
|
683
|
+
await manager.subscribe();
|
|
684
|
+
|
|
685
|
+
// Verify subscriptions were made
|
|
686
|
+
expect((manager as any).subClient.subscribe).toHaveBeenCalled();
|
|
687
|
+
});
|
|
688
|
+
});
|
|
689
|
+
|
|
690
|
+
describe('publish', () => {
|
|
691
|
+
it('should publish invalidate message', async () => {
|
|
692
|
+
await manager.publish({ cacheKey: 'test-key', group: false });
|
|
693
|
+
|
|
694
|
+
expect((manager as any).pubClient.publish).toHaveBeenCalled();
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
it('should not publish protected keys', async () => {
|
|
698
|
+
await manager.publish({ cacheKey: 'protected-key', group: false });
|
|
699
|
+
|
|
700
|
+
expect((manager as any).pubClient.publish).not.toHaveBeenCalled();
|
|
701
|
+
});
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
describe('close', () => {
|
|
705
|
+
it('should close both pub and sub clients', async () => {
|
|
706
|
+
await manager.close();
|
|
707
|
+
|
|
708
|
+
expect((manager as any).pubClient).toBeNull();
|
|
709
|
+
expect((manager as any).subClient).toBeNull();
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
it('should remove message listener before closing', async () => {
|
|
713
|
+
await manager.subscribe();
|
|
714
|
+
await manager.close();
|
|
715
|
+
|
|
716
|
+
// Verify listener was removed
|
|
717
|
+
});
|
|
718
|
+
});
|
|
719
|
+
});
|
|
720
|
+
```
|
|
721
|
+
|
|
722
|
+
### Task 3.3: Cache Interceptor Tests
|
|
723
|
+
|
|
724
|
+
**File**: `test/interceptor/cache.interceptor.spec.ts` (new file)
|
|
725
|
+
|
|
726
|
+
```typescript
|
|
727
|
+
import { describe, it, expect, beforeEach, jest } from '@jest/globals';
|
|
728
|
+
import { CacheInterceptor } from '../../lib/inteceptor/cache.interceptor';
|
|
729
|
+
import { CacheManager } from '../../lib/service/cache-manager';
|
|
730
|
+
import { Reflector } from '@nestjs/core';
|
|
731
|
+
import { ExecutionContext, CallHandler } from '@nestjs/common';
|
|
732
|
+
import { createMock } from '@golevelup/ts-jest';
|
|
733
|
+
import { of } from 'rxjs';
|
|
734
|
+
|
|
735
|
+
describe('CacheInterceptor', () => {
|
|
736
|
+
let interceptor: CacheInterceptor;
|
|
737
|
+
let mockCacheManager: jest.Mocked<CacheManager>;
|
|
738
|
+
let mockReflector: jest.Mocked<Reflector>;
|
|
739
|
+
|
|
740
|
+
beforeEach(() => {
|
|
741
|
+
mockCacheManager = createMock<CacheManager>();
|
|
742
|
+
mockReflector = createMock<Reflector>();
|
|
743
|
+
interceptor = new CacheInterceptor(mockCacheManager, mockReflector);
|
|
744
|
+
});
|
|
745
|
+
|
|
746
|
+
it('should return cached value on cache hit', async () => {
|
|
747
|
+
mockCacheManager.getRaw.mockResolvedValue('cached-data');
|
|
748
|
+
mockReflector.get.mockReturnValue({ cacheKey: 'test-key' });
|
|
749
|
+
|
|
750
|
+
const context = createMockContext('GET');
|
|
751
|
+
const next = createMock<CallHandler>({ handle: () => of('fresh-data') });
|
|
752
|
+
|
|
753
|
+
const result = await interceptor.intercept(context, next);
|
|
754
|
+
const value = await result.toPromise();
|
|
755
|
+
|
|
756
|
+
expect(value).toBe('cached-data');
|
|
757
|
+
});
|
|
758
|
+
|
|
759
|
+
it('should skip caching for non-GET requests', async () => {
|
|
760
|
+
mockReflector.get.mockReturnValue(null);
|
|
761
|
+
|
|
762
|
+
const context = createMockContext('POST');
|
|
763
|
+
const next = createMock<CallHandler>({ handle: () => of('response') });
|
|
764
|
+
|
|
765
|
+
const result = await interceptor.intercept(context, next);
|
|
766
|
+
const value = await result.toPromise();
|
|
767
|
+
|
|
768
|
+
expect(value).toBe('response');
|
|
769
|
+
expect(mockCacheManager.getRaw).not.toHaveBeenCalled();
|
|
770
|
+
});
|
|
771
|
+
|
|
772
|
+
it('should set X-Cache header to HIT on cache hit', async () => {
|
|
773
|
+
mockCacheManager.getRaw.mockResolvedValue('cached-data');
|
|
774
|
+
mockReflector.get.mockReturnValue({ cacheKey: 'test-key' });
|
|
775
|
+
|
|
776
|
+
const mockSetHeader = jest.fn();
|
|
777
|
+
const context = createMockContextWithAdapter('GET', mockSetHeader);
|
|
778
|
+
const next = createMock<CallHandler>({ handle: () => of('fresh-data') });
|
|
779
|
+
|
|
780
|
+
await interceptor.intercept(context, next);
|
|
781
|
+
|
|
782
|
+
expect(mockSetHeader).toHaveBeenCalledWith(expect.anything(), 'X-Cache', 'HIT');
|
|
783
|
+
});
|
|
784
|
+
});
|
|
785
|
+
|
|
786
|
+
function createMockContext(method: string): ExecutionContext {
|
|
787
|
+
return createMock<ExecutionContext>({
|
|
788
|
+
switchToHttp: () => ({
|
|
789
|
+
getRequest: () => ({ method }),
|
|
790
|
+
getResponse: () => ({}),
|
|
791
|
+
}),
|
|
792
|
+
getHandler: () => ({}),
|
|
793
|
+
getClass: () => ({}),
|
|
794
|
+
getArgByIndex: () => ({ method }),
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
function createMockContextWithAdapter(method: string, setHeader: jest.Mock): ExecutionContext {
|
|
799
|
+
const context = createMockContext(method);
|
|
800
|
+
(context as any).httpAdapterHost = {
|
|
801
|
+
httpAdapter: {
|
|
802
|
+
getRequestMethod: () => method,
|
|
803
|
+
getRequestUrl: () => '/test',
|
|
804
|
+
setHeader,
|
|
805
|
+
},
|
|
806
|
+
};
|
|
807
|
+
return context;
|
|
808
|
+
}
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
---
|
|
812
|
+
|
|
813
|
+
## Phase 4: Enhancements (P3)
|
|
814
|
+
|
|
815
|
+
### Task 4.1: Add Health Check Interface
|
|
816
|
+
|
|
817
|
+
**File**: `lib/interface/health.interface.ts` (new file)
|
|
818
|
+
|
|
819
|
+
```typescript
|
|
820
|
+
export interface CacheConnectionHealth {
|
|
821
|
+
name: string;
|
|
822
|
+
status: 'connected' | 'disconnected' | 'connecting' | 'error';
|
|
823
|
+
latencyMs?: number;
|
|
824
|
+
error?: string;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
export interface CacheHealthResult {
|
|
828
|
+
healthy: boolean;
|
|
829
|
+
timestamp: Date;
|
|
830
|
+
connections: CacheConnectionHealth[];
|
|
831
|
+
stats?: {
|
|
832
|
+
hits?: number;
|
|
833
|
+
misses?: number;
|
|
834
|
+
keys?: number;
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
export interface CacheHealthCheck {
|
|
839
|
+
/**
|
|
840
|
+
* Check health of all cache connections
|
|
841
|
+
*/
|
|
842
|
+
isHealthy(): Promise<CacheHealthResult>;
|
|
843
|
+
}
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
**File**: `lib/service/cache-manager.ts` (extend)
|
|
847
|
+
|
|
848
|
+
```typescript
|
|
849
|
+
import { CacheHealthCheck, CacheHealthResult } from '../interface/health.interface';
|
|
850
|
+
|
|
851
|
+
export class CacheManager implements CacheHealthCheck {
|
|
852
|
+
// ... existing code ...
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* Check health of cache connections
|
|
856
|
+
*/
|
|
857
|
+
async isHealthy(): Promise<CacheHealthResult> {
|
|
858
|
+
const connections: CacheConnectionHealth[] = [];
|
|
859
|
+
let healthy = true;
|
|
860
|
+
|
|
861
|
+
if (this.useCacheable && this.cacheable) {
|
|
862
|
+
// Check primary (memory) cache
|
|
863
|
+
if (this.cacheable.primary) {
|
|
864
|
+
connections.push({
|
|
865
|
+
name: 'memory',
|
|
866
|
+
status: 'connected',
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// Check secondary (Redis) cache
|
|
871
|
+
if (this.cacheable.secondary?.client) {
|
|
872
|
+
try {
|
|
873
|
+
const start = Date.now();
|
|
874
|
+
await this.cacheable.secondary.client.ping();
|
|
875
|
+
connections.push({
|
|
876
|
+
name: 'redis',
|
|
877
|
+
status: 'connected',
|
|
878
|
+
latencyMs: Date.now() - start,
|
|
879
|
+
});
|
|
880
|
+
} catch (error: any) {
|
|
881
|
+
healthy = false;
|
|
882
|
+
connections.push({
|
|
883
|
+
name: 'redis',
|
|
884
|
+
status: 'error',
|
|
885
|
+
error: error.message,
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
} else {
|
|
890
|
+
// Legacy mode - check cache-manager stores
|
|
891
|
+
try {
|
|
892
|
+
await this.cacheProvider.keys();
|
|
893
|
+
connections.push({
|
|
894
|
+
name: 'cache-manager',
|
|
895
|
+
status: 'connected',
|
|
896
|
+
});
|
|
897
|
+
} catch (error: any) {
|
|
898
|
+
healthy = false;
|
|
899
|
+
connections.push({
|
|
900
|
+
name: 'cache-manager',
|
|
901
|
+
status: 'error',
|
|
902
|
+
error: error.message,
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
return {
|
|
908
|
+
healthy,
|
|
909
|
+
timestamp: new Date(),
|
|
910
|
+
connections,
|
|
911
|
+
stats: await this.getStats(),
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
```
|
|
916
|
+
|
|
917
|
+
---
|
|
918
|
+
|
|
919
|
+
### Task 4.2: Add Metrics Hooks
|
|
920
|
+
|
|
921
|
+
**File**: `lib/interface/metrics.interface.ts` (new file)
|
|
922
|
+
|
|
923
|
+
```typescript
|
|
924
|
+
export interface CacheMetrics {
|
|
925
|
+
/**
|
|
926
|
+
* Called when a cache hit occurs
|
|
927
|
+
*/
|
|
928
|
+
onCacheHit?(key: string, source: 'memory' | 'distributed' | 'legacy'): void;
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* Called when a cache miss occurs
|
|
932
|
+
*/
|
|
933
|
+
onCacheMiss?(key: string): void;
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* Called when a value is set in cache
|
|
937
|
+
*/
|
|
938
|
+
onCacheSet?(key: string, ttlMs: number, size?: number): void;
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* Called when a key is deleted
|
|
942
|
+
*/
|
|
943
|
+
onCacheDelete?(key: string | string[]): void;
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* Called when a cache operation fails
|
|
947
|
+
*/
|
|
948
|
+
onCacheError?(operation: string, error: Error, key?: string): void;
|
|
949
|
+
}
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
**File**: `lib/module/cache-module.interface.ts` (extend)
|
|
953
|
+
|
|
954
|
+
```typescript
|
|
955
|
+
import { CacheMetrics } from '../interface/metrics.interface';
|
|
956
|
+
|
|
957
|
+
export interface EnhancedCacheModuleOptions {
|
|
958
|
+
// ... existing options ...
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* Optional metrics hooks for observability
|
|
962
|
+
*/
|
|
963
|
+
metrics?: CacheMetrics;
|
|
964
|
+
}
|
|
965
|
+
```
|
|
966
|
+
|
|
967
|
+
---
|
|
968
|
+
|
|
969
|
+
### Task 4.3: Add Namespace Support
|
|
970
|
+
|
|
971
|
+
**File**: `lib/service/cache-namespace.ts` (new file)
|
|
972
|
+
|
|
973
|
+
```typescript
|
|
974
|
+
import { CacheManager } from './cache-manager';
|
|
975
|
+
import { CacheKey } from '../interface';
|
|
976
|
+
|
|
977
|
+
/**
|
|
978
|
+
* Namespaced cache operations
|
|
979
|
+
* Groups related cache keys under a common prefix
|
|
980
|
+
*/
|
|
981
|
+
export class CacheNamespace {
|
|
982
|
+
constructor(
|
|
983
|
+
private readonly cacheManager: CacheManager,
|
|
984
|
+
private readonly namespace: string,
|
|
985
|
+
) {}
|
|
986
|
+
|
|
987
|
+
private prefixKey(key: CacheKey): CacheKey {
|
|
988
|
+
if (Array.isArray(key)) {
|
|
989
|
+
return [this.namespace, ...key];
|
|
990
|
+
}
|
|
991
|
+
return [this.namespace, key];
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
async get<T>(key: CacheKey, resolver?: () => Promise<T>, ttl?: number): Promise<T | null> {
|
|
995
|
+
return this.cacheManager.get(this.prefixKey(key), resolver, ttl);
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
async set<T>(key: CacheKey, value: T, ttl?: number): Promise<void> {
|
|
999
|
+
return this.cacheManager.set(this.prefixKey(key), value, ttl);
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
async invalidate(key: CacheKey): Promise<void> {
|
|
1003
|
+
return this.cacheManager.invalidate(this.prefixKey(key));
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
async invalidateAll(): Promise<void> {
|
|
1007
|
+
return this.cacheManager.invalidate([this.namespace], true);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// Extend CacheManager
|
|
1012
|
+
declare module './cache-manager' {
|
|
1013
|
+
interface CacheManager {
|
|
1014
|
+
namespace(name: string): CacheNamespace;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
CacheManager.prototype.namespace = function(name: string): CacheNamespace {
|
|
1019
|
+
return new CacheNamespace(this, name);
|
|
1020
|
+
};
|
|
1021
|
+
```
|
|
1022
|
+
|
|
1023
|
+
---
|
|
1024
|
+
|
|
1025
|
+
## Summary
|
|
1026
|
+
|
|
1027
|
+
| Phase | Tasks | Priority | Est. Effort |
|
|
1028
|
+
|-------|-------|----------|-------------|
|
|
1029
|
+
| 0 | Fix Jest config | P0 | 0.5h |
|
|
1030
|
+
| 1 | Memory leak fixes (3 tasks) | P0 | 2h |
|
|
1031
|
+
| 2 | Security hardening (3 tasks) | P1 | 3h |
|
|
1032
|
+
| 3 | Test coverage (3+ test files) | P2 | 4h |
|
|
1033
|
+
| 4 | Enhancements (3 tasks) | P3 | 3h |
|
|
1034
|
+
|
|
1035
|
+
**Total Estimated Effort**: 12.5 hours
|
|
1036
|
+
|
|
1037
|
+
---
|
|
1038
|
+
|
|
1039
|
+
## Backward Compatibility Checklist
|
|
1040
|
+
|
|
1041
|
+
- [ ] All changes are additive (no API removals)
|
|
1042
|
+
- [ ] Default behavior unchanged (`strategy: LEGACY`)
|
|
1043
|
+
- [ ] New features gracefully degrade in legacy mode
|
|
1044
|
+
- [ ] Existing tests continue to pass
|
|
1045
|
+
- [ ] Migration guide updated if needed
|