tricache 0.9.0 → 1.0.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.
Files changed (47) hide show
  1. package/README.md +7 -3
  2. package/dist/{cache-service-KI5ACF3F.js → cache-service-26GCO3UU.js} +3 -3
  3. package/dist/{cache-service-DVvroyqA.d.ts → cache-service-pJ-nFcVj.d.ts} +29 -12
  4. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  5. package/dist/{chunk-PL5J3ZNT.js → chunk-7SZSQS55.js} +201 -34
  6. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  7. package/dist/cli.cjs +376 -50
  8. package/dist/cli.js +4 -4
  9. package/dist/dashboard/index.d.ts +2 -2
  10. package/dist/drizzle/index.cjs +384 -51
  11. package/dist/drizzle/index.d.ts +2 -2
  12. package/dist/drizzle/index.js +1 -1
  13. package/dist/edge/index.cjs +64 -8
  14. package/dist/edge/index.d.ts +3 -3
  15. package/dist/edge/index.js +37 -9
  16. package/dist/hono/index.cjs +384 -51
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +1 -1
  19. package/dist/{hono-VA9A1m0I.d.ts → hono-DuNvciyq.d.ts} +4 -4
  20. package/dist/http/index.cjs +384 -51
  21. package/dist/http/index.d.ts +3 -3
  22. package/dist/http/index.js +8 -8
  23. package/dist/index.cjs +385 -49
  24. package/dist/index.d.ts +35 -6
  25. package/dist/index.js +16 -6
  26. package/dist/nestjs/index.cjs +375 -49
  27. package/dist/nestjs/index.d.ts +2 -2
  28. package/dist/nestjs/index.js +4 -4
  29. package/dist/next/index.cjs +375 -49
  30. package/dist/next/index.d.ts +2 -2
  31. package/dist/next/index.js +3 -3
  32. package/dist/prisma/index.d.ts +2 -2
  33. package/dist/serialize-worker.cjs +127 -9
  34. package/dist/serialize-worker.js +8 -4
  35. package/dist/{types-B_QkVwJ7.d.ts → types-5HXqBfAf.d.ts} +51 -7
  36. package/package.json +7 -4
  37. package/src/cache-service.ts +238 -33
  38. package/src/cli.ts +1 -1
  39. package/src/compression.ts +193 -15
  40. package/src/cross-region.ts +1 -1
  41. package/src/edge/cache.ts +38 -11
  42. package/src/env.d.ts +13 -0
  43. package/src/index.ts +9 -1
  44. package/src/serialize-worker.ts +6 -2
  45. package/src/types.ts +43 -5
  46. package/src/utils/tag-matcher.ts +90 -0
  47. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
