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
@@ -436,10 +436,35 @@ var MAGIC_ENVELOPE = Buffer.from([84, 82, 73, 67, 69, 78, 86, 49]);
436
436
 
437
437
  // src/compression.ts
438
438
  var import_zlib = __toESM(require("zlib"), 1);
439
+ var import_lz4js = __toESM(require("lz4js"), 1);
440
+ var import_zstd_codec = require("zstd-codec");
439
441
  var PREFIX_COMPRESSED = "cmp:v1:";
440
442
  var PREFIX_ENC_COMPRESSED = "ecp:v1:";
441
443
  var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
442
- function compressBuffer(buf, algorithm) {
444
+ var zstdSimple = null;
445
+ var zstdInitPromise = null;
446
+ function initZstd() {
447
+ if (zstdSimple) return Promise.resolve(zstdSimple);
448
+ if (!zstdInitPromise) {
449
+ zstdInitPromise = new Promise((resolve) => {
450
+ try {
451
+ import_zstd_codec.ZstdCodec.run((zstd) => {
452
+ zstdSimple = new zstd.Simple();
453
+ resolve(zstdSimple);
454
+ });
455
+ } catch {
456
+ resolve(null);
457
+ }
458
+ });
459
+ }
460
+ return zstdInitPromise;
461
+ }
462
+ initZstd().catch(() => {
463
+ });
464
+ function compressBuffer(buf, algorithm, custom) {
465
+ if (custom) {
466
+ return custom.compress(buf);
467
+ }
443
468
  if (algorithm === "brotli") {
444
469
  return import_zlib.default.brotliCompressSync(buf, {
445
470
  params: {
@@ -451,24 +476,114 @@ function compressBuffer(buf, algorithm) {
451
476
  if (algorithm === "gzip") {
452
477
  return import_zlib.default.gzipSync(buf, { level: 6 });
453
478
  }
479
+ if (algorithm === "lz4") {
480
+ return Buffer.from(import_lz4js.default.compress(buf));
481
+ }
482
+ if (algorithm === "zstd") {
483
+ if (!zstdSimple) {
484
+ return import_zlib.default.brotliCompressSync(buf, {
485
+ params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
486
+ });
487
+ }
488
+ return Buffer.from(zstdSimple.compress(buf));
489
+ }
454
490
  return buf;
455
491
  }
456
- function decompressBuffer(buf, algorithm = "brotli") {
492
+ var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
493
+ function decompressBuffer(buf, algorithm = "zstd", custom) {
494
+ if (custom) {
495
+ const res = custom.decompress(buf);
496
+ if (res.length > MAX_DECOMPRESS_BYTES) {
497
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
498
+ }
499
+ return res;
500
+ }
501
+ const checkSafety = (decomp) => {
502
+ if (decomp.length > MAX_DECOMPRESS_BYTES) {
503
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
504
+ }
505
+ return decomp;
506
+ };
507
+ if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
508
+ if (zstdSimple) {
509
+ try {
510
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
511
+ } catch (err) {
512
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
513
+ }
514
+ }
515
+ }
516
+ if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
517
+ try {
518
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
519
+ } catch (err) {
520
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
521
+ }
522
+ }
523
+ if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
524
+ try {
525
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
526
+ } catch (err) {
527
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
528
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
529
+ }
530
+ }
531
+ }
532
+ if (algorithm === "none") {
533
+ return buf;
534
+ }
535
+ if (algorithm === "lz4") {
536
+ try {
537
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
538
+ } catch (err) {
539
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
540
+ }
541
+ }
542
+ if (algorithm === "zstd" && zstdSimple) {
543
+ try {
544
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
545
+ } catch (err) {
546
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
547
+ }
548
+ }
457
549
  const tryBrotli = () => {
458
550
  try {
459
- return import_zlib.default.brotliDecompressSync(buf);
460
- } catch {
551
+ return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
552
+ } catch (err) {
553
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
554
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
555
+ }
461
556
  return null;
462
557
  }
463
558
  };
464
559
  const tryGzip = () => {
465
560
  try {
466
- return import_zlib.default.gunzipSync(buf);
467
- } catch {
561
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
562
+ } catch (err) {
563
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
564
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
565
+ }
566
+ return null;
567
+ }
568
+ };
569
+ const tryLz4 = () => {
570
+ try {
571
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
572
+ } catch (err) {
573
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
468
574
  return null;
469
575
  }
470
576
  };
471
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
577
+ const tryZstd = () => {
578
+ if (!zstdSimple) return null;
579
+ try {
580
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
581
+ } catch (err) {
582
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
583
+ return null;
584
+ }
585
+ };
586
+ const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
472
587
  if (result === null) {
473
588
  throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
474
589
  }
@@ -494,12 +609,15 @@ var enc = new CacheEncryption(
494
609
  prevKeyBase64 || void 0,
495
610
  prevMode
496
611
  );
497
- var cmpAlgo = compression ?? "none";
612
+ var cmpAlgo = compression ?? "zstd";
498
613
  var cmpThreshold = compressionThresholdBytes ?? 1024;
499
614
  import_worker_threads.parentPort.on(
500
615
  "message",
501
- ({ id, type, payload }) => {
616
+ async ({ id, type, payload }) => {
502
617
  try {
618
+ if (cmpAlgo === "zstd") {
619
+ await initZstd();
620
+ }
503
621
  const textPayload = typeof payload === "string" ? payload : Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).toString("utf8");
504
622
  if (type === "encrypt") {
505
623
  let result;
@@ -3,8 +3,9 @@ import {
3
3
  PREFIX_COMPRESSED,
4
4
  PREFIX_ENC_COMPRESSED,
5
5
  compressBuffer,
6
- decompressBuffer
7
- } from "./chunk-LJ5QJB5O.js";
6
+ decompressBuffer,
7
+ initZstd
8
+ } from "./chunk-UBWLPKTI.js";
8
9
 
9
10
  // src/serialize-worker.ts
10
11
  import { parentPort, workerData } from "worker_threads";
@@ -26,12 +27,15 @@ var enc = new CacheEncryption(
26
27
  prevKeyBase64 || void 0,
27
28
  prevMode
28
29
  );
29
- var cmpAlgo = compression ?? "none";
30
+ var cmpAlgo = compression ?? "zstd";
30
31
  var cmpThreshold = compressionThresholdBytes ?? 1024;
31
32
  parentPort.on(
32
33
  "message",
33
- ({ id, type, payload }) => {
34
+ async ({ id, type, payload }) => {
34
35
  try {
36
+ if (cmpAlgo === "zstd") {
37
+ await initZstd();
38
+ }
35
39
  const textPayload = typeof payload === "string" ? payload : Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).toString("utf8");
36
40
  if (type === "encrypt") {
37
41
  let result;
@@ -230,7 +230,7 @@ interface CrossRegionInvalidationEvent {
230
230
  /** Instance ID that initiated the invalidation */
231
231
  originInstanceId: string;
232
232
  /** Invalidation operation */
233
- op: 'del' | 'del-glob' | 'tag_incr';
233
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del';
234
234
  /** Cache key or tag name */
235
235
  key: string;
236
236
  /** New tag version for generational tag invalidation */
@@ -330,6 +330,18 @@ declare function createCrossRegionWebhookHandler(cache: {
330
330
  authSecret?: string;
331
331
  }): (req: WebhookRequestLike) => Promise<WebhookResponseLike>;
332
332
 
333
+ type CompressionAlgorithm = 'brotli' | 'gzip' | 'zstd' | 'lz4' | 'none';
334
+ interface CustomCompressor {
335
+ name: string;
336
+ compress: (buf: Buffer) => Buffer;
337
+ decompress: (buf: Buffer) => Buffer;
338
+ }
339
+ /**
340
+ * Initializes the WebAssembly Zstandard codec.
341
+ * Resolves immediately if already initialized.
342
+ */
343
+ declare function initZstd(): Promise<any>;
344
+
333
345
  /**
334
346
  * tricache — shared types and interfaces
335
347
  */
@@ -850,13 +862,20 @@ interface CacheOptions {
850
862
  */
851
863
  serializeToJSON?: boolean;
852
864
  /**
853
- * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
854
- * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
855
- * - `'gzip'` — faster compression / lower CPU overhead.
865
+ * Compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
866
+ * - `'zstd'` (default) — Facebook Zstandard (via WebAssembly) for ultra-high throughput and ~96% ratio.
867
+ * - `'lz4'` — Ultra-fast compression/decompression for high-throughput, latency-critical workloads.
868
+ * - `'brotli'` — High compression ratio for JSON / text payloads.
869
+ * - `'gzip'` — Standard Deflate/Gzip compression.
856
870
  * - `'none'` — disable compression.
857
- * Default: `'none'` (uncompressed).
871
+ * Default: `'zstd'`.
858
872
  */
859
- compression?: 'brotli' | 'gzip' | 'none';
873
+ compression?: CompressionAlgorithm;
874
+ /**
875
+ * Custom compression engine plugin. When provided, overrides the built-in algorithms
876
+ * and delegates compression/decompression to this provider.
877
+ */
878
+ customCompressor?: CustomCompressor;
860
879
  /**
861
880
  * Minimum payload size in bytes before compression is applied.
862
881
  * Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
@@ -1271,6 +1290,20 @@ interface CacheOptions {
1271
1290
  * Default: `5000` ms (5 seconds).
1272
1291
  */
1273
1292
  tagVersionTtlMs?: number;
1293
+ /**
1294
+ * Automatically expand hierarchical tags into their ancestor namespaces.
1295
+ * For example, tagging an entry with `'org:123:dept:456'` will also associate
1296
+ * it with `'org:123'` and `'org'`, allowing `invalidateTag('org:123')` or
1297
+ * `invalidateTag('org')` to automatically cascade down to this entry.
1298
+ *
1299
+ * Default: `false`.
1300
+ */
1301
+ hierarchicalTags?: boolean;
1302
+ /**
1303
+ * The delimiter used for splitting hierarchical tags when `hierarchicalTags` is enabled.
1304
+ * Default: `':'`.
1305
+ */
1306
+ tagHierarchyDelimiter?: string;
1274
1307
  /**
1275
1308
  * Read safety strategy for returned cached objects:
1276
1309
  * - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
@@ -1307,6 +1340,17 @@ interface CacheOptions {
1307
1340
  */
1308
1341
  meter?: ICacheMeter;
1309
1342
  }
1343
+ /**
1344
+ * Options for tag invalidation operations (`cache.invalidateTag()` and `cache.invalidateTags()`).
1345
+ */
1346
+ interface InvalidateTagOptions {
1347
+ /**
1348
+ * When true, invalidates both the specified tag and any descendant child tags
1349
+ * in the hierarchy (e.g. invalidating 'org:123' also invalidates 'org:123:*').
1350
+ * Default: `false`.
1351
+ */
1352
+ cascade?: boolean;
1353
+ }
1310
1354
  /**
1311
1355
  * Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
1312
1356
  */
@@ -1455,4 +1499,4 @@ interface WTinyLfuStats {
1455
1499
  promotions: number;
1456
1500
  }
1457
1501
 
1458
- export { type ICrossRegionRelay as A, type WebhookRequestLike as B, type CacheOptions as C, type DiskBackpressureStats as D, type EncryptionMode as E, type WebhookResponseLike as F, consoleLogger as G, type HttpMeshRelayOptions as H, type ICacheTracer as I, createCrossRegionWebhookHandler as J, createCustomCrossRegionRelay as K, type LockOptions as L, createCustomSnapshotAdapter as M, createHttpMeshRelay as N, createHttpSnapshotAdapter as O, createMemoryCrossRegionRelay as P, createMemorySnapshotAdapter as Q, type RemoteSnapshotOptions as R, type SmartCacheEntry as S, type WrapOptions as W, type CacheMetrics as a, type CacheHealthStatus as b, type CachePresetType as c, type CrossRegionInvalidationEvent as d, CachePriority as e, type CachePingResult as f, type WTinyLfuStats as g, type ILogger as h, type IRemoteSnapshotAdapter as i, type CategoryLimit as j, type EvictionReason as k, type CacheHit as l, CacheEncryption as m, type DiskCacheEntry as n, type IRedisDriver as o, type IRedisPipeline as p, type CrossRegionRelayOptions as q, EnvelopeEncryption as r, type EnvelopeEncryptionOptions as s, type HttpSnapshotAdapterOptions as t, type ICacheBatchObservableCallback as u, type ICacheCounter as v, type ICacheMeter as w, type ICacheObservableGauge as x, type ICacheSpan as y, type ICacheSpanLink as z };
1502
+ export { type ICacheObservableGauge as A, type ICacheSpan as B, type CacheOptions as C, type DiskBackpressureStats as D, type EncryptionMode as E, type ICacheSpanLink as F, type ICrossRegionRelay as G, type HttpMeshRelayOptions as H, type ICacheTracer as I, type WebhookRequestLike as J, type WebhookResponseLike as K, type LockOptions as L, consoleLogger as M, createCrossRegionWebhookHandler as N, createCustomCrossRegionRelay as O, createCustomSnapshotAdapter as P, createHttpMeshRelay as Q, type RemoteSnapshotOptions as R, type SmartCacheEntry as S, createHttpSnapshotAdapter as T, createMemoryCrossRegionRelay as U, createMemorySnapshotAdapter as V, type WrapOptions as W, initZstd as X, type InvalidateTagOptions as a, type CacheMetrics as b, type CacheHealthStatus as c, type CachePresetType as d, type CrossRegionInvalidationEvent as e, CachePriority as f, type CachePingResult as g, type WTinyLfuStats as h, type ILogger as i, type IRemoteSnapshotAdapter as j, type CategoryLimit as k, type EvictionReason as l, type CacheHit as m, CacheEncryption as n, type CompressionAlgorithm as o, type DiskCacheEntry as p, type IRedisDriver as q, type IRedisPipeline as r, type CrossRegionRelayOptions as s, type CustomCompressor as t, EnvelopeEncryption as u, type EnvelopeEncryptionOptions as v, type HttpSnapshotAdapterOptions as w, type ICacheBatchObservableCallback as x, type ICacheCounter as y, type ICacheMeter as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.9.0",
3
+ "version": "1.0.0",
4
4
  "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
@@ -114,7 +114,9 @@
114
114
  },
115
115
  "dependencies": {
116
116
  "ioredis": "6.0.0",
117
- "msgpackr": "2.1.0"
117
+ "lz4js": "^0.2.0",
118
+ "msgpackr": "2.1.2",
119
+ "zstd-codec": "^0.1.5"
118
120
  },
119
121
  "devDependencies": {
120
122
  "@nestjs/common": "^11.0.0",
@@ -127,9 +129,9 @@
127
129
  "tsup": "^8.5.1",
128
130
  "tsx": "^4.23.15",
129
131
  "typescript": "^6.0.3",
130
- "vite": "^8.2.2",
132
+ "vite": "^8.3.5",
131
133
  "vitepress": "2.0.0-alpha.20",
132
- "vitest": "^4.1.11"
134
+ "vitest": "^4.1.12"
133
135
  },
134
136
  "engines": {
135
137
  "node": ">=20.10.0"
@@ -147,6 +149,7 @@
147
149
  "test:watch": "vitest",
148
150
  "bench": "node --expose-gc --max-old-space-size=8192 --import tsx/esm bench/benchmark.ts",
149
151
  "bench:roi": "tsx bench/cloud-roi-simulation.ts",
152
+ "bench:compression": "tsx bench/compression.bench.ts",
150
153
  "docs:dev": "vitepress dev docs",
151
154
  "docs:build": "vitepress build docs",
152
155
  "docs:preview": "vitepress preview docs",