tricache 0.9.0 → 1.0.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/README.md +7 -3
- package/dist/{cache-service-DVvroyqA.d.ts → cache-service-CREOp7MM.d.ts} +57 -12
- package/dist/{cache-service-KI5ACF3F.js → cache-service-MG7PN6MX.js} +3 -3
- package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
- package/dist/{chunk-QNU7B43J.js → chunk-3I5L7K6I.js} +17 -0
- package/dist/{chunk-PL5J3ZNT.js → chunk-JYQFQJNJ.js} +682 -277
- package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
- package/dist/cli.cjs +857 -293
- package/dist/cli.js +4 -4
- package/dist/dashboard/index.d.ts +2 -2
- package/dist/drizzle/index.cjs +865 -294
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +115 -36
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +88 -37
- package/dist/hono/index.cjs +865 -294
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +1 -1
- package/dist/{hono-VA9A1m0I.d.ts → hono-DSV2ve66.d.ts} +11 -4
- package/dist/http/index.cjs +917 -315
- package/dist/http/index.d.ts +3 -3
- package/dist/http/index.js +60 -29
- package/dist/index.cjs +885 -294
- package/dist/index.d.ts +37 -7
- package/dist/index.js +16 -6
- package/dist/nestjs/index.cjs +856 -292
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +4 -4
- package/dist/next/index.cjs +858 -300
- package/dist/next/index.d.ts +2 -2
- package/dist/next/index.js +5 -11
- package/dist/prisma/index.d.ts +2 -2
- package/dist/serialize-worker.cjs +127 -9
- package/dist/serialize-worker.js +8 -4
- package/dist/{types-B_QkVwJ7.d.ts → types-Dyip5wAl.d.ts} +53 -7
- package/package.json +7 -4
- package/src/adapters/node-redis.ts +19 -0
- package/src/cache-service.ts +781 -297
- package/src/cli.ts +1 -1
- package/src/compression.ts +193 -15
- package/src/cross-region.ts +1 -1
- package/src/edge/cache.ts +94 -42
- package/src/env.d.ts +13 -0
- package/src/http/express.ts +55 -16
- package/src/http/fastify.ts +3 -7
- package/src/index.ts +9 -1
- package/src/next/cache-handler.ts +1 -4
- package/src/next/isr-handler.ts +1 -4
- package/src/serialize-worker.ts +6 -2
- package/src/smart-memory-cache.ts +3 -2
- package/src/types.ts +45 -5
- package/src/utils/tag-matcher.ts +90 -0
package/src/cli.ts
CHANGED
|
@@ -60,7 +60,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
|
|
|
60
60
|
// (bin/tricache.js). Output must go directly to process stdout without logger prefixes
|
|
61
61
|
// to support UNIX pipes, terminal formatting, and automated tooling.
|
|
62
62
|
if (values.version || command === 'version') {
|
|
63
|
-
let version = '0.
|
|
63
|
+
let version = '1.0.1';
|
|
64
64
|
try {
|
|
65
65
|
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
66
66
|
if (pkg?.version) version = pkg.version;
|
package/src/compression.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import zlib from 'zlib';
|
|
2
|
+
import lz4js from 'lz4js';
|
|
3
|
+
import { ZstdCodec } from 'zstd-codec';
|
|
2
4
|
|
|
3
|
-
export type CompressionAlgorithm = 'brotli' | 'gzip' | 'none';
|
|
5
|
+
export type CompressionAlgorithm = 'brotli' | 'gzip' | 'zstd' | 'lz4' | 'none';
|
|
6
|
+
|
|
7
|
+
export interface CustomCompressor {
|
|
8
|
+
name: string;
|
|
9
|
+
compress: (buf: Buffer) => Buffer;
|
|
10
|
+
decompress: (buf: Buffer) => Buffer;
|
|
11
|
+
}
|
|
4
12
|
|
|
5
13
|
export const PREFIX_COMPRESSED = 'cmp:v1:';
|
|
6
14
|
export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
|
|
@@ -8,11 +16,45 @@ export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
|
|
|
8
16
|
/** "TRC\x01" 4-byte marker prefix identifying compressed data */
|
|
9
17
|
const COMPRESSION_MAGIC = Buffer.from([0x54, 0x52, 0x43, 0x01]);
|
|
10
18
|
|
|
19
|
+
let zstdSimple: any = null;
|
|
20
|
+
let zstdInitPromise: Promise<any> | null = null;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Initializes the WebAssembly Zstandard codec.
|
|
24
|
+
* Resolves immediately if already initialized.
|
|
25
|
+
*/
|
|
26
|
+
export function initZstd(): Promise<any> {
|
|
27
|
+
if (zstdSimple) return Promise.resolve(zstdSimple);
|
|
28
|
+
if (!zstdInitPromise) {
|
|
29
|
+
zstdInitPromise = new Promise((resolve) => {
|
|
30
|
+
try {
|
|
31
|
+
ZstdCodec.run((zstd: any) => {
|
|
32
|
+
zstdSimple = new zstd.Simple();
|
|
33
|
+
resolve(zstdSimple);
|
|
34
|
+
});
|
|
35
|
+
} catch {
|
|
36
|
+
resolve(null);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return zstdInitPromise;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Auto-start initialization immediately in the background
|
|
44
|
+
initZstd().catch(() => {});
|
|
45
|
+
|
|
11
46
|
export function isCompressed(buf: Buffer): boolean {
|
|
12
47
|
return buf.length >= 4 && buf[0] === 0x54 && buf[1] === 0x52 && buf[2] === 0x43 && buf[3] === 0x01;
|
|
13
48
|
}
|
|
14
49
|
|
|
15
|
-
export function compressBuffer(
|
|
50
|
+
export function compressBuffer(
|
|
51
|
+
buf: Buffer,
|
|
52
|
+
algorithm: CompressionAlgorithm,
|
|
53
|
+
custom?: CustomCompressor,
|
|
54
|
+
): Buffer {
|
|
55
|
+
if (custom) {
|
|
56
|
+
return custom.compress(buf);
|
|
57
|
+
}
|
|
16
58
|
if (algorithm === 'brotli') {
|
|
17
59
|
return zlib.brotliCompressSync(buf, {
|
|
18
60
|
params: {
|
|
@@ -23,34 +65,170 @@ export function compressBuffer(buf: Buffer, algorithm: CompressionAlgorithm): Bu
|
|
|
23
65
|
if (algorithm === 'gzip') {
|
|
24
66
|
return zlib.gzipSync(buf, { level: 6 });
|
|
25
67
|
}
|
|
68
|
+
if (algorithm === 'lz4') {
|
|
69
|
+
return Buffer.from(lz4js.compress(buf));
|
|
70
|
+
}
|
|
71
|
+
if (algorithm === 'zstd') {
|
|
72
|
+
if (!zstdSimple) {
|
|
73
|
+
// If zstd WASM compile has not yet finished, fallback to fast Brotli level 4
|
|
74
|
+
return zlib.brotliCompressSync(buf, {
|
|
75
|
+
params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 },
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return Buffer.from(zstdSimple.compress(buf));
|
|
79
|
+
}
|
|
26
80
|
return buf;
|
|
27
81
|
}
|
|
28
82
|
|
|
29
|
-
export
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
83
|
+
export const MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024; // 25 MB decompression bomb safety ceiling
|
|
84
|
+
|
|
85
|
+
export function decompressBuffer(
|
|
86
|
+
buf: Buffer,
|
|
87
|
+
algorithm: CompressionAlgorithm = 'zstd',
|
|
88
|
+
custom?: CustomCompressor,
|
|
89
|
+
): Buffer {
|
|
90
|
+
if (custom) {
|
|
91
|
+
const res = custom.decompress(buf);
|
|
92
|
+
if (res.length > MAX_DECOMPRESS_BYTES) {
|
|
93
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
94
|
+
}
|
|
95
|
+
return res;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const checkSafety = (decomp: Buffer): Buffer => {
|
|
99
|
+
if (decomp.length > MAX_DECOMPRESS_BYTES) {
|
|
100
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
101
|
+
}
|
|
102
|
+
return decomp;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// 1. Zstandard magic header: 0x28 0xB5 0x2F 0xFD
|
|
106
|
+
if (buf.length >= 4 && buf[0] === 0x28 && buf[1] === 0xb5 && buf[2] === 0x2f && buf[3] === 0xfd) {
|
|
107
|
+
if (zstdSimple) {
|
|
108
|
+
try {
|
|
109
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
110
|
+
} catch (err: any) {
|
|
111
|
+
if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
|
|
112
|
+
/* try recovery */
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// 2. LZ4 frame magic header: 0x04 0x22 0x4D 0x18
|
|
118
|
+
if (buf.length >= 4 && buf[0] === 0x04 && buf[1] === 0x22 && buf[2] === 0x4d && buf[3] === 0x18) {
|
|
119
|
+
try {
|
|
120
|
+
return checkSafety(Buffer.from(lz4js.decompress(buf)));
|
|
121
|
+
} catch (err: any) {
|
|
122
|
+
if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
|
|
123
|
+
/* try recovery */
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 3. Gzip magic header: 0x1F 0x8B
|
|
128
|
+
if (buf.length >= 2 && buf[0] === 0x1f && buf[1] === 0x8b) {
|
|
129
|
+
try {
|
|
130
|
+
return zlib.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
131
|
+
} catch (err: any) {
|
|
132
|
+
if (err?.code === 'ERR_BUFFER_TOO_LARGE') {
|
|
133
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
134
|
+
}
|
|
135
|
+
/* try recovery */
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (algorithm === 'none') {
|
|
140
|
+
return buf;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// 4. Algorithm-specific attempts
|
|
144
|
+
if (algorithm === 'lz4') {
|
|
145
|
+
try {
|
|
146
|
+
return checkSafety(Buffer.from(lz4js.decompress(buf)));
|
|
147
|
+
} catch (err: any) {
|
|
148
|
+
if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
|
|
149
|
+
/* fallback */
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (algorithm === 'zstd' && zstdSimple) {
|
|
154
|
+
try {
|
|
155
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
156
|
+
} catch (err: any) {
|
|
157
|
+
if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
|
|
158
|
+
/* fallback */
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 5. Universal fallback & recovery
|
|
163
|
+
const tryBrotli = (): Buffer | null => {
|
|
164
|
+
try {
|
|
165
|
+
return zlib.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
166
|
+
} catch (err: any) {
|
|
167
|
+
if (err?.code === 'ERR_BUFFER_TOO_LARGE') {
|
|
168
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
const tryGzip = (): Buffer | null => {
|
|
174
|
+
try {
|
|
175
|
+
return zlib.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
176
|
+
} catch (err: any) {
|
|
177
|
+
if (err?.code === 'ERR_BUFFER_TOO_LARGE') {
|
|
178
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
179
|
+
}
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const tryLz4 = (): Buffer | null => {
|
|
184
|
+
try {
|
|
185
|
+
return checkSafety(Buffer.from(lz4js.decompress(buf)));
|
|
186
|
+
} catch (err: any) {
|
|
187
|
+
if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
const tryZstd = (): Buffer | null => {
|
|
192
|
+
if (!zstdSimple) return null;
|
|
193
|
+
try {
|
|
194
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
195
|
+
} catch (err: any) {
|
|
196
|
+
if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const result = (algorithm === 'gzip' ? tryGzip() : null) ??
|
|
202
|
+
(algorithm === 'lz4' ? tryLz4() : null) ??
|
|
203
|
+
(algorithm === 'zstd' ? tryZstd() : null) ??
|
|
204
|
+
tryBrotli() ??
|
|
205
|
+
tryGzip() ??
|
|
206
|
+
tryLz4() ??
|
|
207
|
+
tryZstd();
|
|
37
208
|
|
|
38
|
-
const result = algorithm === 'gzip' ? (tryGzip() ?? tryBrotli()) : (tryBrotli() ?? tryGzip());
|
|
39
209
|
if (result === null) {
|
|
40
210
|
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
41
211
|
}
|
|
42
212
|
return result;
|
|
43
213
|
}
|
|
44
214
|
|
|
45
|
-
export function compressWithHeader(
|
|
215
|
+
export function compressWithHeader(
|
|
216
|
+
buf: Buffer,
|
|
217
|
+
algorithm: CompressionAlgorithm,
|
|
218
|
+
custom?: CustomCompressor,
|
|
219
|
+
): Buffer {
|
|
46
220
|
if (algorithm === 'none') return buf;
|
|
47
|
-
const compressed = compressBuffer(buf, algorithm);
|
|
221
|
+
const compressed = compressBuffer(buf, algorithm, custom);
|
|
48
222
|
return Buffer.concat([COMPRESSION_MAGIC, compressed]);
|
|
49
223
|
}
|
|
50
224
|
|
|
51
|
-
export function decompressWithHeader(
|
|
225
|
+
export function decompressWithHeader(
|
|
226
|
+
buf: Buffer,
|
|
227
|
+
algorithm: CompressionAlgorithm = 'zstd',
|
|
228
|
+
custom?: CustomCompressor,
|
|
229
|
+
): Buffer {
|
|
52
230
|
if (isCompressed(buf)) {
|
|
53
|
-
return decompressBuffer(buf.subarray(4), algorithm);
|
|
231
|
+
return decompressBuffer(buf.subarray(4), algorithm, custom);
|
|
54
232
|
}
|
|
55
233
|
return buf;
|
|
56
234
|
}
|
package/src/cross-region.ts
CHANGED
|
@@ -14,7 +14,7 @@ export interface CrossRegionInvalidationEvent {
|
|
|
14
14
|
/** Instance ID that initiated the invalidation */
|
|
15
15
|
originInstanceId: string;
|
|
16
16
|
/** Invalidation operation */
|
|
17
|
-
op: 'del' | 'del-glob' | 'tag_incr';
|
|
17
|
+
op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del';
|
|
18
18
|
/** Cache key or tag name */
|
|
19
19
|
key: string;
|
|
20
20
|
/** New tag version for generational tag invalidation */
|
package/src/edge/cache.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ICacheSpan, ICacheTracer } from '../types';
|
|
1
|
+
import type { ICacheSpan, ICacheTracer, InvalidateTagOptions } from '../types';
|
|
2
2
|
import type {
|
|
3
3
|
EdgeCacheOptions,
|
|
4
4
|
EdgeGetOptions,
|
|
@@ -13,6 +13,7 @@ import type {
|
|
|
13
13
|
import { WebCryptoEncryption } from './crypto';
|
|
14
14
|
import { WasmBloomFilter } from '../wasm/bloom-filter-wasm';
|
|
15
15
|
import { Murmur3BloomFilter } from './utils/murmur3';
|
|
16
|
+
import { isWildcardTag, matchesTagPattern, isChildTag } from '../utils/tag-matcher';
|
|
16
17
|
|
|
17
18
|
interface EdgeL1Entry<T = unknown> {
|
|
18
19
|
value: T;
|
|
@@ -57,6 +58,7 @@ export class EdgeCacheService {
|
|
|
57
58
|
private readonly tagIndex = new Map<string, Set<string>>();
|
|
58
59
|
|
|
59
60
|
// Tag version in-isolate cache with 800ms micro-TTL (prevents HTTP fetch amplification on L1 hits)
|
|
61
|
+
private static readonly MAX_TAG_VERSION_CACHE = 10_000;
|
|
60
62
|
private readonly tagVersionCache = new Map<string, { version: number; expiresAt: number }>();
|
|
61
63
|
private readonly tagVersionTtlMs = 800;
|
|
62
64
|
|
|
@@ -146,6 +148,22 @@ export class EdgeCacheService {
|
|
|
146
148
|
};
|
|
147
149
|
}
|
|
148
150
|
|
|
151
|
+
private _setTagVersionCache(tag: string, version: number, expiresAt: number): void {
|
|
152
|
+
if (this.tagVersionCache.size >= EdgeCacheService.MAX_TAG_VERSION_CACHE && !this.tagVersionCache.has(tag)) {
|
|
153
|
+
const now = Date.now();
|
|
154
|
+
for (const [k, v] of this.tagVersionCache) {
|
|
155
|
+
if (v.expiresAt <= now) {
|
|
156
|
+
this.tagVersionCache.delete(k);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (this.tagVersionCache.size >= EdgeCacheService.MAX_TAG_VERSION_CACHE) {
|
|
160
|
+
const oldestKey = this.tagVersionCache.keys().next().value;
|
|
161
|
+
if (oldestKey !== undefined) this.tagVersionCache.delete(oldestKey);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
this.tagVersionCache.set(tag, { version, expiresAt });
|
|
165
|
+
}
|
|
166
|
+
|
|
149
167
|
private async _getTagVersion(tag: string): Promise<number> {
|
|
150
168
|
const cached = this.tagVersionCache.get(tag);
|
|
151
169
|
const now = Date.now();
|
|
@@ -167,7 +185,7 @@ export class EdgeCacheService {
|
|
|
167
185
|
} else {
|
|
168
186
|
version = cached?.version ?? 1;
|
|
169
187
|
}
|
|
170
|
-
this.
|
|
188
|
+
this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
|
|
171
189
|
return version;
|
|
172
190
|
}
|
|
173
191
|
|
|
@@ -194,7 +212,7 @@ export class EdgeCacheService {
|
|
|
194
212
|
const t = missingTags[i];
|
|
195
213
|
const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
|
|
196
214
|
result[t] = v;
|
|
197
|
-
this.
|
|
215
|
+
this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
|
|
198
216
|
}
|
|
199
217
|
} else {
|
|
200
218
|
await Promise.all(missingTags.map(async t => {
|
|
@@ -398,19 +416,20 @@ export class EdgeCacheService {
|
|
|
398
416
|
key: string,
|
|
399
417
|
value: T,
|
|
400
418
|
ttlSeconds?: number,
|
|
401
|
-
options?: { tags?: string[]; swr?: number },
|
|
419
|
+
options?: { tags?: string[]; swr?: number } | string[],
|
|
402
420
|
): Promise<void> {
|
|
403
421
|
const span = this._startSpan('tricache.set');
|
|
404
422
|
span.setAttribute('cache.key', key);
|
|
405
423
|
const nsKey = this.nk(key);
|
|
406
424
|
const resolvedTtl = ttlSeconds ?? this.defaultTtl;
|
|
407
425
|
const now = Date.now();
|
|
408
|
-
const
|
|
426
|
+
const optObj = Array.isArray(options) ? { tags: options } : options;
|
|
427
|
+
const swrSeconds = optObj?.swr ?? 0;
|
|
409
428
|
|
|
410
429
|
try {
|
|
411
430
|
let activeTagVersions: Record<string, number> | undefined;
|
|
412
|
-
if (
|
|
413
|
-
activeTagVersions = await this._batchGetTagVersions(
|
|
431
|
+
if (optObj?.tags?.length) {
|
|
432
|
+
activeTagVersions = await this._batchGetTagVersions(optObj.tags);
|
|
414
433
|
}
|
|
415
434
|
|
|
416
435
|
const serialized = JSON.stringify(value);
|
|
@@ -426,7 +445,7 @@ export class EdgeCacheService {
|
|
|
426
445
|
bytes,
|
|
427
446
|
expiresAt: now + resolvedTtl * 1000,
|
|
428
447
|
staleUntil: now + (resolvedTtl + swrSeconds) * 1000,
|
|
429
|
-
tags:
|
|
448
|
+
tags: optObj?.tags,
|
|
430
449
|
tagVersions: activeTagVersions,
|
|
431
450
|
};
|
|
432
451
|
|
|
@@ -434,8 +453,8 @@ export class EdgeCacheService {
|
|
|
434
453
|
this.currentBytes += bytes;
|
|
435
454
|
|
|
436
455
|
// Index tags
|
|
437
|
-
if (
|
|
438
|
-
for (const tag of
|
|
456
|
+
if (optObj?.tags) {
|
|
457
|
+
for (const tag of optObj.tags) {
|
|
439
458
|
let s = this.tagIndex.get(tag);
|
|
440
459
|
if (!s) {
|
|
441
460
|
s = new Set<string>();
|
|
@@ -490,45 +509,77 @@ export class EdgeCacheService {
|
|
|
490
509
|
}
|
|
491
510
|
|
|
492
511
|
/**
|
|
493
|
-
*
|
|
512
|
+
* Executes invalidation for a single already-resolved concrete tag without
|
|
513
|
+
* re-entering wildcard/cascade resolution.
|
|
494
514
|
*/
|
|
495
|
-
async
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
const key = this.nk(`tag_ver:${tag}`);
|
|
507
|
-
const current = await this._getTagVersion(tag);
|
|
508
|
-
newVer = Math.max(current + 1, Date.now());
|
|
509
|
-
await this.remoteStorage.set(key, String(newVer));
|
|
510
|
-
}
|
|
511
|
-
} catch {
|
|
512
|
-
const current = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
513
|
-
newVer = current + 1;
|
|
515
|
+
private async _invalidateConcreteTag(tag: string): Promise<void> {
|
|
516
|
+
let newVer = 1;
|
|
517
|
+
if (this.remoteStorage) {
|
|
518
|
+
try {
|
|
519
|
+
if (typeof this.remoteStorage.incrementTagVersion === 'function') {
|
|
520
|
+
newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
|
|
521
|
+
} else {
|
|
522
|
+
const key = this.nk(`tag_ver:${tag}`);
|
|
523
|
+
const current = await this._getTagVersion(tag);
|
|
524
|
+
newVer = Math.max(current + 1, Date.now());
|
|
525
|
+
await this.remoteStorage.set(key, String(newVer));
|
|
514
526
|
}
|
|
515
|
-
}
|
|
527
|
+
} catch {
|
|
516
528
|
const current = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
517
529
|
newVer = current + 1;
|
|
518
530
|
}
|
|
531
|
+
} else {
|
|
532
|
+
const current = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
533
|
+
newVer = current + 1;
|
|
534
|
+
}
|
|
519
535
|
|
|
520
|
-
|
|
521
|
-
|
|
536
|
+
// Update in-isolate version cache immediately (with 60s pin)
|
|
537
|
+
this._setTagVersionCache(tag, newVer, Date.now() + 60_000);
|
|
522
538
|
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
539
|
+
// Invalidate local L1 entries
|
|
540
|
+
const keys = this.tagIndex.get(tag);
|
|
541
|
+
if (keys) {
|
|
542
|
+
const keysArr = Array.from(keys);
|
|
543
|
+
for (const k of keysArr) {
|
|
544
|
+
this._deleteL1(k);
|
|
545
|
+
}
|
|
546
|
+
this.tagIndex.delete(tag);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Invalidates all cached entries associated with a tag.
|
|
552
|
+
*/
|
|
553
|
+
async invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void> {
|
|
554
|
+
const span = this._startSpan('tricache.invalidate_tag');
|
|
555
|
+
span.setAttribute('cache.tag', tag);
|
|
556
|
+
if (opts?.cascade) span.setAttribute('cache.cascade', true);
|
|
557
|
+
|
|
558
|
+
try {
|
|
559
|
+
const isPattern = isWildcardTag(tag);
|
|
560
|
+
const shouldCascade = Boolean(opts?.cascade);
|
|
561
|
+
if (isPattern || shouldCascade) {
|
|
562
|
+
const matched = new Set<string>();
|
|
563
|
+
const tagMatches = (t: string) => {
|
|
564
|
+
if (t === tag) return true;
|
|
565
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
566
|
+
if (shouldCascade && isChildTag(tag, t, ':')) return true;
|
|
567
|
+
return false;
|
|
568
|
+
};
|
|
569
|
+
for (const t of this.tagIndex.keys()) {
|
|
570
|
+
if (tagMatches(t)) matched.add(t);
|
|
571
|
+
}
|
|
572
|
+
for (const t of this.tagVersionCache.keys()) {
|
|
573
|
+
if (tagMatches(t)) matched.add(t);
|
|
529
574
|
}
|
|
530
|
-
|
|
575
|
+
if (shouldCascade && !isPattern) matched.add(tag);
|
|
576
|
+
for (const t of matched) {
|
|
577
|
+
await this._invalidateConcreteTag(t);
|
|
578
|
+
}
|
|
579
|
+
return;
|
|
531
580
|
}
|
|
581
|
+
|
|
582
|
+
await this._invalidateConcreteTag(tag);
|
|
532
583
|
} catch (err) {
|
|
533
584
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
534
585
|
span.recordException?.(err);
|
|
@@ -568,7 +619,7 @@ export class EdgeCacheService {
|
|
|
568
619
|
*/
|
|
569
620
|
async mget<T>(
|
|
570
621
|
keys: string[],
|
|
571
|
-
fetchFn?: (missKeys: string[]) => Promise<Record<string, T>>,
|
|
622
|
+
fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>,
|
|
572
623
|
ttlSeconds?: number,
|
|
573
624
|
): Promise<(T | null)[]> {
|
|
574
625
|
const span = this._startSpan('tricache.mget');
|
|
@@ -594,9 +645,10 @@ export class EdgeCacheService {
|
|
|
594
645
|
|
|
595
646
|
if (missKeys.length > 0 && fetchFn) {
|
|
596
647
|
const fetchedMap = await fetchFn(missKeys);
|
|
648
|
+
const isMap = fetchedMap instanceof Map;
|
|
597
649
|
for (let j = 0; j < missKeys.length; j++) {
|
|
598
650
|
const k = missKeys[j];
|
|
599
|
-
const fetchedVal = fetchedMap[k];
|
|
651
|
+
const fetchedVal = isMap ? (fetchedMap as Map<string, T>).get(k) : (fetchedMap as Record<string, T>)[k];
|
|
600
652
|
if (fetchedVal !== undefined) {
|
|
601
653
|
results[missIndices[j]] = fetchedVal;
|
|
602
654
|
await this.set(k, fetchedVal, ttlSeconds);
|
package/src/env.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
declare module 'lz4js' {
|
|
2
|
+
const lz4js: {
|
|
3
|
+
compress: (buf: Uint8Array | Buffer) => Uint8Array;
|
|
4
|
+
decompress: (buf: Uint8Array | Buffer) => Uint8Array;
|
|
5
|
+
};
|
|
6
|
+
export default lz4js;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
declare module 'zstd-codec' {
|
|
10
|
+
export const ZstdCodec: {
|
|
11
|
+
run: (callback: (zstd: any) => void) => void;
|
|
12
|
+
};
|
|
13
|
+
}
|
package/src/http/express.ts
CHANGED
|
@@ -84,14 +84,45 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
84
84
|
|
|
85
85
|
const resolvedTags = typeof tags === 'function' ? tags(req) : tags;
|
|
86
86
|
|
|
87
|
+
let respondedLocally = false;
|
|
88
|
+
|
|
87
89
|
try {
|
|
88
90
|
const cached = await activeCache.get<CachedHttpResponse>(
|
|
89
91
|
key,
|
|
90
92
|
async () => {
|
|
91
|
-
return new Promise<CachedHttpResponse>((resolve) => {
|
|
92
|
-
const
|
|
93
|
-
const
|
|
94
|
-
const
|
|
93
|
+
return new Promise<CachedHttpResponse>((resolve, reject) => {
|
|
94
|
+
const rawJson = res.json;
|
|
95
|
+
const rawSend = res.send;
|
|
96
|
+
const rawEnd = res.end;
|
|
97
|
+
const origJson = rawJson?.bind(res);
|
|
98
|
+
const origSend = rawSend?.bind(res);
|
|
99
|
+
const origEnd = rawEnd?.bind(res);
|
|
100
|
+
let settled = false;
|
|
101
|
+
|
|
102
|
+
const cleanup = () => {
|
|
103
|
+
if (rawJson !== undefined) res.json = rawJson;
|
|
104
|
+
if (rawSend !== undefined) res.send = rawSend;
|
|
105
|
+
if (rawEnd !== undefined) res.end = rawEnd;
|
|
106
|
+
res.removeListener?.('close', onClose);
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const settle = (response: CachedHttpResponse) => {
|
|
110
|
+
if (settled) return;
|
|
111
|
+
settled = true;
|
|
112
|
+
respondedLocally = true;
|
|
113
|
+
cleanup();
|
|
114
|
+
resolve(response);
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const onClose = () => {
|
|
118
|
+
if (settled) return;
|
|
119
|
+
settled = true;
|
|
120
|
+
respondedLocally = true;
|
|
121
|
+
cleanup();
|
|
122
|
+
reject(new Error('Express response closed before completion'));
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
res.once?.('close', onClose);
|
|
95
126
|
|
|
96
127
|
const getStatusCode = () => (res.statusCode ?? 200);
|
|
97
128
|
|
|
@@ -101,15 +132,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
101
132
|
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
102
133
|
const contentType = res.getHeader?.('content-type') || 'application/json; charset=utf-8';
|
|
103
134
|
|
|
104
|
-
|
|
135
|
+
settle({ body, contentType, etag: bodyEtag, status });
|
|
105
136
|
|
|
106
|
-
if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
137
|
+
if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
107
138
|
res.status?.(304);
|
|
108
139
|
origEnd?.();
|
|
109
140
|
return;
|
|
110
141
|
}
|
|
111
142
|
|
|
112
|
-
if (bodyEtag && res.setHeader) {
|
|
143
|
+
if (status >= 200 && status < 300 && bodyEtag && res.setHeader) {
|
|
113
144
|
res.setHeader('ETag', bodyEtag);
|
|
114
145
|
}
|
|
115
146
|
return origJson(body);
|
|
@@ -122,15 +153,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
122
153
|
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
123
154
|
const contentType = res.getHeader?.('content-type') as string | undefined;
|
|
124
155
|
|
|
125
|
-
|
|
156
|
+
settle({ body, contentType, etag: bodyEtag, status });
|
|
126
157
|
|
|
127
|
-
if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
158
|
+
if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
128
159
|
res.status?.(304);
|
|
129
160
|
origEnd?.();
|
|
130
161
|
return;
|
|
131
162
|
}
|
|
132
163
|
|
|
133
|
-
if (bodyEtag && res.setHeader) {
|
|
164
|
+
if (status >= 200 && status < 300 && bodyEtag && res.setHeader) {
|
|
134
165
|
res.setHeader('ETag', bodyEtag);
|
|
135
166
|
}
|
|
136
167
|
return origSend(body);
|
|
@@ -143,12 +174,20 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
143
174
|
const bodyEtag = etag && body != null ? generateETag(body) : undefined;
|
|
144
175
|
const contentType = res.getHeader?.('content-type') as string | undefined;
|
|
145
176
|
|
|
146
|
-
|
|
177
|
+
settle({ body, contentType, etag: bodyEtag, status });
|
|
147
178
|
return origEnd(body as never);
|
|
148
179
|
};
|
|
149
180
|
}
|
|
150
181
|
|
|
151
|
-
|
|
182
|
+
try {
|
|
183
|
+
next();
|
|
184
|
+
} catch (err) {
|
|
185
|
+
if (!settled) {
|
|
186
|
+
settled = true;
|
|
187
|
+
cleanup();
|
|
188
|
+
reject(err);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
152
191
|
});
|
|
153
192
|
},
|
|
154
193
|
ttl,
|
|
@@ -156,13 +195,13 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
156
195
|
);
|
|
157
196
|
|
|
158
197
|
// Status gate: only cache 2xx successful responses
|
|
159
|
-
|
|
198
|
+
const isNon2xx = typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300);
|
|
199
|
+
if (isNon2xx) {
|
|
160
200
|
await activeCache.delete(key).catch(() => {});
|
|
161
|
-
return;
|
|
162
201
|
}
|
|
163
202
|
|
|
164
|
-
if (!res.headersSent) {
|
|
165
|
-
if (cached.etag) {
|
|
203
|
+
if (!respondedLocally && !res.headersSent) {
|
|
204
|
+
if (!isNon2xx && cached.etag) {
|
|
166
205
|
if (res.setHeader) res.setHeader('ETag', cached.etag);
|
|
167
206
|
if (ifNoneMatch === cached.etag) {
|
|
168
207
|
return res.status(304).end();
|
package/src/http/fastify.ts
CHANGED
|
@@ -71,12 +71,8 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
|
|
|
71
71
|
? (req.headers['if-none-match'] || req.headers['If-None-Match'])
|
|
72
72
|
: undefined;
|
|
73
73
|
|
|
74
|
-
// Fast probe in cache
|
|
75
|
-
const cached = await activeCache!.
|
|
76
|
-
key,
|
|
77
|
-
async () => null,
|
|
78
|
-
0
|
|
79
|
-
);
|
|
74
|
+
// Fast probe in cache without writing null entries on misses
|
|
75
|
+
const cached = await activeCache!.peek<CachedFastifyResponse>(key);
|
|
80
76
|
|
|
81
77
|
if (cached && typeof cached === 'object' && cached.body !== null) {
|
|
82
78
|
if (cached.etag) {
|
|
@@ -140,7 +136,7 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
|
|
|
140
136
|
|
|
141
137
|
void activeCache!.set(key, entry, mergedOpts.ttl ?? ttl, undefined, {
|
|
142
138
|
tags: req._tricacheTags,
|
|
143
|
-
});
|
|
139
|
+
}).catch(() => {});
|
|
144
140
|
}
|
|
145
141
|
|
|
146
142
|
return payload;
|