Repository navigation
Expand file tree
/
Copy pathcli.ts
More file actions
278 lines (250 loc) Β· 11 KB
/
Copy pathcli.ts
File metadata and controls
278 lines (250 loc) Β· 11 KB
1
2
3
4
5
6
7
8
9
10
11
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
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
* TriCache CLI β Developer & Troubleshooting Inspector
*
* Usage:
* npx tricache top [--socket <path>] [--pid <pid>] [--interval <ms>] [--once]
* npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
* npx tricache ping [--redis redis://localhost:6379]
* npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
*/
import { readFileSync } from 'node:fs';
import { parseArgs } from 'node:util';
import { CacheService } from './cache-service.js';
import {
IpcTelemetryClient,
resolveIpcSocketPath,
findActiveSockets,
renderTopDashboard,
} from './ipc-telemetry.js';
export async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {
const options = {
redis: { type: 'string' as const, short: 'r' },
port: { type: 'string' as const, short: 'p' },
namespace: { type: 'string' as const, short: 'n' },
prefix: { type: 'string' as const },
disk: { type: 'string' as const, short: 'd' },
pid: { type: 'string' as const },
socket: { type: 'string' as const, short: 's' },
interval: { type: 'string' as const, short: 'i' },
once: { type: 'boolean' as const },
json: { type: 'boolean' as const },
help: { type: 'boolean' as const, short: 'h' },
version: { type: 'boolean' as const, short: 'v' },
};
let parsed;
try {
parsed = parseArgs({
args,
options,
allowPositionals: true,
strict: false,
});
} catch (err) {
console.error(`Error: ${(err as Error).message}\n`);
printHelp();
process.exit(1);
}
const { values, positionals } = parsed;
const command = positionals[0] || 'inspect';
if (values.help || command === 'help') {
printHelp();
return;
}
// NOTE: console.log is INTENTIONAL across cli.ts β this file is the terminal CLI runner
// (bin/tricache.js). Output must go directly to process stdout without logger prefixes
// to support UNIX pipes, terminal formatting, and automated tooling.
if (values.version || command === 'version') {
let version = '1.0.0';
try {
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
if (pkg?.version) version = pkg.version;
} catch {
// fallback to default version
}
console.log(`tricache v${version}`);
return;
}
// Handle 'top' monitor command directly without constructing a local CacheService
if (command === 'top') {
let targetSocket = typeof values.socket === 'string' ? values.socket : undefined;
if (!targetSocket && typeof values.pid === 'string') {
targetSocket = resolveIpcSocketPath(values.pid);
}
if (!targetSocket) {
const active = await findActiveSockets();
if (active.length > 0) {
targetSocket = active[0];
}
}
if (!targetSocket) {
console.error('No active TriCache instances found to monitor.\n');
console.error('To use `tricache top`:');
console.error(' 1. Ensure your running application enables IPC telemetry:');
console.error(" const cache = new CacheService({ namespace: 'my-app', enableIpc: true, ... });\n");
console.error(' 2. If the application is already running, specify its PID or socket:');
console.error(' npx tricache top --pid <pid>');
console.error(' npx tricache top --socket <path>\n');
process.exit(1);
}
const client = new IpcTelemetryClient(targetSocket);
const intervalMs = typeof values.interval === 'string'
? Math.max(200, parseInt(values.interval, 10))
: 1000;
const isOnce = Boolean(values.once || !process.stdout.isTTY);
const asJson = Boolean(values.json);
if (isOnce) {
try {
const payload = await client.getMetrics();
if (asJson) {
console.log(JSON.stringify(payload, null, 2));
} else {
console.log(renderTopDashboard(payload));
}
return;
} catch (err) {
console.error(`Failed to connect to TriCache IPC at ${targetSocket}: ${(err as Error).message}`);
process.exit(1);
}
}
// Interactive TTY mode: switch to alternate screen buffer and hide cursor
process.stdout.write('\x1b[?1049h\x1b[?25l');
let activeInterval: NodeJS.Timeout | null = null;
let cleaningUp = false;
const cleanup = () => {
if (cleaningUp) return;
cleaningUp = true;
if (activeInterval) clearInterval(activeInterval);
if (process.stdout.isTTY) {
process.stdout.write('\x1b[?25h\x1b[?1049l');
}
if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
try {
process.stdin.setRawMode(false);
process.stdin.pause();
} catch {
// Ignore TTY reset errors
}
}
process.exit(0);
};
process.once('SIGINT', cleanup);
process.once('SIGTERM', cleanup);
if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
try {
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', (key: string) => {
if (key === 'q' || key === 'Q' || key === '\u0003') {
cleanup();
}
});
} catch {
// Raw mode not supported
}
}
const tick = async () => {
try {
const payload = await client.getMetrics();
const screen = renderTopDashboard(payload);
process.stdout.write('\x1b[H' + screen + '\n Press "q" or Ctrl+C to exit\n');
} catch (err) {
process.stdout.write(`\x1b[HConnecting to ${targetSocket}...\nError: ${(err as Error).message}\n\nWaiting for TriCache IPC server. Ensure the target process is running with enableIpc: true.\nPress "q" or Ctrl+C to exit\n`);
}
};
await tick();
activeInterval = setInterval(tick, intervalMs);
// Keep process alive in interactive loop until exit
await new Promise<void>(() => {});
return;
}
const redisStr = typeof values.redis === 'string' ? values.redis : undefined;
const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, '').split(':')[0] : undefined;
const redisPort = typeof values.port === 'string'
? parseInt(values.port, 10)
: (redisStr && redisStr.includes(':') ? parseInt(redisStr.split(':')[1], 10) : 6379);
const namespace = typeof values.namespace === 'string' ? values.namespace : undefined;
const diskCacheDir = typeof values.disk === 'string' ? values.disk : undefined;
const cache = new CacheService({
redisHost,
redisPort,
namespace,
diskCacheDir,
disableRedis: !redisHost,
});
try {
if (command === 'inspect') {
const ping = await cache.ping();
const metrics = cache.metrics();
const stats = cache.stats();
const hot = cache.hotKeys(5);
const divPct = (n: number) => `${(n * 100).toFixed(1)}%`;
const l1MaxKB = Math.round((cache.options.l1MaxBytes ?? 200 * 1024 * 1024) / 1024);
console.log(`
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TriCache Engine Dashboard (Namespace: ${namespace || '(default)'})
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Tiers Active: L1 (RAM) β L1.5 (NVMe Disk) β L2 (${redisHost ? 'Redis' : 'Disabled'})
β Latencies: L1: ${ping.l1}ms | Disk: ${ping.disk}ms | L2: ${ping.l2 !== null ? `${ping.l2}ms` : 'N/A'}
β L1 Entries: ${stats.l1.entries} (${stats.l1.sizeKB} KB / ${l1MaxKB} KB)
β Disk Files: ${stats.disk.files} (${stats.disk.sizeKB} KB / ${stats.disk.maxKB} KB)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β L1 Hit Ratio: ${divPct(metrics.gets.l1HitRate)} (${metrics.gets.l1Hits} hits)
β L2 Hit Ratio: ${divPct(metrics.gets.l2HitRate)} (${metrics.gets.l2Hits} hits)
β Disk Hit Ratio: ${divPct(metrics.gets.diskHitRate)} (${metrics.gets.diskHits} hits)
β Stampedes Saved: ${metrics.gets.stampedePrevented} coalesced requests
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β π₯ Top Hot Keys (Count-Min Sketch):`);
if (hot.length === 0) {
console.log('β (no hot keys recorded yet)');
} else {
hot.forEach(({ key, hits, sizeBytes }, idx) => {
const size = sizeBytes > 1024 ? `${(sizeBytes / 1024).toFixed(1)} KB` : `${sizeBytes} B`;
console.log(`β ${idx + 1}. ${key.padEnd(24)} (${hits} hits, ${size})`);
});
}
console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
} else if (command === 'ping') {
const ping = await cache.ping();
console.log(`TriCache Ping Results:`);
console.log(` β’ L1 RAM: ${ping.l1}ms`);
console.log(` β’ Disk: ${ping.disk}ms`);
console.log(` β’ L2 Redis:${ping.l2 !== null ? ` ${ping.l2}ms` : ' Disabled'}`);
} else if (command === 'clear') {
const prefix = typeof values.prefix === 'string' ? values.prefix : undefined;
await cache.clear(prefix);
console.log(`Cleared cache${prefix ? ` for prefix "${prefix}"` : ' (all entries)'} in namespace "${namespace || '(default)'}".`);
} else {
console.error(`Unknown command: ${command}\n`);
printHelp();
process.exit(1);
}
} finally {
await cache.destroy();
}
}
function printHelp(): void {
console.log(`
TriCache CLI β Developer & Troubleshooting Tool
Usage:
tricache <command> [options]
Commands:
top Live ASCII terminal dashboard monitoring an active TriCache process
inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
clear Flush all entries or keys matching a prefix
Options:
-s, --socket <path> IPC socket path or Windows named pipe
--pid <pid> Process ID of the target TriCache process to monitor
-i, --interval <ms> Refresh interval in milliseconds for top (default: 1000)
--once Output single snapshot and exit (non-interactive)
--json Format output as raw JSON
-r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
-p, --port <port> Redis port (default: 6379)
-n, --namespace <ns> Cache namespace
--prefix <prefix> Key prefix filter for clear command
-d, --disk <path> Custom disk cache directory path
-h, --help Show this help message
-v, --version Display version number
`);
}