@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.
- package/CLAUDE.md +149 -0
- package/README.md +330 -420
- package/TODO.md +56 -0
- package/dist/enum/strategy.enum.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -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 +16 -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 +2 -0
- package/dist/interface/index.js +2 -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 +1 -0
- package/dist/module/cache.module.d.ts +2 -1
- package/dist/module/cache.module.js +7 -3
- package/dist/module/cache.module.js.map +1 -1
- package/dist/module/cache.provider.js +69 -1
- package/dist/module/cache.provider.js.map +1 -1
- package/dist/provider/cacheable.provider.d.ts +3 -0
- package/dist/provider/cacheable.provider.js +120 -35
- package/dist/provider/cacheable.provider.js.map +1 -1
- 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 +39 -8
- package/dist/service/cache-manager.js +579 -71
- 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 +1 -0
- package/dist/service/index.js +1 -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.js +4 -0
- package/dist/service/redis-pattern-invalidation.js.map +1 -1
- 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 +1 -0
- package/dist/utils/deprecation.js +13 -2
- package/dist/utils/deprecation.js.map +1 -1
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +3 -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 +13 -6
- 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,266 @@
|
|
|
1
|
+
# Phase 3: Test Coverage Improvements (Remaining)
|
|
2
|
+
|
|
3
|
+
## Task 3.2: RedisCacheInvalidateManager Unit Tests
|
|
4
|
+
**File**: `test/service/redis-cache-invalidate.manager.spec.ts`
|
|
5
|
+
|
|
6
|
+
```typescript
|
|
7
|
+
import { describe, it, expect, beforeEach, jest } from '@jest/globals';
|
|
8
|
+
import { RedisCacheInvalidateManager } from '../../lib/service/redis-cache-invalidate.manager';
|
|
9
|
+
import { CacheProvider } from '../../lib/service/cache-provider';
|
|
10
|
+
import { createMock } from '@golevelup/ts-jest';
|
|
11
|
+
|
|
12
|
+
// Mock ioredis
|
|
13
|
+
jest.mock('ioredis', () => {
|
|
14
|
+
return jest.fn().mockImplementation(() => ({
|
|
15
|
+
subscribe: jest.fn((channel: string, cb: Function) => cb(null, 1)),
|
|
16
|
+
on: jest.fn(),
|
|
17
|
+
removeListener: jest.fn(),
|
|
18
|
+
publish: jest.fn().mockResolvedValue(1),
|
|
19
|
+
quit: jest.fn().mockResolvedValue('OK'),
|
|
20
|
+
}));
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe('RedisCacheInvalidateManager', () => {
|
|
24
|
+
let manager: RedisCacheInvalidateManager;
|
|
25
|
+
let mockCacheProvider: jest.Mocked<CacheProvider>;
|
|
26
|
+
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
mockCacheProvider = createMock<CacheProvider>();
|
|
29
|
+
manager = new RedisCacheInvalidateManager(
|
|
30
|
+
{ host: 'localhost', port: 6379 },
|
|
31
|
+
mockCacheProvider,
|
|
32
|
+
{ protectedKeys: ['PROTECTED-KEY'] }
|
|
33
|
+
);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe('subscribe', () => {
|
|
37
|
+
it('should subscribe to invalidate channels', async () => {
|
|
38
|
+
await manager.subscribe();
|
|
39
|
+
const subClient = (manager as any).subClient;
|
|
40
|
+
expect(subClient.subscribe).toHaveBeenCalledWith('CACHE_INVALIDATE_CHANNEL', expect.any(Function));
|
|
41
|
+
expect(subClient.subscribe).toHaveBeenCalledWith('CACHE_MULTI_INVALIDATE_CHANNEL', expect.any(Function));
|
|
42
|
+
expect(subClient.on).toHaveBeenCalledWith('message', expect.any(Function));
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('publish', () => {
|
|
47
|
+
it('should publish single key invalidate message', async () => {
|
|
48
|
+
const pubClient = (manager as any).pubClient;
|
|
49
|
+
await manager.publish({ cacheKey: 'test-key', group: false });
|
|
50
|
+
|
|
51
|
+
expect(pubClient.publish).toHaveBeenCalledWith(
|
|
52
|
+
'CACHE_INVALIDATE_CHANNEL',
|
|
53
|
+
JSON.stringify({ cacheKey: 'TEST-KEY', group: false })
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should publish multi-key invalidate message', async () => {
|
|
58
|
+
const pubClient = (manager as any).pubClient;
|
|
59
|
+
await manager.publish({ cacheKeys: ['key1', 'key2'], group: true });
|
|
60
|
+
|
|
61
|
+
expect(pubClient.publish).toHaveBeenCalledWith(
|
|
62
|
+
'CACHE_MULTI_INVALIDATE_CHANNEL',
|
|
63
|
+
JSON.stringify({ cacheKeys: ['KEY1', 'KEY2'], group: true })
|
|
64
|
+
);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('should not publish protected keys', async () => {
|
|
68
|
+
const pubClient = (manager as any).pubClient;
|
|
69
|
+
await manager.publish({ cacheKey: 'protected-key', group: false });
|
|
70
|
+
|
|
71
|
+
expect(pubClient.publish).not.toHaveBeenCalled();
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
describe('close', () => {
|
|
76
|
+
it('should close both pub and sub clients and remove listener', async () => {
|
|
77
|
+
await manager.subscribe();
|
|
78
|
+
const subClient = (manager as any).subClient;
|
|
79
|
+
const pubClient = (manager as any).pubClient;
|
|
80
|
+
|
|
81
|
+
await manager.close();
|
|
82
|
+
|
|
83
|
+
expect(subClient.removeListener).toHaveBeenCalledWith('message', expect.any(Function));
|
|
84
|
+
expect(subClient.quit).toHaveBeenCalled();
|
|
85
|
+
expect(pubClient.quit).toHaveBeenCalled();
|
|
86
|
+
expect((manager as any).pubClient).toBeNull();
|
|
87
|
+
expect((manager as any).subClient).toBeNull();
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Task 3.3: CacheInterceptor Unit Tests
|
|
94
|
+
**File**: `test/interceptor/cache.interceptor.spec.ts`
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
import { describe, it, expect, beforeEach, jest } from '@jest/globals';
|
|
98
|
+
import { CacheInterceptor } from '../../lib/inteceptor/cache.interceptor';
|
|
99
|
+
import { CacheManager } from '../../lib/service/cache-manager';
|
|
100
|
+
import { Reflector } from '@nestjs/core';
|
|
101
|
+
import { ExecutionContext, CallHandler } from '@nestjs/common';
|
|
102
|
+
import { createMock } from '@golevelup/ts-jest';
|
|
103
|
+
import { of } from 'rxjs';
|
|
104
|
+
|
|
105
|
+
describe('CacheInterceptor', () => {
|
|
106
|
+
let interceptor: CacheInterceptor;
|
|
107
|
+
let mockCacheManager: jest.Mocked<CacheManager>;
|
|
108
|
+
let mockReflector: jest.Mocked<Reflector>;
|
|
109
|
+
|
|
110
|
+
beforeEach(() => {
|
|
111
|
+
mockCacheManager = createMock<CacheManager>();
|
|
112
|
+
mockReflector = createMock<Reflector>();
|
|
113
|
+
interceptor = new CacheInterceptor(mockCacheManager, mockReflector);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('should return cached value on cache hit', async () => {
|
|
117
|
+
mockCacheManager.getRaw.mockResolvedValue('cached-data');
|
|
118
|
+
mockReflector.get.mockReturnValue({ prefix: 'test' });
|
|
119
|
+
|
|
120
|
+
const context = createMockContext('GET', '/test-url');
|
|
121
|
+
const next = createMock<CallHandler>();
|
|
122
|
+
|
|
123
|
+
const result = await interceptor.intercept(context, next);
|
|
124
|
+
const value = await result.toPromise();
|
|
125
|
+
|
|
126
|
+
expect(value).toBe('cached-data');
|
|
127
|
+
expect(mockCacheManager.getRaw).toHaveBeenCalledWith('TEST:/TEST-URL');
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('should call next.handle() and cache result on cache miss', async () => {
|
|
131
|
+
mockCacheManager.getRaw.mockResolvedValue(null);
|
|
132
|
+
mockReflector.get.mockReturnValue({ prefix: 'test', ttl: 1000 });
|
|
133
|
+
|
|
134
|
+
const context = createMockContext('GET', '/test-url');
|
|
135
|
+
const next = createMock<CallHandler>({
|
|
136
|
+
handle: () => of('fresh-data')
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
const result = await interceptor.intercept(context, next);
|
|
140
|
+
const value = await result.toPromise();
|
|
141
|
+
|
|
142
|
+
expect(value).toBe('fresh-data');
|
|
143
|
+
expect(mockCacheManager.setRaw).toHaveBeenCalledWith('TEST:/TEST-URL', 'fresh-data', 1000);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('should skip caching for non-GET requests', async () => {
|
|
147
|
+
const context = createMockContext('POST', '/test-url');
|
|
148
|
+
const next = createMock<CallHandler>({
|
|
149
|
+
handle: () => of('response')
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
await interceptor.intercept(context, next);
|
|
153
|
+
expect(mockCacheManager.getRaw).not.toHaveBeenCalled();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
function createMockContext(method: string, url: string): ExecutionContext {
|
|
158
|
+
return createMock<ExecutionContext>({
|
|
159
|
+
switchToHttp: () => ({
|
|
160
|
+
getRequest: () => ({ method }),
|
|
161
|
+
getResponse: () => ({}),
|
|
162
|
+
}),
|
|
163
|
+
getHandler: () => ({}),
|
|
164
|
+
getClass: () => ({}),
|
|
165
|
+
getArgByIndex: () => ({ method }),
|
|
166
|
+
// Mock for httpAdapterHost
|
|
167
|
+
}) as any;
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Task 3.4: CacheInvalidateInterceptor Unit Tests
|
|
172
|
+
**File**: `test/interceptor/cache-invalidate.interceptor.spec.ts`
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { describe, it, expect, beforeEach, jest } from '@jest/globals';
|
|
176
|
+
import { CacheInvalidateInterceptor } from '../../lib/inteceptor/cache-invalidate.interceptor';
|
|
177
|
+
import { CacheManager } from '../../lib/service/cache-manager';
|
|
178
|
+
import { Reflector } from '@nestjs/core';
|
|
179
|
+
import { ExecutionContext, CallHandler } from '@nestjs/common';
|
|
180
|
+
import { createMock } from '@golevelup/ts-jest';
|
|
181
|
+
import { of } from 'rxjs';
|
|
182
|
+
|
|
183
|
+
describe('CacheInvalidateInterceptor', () => {
|
|
184
|
+
let interceptor: CacheInvalidateInterceptor;
|
|
185
|
+
let mockCacheManager: jest.Mocked<CacheManager>;
|
|
186
|
+
let mockReflector: jest.Mocked<Reflector>;
|
|
187
|
+
|
|
188
|
+
beforeEach(() => {
|
|
189
|
+
mockCacheManager = createMock<CacheManager>();
|
|
190
|
+
mockReflector = createMock<Reflector>();
|
|
191
|
+
interceptor = new CacheInvalidateInterceptor(mockCacheManager, mockReflector);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('should invalidate cache after successful execution', async () => {
|
|
195
|
+
mockReflector.get.mockReturnValue({ prefix: 'user', byPattern: true });
|
|
196
|
+
|
|
197
|
+
const context = createMockContext('POST', '/users/1');
|
|
198
|
+
const next = createMock<CallHandler>({
|
|
199
|
+
handle: () => of({ id: 1 })
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
const result = await interceptor.intercept(context, next);
|
|
203
|
+
await result.toPromise();
|
|
204
|
+
|
|
205
|
+
expect(mockCacheManager.invalidate).toHaveBeenCalledWith('USER:/USERS/1', true);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('should skip if no metadata found', async () => {
|
|
209
|
+
mockReflector.get.mockReturnValue(null);
|
|
210
|
+
const context = createMockContext('POST', '/test');
|
|
211
|
+
const next = createMock<CallHandler>({ handle: () => of('ok') });
|
|
212
|
+
|
|
213
|
+
await interceptor.intercept(context, next);
|
|
214
|
+
expect(mockCacheManager.invalidate).not.toHaveBeenCalled();
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
function createMockContext(method: string, url: string): ExecutionContext {
|
|
219
|
+
return createMock<ExecutionContext>({
|
|
220
|
+
switchToHttp: () => ({
|
|
221
|
+
getRequest: () => ({ method }),
|
|
222
|
+
}),
|
|
223
|
+
getHandler: () => ({}),
|
|
224
|
+
getClass: () => ({}),
|
|
225
|
+
getArgByIndex: () => ({ method }),
|
|
226
|
+
}) as any;
|
|
227
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## Task 3.5: Module Lifecycle Tests
|
|
231
|
+
**File**: `test/module/lifecycle.spec.ts`
|
|
232
|
+
|
|
233
|
+
```typescript
|
|
234
|
+
import { Test, TestingModule } from '@nestjs/testing';
|
|
235
|
+
import { CacheModule } from '../../lib/module/cache.module';
|
|
236
|
+
import { CacheInvalidateManager } from '../../lib/service';
|
|
237
|
+
import { CACHE_INVALIDATE_MANAGER } from '../../lib/constant/cache.constant';
|
|
238
|
+
import { createMock } from '@golevelup/ts-jest';
|
|
239
|
+
|
|
240
|
+
describe('CacheModule Lifecycle', () => {
|
|
241
|
+
let module: TestingModule;
|
|
242
|
+
let mockInvalidateManager: jest.Mocked<CacheInvalidateManager>;
|
|
243
|
+
|
|
244
|
+
beforeEach(async () => {
|
|
245
|
+
mockInvalidateManager = createMock<CacheInvalidateManager>();
|
|
246
|
+
module = await Test.createTestingModule({
|
|
247
|
+
imports: [CacheModule.register({ strategy: 'LEGACY' as any })],
|
|
248
|
+
})
|
|
249
|
+
.overrideProvider(CACHE_INVALIDATE_MANAGER)
|
|
250
|
+
.useValue(mockInvalidateManager)
|
|
251
|
+
.compile();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it('should subscribe on module init', async () => {
|
|
255
|
+
const cacheModule = module.get(CacheModule);
|
|
256
|
+
await cacheModule.onModuleInit();
|
|
257
|
+
expect(mockInvalidateManager.subscribe).toHaveBeenCalled();
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it('should close on application shutdown', async () => {
|
|
261
|
+
const cacheModule = module.get(CacheModule);
|
|
262
|
+
await cacheModule.onApplicationShutdown();
|
|
263
|
+
expect(mockInvalidateManager.close).toHaveBeenCalled();
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
```
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
# Tag-Based Cache Invalidation — Implementation Plan
|
|
2
|
+
|
|
3
|
+
**Date:** 2026-02-10
|
|
4
|
+
**Status:** Approved
|
|
5
|
+
**Branch:** `cache-cacheable-migration`
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Overview
|
|
10
|
+
|
|
11
|
+
Add tag-based cache invalidation to `@nathapp/nestjs-cache`. Tags allow grouping cache keys for efficient bulk invalidation without Redis `SCAN` (O(n) keyspace scan → O(m) tagged keys only).
|
|
12
|
+
|
|
13
|
+
### API Example
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// Set with tags
|
|
17
|
+
await cacheManager.set(['USER', '123', 'POST', '456'], postData, 5000, {
|
|
18
|
+
tags: ['USER:123:POSTS', 'USER:123'],
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
// Invalidate all posts for user 123 — only touches tagged keys
|
|
22
|
+
await cacheManager.invalidateByTag('USER:123:POSTS');
|
|
23
|
+
|
|
24
|
+
// Invalidate everything for user 123
|
|
25
|
+
await cacheManager.invalidateByTag('USER:123');
|
|
26
|
+
|
|
27
|
+
// Invalidate multiple tags at once
|
|
28
|
+
await cacheManager.invalidateByTags(['USER:123:POSTS', 'USER:456:POSTS']);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### How It Works
|
|
32
|
+
|
|
33
|
+
```
|
|
34
|
+
Cache Keys Tag Registry (Redis Sets)
|
|
35
|
+
───────────── ─────────────────────────
|
|
36
|
+
USER:123:POST:456 → {data} _TAG:USER:123:POSTS → { USER:123:POST:456, USER:123:POST:789 }
|
|
37
|
+
USER:123:POST:789 → {data} _TAG:USER:123 → { USER:123:POST:456, USER:123:POST:789, USER:123:PROFILE }
|
|
38
|
+
USER:123:PROFILE → {data}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
On `invalidateByTag('USER:123:POSTS')`:
|
|
42
|
+
1. `SMEMBERS _TAG:USER:123:POSTS` → `['USER:123:POST:456', 'USER:123:POST:789']`
|
|
43
|
+
2. `UNLINK USER:123:POST:456 USER:123:POST:789` (batch delete)
|
|
44
|
+
3. `DEL _TAG:USER:123:POSTS` (clean up the tag set)
|
|
45
|
+
|
|
46
|
+
**Complexity:** O(m) where m = number of tagged keys. Not O(n) like SCAN.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Architecture
|
|
51
|
+
|
|
52
|
+
### Storage Layer
|
|
53
|
+
|
|
54
|
+
Tags are stored as **Redis Sets** with a configurable prefix (default `_TAG:`).
|
|
55
|
+
|
|
56
|
+
| Component | Storage | Notes |
|
|
57
|
+
|---|---|---|
|
|
58
|
+
| Cache values | Cacheable (Keyv/Redis) | Existing — no change |
|
|
59
|
+
| Tag→keys mapping | Redis Sets via ioredis | New — direct Redis client |
|
|
60
|
+
| Tag registration | Happens inside `set()` | Automatic when tags provided |
|
|
61
|
+
| Tag cleanup | Happens inside `invalidateByTag()` | Deletes tag set after invalidation |
|
|
62
|
+
|
|
63
|
+
### Why direct Redis client (not Cacheable)?
|
|
64
|
+
|
|
65
|
+
Cacheable/Keyv stores serialized key-value pairs. Tags need Redis **Set** operations (`SADD`, `SMEMBERS`, `SREM`). These are native Redis data structures that Keyv doesn't expose. We use the same Redis connection but access it directly for tag operations.
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## Detailed Implementation
|
|
70
|
+
|
|
71
|
+
### Phase 1: Tag Registry Service
|
|
72
|
+
|
|
73
|
+
**New file:** `lib/service/cache-tag-registry.ts`
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
export interface CacheTagRegistryOptions {
|
|
77
|
+
/** Prefix for tag sets in Redis. Default: '_TAG:' */
|
|
78
|
+
tagPrefix?: string;
|
|
79
|
+
/** TTL for tag sets in seconds. Default: same as max cache TTL or 86400 (24h) */
|
|
80
|
+
tagTtl?: number;
|
|
81
|
+
/** Maximum tags per key. Default: 10 */
|
|
82
|
+
maxTagsPerKey?: number;
|
|
83
|
+
/** Maximum keys per tag (safety limit). Default: 10000 */
|
|
84
|
+
maxKeysPerTag?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export class CacheTagRegistry {
|
|
88
|
+
constructor(
|
|
89
|
+
private readonly redisClient: any,
|
|
90
|
+
private readonly options: CacheTagRegistryOptions = {},
|
|
91
|
+
) {}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Register a cache key under one or more tags
|
|
95
|
+
* Uses SADD + EXPIRE for atomic tag registration
|
|
96
|
+
*/
|
|
97
|
+
async registerTags(cacheKey: string, tags: string[]): Promise<void>;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Get all cache keys registered under a tag
|
|
101
|
+
*/
|
|
102
|
+
async getKeysByTag(tag: string): Promise<string[]>;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Remove a cache key from all its tags (on explicit delete/invalidate)
|
|
106
|
+
*/
|
|
107
|
+
async unregisterKey(cacheKey: string, tags: string[]): Promise<void>;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Delete all keys for a tag and clean up the tag set
|
|
111
|
+
* Returns the list of keys that were tagged (caller handles actual cache deletion)
|
|
112
|
+
*/
|
|
113
|
+
async consumeTag(tag: string): Promise<string[]>;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Delete all keys for multiple tags
|
|
117
|
+
*/
|
|
118
|
+
async consumeTags(tags: string[]): Promise<string[]>;
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
**Key implementation details:**
|
|
123
|
+
|
|
124
|
+
- `registerTags()`: For each tag, run `SADD _TAG:{tag} {cacheKey}` + `EXPIRE _TAG:{tag} {tagTtl}`. Use pipeline for atomicity.
|
|
125
|
+
- `consumeTag()`: `SMEMBERS _TAG:{tag}` → return keys → `DEL _TAG:{tag}`. This is a "consume and delete" pattern.
|
|
126
|
+
- Safety: Enforce `maxKeysPerTag` via `SCARD` check before `SADD`. Log warning if exceeded.
|
|
127
|
+
- Safety: Enforce `maxTagsPerKey` at the caller (CacheManager) before calling `registerTags()`.
|
|
128
|
+
|
|
129
|
+
### Phase 2: CacheManager Integration
|
|
130
|
+
|
|
131
|
+
**Modified file:** `lib/service/cache-manager.ts`
|
|
132
|
+
|
|
133
|
+
#### 2a. Extend `set()` signature
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// New options interface
|
|
137
|
+
export interface CacheSetOptions {
|
|
138
|
+
tags?: string[];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Updated set signature (backward compatible)
|
|
142
|
+
async set<T>(
|
|
143
|
+
keys: CacheKey,
|
|
144
|
+
value: T,
|
|
145
|
+
expirationMs?: number,
|
|
146
|
+
options?: CacheSetOptions,
|
|
147
|
+
): Promise<void>;
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Inside `set()`, after the cache write succeeds:
|
|
151
|
+
```ts
|
|
152
|
+
if (options?.tags?.length && this.tagRegistry) {
|
|
153
|
+
await this.tagRegistry.registerTags(cacheKey, options.tags);
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
#### 2b. New `invalidateByTag()` and `invalidateByTags()` methods
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
/**
|
|
161
|
+
* Invalidate all cache keys associated with a tag
|
|
162
|
+
* O(m) where m = number of tagged keys (not O(n) keyspace)
|
|
163
|
+
*/
|
|
164
|
+
async invalidateByTag(tag: string): Promise<number>;
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Invalidate multiple tags at once
|
|
168
|
+
* Deduplicates keys across tags before deletion
|
|
169
|
+
*/
|
|
170
|
+
async invalidateByTags(tags: string[]): Promise<number>;
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Implementation:
|
|
174
|
+
1. `consumeTag(tag)` → get keys from registry
|
|
175
|
+
2. Delete all keys via `cacheable.deleteMany(keys)` (enhanced) or `cacheProvider.mdel(keys)` (legacy)
|
|
176
|
+
3. Emit `onCacheDelete` metric with count
|
|
177
|
+
4. Return number of keys deleted
|
|
178
|
+
|
|
179
|
+
#### 2c. Extend `mset()` with tags
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
async mset<T>(list: Array<{
|
|
183
|
+
key: CacheKey;
|
|
184
|
+
value: T;
|
|
185
|
+
ttl?: number;
|
|
186
|
+
tags?: string[];
|
|
187
|
+
}>): Promise<void>;
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### 2d. Namespace support
|
|
191
|
+
|
|
192
|
+
Extend `namespace()` to support tags:
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
namespace(name: string) {
|
|
196
|
+
return {
|
|
197
|
+
...existing,
|
|
198
|
+
set: async <T>(key, value, ttl?, options?) => {
|
|
199
|
+
// Auto-prefix tags with namespace
|
|
200
|
+
const namespacedTags = options?.tags?.map(t => `${namespacePrefix}:${t}`);
|
|
201
|
+
...
|
|
202
|
+
},
|
|
203
|
+
invalidateByTag: async (tag: string) => {
|
|
204
|
+
return this.invalidateByTag(`${namespacePrefix}:${tag}`);
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
### Phase 3: Redis Client Access
|
|
211
|
+
|
|
212
|
+
**Modified file:** `lib/module/cache.provider.ts` + `lib/service/cache-manager.ts`
|
|
213
|
+
|
|
214
|
+
The `CacheTagRegistry` needs a Redis client. For enhanced mode, extract it from Cacheable's Keyv store. For legacy mode with Redis invalidation, reuse the existing ioredis client.
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
// In createCacheManager factory
|
|
218
|
+
const tagRegistry = createTagRegistry(cacheable, cacheInvalidateManager, options);
|
|
219
|
+
|
|
220
|
+
function createTagRegistry(cacheable, invalidateManager, options): CacheTagRegistry | null {
|
|
221
|
+
// Option 1: Enhanced mode — get Redis client from Cacheable's secondary store
|
|
222
|
+
if (cacheable?.secondary?.store?.client) {
|
|
223
|
+
return new CacheTagRegistry(cacheable.secondary.store.client, options.tags);
|
|
224
|
+
}
|
|
225
|
+
// Option 2: Enhanced mode DISTRIBUTED — primary is Redis
|
|
226
|
+
if (cacheable?.primary?.store?.client) {
|
|
227
|
+
return new CacheTagRegistry(cacheable.primary.store.client, options.tags);
|
|
228
|
+
}
|
|
229
|
+
// Option 3: Legacy mode with Redis invalidation — reuse ioredis pub client
|
|
230
|
+
if (invalidateManager instanceof RedisCacheInvalidateManager) {
|
|
231
|
+
return new CacheTagRegistry(invalidateManager.pubClient, options.tags);
|
|
232
|
+
}
|
|
233
|
+
// No Redis available — tags not supported (memory-only mode)
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### Phase 4: Configuration
|
|
239
|
+
|
|
240
|
+
**Modified file:** `lib/interface/enhanced-cache-options.interface.ts`
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
export interface TagOptions {
|
|
244
|
+
/** Enable tag-based invalidation. Default: true when Redis is available */
|
|
245
|
+
enabled?: boolean;
|
|
246
|
+
/** Prefix for tag sets in Redis. Default: '_TAG:' */
|
|
247
|
+
tagPrefix?: string;
|
|
248
|
+
/** TTL for tag sets in seconds. Default: 86400 (24h) */
|
|
249
|
+
tagTtl?: number;
|
|
250
|
+
/** Maximum tags per cache key. Default: 10 */
|
|
251
|
+
maxTagsPerKey?: number;
|
|
252
|
+
/** Maximum keys tracked per tag. Default: 10000 */
|
|
253
|
+
maxKeysPerTag?: number;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export interface EnhancedCacheModuleOptions {
|
|
257
|
+
...existing,
|
|
258
|
+
/** Tag-based invalidation options */
|
|
259
|
+
tags?: TagOptions;
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
### Phase 5: Pub/Sub Integration (Optional — Broker Mode)
|
|
264
|
+
|
|
265
|
+
If `invalidateOptions.strategy === BROKER`, `invalidateByTag()` should publish tag invalidation over pub/sub so all instances invalidate:
|
|
266
|
+
|
|
267
|
+
**Modified file:** `lib/service/redis-cache-invalidate.manager.ts`
|
|
268
|
+
|
|
269
|
+
Add a new channel for tag invalidation:
|
|
270
|
+
```ts
|
|
271
|
+
CACHE_TAG_INVALIDATE_CHANNEL = 'cache:tag:invalidate'
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
Message format:
|
|
275
|
+
```json
|
|
276
|
+
{ "tags": ["USER:123:POSTS"], "group": false }
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
On receive: each instance calls its local `tagRegistry.consumeTag()` + deletes from local cache.
|
|
280
|
+
|
|
281
|
+
### Phase 6: Decorator Support
|
|
282
|
+
|
|
283
|
+
**Modified file:** `lib/decorator/cache.decorator.ts`
|
|
284
|
+
|
|
285
|
+
Add `tags` to the `@Cache()` decorator options:
|
|
286
|
+
|
|
287
|
+
```ts
|
|
288
|
+
@Cache({
|
|
289
|
+
cacheKey: (req) => ['USER', req.params.userId, 'POST', req.params.postId],
|
|
290
|
+
tags: (req) => [`USER:${req.params.userId}:POSTS`],
|
|
291
|
+
ttl: 300000,
|
|
292
|
+
})
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
And a new `@CacheInvalidateByTag()` decorator:
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
@CacheInvalidateByTag({
|
|
299
|
+
tags: (req) => [`USER:${req.params.userId}:POSTS`],
|
|
300
|
+
})
|
|
301
|
+
@Post('users/:userId/posts')
|
|
302
|
+
async createPost() { ... }
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### Phase 7: Tests
|
|
306
|
+
|
|
307
|
+
| Test File | Description |
|
|
308
|
+
|---|---|
|
|
309
|
+
| `test/service/cache-tag-registry.spec.ts` | Unit tests for CacheTagRegistry (mock Redis client) |
|
|
310
|
+
| `test/service/cache-manager-tags.spec.ts` | Unit tests for CacheManager tag methods |
|
|
311
|
+
| `test/e2e/tags.e2e-spec.ts` | E2E test with real Redis — set with tags, invalidate by tag, verify deletion |
|
|
312
|
+
| `test/e2e/tags-multi-tier.e2e-spec.ts` | E2E test for MULTI_TIER with tags (verify L1+L2 both invalidated) |
|
|
313
|
+
|
|
314
|
+
### Phase 8: Documentation
|
|
315
|
+
|
|
316
|
+
- Update `README.md` with tag-based invalidation examples
|
|
317
|
+
- Add JSDoc to all new public methods
|
|
318
|
+
- Update `docs/` with migration guide for existing pattern-based users
|
|
319
|
+
|
|
320
|
+
---
|
|
321
|
+
|
|
322
|
+
## File Changes Summary
|
|
323
|
+
|
|
324
|
+
| File | Change |
|
|
325
|
+
|---|---|
|
|
326
|
+
| `lib/service/cache-tag-registry.ts` | **NEW** — Tag registry service |
|
|
327
|
+
| `lib/service/cache-manager.ts` | Add `invalidateByTag()`, `invalidateByTags()`, extend `set()` + `mset()` |
|
|
328
|
+
| `lib/module/cache.provider.ts` | Wire `CacheTagRegistry` into `CacheManager` factory |
|
|
329
|
+
| `lib/interface/enhanced-cache-options.interface.ts` | Add `TagOptions` interface |
|
|
330
|
+
| `lib/module/cache-module.interface.ts` | Surface `tags` config |
|
|
331
|
+
| `lib/decorator/cache.decorator.ts` | Add `tags` to decorator options |
|
|
332
|
+
| `lib/interceptor/cache.interceptor.ts` | Pass tags from decorator to `set()` |
|
|
333
|
+
| `lib/interceptor/cache-invalidate.interceptor.ts` | Add tag-based invalidation support |
|
|
334
|
+
| `lib/service/redis-cache-invalidate.manager.ts` | Add tag invalidation channel (broker mode) |
|
|
335
|
+
| `lib/index.ts` | Export new types |
|
|
336
|
+
| `test/service/cache-tag-registry.spec.ts` | **NEW** — Unit tests |
|
|
337
|
+
| `test/service/cache-manager-tags.spec.ts` | **NEW** — Unit tests |
|
|
338
|
+
| `test/e2e/tags.e2e-spec.ts` | **NEW** — E2E with real Redis |
|
|
339
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
## Execution Order
|
|
343
|
+
|
|
344
|
+
1. **Phase 1** — `CacheTagRegistry` service + unit tests
|
|
345
|
+
2. **Phase 2** — `CacheManager` integration + unit tests
|
|
346
|
+
3. **Phase 3** — Redis client wiring in module providers
|
|
347
|
+
4. **Phase 4** — Configuration interfaces
|
|
348
|
+
5. **Phase 7 (partial)** — E2E tests with real Redis
|
|
349
|
+
6. **Phase 5** — Pub/sub broker integration (if needed)
|
|
350
|
+
7. **Phase 6** — Decorator support
|
|
351
|
+
8. **Phase 8** — Documentation
|
|
352
|
+
|
|
353
|
+
Phases 1-4 + 7 are core. Phases 5-6 are enhancements that can be done in a follow-up.
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
## Edge Cases & Safety
|
|
358
|
+
|
|
359
|
+
| Scenario | Handling |
|
|
360
|
+
|---|---|
|
|
361
|
+
| Tag set grows unbounded | `maxKeysPerTag` limit (default 10,000). Log warning + reject new additions. |
|
|
362
|
+
| Key expires but tag set still references it | Stale references are harmless — `UNLINK` on non-existent keys is a no-op. Tag set itself has TTL. |
|
|
363
|
+
| Tag TTL expires before cache key | Keys become "untagged" — they'll expire naturally via their own TTL. Not a correctness issue. |
|
|
364
|
+
| Redis unavailable | `CacheTagRegistry` operations wrapped in try/catch. Tag failure doesn't block cache writes. |
|
|
365
|
+
| Memory-only mode (no Redis) | `tagRegistry` is `null`. `set()` with tags logs a warning. `invalidateByTag()` throws clear error. |
|
|
366
|
+
| Concurrent `invalidateByTag` + `set` with same tag | `consumeTag()` atomically reads+deletes the tag set. A concurrent `set` will create a new tag set — the new key won't be in the consumed batch (correct behavior). |
|
|
367
|
+
| Tag names with special characters | Tags go through `sanitizeCacheKeyPart()` — same rules as cache keys. |
|