tricache 0.6.6 → 0.7.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/LICENSE +1 -1
- package/README.md +500 -24
- package/bin/tricache.js +8 -0
- package/dist/cache-service-AJASH5FX.js +7 -0
- package/dist/cache-service-BblHuF3i.d.ts +1476 -0
- package/dist/chunk-3XQUQBOZ.js +4583 -0
- package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
- package/dist/chunk-UBSR5UYA.js +0 -0
- package/dist/cli.cjs +5181 -0
- package/dist/cli.d.ts +11 -0
- package/dist/cli.js +130 -0
- package/dist/drizzle/index.cjs +5161 -0
- package/dist/drizzle/index.d.ts +44 -0
- package/dist/drizzle/index.js +46 -0
- package/dist/http/index.cjs +5289 -0
- package/dist/http/index.d.ts +33 -0
- package/dist/http/index.js +172 -0
- package/dist/index.cjs +1181 -194
- package/dist/index.d.ts +15 -1230
- package/dist/index.js +11 -3697
- package/dist/nestjs/index.cjs +5305 -0
- package/dist/nestjs/index.d.ts +210 -0
- package/dist/nestjs/index.js +250 -0
- package/dist/next/index.cjs +5327 -0
- package/dist/next/index.d.ts +204 -0
- package/dist/next/index.js +274 -0
- package/dist/prisma/index.cjs +122 -0
- package/dist/prisma/index.d.ts +60 -0
- package/dist/prisma/index.js +86 -0
- package/dist/serialize-worker.cjs +177 -13
- package/dist/serialize-worker.js +63 -12
- package/package.json +64 -15
- package/src/cache-service.ts +1005 -192
- package/src/cli.ts +143 -0
- package/src/compression.ts +63 -0
- package/src/disk-tier.ts +71 -7
- package/src/drizzle/index.ts +86 -0
- package/src/encryption.ts +56 -5
- package/src/http/index.ts +223 -0
- package/src/index.ts +7 -0
- package/src/nestjs/decorators.ts +161 -0
- package/src/nestjs/index.ts +23 -0
- package/src/nestjs/tricache.module.ts +104 -0
- package/src/nestjs/tricache.store.ts +97 -0
- package/src/nestjs/types.ts +79 -0
- package/src/next/cache-handler.ts +244 -0
- package/src/next/index.ts +37 -0
- package/src/next/isr-handler.ts +105 -0
- package/src/next/types.ts +130 -0
- package/src/prisma/index.ts +151 -0
- package/src/serialize-worker.ts +77 -13
- package/src/smart-memory-cache.ts +22 -8
- package/src/types.ts +172 -2
- package/src/wasm/bloom-filter-wasm.ts +3 -2
- package/src/worker-pool.ts +156 -42
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache/http — Universal HTTP Caching, ETag generation, and 304 Not Modified middleware
|
|
3
|
+
* for Express, Fastify, and Hono.
|
|
4
|
+
*
|
|
5
|
+
* Usage with Express:
|
|
6
|
+
* import { expressCache } from 'tricache/http';
|
|
7
|
+
* app.get('/api/users', expressCache({ cache, ttl: 300, tags: ['users'] }), handler);
|
|
8
|
+
*
|
|
9
|
+
* Usage with Hono:
|
|
10
|
+
* import { honoCache } from 'tricache/http';
|
|
11
|
+
* app.get('/api/users', honoCache({ cache, ttl: 300, tags: ['users'] }), handler);
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { CacheService } from '../cache-service.js';
|
|
15
|
+
import type { WrapOptions } from '../types.js';
|
|
16
|
+
import crypto from 'crypto';
|
|
17
|
+
|
|
18
|
+
export interface HttpCacheOptions extends WrapOptions {
|
|
19
|
+
/** TriCache instance. If omitted, uses singleton CacheService.create(). */
|
|
20
|
+
cache?: CacheService;
|
|
21
|
+
/** Custom key derivation function. Defaults to `${method}:${url}`. */
|
|
22
|
+
keyGenerator?: (req: any) => string;
|
|
23
|
+
/** Whether to emit weak ETags (default: true). */
|
|
24
|
+
etag?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Compute a weak ETag from a string, Buffer, or object */
|
|
28
|
+
export function generateETag(data: unknown): string {
|
|
29
|
+
const str = typeof data === 'string'
|
|
30
|
+
? data
|
|
31
|
+
: Buffer.isBuffer(data)
|
|
32
|
+
? data.toString('utf8')
|
|
33
|
+
: JSON.stringify(data);
|
|
34
|
+
const hash = crypto.createHash('sha1').update(str).digest('hex').slice(0, 16);
|
|
35
|
+
return `W/"${str.length.toString(16)}-${hash}"`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Express / Connect middleware */
|
|
39
|
+
export function expressCache(options: HttpCacheOptions = {}) {
|
|
40
|
+
const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
|
|
41
|
+
|
|
42
|
+
return async (req: any, res: any, next: any) => {
|
|
43
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
44
|
+
return next();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let activeCache = cache;
|
|
48
|
+
if (!activeCache) {
|
|
49
|
+
const { CacheService } = await import('../cache-service.js');
|
|
50
|
+
activeCache = CacheService.create();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.originalUrl || req.url}`;
|
|
54
|
+
const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string }>(
|
|
58
|
+
key,
|
|
59
|
+
async () => {
|
|
60
|
+
return new Promise((resolve) => {
|
|
61
|
+
const origJson = res.json?.bind(res);
|
|
62
|
+
const origSend = res.send?.bind(res);
|
|
63
|
+
|
|
64
|
+
if (origJson) {
|
|
65
|
+
res.json = (body: any) => {
|
|
66
|
+
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
67
|
+
resolve({ body, contentType: 'application/json; charset=utf-8', etag: bodyEtag });
|
|
68
|
+
if (ifNoneMatch && ifNoneMatch === bodyEtag) {
|
|
69
|
+
return res.status(304).end();
|
|
70
|
+
}
|
|
71
|
+
if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
|
|
72
|
+
return origJson(body);
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (origSend) {
|
|
77
|
+
res.send = (body: any) => {
|
|
78
|
+
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
79
|
+
resolve({ body, contentType: res.getHeader ? res.getHeader('content-type') : undefined, etag: bodyEtag });
|
|
80
|
+
if (ifNoneMatch && ifNoneMatch === bodyEtag) {
|
|
81
|
+
return res.status(304).end();
|
|
82
|
+
}
|
|
83
|
+
if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
|
|
84
|
+
return origSend(body);
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
next();
|
|
89
|
+
});
|
|
90
|
+
},
|
|
91
|
+
ttl,
|
|
92
|
+
{ swr, tags }
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
if (!res.headersSent) {
|
|
96
|
+
if (cached.etag) {
|
|
97
|
+
if (res.setHeader) res.setHeader('ETag', cached.etag);
|
|
98
|
+
if (ifNoneMatch === cached.etag) {
|
|
99
|
+
return res.status(304).end();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (cached.contentType && res.setHeader) {
|
|
103
|
+
res.setHeader('Content-Type', cached.contentType);
|
|
104
|
+
}
|
|
105
|
+
if (typeof cached.body === 'object' && cached.body !== null && res.json) {
|
|
106
|
+
return res.json(cached.body);
|
|
107
|
+
} else if (res.send) {
|
|
108
|
+
return res.send(cached.body);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
} catch (err) {
|
|
112
|
+
next(err);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Hono / Web Standard middleware */
|
|
118
|
+
export function honoCache(options: HttpCacheOptions = {}) {
|
|
119
|
+
const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
|
|
120
|
+
|
|
121
|
+
return async (c: any, next: any) => {
|
|
122
|
+
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
|
|
123
|
+
return await next();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let activeCache = cache;
|
|
127
|
+
if (!activeCache) {
|
|
128
|
+
const { CacheService } = await import('../cache-service.js');
|
|
129
|
+
activeCache = CacheService.create();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const key = keyGenerator ? keyGenerator(c.req) : `http:${c.req.method}:${c.req.url}`;
|
|
133
|
+
const ifNoneMatch = c.req.header ? c.req.header('if-none-match') : undefined;
|
|
134
|
+
|
|
135
|
+
const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string }>(
|
|
136
|
+
key,
|
|
137
|
+
async () => {
|
|
138
|
+
await next();
|
|
139
|
+
const res = c.res;
|
|
140
|
+
const text = await res.clone().text();
|
|
141
|
+
const bodyEtag = etag ? generateETag(text) : undefined;
|
|
142
|
+
return {
|
|
143
|
+
body: text,
|
|
144
|
+
contentType: res.headers.get('content-type') ?? 'text/plain',
|
|
145
|
+
etag: bodyEtag,
|
|
146
|
+
};
|
|
147
|
+
},
|
|
148
|
+
ttl,
|
|
149
|
+
{ swr, tags }
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
if (cached.etag && ifNoneMatch === cached.etag) {
|
|
153
|
+
return c.body(null, 304, { ETag: cached.etag });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const headers: Record<string, string> = {};
|
|
157
|
+
if (cached.etag) headers['ETag'] = cached.etag;
|
|
158
|
+
if (cached.contentType) headers['Content-Type'] = cached.contentType;
|
|
159
|
+
|
|
160
|
+
return c.body(cached.body, 200, headers);
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Fastify preHandler hook */
|
|
165
|
+
export function fastifyCache(options: HttpCacheOptions = {}) {
|
|
166
|
+
const { cache, keyGenerator, etag = true, ttl = 300, tags } = options;
|
|
167
|
+
|
|
168
|
+
return async (req: any, reply: any) => {
|
|
169
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return;
|
|
170
|
+
|
|
171
|
+
let activeCache = cache;
|
|
172
|
+
if (!activeCache) {
|
|
173
|
+
const { CacheService } = await import('../cache-service.js');
|
|
174
|
+
activeCache = CacheService.create();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.url}`;
|
|
178
|
+
const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
|
|
179
|
+
|
|
180
|
+
// Fast-path: Check if already cached in L1 / Disk / Redis
|
|
181
|
+
const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string } | null>(
|
|
182
|
+
key,
|
|
183
|
+
async () => null,
|
|
184
|
+
0
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
if (cached) {
|
|
188
|
+
if (cached.etag) {
|
|
189
|
+
if (reply.header) reply.header('ETag', cached.etag);
|
|
190
|
+
if (ifNoneMatch === cached.etag) {
|
|
191
|
+
if (reply.code) reply.code(304);
|
|
192
|
+
else if (reply.status) reply.status(304);
|
|
193
|
+
if (reply.send) return reply.send();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (cached.contentType && reply.header) {
|
|
198
|
+
reply.header('Content-Type', cached.contentType);
|
|
199
|
+
}
|
|
200
|
+
if (reply.send) return reply.send(cached.body);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Miss path: intercept reply.send on completion
|
|
205
|
+
const origSend = reply.send?.bind(reply);
|
|
206
|
+
if (origSend) {
|
|
207
|
+
reply.send = function (payload: any) {
|
|
208
|
+
if (payload !== undefined && payload !== null) {
|
|
209
|
+
const payloadEtag = etag ? generateETag(payload) : undefined;
|
|
210
|
+
const contentType = (reply.getHeader && reply.getHeader('content-type')) || (typeof payload === 'object' ? 'application/json' : 'text/plain');
|
|
211
|
+
activeCache!.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, undefined, { tags }).catch(() => {});
|
|
212
|
+
if (ifNoneMatch && ifNoneMatch === payloadEtag) {
|
|
213
|
+
if (reply.code) reply.code(304);
|
|
214
|
+
else if (reply.status) reply.status(304);
|
|
215
|
+
return origSend();
|
|
216
|
+
}
|
|
217
|
+
if (payloadEtag && reply.header) reply.header('ETag', payloadEtag);
|
|
218
|
+
}
|
|
219
|
+
return origSend(payload);
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -22,6 +22,7 @@ export { CacheEncryption, type EncryptionMode } from './encryption';
|
|
|
22
22
|
export { SmartMemoryCache } from './smart-memory-cache';
|
|
23
23
|
export { DiskTier } from './disk-tier';
|
|
24
24
|
export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
25
|
+
export { type CompressionAlgorithm } from './compression';
|
|
25
26
|
|
|
26
27
|
export {
|
|
27
28
|
CachePriority,
|
|
@@ -37,4 +38,10 @@ export {
|
|
|
37
38
|
type CachePingResult,
|
|
38
39
|
type ICacheTracer,
|
|
39
40
|
type ICacheSpan,
|
|
41
|
+
type WrapOptions,
|
|
42
|
+
type LockOptions,
|
|
43
|
+
type ICacheCounter,
|
|
44
|
+
type ICacheObservableGauge,
|
|
45
|
+
type ICacheBatchObservableCallback,
|
|
46
|
+
type ICacheMeter,
|
|
40
47
|
} from './types';
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { CacheService } from '../cache-service.js';
|
|
2
|
+
import type { CachePriority } from '../types.js';
|
|
3
|
+
|
|
4
|
+
export interface CacheableOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Static key string or dynamic key generator function.
|
|
7
|
+
* Example: (id: string) => `user:${id}`
|
|
8
|
+
*/
|
|
9
|
+
key?: string | ((...args: any[]) => string);
|
|
10
|
+
/** TTL in seconds (or milliseconds if specified / detected). Default: 300 s. */
|
|
11
|
+
ttl?: number;
|
|
12
|
+
/** Explicit time unit for the ttl option. Default: 'seconds'. */
|
|
13
|
+
ttlUnit?: 'seconds' | 'milliseconds';
|
|
14
|
+
/** Stale-While-Revalidate grace period in seconds. */
|
|
15
|
+
swr?: number;
|
|
16
|
+
/** Semantic tags for invalidation. */
|
|
17
|
+
tags?: string[] | ((...args: any[]) => string[]);
|
|
18
|
+
/** Dependency cascade patterns. */
|
|
19
|
+
dependsOn?: string[] | ((...args: any[]) => string[]);
|
|
20
|
+
/** Cache eviction priority. */
|
|
21
|
+
priority?: CachePriority;
|
|
22
|
+
/** 0–1 fraction of TTL elapsed for background recompute. */
|
|
23
|
+
refreshAhead?: number;
|
|
24
|
+
/** XFetch probabilistic early expiration factor (0.5–2.0). */
|
|
25
|
+
xfetchBeta?: number;
|
|
26
|
+
/** Condition predicate to determine whether caching should occur. */
|
|
27
|
+
condition?: (...args: any[]) => boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface CacheEvictOptions {
|
|
31
|
+
/** Key or pattern to delete. */
|
|
32
|
+
key?: string | ((...args: any[]) => string);
|
|
33
|
+
/** Tags to invalidate. */
|
|
34
|
+
tags?: string[] | ((...args: any[]) => string[]);
|
|
35
|
+
/** Invalidate before method execution (default: false = after successful execution). */
|
|
36
|
+
beforeInvocation?: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function resolveCacheInstance(ctx: any): CacheService {
|
|
40
|
+
return ctx?.cacheService || ctx?.cache || ctx?.cacheStore?.cache || CacheService.create();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Declarative method decorator that caches the return value of an async method.
|
|
45
|
+
*
|
|
46
|
+
* Automatically intercepts calls, checks TriCache (L1 -> L1.5 -> L2), and falls
|
|
47
|
+
* back to executing the decorated method on cache miss with thundering-herd protection.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* @Injectable()
|
|
52
|
+
* export class UserService {
|
|
53
|
+
* @Cacheable({ key: (id) => `user:${id}`, ttl: 300, tags: ['users'] })
|
|
54
|
+
* async findById(id: string) {
|
|
55
|
+
* return this.db.find(id);
|
|
56
|
+
* }
|
|
57
|
+
* }
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export function Cacheable(options: CacheableOptions = {}): MethodDecorator {
|
|
61
|
+
return function (
|
|
62
|
+
target: any,
|
|
63
|
+
propertyKey: string | symbol,
|
|
64
|
+
descriptor: TypedPropertyDescriptor<any>,
|
|
65
|
+
) {
|
|
66
|
+
const originalMethod = descriptor.value;
|
|
67
|
+
const methodName = String(propertyKey);
|
|
68
|
+
const className = target?.constructor?.name || 'Service';
|
|
69
|
+
|
|
70
|
+
descriptor.value = async function (...args: any[]) {
|
|
71
|
+
if (options.condition && !options.condition(...args)) {
|
|
72
|
+
return originalMethod.apply(this, args);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const cache = resolveCacheInstance(this);
|
|
76
|
+
const key = typeof options.key === 'function'
|
|
77
|
+
? options.key(...args)
|
|
78
|
+
: (typeof options.key === 'string' ? options.key : `${className}:${methodName}:${JSON.stringify(args)}`);
|
|
79
|
+
|
|
80
|
+
let ttlSeconds = options.ttl ?? 300;
|
|
81
|
+
const rawTtl = options.ttl;
|
|
82
|
+
if (typeof rawTtl === 'number') {
|
|
83
|
+
if (options.ttlUnit === 'milliseconds' || (rawTtl >= 1000 && rawTtl % 1000 === 0 && options.ttlUnit !== 'seconds')) {
|
|
84
|
+
ttlSeconds = Math.round(rawTtl / 1000);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const tags = typeof options.tags === 'function' ? options.tags(...args) : options.tags;
|
|
89
|
+
const dependsOn = typeof options.dependsOn === 'function' ? options.dependsOn(...args) : options.dependsOn;
|
|
90
|
+
|
|
91
|
+
return cache.wrap(
|
|
92
|
+
key,
|
|
93
|
+
() => originalMethod.apply(this, args),
|
|
94
|
+
{
|
|
95
|
+
ttl: ttlSeconds,
|
|
96
|
+
swr: options.swr,
|
|
97
|
+
tags,
|
|
98
|
+
dependsOn,
|
|
99
|
+
priority: options.priority,
|
|
100
|
+
refreshAhead: options.refreshAhead,
|
|
101
|
+
xfetchBeta: options.xfetchBeta,
|
|
102
|
+
},
|
|
103
|
+
);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return descriptor;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Declarative method decorator that invalidates cache keys or tags upon method execution.
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```typescript
|
|
115
|
+
* @Injectable()
|
|
116
|
+
* export class UserService {
|
|
117
|
+
* @CacheEvict({ tags: ['users'] })
|
|
118
|
+
* async update(id: string, dto: UpdateUserDto) {
|
|
119
|
+
* return this.db.update(id, dto);
|
|
120
|
+
* }
|
|
121
|
+
* }
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export function CacheEvict(options: CacheEvictOptions = {}): MethodDecorator {
|
|
125
|
+
return function (
|
|
126
|
+
_target: any,
|
|
127
|
+
_propertyKey: string | symbol,
|
|
128
|
+
descriptor: TypedPropertyDescriptor<any>,
|
|
129
|
+
) {
|
|
130
|
+
const originalMethod = descriptor.value;
|
|
131
|
+
|
|
132
|
+
descriptor.value = async function (...args: any[]) {
|
|
133
|
+
const cache = resolveCacheInstance(this);
|
|
134
|
+
|
|
135
|
+
const performEviction = async () => {
|
|
136
|
+
if (options.key) {
|
|
137
|
+
const k = typeof options.key === 'function' ? options.key(...args) : options.key;
|
|
138
|
+
await cache.delete(k);
|
|
139
|
+
}
|
|
140
|
+
if (options.tags) {
|
|
141
|
+
const t = typeof options.tags === 'function' ? options.tags(...args) : options.tags;
|
|
142
|
+
await cache.invalidateTags(t);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
if (options.beforeInvocation) {
|
|
147
|
+
await performEviction();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const result = await originalMethod.apply(this, args);
|
|
151
|
+
|
|
152
|
+
if (!options.beforeInvocation) {
|
|
153
|
+
await performEviction();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return result;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
return descriptor;
|
|
160
|
+
};
|
|
161
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { TriCacheModule } from './tricache.module.js';
|
|
2
|
+
|
|
3
|
+
export { TriCacheModule };
|
|
4
|
+
export { TriCacheStore } from './tricache.store.js';
|
|
5
|
+
export {
|
|
6
|
+
Cacheable,
|
|
7
|
+
CacheEvict,
|
|
8
|
+
type CacheableOptions,
|
|
9
|
+
type CacheEvictOptions,
|
|
10
|
+
} from './decorators.js';
|
|
11
|
+
export {
|
|
12
|
+
TRICACHE_SERVICE,
|
|
13
|
+
CACHE_MANAGER,
|
|
14
|
+
type DynamicModule,
|
|
15
|
+
type Provider,
|
|
16
|
+
type InjectionToken,
|
|
17
|
+
type Type,
|
|
18
|
+
type TriCacheAsyncOptions,
|
|
19
|
+
type TriCacheOptionsFactory,
|
|
20
|
+
type NestCacheStore,
|
|
21
|
+
} from './types.js';
|
|
22
|
+
|
|
23
|
+
export default TriCacheModule;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { CacheService, type CacheOptions } from '../index.js';
|
|
2
|
+
import { TriCacheStore } from './tricache.store.js';
|
|
3
|
+
import {
|
|
4
|
+
TRICACHE_SERVICE,
|
|
5
|
+
CACHE_MANAGER,
|
|
6
|
+
type DynamicModule,
|
|
7
|
+
type Provider,
|
|
8
|
+
type TriCacheAsyncOptions,
|
|
9
|
+
type TriCacheOptionsFactory,
|
|
10
|
+
} from './types.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* TriCacheModule — NestJS dynamic module providing TriCacheService and standard CacheStore.
|
|
14
|
+
*
|
|
15
|
+
* Can be registered synchronously via `TriCacheModule.register(options)`
|
|
16
|
+
* or asynchronously via `TriCacheModule.registerAsync({ useFactory: ... })`.
|
|
17
|
+
*
|
|
18
|
+
* Exports:
|
|
19
|
+
* - `TRICACHE_SERVICE` (`CacheService` instance)
|
|
20
|
+
* - `CACHE_MANAGER` (`TriCacheStore` adapter conforming to @nestjs/cache-manager)
|
|
21
|
+
*/
|
|
22
|
+
export class TriCacheModule {
|
|
23
|
+
/**
|
|
24
|
+
* Register TriCache module synchronously with static configuration options.
|
|
25
|
+
*/
|
|
26
|
+
static register(options: CacheOptions = {}): DynamicModule {
|
|
27
|
+
const cache = CacheService.create(options);
|
|
28
|
+
const store = new TriCacheStore(cache);
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
module: TriCacheModule,
|
|
32
|
+
global: true,
|
|
33
|
+
providers: [
|
|
34
|
+
{ provide: TRICACHE_SERVICE, useValue: cache },
|
|
35
|
+
{ provide: CACHE_MANAGER, useValue: store },
|
|
36
|
+
],
|
|
37
|
+
exports: [TRICACHE_SERVICE, CACHE_MANAGER],
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Register TriCache module asynchronously with factory or class injection.
|
|
43
|
+
*/
|
|
44
|
+
static registerAsync(asyncOptions: TriCacheAsyncOptions): DynamicModule {
|
|
45
|
+
const asyncProviders = this.createAsyncProviders(asyncOptions);
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
module: TriCacheModule,
|
|
49
|
+
global: true,
|
|
50
|
+
imports: asyncOptions.imports || [],
|
|
51
|
+
providers: [
|
|
52
|
+
...asyncProviders,
|
|
53
|
+
{
|
|
54
|
+
provide: CACHE_MANAGER,
|
|
55
|
+
useFactory: (cache: any) => new TriCacheStore(cache as CacheService),
|
|
56
|
+
inject: [TRICACHE_SERVICE],
|
|
57
|
+
},
|
|
58
|
+
...(asyncOptions.extraProviders || []),
|
|
59
|
+
],
|
|
60
|
+
exports: [TRICACHE_SERVICE, CACHE_MANAGER],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private static createAsyncProviders(options: TriCacheAsyncOptions): Provider[] {
|
|
65
|
+
if (options.useExisting || options.useFactory) {
|
|
66
|
+
return [this.createAsyncOptionsProvider(options)];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (options.useClass) {
|
|
70
|
+
return [
|
|
71
|
+
this.createAsyncOptionsProvider(options),
|
|
72
|
+
{
|
|
73
|
+
provide: options.useClass,
|
|
74
|
+
useClass: options.useClass,
|
|
75
|
+
},
|
|
76
|
+
];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return [];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private static createAsyncOptionsProvider(options: TriCacheAsyncOptions): Provider {
|
|
83
|
+
if (options.useFactory) {
|
|
84
|
+
return {
|
|
85
|
+
provide: TRICACHE_SERVICE,
|
|
86
|
+
useFactory: async (...args: any[]) => {
|
|
87
|
+
const cacheOptions = await options.useFactory!(...args);
|
|
88
|
+
return CacheService.create(cacheOptions);
|
|
89
|
+
},
|
|
90
|
+
inject: options.inject || [],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const injectToken = options.useExisting || options.useClass!;
|
|
95
|
+
return {
|
|
96
|
+
provide: TRICACHE_SERVICE,
|
|
97
|
+
useFactory: async (optionsFactory: any) => {
|
|
98
|
+
const cacheOptions = await (optionsFactory as TriCacheOptionsFactory).createTriCacheOptions();
|
|
99
|
+
return CacheService.create(cacheOptions);
|
|
100
|
+
},
|
|
101
|
+
inject: [injectToken],
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { CacheService } from '../index.js';
|
|
2
|
+
import type { NestCacheStore } from './types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* TriCacheStore — drop-in CacheStore conforming to @nestjs/cache-manager and cache-manager v5/v6.
|
|
6
|
+
*
|
|
7
|
+
* Implements millisecond-based TTL semantics expected by cache-manager v5/v6
|
|
8
|
+
* while dispatching to TriCache's three-tier engine with L1 memory, L1.5 NVMe disk spill,
|
|
9
|
+
* and L2 Redis/Valkey tiers.
|
|
10
|
+
*/
|
|
11
|
+
export class TriCacheStore implements NestCacheStore {
|
|
12
|
+
constructor(public readonly cache: CacheService) {}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Retrieve an item from the cache.
|
|
16
|
+
* Returns undefined on miss (matching cache-manager v5/v6 contract).
|
|
17
|
+
*/
|
|
18
|
+
async get<T>(key: string): Promise<T | undefined> {
|
|
19
|
+
const val = await this.cache.peek<T>(key);
|
|
20
|
+
return val !== null ? val : undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Set an item in the cache.
|
|
25
|
+
* @param key - Cache key
|
|
26
|
+
* @param value - Cache value
|
|
27
|
+
* @param ttl - TTL in milliseconds (0 = indefinite / default engine TTL)
|
|
28
|
+
*/
|
|
29
|
+
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
|
|
30
|
+
const ttlSeconds = typeof ttl === 'number' && ttl > 0 ? Math.round(ttl / 1000) : (ttl === 0 ? 0 : undefined);
|
|
31
|
+
await this.cache.set(key, value, ttlSeconds);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Remove an item from the cache.
|
|
36
|
+
*/
|
|
37
|
+
async del(key: string): Promise<void> {
|
|
38
|
+
await this.cache.delete(key);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Clear the entire cache namespace.
|
|
43
|
+
*/
|
|
44
|
+
async reset(): Promise<void> {
|
|
45
|
+
await this.cache.clear();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Batch get multiple items from the cache.
|
|
50
|
+
*/
|
|
51
|
+
async mget<T>(...keys: string[]): Promise<(T | undefined)[]> {
|
|
52
|
+
if (keys.length === 0) return [];
|
|
53
|
+
return this.cache.mget<T>(keys, async () => ({}));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Batch set multiple entries with per-entry millisecond TTL.
|
|
58
|
+
*/
|
|
59
|
+
async mset(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<void> {
|
|
60
|
+
if (entries.length === 0) return;
|
|
61
|
+
const batch: Record<string, { value: unknown; ttl?: number }> = {};
|
|
62
|
+
for (const e of entries) {
|
|
63
|
+
batch[e.key] = {
|
|
64
|
+
value: e.value,
|
|
65
|
+
ttl: typeof e.ttl === 'number' && e.ttl > 0 ? Math.round(e.ttl / 1000) : (e.ttl === 0 ? 0 : undefined),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
await this.cache.mset(batch);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Batch delete multiple keys.
|
|
73
|
+
*/
|
|
74
|
+
async mdel(...keys: string[]): Promise<void> {
|
|
75
|
+
if (keys.length === 0) return;
|
|
76
|
+
await this.cache.mdel(keys);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Scan keys currently resident in the cache.
|
|
81
|
+
*/
|
|
82
|
+
async keys(pattern?: string): Promise<string[]> {
|
|
83
|
+
const all: string[] = [];
|
|
84
|
+
for (const k of this.cache.keys()) {
|
|
85
|
+
if (!pattern || k.includes(pattern)) all.push(k);
|
|
86
|
+
}
|
|
87
|
+
return all;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Get remaining TTL for a key in milliseconds.
|
|
92
|
+
*/
|
|
93
|
+
async ttl(key: string): Promise<number | undefined> {
|
|
94
|
+
const rem = this.cache.ttl(key);
|
|
95
|
+
return rem !== null ? rem * 1000 : undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|