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.
Files changed (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +500 -24
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-AJASH5FX.js +7 -0
  5. package/dist/cache-service-BblHuF3i.d.ts +1476 -0
  6. package/dist/chunk-3XQUQBOZ.js +4583 -0
  7. package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
  8. package/dist/chunk-UBSR5UYA.js +0 -0
  9. package/dist/cli.cjs +5181 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5161 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5289 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +172 -0
  18. package/dist/index.cjs +1181 -194
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3697
  21. package/dist/nestjs/index.cjs +5305 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5327 -0
  25. package/dist/next/index.d.ts +204 -0
  26. package/dist/next/index.js +274 -0
  27. package/dist/prisma/index.cjs +122 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +86 -0
  30. package/dist/serialize-worker.cjs +177 -13
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +64 -15
  33. package/src/cache-service.ts +1005 -192
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +63 -0
  36. package/src/disk-tier.ts +71 -7
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +56 -5
  39. package/src/http/index.ts +223 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +244 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +151 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +22 -8
  53. package/src/types.ts +172 -2
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
package/src/cli.ts ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * TriCache CLI — Developer & Troubleshooting Inspector
3
+ *
4
+ * Usage:
5
+ * npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
6
+ * npx tricache ping [--redis redis://localhost:6379]
7
+ * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
8
+ */
9
+
10
+ import { parseArgs } from 'node:util';
11
+ import { CacheService } from './cache-service.js';
12
+
13
+ export async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {
14
+ const options = {
15
+ redis: { type: 'string' as const, short: 'r' },
16
+ port: { type: 'string' as const, short: 'p' },
17
+ namespace: { type: 'string' as const, short: 'n' },
18
+ prefix: { type: 'string' as const },
19
+ disk: { type: 'string' as const, short: 'd' },
20
+ help: { type: 'boolean' as const, short: 'h' },
21
+ version: { type: 'boolean' as const, short: 'v' },
22
+ };
23
+
24
+ let parsed;
25
+ try {
26
+ parsed = parseArgs({
27
+ args,
28
+ options,
29
+ allowPositionals: true,
30
+ strict: false,
31
+ });
32
+ } catch (err) {
33
+ console.error(`Error: ${(err as Error).message}\n`);
34
+ printHelp();
35
+ process.exit(1);
36
+ }
37
+
38
+ const { values, positionals } = parsed;
39
+ const command = positionals[0] || 'inspect';
40
+
41
+ if (values.help || command === 'help') {
42
+ printHelp();
43
+ return;
44
+ }
45
+
46
+ if (values.version || command === 'version') {
47
+ console.log('tricache v0.7.0');
48
+ return;
49
+ }
50
+
51
+ const redisStr = typeof values.redis === 'string' ? values.redis : undefined;
52
+ const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, '').split(':')[0] : undefined;
53
+ const redisPort = typeof values.port === 'string'
54
+ ? parseInt(values.port, 10)
55
+ : (redisStr && redisStr.includes(':') ? parseInt(redisStr.split(':')[1], 10) : 6379);
56
+ const namespace = typeof values.namespace === 'string' ? values.namespace : undefined;
57
+ const diskCacheDir = typeof values.disk === 'string' ? values.disk : undefined;
58
+
59
+ const cache = new CacheService({
60
+ redisHost,
61
+ redisPort,
62
+ namespace,
63
+ diskCacheDir,
64
+ disableRedis: !redisHost,
65
+ });
66
+
67
+ try {
68
+ if (command === 'inspect') {
69
+ const ping = await cache.ping();
70
+ const metrics = cache.metrics();
71
+ const stats = cache.stats();
72
+ const hot = cache.hotKeys(5);
73
+
74
+ const divPct = (n: number) => `${(n * 100).toFixed(1)}%`;
75
+ const l1MaxKB = Math.round((cache.options.l1MaxBytes ?? 200 * 1024 * 1024) / 1024);
76
+
77
+ console.log(`
78
+ ┌──────────────────────────────────────────────────────────────┐
79
+ │ TriCache Engine Dashboard (Namespace: ${namespace || '(default)'})
80
+ ├──────────────────────────────────────────────────────────────┤
81
+ │ Tiers Active: L1 (RAM) → L1.5 (NVMe Disk) → L2 (${redisHost ? 'Redis' : 'Disabled'})
82
+ │ Latencies: L1: ${ping.l1}ms | Disk: ${ping.disk}ms | L2: ${ping.l2 !== null ? `${ping.l2}ms` : 'N/A'}
83
+ │ L1 Entries: ${stats.l1.entries} (${stats.l1.sizeKB} KB / ${l1MaxKB} KB)
84
+ │ Disk Files: ${stats.disk.files} (${stats.disk.sizeKB} KB / ${stats.disk.maxKB} KB)
85
+ ├──────────────────────────────────────────────────────────────┤
86
+ │ L1 Hit Ratio: ${divPct(metrics.gets.l1HitRate)} (${metrics.gets.l1Hits} hits)
87
+ │ L2 Hit Ratio: ${divPct(metrics.gets.l2HitRate)} (${metrics.gets.l2Hits} hits)
88
+ │ Disk Hit Ratio: ${divPct(metrics.gets.diskHitRate)} (${metrics.gets.diskHits} hits)
89
+ │ Stampedes Saved: ${metrics.gets.stampedePrevented} coalesced requests
90
+ ├──────────────────────────────────────────────────────────────┤
91
+ │ 🔥 Top Hot Keys (Count-Min Sketch):`);
92
+
93
+ if (hot.length === 0) {
94
+ console.log('│ (no hot keys recorded yet)');
95
+ } else {
96
+ hot.forEach(({ key, hits, sizeBytes }, idx) => {
97
+ const size = sizeBytes > 1024 ? `${(sizeBytes / 1024).toFixed(1)} KB` : `${sizeBytes} B`;
98
+ console.log(`│ ${idx + 1}. ${key.padEnd(24)} (${hits} hits, ${size})`);
99
+ });
100
+ }
101
+ console.log('└──────────────────────────────────────────────────────────────┘\n');
102
+ } else if (command === 'ping') {
103
+ const ping = await cache.ping();
104
+ console.log(`TriCache Ping Results:`);
105
+ console.log(` • L1 RAM: ${ping.l1}ms`);
106
+ console.log(` • Disk: ${ping.disk}ms`);
107
+ console.log(` • L2 Redis:${ping.l2 !== null ? ` ${ping.l2}ms` : ' Disabled'}`);
108
+ } else if (command === 'clear') {
109
+ const prefix = typeof values.prefix === 'string' ? values.prefix : undefined;
110
+ await cache.clear(prefix);
111
+ console.log(`Cleared cache${prefix ? ` for prefix "${prefix}"` : ' (all entries)'} in namespace "${namespace || '(default)'}".`);
112
+ } else {
113
+ console.error(`Unknown command: ${command}\n`);
114
+ printHelp();
115
+ process.exit(1);
116
+ }
117
+ } finally {
118
+ await cache.destroy();
119
+ }
120
+ }
121
+
122
+ function printHelp(): void {
123
+ console.log(`
124
+ TriCache CLI — Developer & Troubleshooting Tool
125
+
126
+ Usage:
127
+ tricache <command> [options]
128
+
129
+ Commands:
130
+ inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
131
+ ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
132
+ clear Flush all entries or keys matching a prefix
133
+
134
+ Options:
135
+ -r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
136
+ -p, --port <port> Redis port (default: 6379)
137
+ -n, --namespace <ns> Cache namespace
138
+ --prefix <prefix> Key prefix filter for clear command
139
+ -d, --disk <path> Custom disk cache directory path
140
+ -h, --help Show this help message
141
+ -v, --version Display version number
142
+ `);
143
+ }
@@ -0,0 +1,63 @@
1
+ import zlib from 'zlib';
2
+
3
+ export type CompressionAlgorithm = 'brotli' | 'gzip' | 'none';
4
+
5
+ export const PREFIX_COMPRESSED = 'cmp:v1:';
6
+ export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
7
+
8
+ /** "TRC\x01" 4-byte marker prefix identifying compressed data */
9
+ const COMPRESSION_MAGIC = Buffer.from([0x54, 0x52, 0x43, 0x01]);
10
+
11
+ export function isCompressed(buf: Buffer): boolean {
12
+ return buf.length >= 4 && buf[0] === 0x54 && buf[1] === 0x52 && buf[2] === 0x43 && buf[3] === 0x01;
13
+ }
14
+
15
+ export function compressBuffer(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
16
+ if (algorithm === 'brotli') {
17
+ return zlib.brotliCompressSync(buf, {
18
+ params: {
19
+ [zlib.constants.BROTLI_PARAM_QUALITY]: 4, // Fast level 4 compression
20
+ },
21
+ });
22
+ }
23
+ if (algorithm === 'gzip') {
24
+ return zlib.gzipSync(buf, { level: 6 });
25
+ }
26
+ return buf;
27
+ }
28
+
29
+ export function decompressBuffer(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
30
+ if (algorithm === 'gzip') {
31
+ try {
32
+ return zlib.gunzipSync(buf);
33
+ } catch {
34
+ try {
35
+ return zlib.brotliDecompressSync(buf);
36
+ } catch {
37
+ return buf;
38
+ }
39
+ }
40
+ }
41
+ try {
42
+ return zlib.brotliDecompressSync(buf);
43
+ } catch {
44
+ try {
45
+ return zlib.gunzipSync(buf);
46
+ } catch {
47
+ return buf;
48
+ }
49
+ }
50
+ }
51
+
52
+ export function compressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
53
+ if (algorithm === 'none') return buf;
54
+ const compressed = compressBuffer(buf, algorithm);
55
+ return Buffer.concat([COMPRESSION_MAGIC, compressed]);
56
+ }
57
+
58
+ export function decompressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
59
+ if (isCompressed(buf)) {
60
+ return decompressBuffer(buf.subarray(4), algorithm);
61
+ }
62
+ return buf;
63
+ }
package/src/disk-tier.ts CHANGED
@@ -18,8 +18,13 @@ import fs from 'fs';
18
18
  import path from 'path';
