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,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache/prisma — First-class Prisma Client extension for TriCache.
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* import { PrismaClient } from '@prisma/client';
|
|
6
|
+
* import { withTriCache } from 'tricache/prisma';
|
|
7
|
+
*
|
|
8
|
+
* const prisma = new PrismaClient().$extends(
|
|
9
|
+
* withTriCache({
|
|
10
|
+
* cache,
|
|
11
|
+
* defaultTtl: 300,
|
|
12
|
+
* autoInvalidate: true, // Invalidate model tags on create/update/delete
|
|
13
|
+
* })
|
|
14
|
+
* );
|
|
15
|
+
*
|
|
16
|
+
* // Query with cache options:
|
|
17
|
+
* const users = await prisma.user.findMany({
|
|
18
|
+
* where: { active: true },
|
|
19
|
+
* cache: { ttl: 60, tags: ['users'], swr: 30 },
|
|
20
|
+
* });
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { CacheService } from '../cache-service.js';
|
|
24
|
+
import type { WrapOptions } from '../types.js';
|
|
25
|
+
import crypto from 'crypto';
|
|
26
|
+
|
|
27
|
+
export interface PrismaCacheQueryOptions extends WrapOptions {
|
|
28
|
+
/** Explicit cache key. Defaults to SHA-256 hash of (model + operation + args). */
|
|
29
|
+
key?: string;
|
|
30
|
+
/** Explicit tags for invalidation. Automatically includes `[model.toLowerCase()]`. */
|
|
31
|
+
tags?: string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface PrismaTriCacheOptions {
|
|
35
|
+
/** TriCache instance to use for caching. */
|
|
36
|
+
cache: CacheService;
|
|
37
|
+
/** Default TTL in seconds for cached queries (default: 300 s). */
|
|
38
|
+
defaultTtl?: number;
|
|
39
|
+
/** Whether to automatically invalidate model tags on write operations (default: true). */
|
|
40
|
+
autoInvalidate?: boolean;
|
|
41
|
+
/** Automatically cache all read queries even if `cache` options are not provided (default: false). */
|
|
42
|
+
autoCache?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const READ_OPERATIONS = new Set([
|
|
46
|
+
'findUnique',
|
|
47
|
+
'findUniqueOrThrow',
|
|
48
|
+
'findFirst',
|
|
49
|
+
'findFirstOrThrow',
|
|
50
|
+
'findMany',
|
|
51
|
+
'count',
|
|
52
|
+
'aggregate',
|
|
53
|
+
'groupBy',
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
const MUTATION_OPERATIONS = new Set([
|
|
57
|
+
'create',
|
|
58
|
+
'createMany',
|
|
59
|
+
'createManyAndReturn',
|
|
60
|
+
'update',
|
|
61
|
+
'updateMany',
|
|
62
|
+
'updateManyAndReturn',
|
|
63
|
+
'upsert',
|
|
64
|
+
'delete',
|
|
65
|
+
'deleteMany',
|
|
66
|
+
]);
|
|
67
|
+
|
|
68
|
+
/** Recursively sorts object keys for deterministic serialization of nested query filters */
|
|
69
|
+
function deterministicStringify(val: unknown): string {
|
|
70
|
+
if (val === null || typeof val !== 'object') {
|
|
71
|
+
return JSON.stringify(val);
|
|
72
|
+
}
|
|
73
|
+
if (Array.isArray(val)) {
|
|
74
|
+
return `[${val.map(deterministicStringify).join(',')}]`;
|
|
75
|
+
}
|
|
76
|
+
const obj = val as Record<string, unknown>;
|
|
77
|
+
const keys = Object.keys(obj).sort();
|
|
78
|
+
return `{${keys.map(k => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(',')}}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Generate a deterministic SHA-256 hash key for a Prisma query. */
|
|
82
|
+
export function generatePrismaCacheKey(model: string, operation: string, args: unknown): string {
|
|
83
|
+
const normalized = deterministicStringify({ model, operation, args });
|
|
84
|
+
const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
|
|
85
|
+
return `prisma:${model.toLowerCase()}:${operation}:${hash}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Creates a Prisma Client Extension for TriCache.
|
|
90
|
+
*/
|
|
91
|
+
export function withTriCache(options: PrismaTriCacheOptions) {
|
|
92
|
+
const { cache, defaultTtl = 300, autoInvalidate = true, autoCache = false } = options;
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
name: 'tricache-prisma-extension',
|
|
96
|
+
query: {
|
|
97
|
+
$allModels: {
|
|
98
|
+
async $allOperations({ model, operation, args, query }: {
|
|
99
|
+
model: string;
|
|
100
|
+
operation: string;
|
|
101
|
+
args: Record<string, unknown> | undefined;
|
|
102
|
+
query: (args: unknown) => Promise<unknown>;
|
|
103
|
+
}) {
|
|
104
|
+
const modelTag = model.toLowerCase();
|
|
105
|
+
|
|
106
|
+
// Auto-invalidation on write operations
|
|
107
|
+
if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
|
|
108
|
+
const result = await query(args);
|
|
109
|
+
await cache.invalidateTag(modelTag);
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Read operations
|
|
114
|
+
if (READ_OPERATIONS.has(operation)) {
|
|
115
|
+
const queryArgs = args ?? {};
|
|
116
|
+
const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
|
|
117
|
+
|
|
118
|
+
if (cacheConfig !== undefined || autoCache) {
|
|
119
|
+
const opts: PrismaCacheQueryOptions = typeof cacheConfig === 'object' && cacheConfig !== null
|
|
120
|
+
? cacheConfig
|
|
121
|
+
: {};
|
|
122
|
+
|
|
123
|
+
// Clone args without the `cache` property to pass clean args to Prisma query engine
|
|
124
|
+
const { cache: _c, ...cleanArgs } = queryArgs as Record<string, unknown>;
|
|
125
|
+
|
|
126
|
+
const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
|
|
127
|
+
const tags = [...new Set([modelTag, ...(opts.tags ?? [])])];
|
|
128
|
+
|
|
129
|
+
return cache.wrap(
|
|
130
|
+
key,
|
|
131
|
+
() => query(cleanArgs),
|
|
132
|
+
{
|
|
133
|
+
ttl: opts.ttl ?? defaultTtl,
|
|
134
|
+
swr: opts.swr,
|
|
135
|
+
priority: opts.priority,
|
|
136
|
+
tags,
|
|
137
|
+
dependsOn: opts.dependsOn,
|
|
138
|
+
refreshAhead: opts.refreshAhead,
|
|
139
|
+
xfetchBeta: opts.xfetchBeta,
|
|
140
|
+
notFoundTtl: opts.notFoundTtl,
|
|
141
|
+
},
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return query(args);
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
package/src/serialize-worker.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption.
|
|
2
|
+
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption/compression.
|
|
3
3
|
*
|
|
4
4
|
* Receives messages from WorkerPool:
|
|
5
5
|
* { id: number; type: 'encrypt'; payload: string }
|
|
@@ -17,12 +17,21 @@ import { parentPort, workerData } from 'worker_threads';
|
|
|
17
17
|
import { CacheEncryption } from './encryption.ts';
|
|
18
18
|
import type { EncryptionMode } from './encryption.ts';
|
|
19
19
|
import type { ILogger } from './types.ts';
|
|
20
|
+
import {
|
|
21
|
+
compressBuffer,
|
|
22
|
+
decompressBuffer,
|
|
23
|
+
PREFIX_COMPRESSED,
|
|
24
|
+
PREFIX_ENC_COMPRESSED,
|
|
25
|
+
type CompressionAlgorithm,
|
|
26
|
+
} from './compression.ts';
|
|
20
27
|
|
|
21
28
|
interface WorkerInit {
|
|
22
29
|
keyBase64: string;
|
|
23
30
|
mode: EncryptionMode;
|
|
24
31
|
prevKeyBase64: string | undefined;
|
|
25
32
|
prevMode: EncryptionMode | undefined;
|
|
33
|
+
compression?: CompressionAlgorithm;
|
|
34
|
+
compressionThresholdBytes?: number;
|
|
26
35
|
}
|
|
27
36
|
|
|
28
37
|
// Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
|
|
@@ -33,24 +42,79 @@ const silentLogger: ILogger = {
|
|
|
33
42
|
error: () => {},
|
|
34
43
|
};
|
|
35
44
|
|
|
36
|
-
const { keyBase64, mode, prevKeyBase64, prevMode } =
|
|
45
|
+
const { keyBase64, mode, prevKeyBase64, prevMode, compression, compressionThresholdBytes } =
|
|
46
|
+
workerData as WorkerInit;
|
|
37
47
|
|
|
38
48
|
const enc = new CacheEncryption(
|
|
39
|
-
keyBase64
|
|
49
|
+
keyBase64 || undefined,
|
|
40
50
|
silentLogger,
|
|
41
51
|
mode,
|
|
42
52
|
prevKeyBase64 || undefined,
|
|
43
53
|
prevMode,
|
|
44
54
|
);
|
|
45
55
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
const cmpAlgo = compression ?? 'none';
|
|
57
|
+
const cmpThreshold = compressionThresholdBytes ?? 1024;
|
|
58
|
+
|
|
59
|
+
parentPort!.on(
|
|
60
|
+
'message',
|
|
61
|
+
({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
|
|
62
|
+
try {
|
|
63
|
+
const textPayload =
|
|
64
|
+
typeof payload === 'string'
|
|
65
|
+
? payload
|
|
66
|
+
: Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).toString('utf8');
|
|
67
|
+
|
|
68
|
+
if (type === 'encrypt') {
|
|
69
|
+
let result: string;
|
|
70
|
+
if (cmpAlgo !== 'none' && textPayload.length > cmpThreshold) {
|
|
71
|
+
const compressed = compressBuffer(Buffer.from(textPayload, 'utf8'), cmpAlgo);
|
|
72
|
+
if (enc.isEnabled) {
|
|
73
|
+
const encrypted = enc.encryptBuffer(compressed);
|
|
74
|
+
result = PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
|
|
75
|
+
} else {
|
|
76
|
+
result = PREFIX_COMPRESSED + compressed.toString('base64');
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
result = enc.encrypt(textPayload);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (result.length >= 131_072) {
|
|
83
|
+
const outBuf = Buffer.from(result, 'utf8');
|
|
84
|
+
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
85
|
+
new Uint8Array(transferable).set(outBuf);
|
|
86
|
+
const outputUint8 = new Uint8Array(transferable);
|
|
87
|
+
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
88
|
+
} else {
|
|
89
|
+
parentPort!.postMessage({ id, result });
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
let result: string;
|
|
93
|
+
if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
94
|
+
const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
|
|
95
|
+
const decryptedBuf = enc.decryptBuffer(rawBuf);
|
|
96
|
+
const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
97
|
+
result = decompressed.toString('utf8');
|
|
98
|
+
} else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
|
|
99
|
+
const rawBuf = Buffer.from(textPayload.slice(PREFIX_COMPRESSED.length), 'base64');
|
|
100
|
+
const decompressed = decompressBuffer(rawBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
|
|
101
|
+
result = decompressed.toString('utf8');
|
|
102
|
+
} else {
|
|
103
|
+
result = enc.decrypt(textPayload);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (result.length >= 131_072) {
|
|
107
|
+
const outBuf = Buffer.from(result, 'utf8');
|
|
108
|
+
const transferable = new ArrayBuffer(outBuf.byteLength);
|
|
109
|
+
new Uint8Array(transferable).set(outBuf);
|
|
110
|
+
const outputUint8 = new Uint8Array(transferable);
|
|
111
|
+
parentPort!.postMessage({ id, result: outputUint8, isTransfer: true }, [transferable]);
|
|
112
|
+
} else {
|
|
113
|
+
parentPort!.postMessage({ id, result });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} catch (e) {
|
|
117
|
+
parentPort!.postMessage({ id, error: (e as Error).message });
|
|
52
118
|
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
});
|
|
119
|
+
},
|
|
120
|
+
);
|
|
@@ -17,7 +17,7 @@ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger,
|
|
|
17
17
|
|
|
18
18
|
// Reusable return object for get() — eliminates one heap allocation per hot read.
|
|
19
19
|
// Safe because JS is single-threaded: callers consume all fields before the next get().
|
|
20
|
-
const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined, fetchedAt: 0 };
|
|
20
|
+
const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined, fetchedAt: 0, tagVersions: undefined, setAt: undefined };
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
23
|
* Packed-byte threshold above which the live JS object is NOT stored alongside the
|
|
@@ -250,12 +250,6 @@ function globMatchParts(parts: string[], first: string, last: string, key: strin
|
|
|
250
250
|
return true;
|
|
251
251
|
}
|
|
252
252
|
|
|
253
|
-
function globMatch(pattern: string, key: string): boolean {
|
|
254
|
-
const parts = pattern.split('*');
|
|
255
|
-
if (parts.length === 1) return pattern === key; // no wildcard — exact match
|
|
256
|
-
return globMatchParts(parts, parts[0], parts[parts.length - 1], key);
|
|
257
|
-
}
|
|
258
|
-
|
|
259
253
|
// ─── SmartMemoryCache ─────────────────────────────────────────────────────────
|
|
260
254
|
|
|
261
255
|
export interface SmartMemoryCacheOptions {
|
|
@@ -543,6 +537,8 @@ export class SmartMemoryCache {
|
|
|
543
537
|
_hit.ttlMs = entry.ttlMs;
|
|
544
538
|
_hit.delta = entry.delta;
|
|
545
539
|
_hit.fetchedAt = now;
|
|
540
|
+
_hit.tagVersions = entry.tagVersions;
|
|
541
|
+
_hit.setAt = entry.setAt;
|
|
546
542
|
return _hit;
|
|
547
543
|
}
|
|
548
544
|
|
|
@@ -553,6 +549,7 @@ export class SmartMemoryCache {
|
|
|
553
549
|
priority: CachePriority = 2 /* NORMAL */,
|
|
554
550
|
staleAt?: number,
|
|
555
551
|
delta?: number,
|
|
552
|
+
tagVersions?: Record<string, number>,
|
|
556
553
|
): void {
|
|
557
554
|
// Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
|
|
558
555
|
// "size probe" that was discarded for large payloads (the double-pass).
|
|
@@ -584,7 +581,7 @@ export class SmartMemoryCache {
|
|
|
584
581
|
// buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
|
|
585
582
|
// For large entries, get() falls back to the unpack() path transparently.
|
|
586
583
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
|
|
587
|
-
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now });
|
|
584
|
+
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
|
|
588
585
|
// Only add new keys to the bloom — overwrites already have their bits set.
|
|
589
586
|
// Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
|
|
590
587
|
if (!existingEntry) this.bloom.add(key);
|
|
@@ -800,6 +797,23 @@ export class SmartMemoryCache {
|
|
|
800
797
|
return evicted;
|
|
801
798
|
}
|
|
802
799
|
|
|
800
|
+
/**
|
|
801
|
+
* Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
|
|
802
|
+
* Used for concurrency-safe compare-and-delete on stale generational reads,
|
|
803
|
+
* guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
|
|
804
|
+
*/
|
|
805
|
+
deleteIfSetBefore(key: string, cutoffMs: number): boolean {
|
|
806
|
+
const entry = this.cache.get(key);
|
|
807
|
+
if (!entry) return false;
|
|
808
|
+
const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
|
|
809
|
+
if (setAt <= cutoffMs) {
|
|
810
|
+
const deleted = this._delete(key, 'manual');
|
|
811
|
+
if (deleted) this.maybeRebuildBloom();
|
|
812
|
+
return deleted;
|
|
813
|
+
}
|
|
814
|
+
return false;
|
|
815
|
+
}
|
|
816
|
+
|
|
803
817
|
|
|
804
818
|
|
|
805
819
|
exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
|
package/src/types.ts
CHANGED
|
@@ -33,7 +33,7 @@ export interface ILogger {
|
|
|
33
33
|
|
|
34
34
|
/** Default no-op logger — swap out via CacheService options */
|
|
35
35
|
export const consoleLogger: ILogger = {
|
|
36
|
-
debug: (
|
|
36
|
+
debug: () => {},
|
|
37
37
|
info: (msg, meta) => console.info('[tricache]', msg, meta ?? ''),
|
|
38
38
|
warn: (msg, meta) => console.warn('[tricache]', msg, meta ?? ''),
|
|
39
39
|
error: (msg, meta, err) => console.error('[tricache]', msg, meta ?? '', err ?? ''),
|
|
@@ -112,6 +112,8 @@ export interface SmartCacheEntry {
|
|
|
112
112
|
* Optional for backward compatibility with snapshots written by older versions.
|
|
113
113
|
*/
|
|
114
114
|
setAt?: number;
|
|
115
|
+
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
116
|
+
tagVersions?: Record<string, number>;
|
|
115
117
|
}
|
|
116
118
|
|
|
117
119
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
@@ -129,6 +131,10 @@ export interface CacheHit {
|
|
|
129
131
|
/** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
|
|
130
132
|
* reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
|
|
131
133
|
fetchedAt?: number;
|
|
134
|
+
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
135
|
+
tagVersions?: Record<string, number>;
|
|
136
|
+
/** Timestamp (ms) when this entry was written into memory */
|
|
137
|
+
setAt?: number;
|
|
132
138
|
}
|
|
133
139
|
|
|
134
140
|
// ─── Disk tier ───────────────────────────────────────────────────────────────
|
|
@@ -144,6 +150,8 @@ export interface DiskCacheEntry {
|
|
|
144
150
|
hits: number;
|
|
145
151
|
lastAccess: number;
|
|
146
152
|
priority: number;
|
|
153
|
+
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
154
|
+
tagVersions?: Record<string, number>;
|
|
147
155
|
}
|
|
148
156
|
|
|
149
157
|
// ─── Metrics snapshot ────────────────────────────────────────────────────────
|
|
@@ -209,15 +217,22 @@ export interface CacheMetrics {
|
|
|
209
217
|
bytesSaved: number;
|
|
210
218
|
};
|
|
211
219
|
|
|
212
|
-
/**
|
|
220
|
+
/** Invalidation backplane statistics */
|
|
213
221
|
backplane: {
|
|
214
222
|
enabled: boolean;
|
|
223
|
+
mode: 'pubsub' | 'stream';
|
|
215
224
|
/** Invalidation messages published to other instances */
|
|
216
225
|
sent: number;
|
|
217
226
|
/** Invalidation messages received from other instances */
|
|
218
227
|
received: number;
|
|
219
228
|
/** Own messages silently skipped (prevents double-eviction) */
|
|
220
229
|
skipped: number;
|
|
230
|
+
/** Stream entries received (when backplaneMode is 'stream') */
|
|
231
|
+
streamEntriesReceived?: number;
|
|
232
|
+
/** Replayed invalidations after network reconnect */
|
|
233
|
+
streamReplays?: number;
|
|
234
|
+
/** Stream trim gaps detected (where consumer fell behind oldest entry) */
|
|
235
|
+
streamGaps?: number;
|
|
221
236
|
};
|
|
222
237
|
|
|
223
238
|
/** L2 Redis circuit breaker state */
|
|
@@ -316,6 +331,11 @@ export interface CacheOptions {
|
|
|
316
331
|
* false otherwise.
|
|
317
332
|
*/
|
|
318
333
|
redisTls?: boolean;
|
|
334
|
+
/**
|
|
335
|
+
* Redis wire protocol version (RESP2 or RESP3).
|
|
336
|
+
* Defaults to 3 in ioredis v6+. Set to 2 for legacy proxies or servers without RESP3 support.
|
|
337
|
+
*/
|
|
338
|
+
redisProtocol?: 2 | 3;
|
|
319
339
|
/**
|
|
320
340
|
* Set to `true` to disable L2 Redis entirely (e.g. when running single-process
|
|
321
341
|
* services that don't need distributed caching). Default: false in production,
|
|
@@ -351,6 +371,22 @@ export interface CacheOptions {
|
|
|
351
371
|
/** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
|
|
352
372
|
previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
|
|
353
373
|
|
|
374
|
+
// ── Compression ──────────────────────────────────────────────────────────
|
|
375
|
+
/**
|
|
376
|
+
* Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
|
|
377
|
+
* - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
|
|
378
|
+
* - `'gzip'` — faster compression / lower CPU overhead.
|
|
379
|
+
* - `'none'` — disable compression.
|
|
380
|
+
* Default: `'none'` (uncompressed).
|
|
381
|
+
*/
|
|
382
|
+
compression?: 'brotli' | 'gzip' | 'none';
|
|
383
|
+
/**
|
|
384
|
+
* Minimum payload size in bytes before compression is applied.
|
|
385
|
+
* Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
|
|
386
|
+
* Default: `1024` (1 KB).
|
|
387
|
+
*/
|
|
388
|
+
compressionThresholdBytes?: number;
|
|
389
|
+
|
|
354
390
|
// ── Snapshot ────────────────────────────────────────────────────────────
|
|
355
391
|
/**
|
|
356
392
|
* Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
|
|
@@ -430,6 +466,15 @@ export interface CacheOptions {
|
|
|
430
466
|
*/
|
|
431
467
|
invalidationBackplane?: boolean;
|
|
432
468
|
|
|
469
|
+
/**
|
|
470
|
+
* Enable Redis 7+ Sharded Pub/Sub (`SPUBLISH` / `SSUBSCRIBE`) when connected to
|
|
471
|
+
* a Redis Cluster (`redisClusterNodes`). Scopes pub/sub message routing strictly
|
|
472
|
+
* to the cluster shard handling the key slot, reducing inter-node cluster bus gossip.
|
|
473
|
+
*
|
|
474
|
+
* Default: `false` (standard cluster PUBLISH / SUBSCRIBE).
|
|
475
|
+
*/
|
|
476
|
+
useShardedPubSub?: boolean;
|
|
477
|
+
|
|
433
478
|
// ── OOM protection ──────────────────────────────────────────────────────
|
|
434
479
|
/**
|
|
435
480
|
* Enable the GC-aware OOM guard. When heap utilisation crosses
|
|
@@ -729,4 +774,129 @@ export interface CacheOptions {
|
|
|
729
774
|
* guard enforce the limit even when Redis is unavailable.
|
|
730
775
|
*/
|
|
731
776
|
failClosed?: boolean;
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Strategy used for tag-based cache invalidation:
|
|
780
|
+
* - `'set'` (default): Traditional Redis Set tracking. Members are registered in Redis
|
|
781
|
+
* sets and deleted individually on `invalidateTag()`. Best for low-to-medium cardinality tags.
|
|
782
|
+
* - `'generational'`: Generational tag versioning ($O(1)$ invalidations). Tag invalidation
|
|
783
|
+
* increments an atomic integer version counter in Redis and local memory. Entries store their
|
|
784
|
+
* creation tag versions; stale entries are detected on access and pruned with version-gated
|
|
785
|
+
* compare-and-delete. Eliminates key scans and Redis bulk deletion stalls on large datasets.
|
|
786
|
+
*/
|
|
787
|
+
tagStrategy?: 'set' | 'generational';
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* Milliseconds before an in-memory generational tag version is re-synced from Redis.
|
|
791
|
+
* Bounds maximum partition/missed-broadcast staleness when using `tagStrategy: 'generational'`.
|
|
792
|
+
* Default: `5000` ms (5 seconds).
|
|
793
|
+
*/
|
|
794
|
+
tagVersionTtlMs?: number;
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* Read safety strategy for returned cached objects:
|
|
798
|
+
* - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
|
|
799
|
+
* - `'structuredClone'`: Clones values via native `structuredClone()` on L1 hits, L2 promotions,
|
|
800
|
+
* and fetch returns, preventing caller mutations from polluting the cached reference.
|
|
801
|
+
* Supported types: plain objects, arrays, Dates, Maps, Sets, TypedArrays. Functions and class
|
|
802
|
+
* prototype chains are not preserved.
|
|
803
|
+
*/
|
|
804
|
+
cloneStrategy?: 'none' | 'structuredClone';
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* Invalidation backplane transport mode:
|
|
808
|
+
* - `'pubsub'` (default): Ephemeral Redis Pub/Sub (at-most-once delivery).
|
|
809
|
+
* - `'stream'`: Durable Redis Streams (XADD/XREAD) with missed-event replay on reconnect.
|
|
810
|
+
*/
|
|
811
|
+
backplaneMode?: 'pubsub' | 'stream';
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Maximum retained entries in the Redis invalidation stream (`MAXLEN ~ N`).
|
|
815
|
+
* Default: `10000`.
|
|
816
|
+
*/
|
|
817
|
+
backplaneStreamMaxLen?: number;
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Blocking poll timeout in milliseconds for `XREAD BLOCK`.
|
|
821
|
+
* Default: `2000` ms (2 seconds).
|
|
822
|
+
*/
|
|
823
|
+
backplaneStreamBlockMs?: number;
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* Custom Redis Stream key name.
|
|
827
|
+
* Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
|
|
828
|
+
*/
|
|
829
|
+
backplaneStreamKey?: string;
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* OpenTelemetry Meter instance for native metrics publishing.
|
|
833
|
+
* Compatible with `@opentelemetry/api` Meter.
|
|
834
|
+
*/
|
|
835
|
+
meter?: ICacheMeter;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
|
|
840
|
+
*/
|
|
841
|
+
export interface WrapOptions {
|
|
842
|
+
/** TTL in seconds (default: 300 s). */
|
|
843
|
+
ttl?: number;
|
|
844
|
+
/** Stale-While-Revalidate grace period in seconds. */
|
|
845
|
+
swr?: number;
|
|
846
|
+
/** Override the auto-inferred eviction priority. */
|
|
847
|
+
priority?: CachePriority;
|
|
848
|
+
/** Semantic tags for invalidation. */
|
|
849
|
+
tags?: string[];
|
|
850
|
+
/** Dependency cascade patterns (e.g. `['user:*']`). */
|
|
851
|
+
dependsOn?: string[];
|
|
852
|
+
/** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
|
|
853
|
+
refreshAhead?: number;
|
|
854
|
+
/** XFetch probabilistic early expiration factor (0.5–2.0). */
|
|
855
|
+
xfetchBeta?: number;
|
|
856
|
+
/** Override TTL in seconds for null/undefined fetch results (negative caching). */
|
|
857
|
+
notFoundTtl?: number;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* Options for distributed and in-process mutual exclusion locks via `cache.lock()`.
|
|
862
|
+
*/
|
|
863
|
+
export interface LockOptions {
|
|
864
|
+
/**
|
|
865
|
+
* Lock auto-release TTL in seconds (default: 30 s).
|
|
866
|
+
* Prevents deadlocks if the holding node crashes or is terminated.
|
|
867
|
+
*/
|
|
868
|
+
ttl?: number;
|
|
869
|
+
/**
|
|
870
|
+
* Maximum time to wait to acquire the lock in milliseconds before throwing a timeout error.
|
|
871
|
+
* Default: `5000` ms.
|
|
872
|
+
*/
|
|
873
|
+
acquireTimeout?: number;
|
|
874
|
+
/**
|
|
875
|
+
* Polling retry interval in milliseconds when waiting for lock acquisition.
|
|
876
|
+
* Default: `100` ms.
|
|
877
|
+
*/
|
|
878
|
+
retryInterval?: number;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* Structural typing matching OpenTelemetry Metric interfaces (`@opentelemetry/api`).
|
|
883
|
+
*/
|
|
884
|
+
export interface ICacheCounter {
|
|
885
|
+
add(value: number, attributes?: Record<string, string | number | boolean>): void;
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
export interface ICacheObservableGauge {
|
|
889
|
+
readonly _isGauge?: true;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
export interface ICacheBatchObservableCallback {
|
|
893
|
+
(observableResult: {
|
|
894
|
+
observe: (metric: ICacheObservableGauge, value: number, attributes?: Record<string, string | number | boolean>) => void;
|
|
895
|
+
}): void | Promise<void>;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
export interface ICacheMeter {
|
|
899
|
+
createCounter(name: string, options?: { description?: string; unit?: string }): ICacheCounter;
|
|
900
|
+
createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
|
|
901
|
+
addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
732
902
|
}
|
|
@@ -43,6 +43,7 @@ const BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64,
|
|
|
43
43
|
export class WasmBloomFilter {
|
|
44
44
|
private readonly exports: BloomWasmExports;
|
|
45
45
|
private readonly mem: Uint8Array;
|
|
46
|
+
private readonly stagingTarget: Uint8Array;
|
|
46
47
|
private readonly encoder = new TextEncoder();
|
|
47
48
|
private readonly numBits = 100_000;
|
|
48
49
|
/** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
|
|
@@ -54,14 +55,14 @@ export class WasmBloomFilter {
|
|
|
54
55
|
const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
|
|
55
56
|
this.exports = instance.exports as unknown as BloomWasmExports;
|
|
56
57
|
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
58
|
+
this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
|
|
57
59
|
const k = 7, p = 0.01;
|
|
58
60
|
this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
|
|
59
61
|
}
|
|
60
62
|
|
|
61
63
|
private writeKey(key: string): number {
|
|
62
64
|
if (key.length === 0) return 0;
|
|
63
|
-
|
|
64
|
-
return this.encoder.encodeInto(key, target).written;
|
|
65
|
+
return this.encoder.encodeInto(key, this.stagingTarget).written;
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
add(key: string): void {
|