@@ -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(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
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 function decompressBuffer(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
30
- // Try the configured algorithm first, then the other one as recovery (covers
31
- // entries written under a different compression setting). If BOTH fail, the
32
- // payload is corrupt: THROW instead of returning the raw bytes. Returning raw
33
- // surfaced corruption as garbage JSON.parse errors deep downstream; every
34
- // call site maps a thrown error to a clean cache miss instead.
35
- const tryBrotli = (): Buffer | null => { try { return zlib.brotliDecompressSync(buf); } catch { return null; } };
36
- const tryGzip = (): Buffer | null => { try { return zlib.gunzipSync(buf); } catch { return null; } };
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(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
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(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
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
  }
@@ -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;
@@ -398,19 +399,20 @@ export class EdgeCacheService {
398
399
  key: string,
399
400
  value: T,
400
401
  ttlSeconds?: number,
401
- options?: { tags?: string[]; swr?: number },
402
+ options?: { tags?: string[]; swr?: number } | string[],
402
403
  ): Promise<void> {
403
404
  const span = this._startSpan('tricache.set');
404
405
  span.setAttribute('cache.key', key);
405
406
  const nsKey = this.nk(key);
406
407
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
407
408
  const now = Date.now();
408
- const swrSeconds = options?.swr ?? 0;
409
+ const optObj = Array.isArray(options) ? { tags: options } : options;
410
+ const swrSeconds = optObj?.swr ?? 0;
409
411
 
410
412
  try {
411
413
  let activeTagVersions: Record<string, number> | undefined;
412
- if (options?.tags?.length) {
413
- activeTagVersions = await this._batchGetTagVersions(options.tags);
414
+ if (optObj?.tags?.length) {
415
+ activeTagVersions = await this._batchGetTagVersions(optObj.tags);
414
416
  }
415
417
 
416
418
  const serialized = JSON.stringify(value);
@@ -426,7 +428,7 @@ export class EdgeCacheService {
426
428
  bytes,
427
429
  expiresAt: now + resolvedTtl * 1000,
428
430
  staleUntil: now + (resolvedTtl + swrSeconds) * 1000,
429
- tags: options?.tags,
431
+ tags: optObj?.tags,
430
432
  tagVersions: activeTagVersions,
431
433
  };
432
434
 
@@ -434,8 +436,8 @@ export class EdgeCacheService {
434
436
  this.currentBytes += bytes;
435
437
 
436
438
  // Index tags
437
- if (options?.tags) {
438
- for (const tag of options.tags) {
439
+ if (optObj?.tags) {
440
+ for (const tag of optObj.tags) {
439
441
  let s = this.tagIndex.get(tag);
440
442
  if (!s) {
441
443
  s = new Set<string>();
@@ -492,11 +494,35 @@ export class EdgeCacheService {
492
494
  /**
493
495
  * Invalidates all cached entries associated with a tag.
494
496
  */
495
- async invalidateTag(tag: string): Promise<void> {
497
+ async invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void> {
496
498
  const span = this._startSpan('tricache.invalidate_tag');
497
499
  span.setAttribute('cache.tag', tag);
500
+ if (opts?.cascade) span.setAttribute('cache.cascade', true);
498
501
 
499
502
  try {
503
+ const isPattern = isWildcardTag(tag);
504
+ const shouldCascade = Boolean(opts?.cascade);
505
+ if (isPattern || shouldCascade) {
506
+ const matched = new Set<string>();
507
+ const tagMatches = (t: string) => {
508
+ if (t === tag) return true;
509
+ if (isPattern && matchesTagPattern(tag, t)) return true;
510
+ if (shouldCascade && isChildTag(tag, t, ':')) return true;
511
+ return false;
512
+ };
513
+ for (const t of this.tagIndex.keys()) {
514
+ if (tagMatches(t)) matched.add(t);
515
+ }
516
+ for (const t of this.tagVersionCache.keys()) {
517
+ if (tagMatches(t)) matched.add(t);
518
+ }
519
+ if (shouldCascade && !isPattern) matched.add(tag);
520
+ for (const t of matched) {
521
+ await this.invalidateTag(t);
522
+ }
523
+ return;
524
+ }
525
+
500
526
  let newVer = 1;
501
527
  if (this.remoteStorage) {
502
528
  try {
@@ -568,7 +594,7 @@ export class EdgeCacheService {
568
594
  */
569
595
  async mget<T>(
570
596
  keys: string[],
571
- fetchFn?: (missKeys: string[]) => Promise<Record<string, T>>,
597
+ fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>,
572
598
  ttlSeconds?: number,
573
599
  ): Promise<(T | null)[]> {
574
600
  const span = this._startSpan('tricache.mget');
@@ -594,9 +620,10 @@ export class EdgeCacheService {
594
620
 
595
621
  if (missKeys.length > 0 && fetchFn) {
596
622
  const fetchedMap = await fetchFn(missKeys);
623
+ const isMap = fetchedMap instanceof Map;
597
624
  for (let j = 0; j < missKeys.length; j++) {
598
625
  const k = missKeys[j];
599
- const fetchedVal = fetchedMap[k];
626
+ const fetchedVal = isMap ? (fetchedMap as Map<string, T>).get(k) : (fetchedMap as Record<string, T>)[k];
600
627
  if (fetchedVal !== undefined) {
601
628
  results[missIndices[j]] = fetchedVal;
602
629
  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/index.ts CHANGED
@@ -36,7 +36,7 @@ export {
36
36
  export { DiskTier, resolveDefaultDiskDir } from './disk-tier';
37
37
  export { TierLatencyWatchdog, type LatencyWatchdogOptions, type LatencyWatchdogTelemetry } from './latency-watchdog';
38
38
  export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
39
- export { type CompressionAlgorithm } from './compression';
39
+ export { type CompressionAlgorithm, type CustomCompressor, initZstd } from './compression';
40
40
  export { CacheCodec, defaultCodec, type CacheCodecOptions } from './codec';
41
41
  export {
42
42
  createHttpSnapshotAdapter,
@@ -114,6 +114,7 @@ export {
114
114
  type ICacheBatchObservableCallback,
115
115
  type ICacheMeter,
116
116
  type CacheHealthStatus,
117
+ type InvalidateTagOptions,
117
118
  } from './types';
118
119
 
119
120
  export {
@@ -122,6 +123,13 @@ export {
122
123
  type ParsedTraceParent,
123
124
  } from './utils/tracing';
124
125
 
126
+ export {
127
+ isWildcardTag,
128
+ matchesTagPattern,
129
+ isChildTag,
130
+ expandHierarchicalTags,
131
+ } from './utils/tag-matcher';
132
+
125
133
  export {
126
134
  tricacheDashboard,
127
135
  createNextDashboardHandlers,
@@ -20,6 +20,7 @@ import type { ILogger } from './types.ts';
20
20
  import {
21
21
  compressBuffer,
22
22
  decompressBuffer,
23
+ initZstd,
23
24
  PREFIX_COMPRESSED,
24
25
  PREFIX_ENC_COMPRESSED,
25
26
  type CompressionAlgorithm,
@@ -53,13 +54,16 @@ const enc = new CacheEncryption(
53
54
  prevMode,
54
55
  );
55
56
 
56
- const cmpAlgo = compression ?? 'none';
57
+ const cmpAlgo = compression ?? 'zstd';
57
58
  const cmpThreshold = compressionThresholdBytes ?? 1024;
58
59
 
59
60
  parentPort!.on(
60
61
  'message',
61
- ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
62
+ async ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
62
63
  try {
64
+ if (cmpAlgo === 'zstd') {
65
+ await initZstd();
66
+ }
63
67
  const textPayload =
64
68
  typeof payload === 'string'
65
69
  ? payload
package/src/types.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { RemoteSnapshotOptions } from './remote-snapshot';
2
2
  import type { CrossRegionRelayOptions } from './cross-region';
3
+ import type { CompressionAlgorithm, CustomCompressor } from './compression';
3
4
 
4
5
  /**
5
6
  * tricache — shared types and interfaces
@@ -568,13 +569,22 @@ export interface CacheOptions {
568
569
 
569
570
  // ── Compression ──────────────────────────────────────────────────────────
570
571
  /**
571
- * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
572
- * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
573
- * - `'gzip'` — faster compression / lower CPU overhead.
572
+ * Compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
573
+ * - `'zstd'` (default) — Facebook Zstandard (via WebAssembly) for ultra-high throughput and ~96% ratio.
574
+ * - `'lz4'` — Ultra-fast compression/decompression for high-throughput, latency-critical workloads.
575
+ * - `'brotli'` — High compression ratio for JSON / text payloads.
576
+ * - `'gzip'` — Standard Deflate/Gzip compression.
574
577
  * - `'none'` — disable compression.
575
- * Default: `'none'` (uncompressed).
578
+ * Default: `'zstd'`.
576
579
  */
577
- compression?: 'brotli' | 'gzip' | 'none';
580
+ compression?: CompressionAlgorithm;
581
+
582
+ /**
583
+ * Custom compression engine plugin. When provided, overrides the built-in algorithms
584
+ * and delegates compression/decompression to this provider.
585
+ */
586
+ customCompressor?: CustomCompressor;
587
+
578
588
  /**
579
589
  * Minimum payload size in bytes before compression is applied.
580
590
  * Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
@@ -1033,6 +1043,22 @@ export interface CacheOptions {
1033
1043
  */
1034
1044
  tagVersionTtlMs?: number;
1035
1045
 
1046
+ /**
1047
+ * Automatically expand hierarchical tags into their ancestor namespaces.
1048
+ * For example, tagging an entry with `'org:123:dept:456'` will also associate
1049
+ * it with `'org:123'` and `'org'`, allowing `invalidateTag('org:123')` or
1050
+ * `invalidateTag('org')` to automatically cascade down to this entry.
1051
+ *
1052
+ * Default: `false`.
1053
+ */
1054
+ hierarchicalTags?: boolean;
1055
+
1056
+ /**
1057
+ * The delimiter used for splitting hierarchical tags when `hierarchicalTags` is enabled.
1058
+ * Default: `':'`.
1059
+ */
1060
+ tagHierarchyDelimiter?: string;
1061
+
1036
1062
  /**
1037
1063
  * Read safety strategy for returned cached objects:
1038
1064
  * - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
@@ -1075,6 +1101,18 @@ export interface CacheOptions {
1075
1101
  meter?: ICacheMeter;
1076
1102
  }
1077
1103
 
1104
+ /**
1105
+ * Options for tag invalidation operations (`cache.invalidateTag()` and `cache.invalidateTags()`).
1106
+ */
1107
+ export interface InvalidateTagOptions {
1108
+ /**
1109
+ * When true, invalidates both the specified tag and any descendant child tags
1110
+ * in the hierarchy (e.g. invalidating 'org:123' also invalidates 'org:123:*').
1111
+ * Default: `false`.
1112
+ */
1113
+ cascade?: boolean;
1114
+ }
1115
+
1078
1116
  /**
1079
1117
  * Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
1080
1118
  */
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Utilities for wildcard matching and hierarchical cascading of cache tags.
3
+ */
4
+
5
+ const globRegexCache = new Map<string, RegExp>();
6
+
7
+ /**
8
+ * Returns true if the given tag contains glob wildcard characters ('*' or '?').
9
+ */
10
+ export function isWildcardTag(tag: string): boolean {
11
+ return tag.includes('*') || tag.includes('?');
12
+ }
13
+
14
+ /**
15
+ * Matches a tag name against a pattern supporting '*' (0 or more chars) and '?' (single char).
16
+ * Optimized with fast-paths for exact match, universal wildcard, and single prefix/suffix wildcards.
17
+ */
18
+ export function matchesTagPattern(pattern: string, tag: string): boolean {
19
+ if (pattern === '*' || pattern === tag) return true;
20
+ if (!pattern.includes('*') && !pattern.includes('?')) return pattern === tag;
21
+
22
+ // Fast path: trailing single '*' (e.g. "org:123:*")
23
+ if (pattern.endsWith('*') && !pattern.slice(0, -1).includes('*') && !pattern.includes('?')) {
24
+ const prefix = pattern.slice(0, -1);
25
+ return tag.startsWith(prefix);
26
+ }
27
+
28
+ // Fast path: leading single '*' (e.g. "*:settings")
29
+ if (pattern.startsWith('*') && !pattern.slice(1).includes('*') && !pattern.includes('?')) {
30
+ const suffix = pattern.slice(1);
31
+ return tag.endsWith(suffix);
32
+ }
33
+
34
+ // General glob with bounded RegExp cache
35
+ let re = globRegexCache.get(pattern);
36
+ if (!re) {
37
+ if (globRegexCache.size >= 1000) globRegexCache.clear();
38
+ const escaped = pattern
39
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
40
+ .replace(/\*/g, '.*')
41
+ .replace(/\?/g, '.');
42
+ re = new RegExp(`^${escaped}$`);
43
+ globRegexCache.set(pattern, re);
44
+ }
45
+ return re.test(tag);
46
+ }
47
+
48
+ /**
49
+ * Determines whether `candidateTag` is either identical to `parentTag`
50
+ * or a child descendant in the hierarchy separated by `delimiter`.
51
+ *
52
+ * Example:
53
+ * isChildTag('org:123', 'org:123', ':') -> true
54
+ * isChildTag('org:123', 'org:123:dept', ':') -> true
55
+ * isChildTag('org:123', 'org:1234', ':') -> false (must match delimiter boundary)
56
+ */
57
+ export function isChildTag(parentTag: string, candidateTag: string, delimiter = ':'): boolean {
58
+ if (candidateTag === parentTag) return true;
59
+ const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
60
+ return candidateTag.startsWith(prefix);
61
+ }
62
+
63
+ /**
64
+ * Expands hierarchical tags into all ancestor namespace levels.
65
+ *
66
+ * Example:
67
+ * expandHierarchicalTags(['org:123:dept:456', 'role:admin'], ':')
68
+ * => ['org', 'org:123', 'org:123:dept', 'org:123:dept:456', 'role', 'role:admin']
69
+ */
70
+ export function expandHierarchicalTags(tags: string[], delimiter = ':'): string[] {
71
+ if (!tags.length) return [];
72
+ const result = new Set<string>();
73
+
74
+ for (const tag of tags) {
75
+ if (!tag) continue;
76
+ const parts = tag.split(delimiter).filter(p => p.length > 0);
77
+ if (parts.length <= 1) {
78
+ result.add(tag);
79
+ continue;
80
+ }
81
+
82
+ let accumulated = '';
83
+ for (let i = 0; i < parts.length; i++) {
84
+ accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
85
+ result.add(accumulated);
86
+ }
87
+ }
88
+
89
+ return Array.from(result);
90
+ }
File without changes