tricache 0.7.0 → 0.8.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 (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
package/src/cli.ts CHANGED
@@ -1,143 +1,261 @@
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
- }
1
+ /**
2
+ * TriCache CLI — Developer & Troubleshooting Inspector
3
+ *
4
+ * Usage:
5
+ * npx tricache top [--socket <path>] [--pid <pid>] [--interval <ms>] [--once]
6
+ * npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
7
+ * npx tricache ping [--redis redis://localhost:6379]
8
+ * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
9
+ */
10
+
11
+ import { parseArgs } from 'node:util';
12
+ import { CacheService } from './cache-service.js';
13
+ import {
14
+ IpcTelemetryClient,
15
+ resolveIpcSocketPath,
16
+ findActiveSockets,
17
+ renderTopDashboard,
18
+ } from './ipc-telemetry.js';
19
+
20
+ export async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {
21
+ const options = {
22
+ redis: { type: 'string' as const, short: 'r' },
23
+ port: { type: 'string' as const, short: 'p' },
24
+ namespace: { type: 'string' as const, short: 'n' },
25
+ prefix: { type: 'string' as const },
26
+ disk: { type: 'string' as const, short: 'd' },
27
+ pid: { type: 'string' as const },
28
+ socket: { type: 'string' as const, short: 's' },
29
+ interval: { type: 'string' as const, short: 'i' },
30
+ once: { type: 'boolean' as const },
31
+ json: { type: 'boolean' as const },
32
+ help: { type: 'boolean' as const, short: 'h' },
33
+ version: { type: 'boolean' as const, short: 'v' },
34
+ };
35
+
36
+ let parsed;
37
+ try {
38
+ parsed = parseArgs({
39
+ args,
40
+ options,
41
+ allowPositionals: true,
42
+ strict: false,
43
+ });
44
+ } catch (err) {
45
+ console.error(`Error: ${(err as Error).message}\n`);
46
+ printHelp();
47
+ process.exit(1);
48
+ }
49
+
50
+ const { values, positionals } = parsed;
51
+ const command = positionals[0] || 'inspect';
52
+
53
+ if (values.help || command === 'help') {
54
+ printHelp();
55
+ return;
56
+ }
57
+
58
+ // NOTE: console.log is INTENTIONAL across cli.ts — this file is the terminal CLI runner
59
+ // (bin/tricache.js). Output must go directly to process stdout without logger prefixes
60
+ // to support UNIX pipes, terminal formatting, and automated tooling.
61
+ if (values.version || command === 'version') {
62
+ console.log('tricache v0.8.0');
63
+ return;
64
+ }
65
+
66
+ // Handle 'top' monitor command directly without constructing a local CacheService
67
+ if (command === 'top') {
68
+ let targetSocket = typeof values.socket === 'string' ? values.socket : undefined;
69
+ if (!targetSocket && typeof values.pid === 'string') {
70
+ targetSocket = resolveIpcSocketPath(values.pid);
71
+ }
72
+ if (!targetSocket) {
73
+ const active = await findActiveSockets();
74
+ if (active.length > 0) {
75
+ targetSocket = active[0];
76
+ } else {
77
+ targetSocket = resolveIpcSocketPath(process.pid);
78
+ }
79
+ }
80
+
81
+ const client = new IpcTelemetryClient(targetSocket);
82
+ const intervalMs = typeof values.interval === 'string'
83
+ ? Math.max(200, parseInt(values.interval, 10))
84
+ : 1000;
85
+ const isOnce = Boolean(values.once || !process.stdout.isTTY);
86
+ const asJson = Boolean(values.json);
87
+
88
+ if (isOnce) {
89
+ try {
90
+ const payload = await client.getMetrics();
91
+ if (asJson) {
92
+ console.log(JSON.stringify(payload, null, 2));
93
+ } else {
94
+ console.log(renderTopDashboard(payload));
95
+ }
96
+ return;
97
+ } catch (err) {
98
+ console.error(`Failed to connect to TriCache IPC at ${targetSocket}: ${(err as Error).message}`);
99
+ process.exit(1);
100
+ }
101
+ }
102
+
103
+ // Interactive TTY mode: switch to alternate screen buffer and hide cursor
104
+ process.stdout.write('\x1b[?1049h\x1b[?25l');
105
+
106
+ let activeInterval: NodeJS.Timeout | null = null;
107
+ let cleaningUp = false;
108
+
109
+ const cleanup = () => {
110
+ if (cleaningUp) return;
111
+ cleaningUp = true;
112
+ if (activeInterval) clearInterval(activeInterval);
113
+ if (process.stdout.isTTY) {
114
+ process.stdout.write('\x1b[?25h\x1b[?1049l');
115
+ }
116
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
117
+ try {
118
+ process.stdin.setRawMode(false);
119
+ process.stdin.pause();
120
+ } catch {
121
+ // Ignore TTY reset errors
122
+ }
123
+ }
124
+ process.exit(0);
125
+ };
126
+
127
+ process.once('SIGINT', cleanup);
128
+ process.once('SIGTERM', cleanup);
129
+
130
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
131
+ try {
132
+ process.stdin.setRawMode(true);
133
+ process.stdin.resume();
134
+ process.stdin.setEncoding('utf8');
135
+ process.stdin.on('data', (key: string) => {
136
+ if (key === 'q' || key === 'Q' || key === '\u0003') {
137
+ cleanup();
138
+ }
139
+ });
140
+ } catch {
141
+ // Raw mode not supported
142
+ }
143
+ }
144
+
145
+ const tick = async () => {
146
+ try {
147
+ const payload = await client.getMetrics();
148
+ const screen = renderTopDashboard(payload);
149
+ process.stdout.write('\x1b[H' + screen + '\n Press "q" or Ctrl+C to exit\n');
150
+ } catch (err) {
151
+ process.stdout.write(`\x1b[HConnecting to ${targetSocket}...\nError: ${(err as Error).message}\n`);
152
+ }
153
+ };
154
+
155
+ await tick();
156
+ activeInterval = setInterval(tick, intervalMs);
157
+
158
+ // Keep process alive in interactive loop until exit
159
+ await new Promise<void>(() => {});
160
+ return;
161
+ }
162
+
163
+ const redisStr = typeof values.redis === 'string' ? values.redis : undefined;
164
+ const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, '').split(':')[0] : undefined;
165
+ const redisPort = typeof values.port === 'string'
166
+ ? parseInt(values.port, 10)
167
+ : (redisStr && redisStr.includes(':') ? parseInt(redisStr.split(':')[1], 10) : 6379);
168
+ const namespace = typeof values.namespace === 'string' ? values.namespace : undefined;
169
+ const diskCacheDir = typeof values.disk === 'string' ? values.disk : undefined;
170
+
171
+ const cache = new CacheService({
172
+ redisHost,
173
+ redisPort,
174
+ namespace,
175
+ diskCacheDir,
176
+ disableRedis: !redisHost,
177
+ });
178
+
179
+ try {
180
+ if (command === 'inspect') {
181
+ const ping = await cache.ping();
182
+ const metrics = cache.metrics();
183
+ const stats = cache.stats();
184
+ const hot = cache.hotKeys(5);
185
+
186
+ const divPct = (n: number) => `${(n * 100).toFixed(1)}%`;
187
+ const l1MaxKB = Math.round((cache.options.l1MaxBytes ?? 200 * 1024 * 1024) / 1024);
188
+
189
+ console.log(`
190
+ ┌──────────────────────────────────────────────────────────────┐
191
+ │ TriCache Engine Dashboard (Namespace: ${namespace || '(default)'})
192
+ ├──────────────────────────────────────────────────────────────┤
193
+ │ Tiers Active: L1 (RAM) → L1.5 (NVMe Disk) → L2 (${redisHost ? 'Redis' : 'Disabled'})
194
+ │ Latencies: L1: ${ping.l1}ms | Disk: ${ping.disk}ms | L2: ${ping.l2 !== null ? `${ping.l2}ms` : 'N/A'}
195
+ │ L1 Entries: ${stats.l1.entries} (${stats.l1.sizeKB} KB / ${l1MaxKB} KB)
196
+ │ Disk Files: ${stats.disk.files} (${stats.disk.sizeKB} KB / ${stats.disk.maxKB} KB)
197
+ ├──────────────────────────────────────────────────────────────┤
198
+ │ L1 Hit Ratio: ${divPct(metrics.gets.l1HitRate)} (${metrics.gets.l1Hits} hits)
199
+ │ L2 Hit Ratio: ${divPct(metrics.gets.l2HitRate)} (${metrics.gets.l2Hits} hits)
200
+ │ Disk Hit Ratio: ${divPct(metrics.gets.diskHitRate)} (${metrics.gets.diskHits} hits)
201
+ │ Stampedes Saved: ${metrics.gets.stampedePrevented} coalesced requests
202
+ ├──────────────────────────────────────────────────────────────┤
203
+ │ 🔥 Top Hot Keys (Count-Min Sketch):`);
204
+
205
+ if (hot.length === 0) {
206
+ console.log('│ (no hot keys recorded yet)');
207
+ } else {
208
+ hot.forEach(({ key, hits, sizeBytes }, idx) => {
209
+ const size = sizeBytes > 1024 ? `${(sizeBytes / 1024).toFixed(1)} KB` : `${sizeBytes} B`;
210
+ console.log(`│ ${idx + 1}. ${key.padEnd(24)} (${hits} hits, ${size})`);
211
+ });
212
+ }
213
+ console.log('└──────────────────────────────────────────────────────────────┘\n');
214
+ } else if (command === 'ping') {
215
+ const ping = await cache.ping();
216
+ console.log(`TriCache Ping Results:`);
217
+ console.log(` • L1 RAM: ${ping.l1}ms`);
218
+ console.log(` • Disk: ${ping.disk}ms`);
219
+ console.log(` • L2 Redis:${ping.l2 !== null ? ` ${ping.l2}ms` : ' Disabled'}`);
220
+ } else if (command === 'clear') {
221
+ const prefix = typeof values.prefix === 'string' ? values.prefix : undefined;
222
+ await cache.clear(prefix);
223
+ console.log(`Cleared cache${prefix ? ` for prefix "${prefix}"` : ' (all entries)'} in namespace "${namespace || '(default)'}".`);
224
+ } else {
225
+ console.error(`Unknown command: ${command}\n`);
226
+ printHelp();
227
+ process.exit(1);
228
+ }
229
+ } finally {
230
+ await cache.destroy();
231
+ }
232
+ }
233
+
234
+ function printHelp(): void {
235
+ console.log(`
236
+ TriCache CLI — Developer & Troubleshooting Tool
237
+
238
+ Usage:
239
+ tricache <command> [options]
240
+
241
+ Commands:
242
+ top Live ASCII terminal dashboard monitoring an active TriCache process
243
+ inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
244
+ ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
245
+ clear Flush all entries or keys matching a prefix
246
+
247
+ Options:
248
+ -s, --socket <path> IPC socket path or Windows named pipe
249
+ --pid <pid> Process ID of the target TriCache process to monitor
250
+ -i, --interval <ms> Refresh interval in milliseconds for top (default: 1000)
251
+ --once Output single snapshot and exit (non-interactive)
252
+ --json Format output as raw JSON
253
+ -r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
254
+ -p, --port <port> Redis port (default: 6379)
255
+ -n, --namespace <ns> Cache namespace
256
+ --prefix <prefix> Key prefix filter for clear command
257
+ -d, --disk <path> Custom disk cache directory path
258
+ -h, --help Show this help message
259
+ -v, --version Display version number
260
+ `);
261
+ }
package/src/codec.ts ADDED
@@ -0,0 +1,72 @@
1
+ import { Packr, type Options as MsgpackrOptions } from 'msgpackr';
2
+
3
+ /**
4
+ * Configuration options for the TriCache binary codec.
5
+ */
6
+ export interface CacheCodecOptions {
7
+ /**
8
+ * When true (default), objects with a toJSON() method will have toJSON() invoked.
9
+ * When false (msgpackr 2.1.0+), the object's own internal properties are serialized directly,
10
+ * avoiding accidental HTTP response projections on durable cached state.
11
+ */
12
+ useToJSON?: boolean;
13
+ /**
14
+ * Enable msgpackr record structure extension (default: true).
15
+ * Generates compact record definitions that yield 30-50% smaller encodings for repeated object shapes.
16
+ */
17
+ useRecords?: boolean;
18
+ /**
19
+ * Enable serialization of additional built-in types (Map, Set, TypedArray, Error, RegExp).
20
+ * Default: true.
21
+ */
22
+ moreTypes?: boolean;
23
+ /**
24
+ * Decode MessagePack maps as plain JavaScript objects.
25
+ * Default: true (ensures plain JS objects and standard maps decode to plain objects).
26
+ */
27
+ mapsAsObjects?: boolean;
28
+ }
29
+
30
+ /**
31
+ * CacheCodec wraps msgpackr's Packr/Unpackr to provide unified, high-performance binary
32
+ * serialization across L1 in-memory buffers, L1.5 disk spill, and cold-start snapshots.
33
+ */
34
+ export class CacheCodec {
35
+ private readonly packr: Packr;
36
+
37
+ constructor(options?: CacheCodecOptions) {
38
+ const packrOptions: MsgpackrOptions = {
39
+ useToJSON: options?.useToJSON ?? true,
40
+ useRecords: options?.useRecords ?? true,
41
+ moreTypes: options?.moreTypes ?? true,
42
+ mapsAsObjects: options?.mapsAsObjects ?? true,
43
+ };
44
+ this.packr = new Packr(packrOptions);
45
+ }
46
+
47
+ /**
48
+ * Serializes a JavaScript value to a binary MessagePack Buffer.
49
+ */
50
+ encode(data: unknown): Buffer {
51
+ const packed = this.packr.pack(data);
52
+ return Buffer.isBuffer(packed)
53
+ ? packed
54
+ : Buffer.from((packed as Uint8Array).buffer, (packed as Uint8Array).byteOffset, (packed as Uint8Array).byteLength);
55
+ }
56
+
57
+ /**
58
+ * Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
59
+ */
60
+ decode<T = unknown>(data: Buffer | Uint8Array): T {
61
+ return this.packr.unpack(data) as T;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Default singleton codec configured for high-speed packing, record deduplication, and rich types.
67
+ */
68
+ export const defaultCodec = new CacheCodec({
69
+ useToJSON: true,
70
+ useRecords: true,
71
+ moreTypes: true,
72
+ });
@@ -1,63 +1,56 @@
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
- }
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
+ // 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; } };
37
+
38
+ const result = algorithm === 'gzip' ? (tryGzip() ?? tryBrotli()) : (tryBrotli() ?? tryGzip());
39
+ if (result === null) {
40
+ throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
41
+ }
42
+ return result;
43
+ }
44
+
45
+ export function compressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm): Buffer {
46
+ if (algorithm === 'none') return buf;
47
+ const compressed = compressBuffer(buf, algorithm);
48
+ return Buffer.concat([COMPRESSION_MAGIC, compressed]);
49
+ }
50
+
51
+ export function decompressWithHeader(buf: Buffer, algorithm: CompressionAlgorithm = 'brotli'): Buffer {
52
+ if (isCompressed(buf)) {
53
+ return decompressBuffer(buf.subarray(4), algorithm);
54
+ }
55
+ return buf;
56
+ }