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.
- package/LICENSE +21 -21
- package/README.md +144 -1428
- package/bin/tricache.js +8 -8
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2894 -518
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2648 -508
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +3038 -589
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +238 -62
- package/dist/index.cjs +6962 -2487
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2586 -498
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2633 -519
- package/dist/next/index.d.ts +13 -7
- package/dist/next/index.js +45 -18
- package/dist/prisma/index.cjs +2 -1
- package/dist/prisma/index.d.ts +3 -1
- package/dist/prisma/index.js +2 -1
- package/dist/serialize-worker.cjs +31 -19
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
- package/package.json +37 -7
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +4231 -3226
- package/src/cli.ts +261 -143
- package/src/codec.ts +72 -0
- package/src/compression.ts +56 -63
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +1223 -821
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +203 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +635 -493
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +46 -223
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +271 -244
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/prisma/index.ts +154 -151
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +1109 -1024
- package/src/types.ts +1199 -902
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-AJASH5FX.js +0 -7
- 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
|
|
6
|
-
* npx tricache
|
|
7
|
-
* npx tricache
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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
|
+
});
|
package/src/compression.ts
CHANGED
|
@@ -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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
return
|
|
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
|
+
}
|