19
19
  import crypto from 'crypto';
20
20
  import { pack, unpack } from 'msgpackr';
21
- import { DiskCacheEntry, ILogger } from './types.js';
22
- import { CacheEncryption } from './encryption.js';
21
+ import type { DiskCacheEntry, ILogger } from './types.js';
22
+ import type { CacheEncryption } from './encryption.js';
23
+ import {
24
+ compressWithHeader,
25
+ decompressWithHeader,
26
+ type CompressionAlgorithm,
27
+ } from './compression.js';
23
28
 
24
29
  // ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
25
30
  // Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
@@ -46,7 +51,7 @@ try {
46
51
  // ── Encryption (delegates to CacheEncryption — mode-aware, no reimplementation) ──
47
52
  // DiskTier keeps its own V2 envelope (magic | plaintext expiresAt | payload) but
48
53
  // delegates the payload cipher to CacheEncryption, which already supports all four
49
- // modes (aes-256-gcm, aes-128-gcm, aes-128-ctr, xor) and is the single source of
54
+ // modes (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor) and is the single source of
50
55
  // truth for the on-disk binary format. This avoids a hardcoded aes-256-gcm that
51
56
  // threw (and silently no-op'd the disk tier) for any non-default mode.
52
57
  const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
@@ -81,6 +86,8 @@ export interface DiskTierOptions {
81
86
  * same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
82
87
  * When null, files are written unencrypted. Pass `cache.encryption` here. */
83
88
  encryption?: CacheEncryption | null;
89
+ compression?: CompressionAlgorithm;
90
+ compressionThresholdBytes?: number;
84
91
  logger: ILogger;
85
92
  }
86
93
 
@@ -340,32 +347,52 @@ export class DiskTier {
340
347
  };
341
348
  const packed = pack(payload);
342
349
  if (packed.length > this.opts.entryMaxBytes) return;
350
+ let toEncrypt = packed;
351
+ if (this.opts.compression && this.opts.compression !== 'none' && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
352
+ toEncrypt = compressWithHeader(packed, this.opts.compression);
353
+ }
343
354
  // V2 format: 16-byte plaintext header (magic + expiresAt) followed by the
344
355
  // encrypted-or-raw payload. The plaintext expiresAt allows purgeNextBucket()
345
356
  // to check expiry with a 16-byte partial read — no decrypt or unpack needed.
346
357
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
347
358
  DISK_MAGIC_V2.copy(header, 0);
348
359
  header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
349
- final = Buffer.concat([header, this.encryptV2(packed)]);
360
+ final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
350
361
  } catch (err) {
351
362
  this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
352
363
  return;
353
364
  }
354
365
 
355
- // ── Async phase: mkdir + write (does not block the event loop) ────
366
+ // ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
356
367
  const hash = this.keyToHash(key);
357
368
  const filePath = this.hashToWritePath(hash, entry.expiresAt);
369
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
358
370
  this.diskUsageBytes += final.length; // optimistic — rolled back on error
359
371
  this.fileCount++;
360
372
 
361
373
  try {
362
374
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
363
- await fs.promises.writeFile(filePath, final, { mode: 0o600 });
375
+ await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
376
+
377
+ // Atomic rename with micro-retry loop for Windows NTFS handle release
378
+ try {
379
+ await fs.promises.rename(tmpPath, filePath);
380
+ } catch (renameErr: unknown) {
381
+ const code = (renameErr as { code?: string })?.code;
382
+ if (code === 'EBUSY' || code === 'EPERM') {
383
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
384
+ await fs.promises.rename(tmpPath, filePath);
385
+ } else {
386
+ throw renameErr;
387
+ }
388
+ }
389
+
364
390
  if (this._db) {
365
391
  this._stmtInsert!.run(hash, filePath, entry.expiresAt, final.length);
366
392
  }
367
393
  this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
368
394
  } catch (err) {
395
+ try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
369
396
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
370
397
  this.fileCount = Math.max(0, this.fileCount - 1);
371
398
  if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
@@ -449,7 +476,8 @@ export class DiskTier {
449
476
  try { decrypted = this.decrypt(raw); } catch { return null; }
450
477
  }
451
478
 
452
- const payload = unpack(decrypted) as DiskPayload;
479
+ const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
480
+ const payload = unpack(uncompressed) as DiskPayload;
453
481
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
454
482
  if (payload.entry.expiresAt <= Date.now()) return null;
455
483
 
@@ -512,6 +540,18 @@ export class DiskTier {
512
540
  for (const filePath of this.walkCacheFiles()) {
513
541
  const filename = path.basename(filePath);
514
542
 
543
+ // Clean up orphaned .tmp files older than 5 minutes
544
+ if (filename.endsWith('.tmp')) {
545
+ try {
546
+ const stat = fs.statSync(filePath);
547
+ if (now - stat.mtimeMs > 5 * 60 * 1000) {
548
+ fs.unlinkSync(filePath);
549
+ purged++;
550
+ }
551
+ } catch { /* already gone */ }
552
+ continue;
553
+ }
554
+
515
555
  // ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
516
556
  if (filename.length === 77 && filename[64] === '_') {
517
557
  const expiresAt = parseInt(filename.slice(65), 16);
@@ -617,6 +657,17 @@ export class DiskTier {
617
657
  let orphanFiles: string[];
618
658
  try { orphanFiles = fs.readdirSync(orphanBucketP); } catch { return expired.length; }
619
659
  for (const file of orphanFiles) {
660
+ if (file.endsWith('.tmp')) {
661
+ const fp = path.join(orphanBucketP, file);
662
+ try {
663
+ const stat = fs.statSync(fp);
664
+ if (now - stat.mtimeMs > 5 * 60 * 1000) {
665
+ fs.unlinkSync(fp);
666
+ }
667
+ } catch { /* already gone */ }
668
+ continue;
669
+ }
670
+
620
671
  if (file.length === 77 && file[64] === '_') {
621
672
  const expiresAt = parseInt(file.slice(65), 16);
622
673
  if (expiresAt <= now) {
@@ -644,6 +695,19 @@ export class DiskTier {
644
695
  // One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
645
696
  const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
646
697
  for (const file of files) {
698
+ // Clean up orphaned .tmp files older than 5 minutes
699
+ if (file.endsWith('.tmp')) {
700
+ const fp = path.join(bucketPath, file);
701
+ try {
702
+ const stat = fs.statSync(fp);
703
+ if (now - stat.mtimeMs > 5 * 60 * 1000) {
704
+ fs.unlinkSync(fp);
705
+ purged++;
706
+ }
707
+ } catch { /* already gone */ }
708
+ continue;
709
+ }
710
+
647
711
  // ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
648
712
  // Filename format: {sha256-64-hex}_{expiresAt-12-hex} = 77 chars total.
649
713
  if (file.length === 77 && file[64] === '_') {
@@ -0,0 +1,86 @@
1
+ /**
2
+ * tricache/drizzle — First-class Drizzle ORM query caching wrapper for TriCache.
3
+ *
4
+ * Usage:
5
+ * import { withCache } from 'tricache/drizzle';
6
+ *
7
+ * const activeUsers = await withCache(
8
+ * db.select().from(users).where(eq(users.active, true)),
9
+ * { cache, ttl: 300, tags: ['users'] }
10
+ * );
11
+ */
12
+
13
+ import type { CacheService } from '../cache-service.js';
14
+ import type { WrapOptions } from '../types.js';
15
+ import crypto from 'crypto';
16
+
17
+ export interface DrizzleCacheOptions extends WrapOptions {
18
+ /** TriCache instance to use. If omitted, uses process-level singleton `CacheService.create()`. */
19
+ cache?: CacheService;
20
+ /** Explicit cache key. If omitted, automatically derived from SHA-256 hash of `{ sql, params }`. */
21
+ key?: string;
22
+ }
23
+
24
+ export interface DrizzleExecutableQuery<T> {
25
+ toSQL(): { sql: string; params: unknown[] };
26
+ execute?(): Promise<T>;
27
+ then?: (onfulfilled?: (value: T) => unknown, onrejected?: (reason: unknown) => unknown) => Promise<unknown>;
28
+ }
29
+
30
+ /**
31
+ * Generate a deterministic SHA-256 hash key for a Drizzle query based on its compiled SQL and parameters.
32
+ */
33
+ export function generateDrizzleCacheKey(sqlInfo: { sql: string; params: unknown[] }): string {
34
+ const normalized = JSON.stringify(sqlInfo);
35
+ const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
36
+ return `drizzle:${hash}`;
37
+ }
38
+
39
+ /**
40
+ * Wraps a Drizzle ORM query with TriCache caching.
41
+ *
42
+ * @param query Drizzle query builder or executable query instance.
43
+ * @param options Cache options including TTL, tags, SWR, priority, and optional key.
44
+ */
45
+ export async function withCache<T>(
46
+ query: DrizzleExecutableQuery<T>,
47
+ options: DrizzleCacheOptions = {},
48
+ ): Promise<T> {
49
+ const { cache, key, ttl = 300, swr, priority, tags, dependsOn, refreshAhead, xfetchBeta, notFoundTtl } = options;
50
+
51
+ let activeCache = cache;
52
+ if (!activeCache) {
53
+ const { CacheService } = await import('../cache-service.js');
54
+ activeCache = CacheService.create();
55
+ }
56
+
57
+ let cacheKey = key;
58
+ if (!cacheKey) {
59
+ if (typeof query.toSQL === 'function') {
60
+ const sqlInfo = query.toSQL();
61
+ cacheKey = generateDrizzleCacheKey(sqlInfo);
62
+ } else {
63
+ throw new Error('tricache/drizzle: query must provide a .toSQL() method or an explicit key option.');
64
+ }
65
+ }
66
+
67
+ const executeFn = async (): Promise<T> => {
68
+ if (typeof query.execute === 'function') {
69
+ return await query.execute();
70
+ } else if (typeof query.then === 'function') {
71
+ return await (query as unknown as Promise<T>);
72
+ }
73
+ throw new Error('tricache/drizzle: query is neither executable via .execute() nor thenable.');
74
+ };
75
+
76
+ return activeCache.wrap(cacheKey, executeFn, {
77
+ ttl,
78
+ swr,
79
+ priority,
80
+ tags,
81
+ dependsOn,
82
+ refreshAhead,
83
+ xfetchBeta,
84
+ notFoundTtl,
85
+ });
86
+ }
package/src/encryption.ts CHANGED
@@ -34,7 +34,7 @@
34
34
  */
35
35
 
36
36
  import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync, type KeyObject } from 'crypto';
37
- import type { ILogger } from './types';
37
+ import { type ILogger, consoleLogger } from './types';
38
38
 
39
39
  // ── Public type ───────────────────────────────────────────────────────────────
40
40
  /** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
@@ -73,7 +73,7 @@ const IV_POOL_COUNT = 64;
73
73
  export class CacheEncryption {
74
74
  private _key: Buffer | null = null; // raw bytes — used only for XOR
75
75
  private _keyObj: KeyObject | null = null; // parsed KeyObject — used for all AES modes
76
- private readonly _mode: EncryptionMode;
76
+ private _mode: EncryptionMode;
77
77
  private _prevKey: Buffer | null = null;
78
78
  private _prevKeyObj: KeyObject | null = null;
79
79
  private _prevMode: EncryptionMode = 'aes-256-gcm';
@@ -156,12 +156,19 @@ export class CacheEncryption {
156
156
 
157
157
  constructor(
158
158
  keyBase64: string | undefined,
159
- logger: ILogger,
159
+ loggerOrMode: ILogger | EncryptionMode = consoleLogger,
160
160
  mode: EncryptionMode = 'aes-256-gcm',
161
161
  previousKeyBase64?: string,
162
162
  previousMode?: EncryptionMode,
163
163
  ) {
164
- this._mode = mode;
164
+ const logger: ILogger = (typeof loggerOrMode === 'object' && loggerOrMode !== null)
165
+ ? loggerOrMode
166
+ : consoleLogger;
167
+ const resolvedMode: EncryptionMode = typeof loggerOrMode === 'string'
168
+ ? loggerOrMode
169
+ : mode;
170
+
171
+ this._mode = resolvedMode;
165
172
  if (!keyBase64) {
166
173
  if (process.env.NODE_ENV === 'production') {
167
174
  logger.warn(
@@ -173,7 +180,7 @@ export class CacheEncryption {
173
180
  }
174
181
  try {
175
182
  const buf = Buffer.from(keyBase64, 'base64');
176
- const requiredLen = mode === 'aes-256-gcm' ? 32 : (mode === 'aes-128-gcm' || mode === 'aes-128-ctr') ? 16 : 0;
183
+ const requiredLen = resolvedMode === 'aes-256-gcm' ? 32 : (resolvedMode === 'aes-128-gcm' || resolvedMode === 'aes-128-ctr') ? 16 : 0;
177
184
  if (requiredLen > 0 && buf.length !== requiredLen) {
178
185
  throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
179
186
  }
@@ -227,6 +234,7 @@ export class CacheEncryption {
227
234
  }
228
235
 
229
236
  get isEnabled(): boolean { return this._key !== null; }
237
+ get mode(): EncryptionMode { return this._mode; }
230
238
 
231
239
  /**
232
240
  * Snapshot the key material needed to spin up an off-main-thread worker pool.
@@ -248,6 +256,49 @@ export class CacheEncryption {
248
256
  };
249
257
  }
250
258
 
259
+ /**
260
+ * Rotate the active encryption key dynamically at runtime.
261
+ * Promotes the current primary key to previousEncryptionKey for zero-downtime
262
+ * fallback decryption of existing cache entries in L2/Disk, and installs
263
+ * the new key as primary for all subsequent writes.
264
+ */
265
+ rotateKey(newKeyBase64: string, newMode?: EncryptionMode): void {
266
+ if (!newKeyBase64) {
267
+ throw new Error('rotateKey requires a valid non-empty base64 key');
268
+ }
269
+ const mode = newMode ?? this._mode;
270
+ const buf = Buffer.from(newKeyBase64, 'base64');
271
+ const requiredLen = mode === 'aes-256-gcm' ? 32 : (mode === 'aes-128-gcm' || mode === 'aes-128-ctr') ? 16 : 0;
272
+ if (requiredLen > 0 && buf.length !== requiredLen) {
273
+ throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
274
+ }
275
+ if (buf.length < 1) {
276
+ throw new Error('XOR key must be at least 1 byte');
277
+ }
278
+
279
+ let newKeyObj: KeyObject | null = null;
280
+ if (mode !== 'xor') {
281
+ newKeyObj = createSecretKey(buf);
282
+ const _wc = createCipheriv(
283
+ mode,
284
+ newKeyObj,
285
+ Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
286
+ );
287
+ _wc.update(Buffer.alloc(0));
288
+ _wc.final();
289
+ }
290
+
291
+ // Shift current primary to previous key
292
+ this._prevKey = this._key;
293
+ this._prevKeyObj = this._keyObj;
294
+ this._prevMode = this._mode;
295
+
296
+ // Set new primary key
297
+ this._key = buf;
298
+ this._keyObj = newKeyObj;
299
+ this._mode = mode;
300
+ }
301
+
251
302
  // ── String (Redis) ────────────────────────────────────────────────────────
252
303
 
253
304
  /**