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
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import type { CacheMetrics, CacheHealthStatus, CacheOptions } from './types.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Platform-agnostic IPC socket / named pipe path resolver.
|
|
8
|
+
* - POSIX: `/tmp/tricache-<id>.sock` (or `$TMPDIR/tricache-<id>.sock`)
|
|
9
|
+
* - Windows: `\\.\pipe\tricache-<id>`
|
|
10
|
+
*/
|
|
11
|
+
export function resolveIpcSocketPath(id: string | number = process.pid): string {
|
|
12
|
+
if (process.platform === 'win32') {
|
|
13
|
+
return `\\\\.\\pipe\\tricache-${id}`;
|
|
14
|
+
}
|
|
15
|
+
const dir = process.env.TMPDIR || '/tmp';
|
|
16
|
+
return path.join(dir, `tricache-${id}.sock`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Cache provider interface required by the IPC telemetry server.
|
|
21
|
+
*/
|
|
22
|
+
export interface IIpcCacheProvider {
|
|
23
|
+
options?: CacheOptions;
|
|
24
|
+
metrics(): CacheMetrics;
|
|
25
|
+
stats?(): {
|
|
26
|
+
l1: Record<string, unknown>;
|
|
27
|
+
disk: Record<string, unknown>;
|
|
28
|
+
};
|
|
29
|
+
hotKeys?(n?: number): Array<{ key: string; hits: number; sizeBytes: number }>;
|
|
30
|
+
health?(): CacheHealthStatus;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Serialized telemetry payload transferred across the IPC bridge.
|
|
35
|
+
*/
|
|
36
|
+
export interface IpcMetricsPayload {
|
|
37
|
+
pid: number;
|
|
38
|
+
uptimeMs: number;
|
|
39
|
+
timestamp: number;
|
|
40
|
+
namespace?: string;
|
|
41
|
+
l1MaxBytes?: number;
|
|
42
|
+
metrics: CacheMetrics;
|
|
43
|
+
stats?: {
|
|
44
|
+
l1: Record<string, unknown>;
|
|
45
|
+
disk: Record<string, unknown>;
|
|
46
|
+
};
|
|
47
|
+
hotKeys?: Array<{ key: string; hits: number; sizeBytes: number }>;
|
|
48
|
+
health?: CacheHealthStatus;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Lightweight, non-blocking IPC Telemetry Server.
|
|
53
|
+
* Exposes real-time cache metrics over Unix domain sockets (POSIX) or Named Pipes (Windows).
|
|
54
|
+
*/
|
|
55
|
+
export class IpcTelemetryServer {
|
|
56
|
+
private server: net.Server | null = null;
|
|
57
|
+
public readonly socketPath: string;
|
|
58
|
+
private _closed = false;
|
|
59
|
+
private _exitHandler: (() => void) | null = null;
|
|
60
|
+
private _sigintHandler: (() => void) | null = null;
|
|
61
|
+
private _sigtermHandler: (() => void) | null = null;
|
|
62
|
+
|
|
63
|
+
constructor(
|
|
64
|
+
private readonly cache: IIpcCacheProvider,
|
|
65
|
+
customSocketPath?: string,
|
|
66
|
+
) {
|
|
67
|
+
this.socketPath = customSocketPath || resolveIpcSocketPath();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Start listening on the IPC socket / pipe.
|
|
72
|
+
*/
|
|
73
|
+
async start(): Promise<void> {
|
|
74
|
+
if (this.server && this.server.listening) return;
|
|
75
|
+
|
|
76
|
+
// Hygiene on POSIX: check if an orphaned socket file exists from a crashed run
|
|
77
|
+
if (process.platform !== 'win32' && fs.existsSync(this.socketPath)) {
|
|
78
|
+
await new Promise<void>((resolve) => {
|
|
79
|
+
const testSocket = net.createConnection(this.socketPath);
|
|
80
|
+
testSocket.once('connect', () => {
|
|
81
|
+
testSocket.destroy();
|
|
82
|
+
// Active server already listening on this socket
|
|
83
|
+
resolve();
|
|
84
|
+
});
|
|
85
|
+
testSocket.once('error', () => {
|
|
86
|
+
testSocket.destroy();
|
|
87
|
+
// Stale socket file: safe to unlink
|
|
88
|
+
try {
|
|
89
|
+
fs.unlinkSync(this.socketPath);
|
|
90
|
+
} catch {
|
|
91
|
+
// Ignore unlink errors
|
|
92
|
+
}
|
|
93
|
+
resolve();
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
this.server = net.createServer((socket) => {
|
|
99
|
+
let buffer = '';
|
|
100
|
+
|
|
101
|
+
socket.on('data', (chunk) => {
|
|
102
|
+
buffer += chunk.toString('utf8');
|
|
103
|
+
let newlineIndex: number;
|
|
104
|
+
while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
|
|
105
|
+
const line = buffer.slice(0, newlineIndex).trim();
|
|
106
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
107
|
+
if (!line) continue;
|
|
108
|
+
|
|
109
|
+
// Non-blocking telemetry pull: pull stats snapshot on tick boundaries
|
|
110
|
+
// using setImmediate so serialization never introduces event loop stalls.
|
|
111
|
+
setImmediate(() => {
|
|
112
|
+
if (socket.destroyed) return;
|
|
113
|
+
try {
|
|
114
|
+
let cmd = line;
|
|
115
|
+
try {
|
|
116
|
+
const parsed = JSON.parse(line);
|
|
117
|
+
if (parsed && typeof parsed.cmd === 'string') {
|
|
118
|
+
cmd = parsed.cmd;
|
|
119
|
+
}
|
|
120
|
+
} catch {
|
|
121
|
+
// Keep raw line as command
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (cmd === 'PING') {
|
|
125
|
+
socket.write(JSON.stringify({ pong: true, timestamp: Date.now() }) + '\n');
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (cmd === 'GET_METRICS' || cmd === 'INSPECT') {
|
|
130
|
+
const payload = this.getSnapshot();
|
|
131
|
+
const serialized = JSON.stringify(payload) + '\n';
|
|
132
|
+
socket.write(serialized);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
socket.write(JSON.stringify({ error: `Unknown command: ${cmd}` }) + '\n');
|
|
137
|
+
} catch (err) {
|
|
138
|
+
if (!socket.destroyed) {
|
|
139
|
+
socket.write(JSON.stringify({ error: (err as Error).message }) + '\n');
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
socket.on('error', () => {
|
|
147
|
+
// Suppress client disconnection errors on IPC socket
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
await new Promise<void>((resolve, reject) => {
|
|
152
|
+
this.server!.once('error', reject);
|
|
153
|
+
this.server!.listen(this.socketPath, () => {
|
|
154
|
+
this.server!.removeListener('error', reject);
|
|
155
|
+
resolve();
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// Register process termination handlers to guarantee socket hygiene
|
|
160
|
+
this._exitHandler = () => this._unlinkSocket();
|
|
161
|
+
this._sigintHandler = () => {
|
|
162
|
+
this._unlinkSocket();
|
|
163
|
+
process.exit(0);
|
|
164
|
+
};
|
|
165
|
+
this._sigtermHandler = () => {
|
|
166
|
+
this._unlinkSocket();
|
|
167
|
+
process.exit(0);
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
process.once('exit', this._exitHandler);
|
|
171
|
+
process.once('SIGINT', this._sigintHandler);
|
|
172
|
+
process.once('SIGTERM', this._sigtermHandler);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Build a complete telemetry snapshot from the underlying cache provider.
|
|
177
|
+
*/
|
|
178
|
+
getSnapshot(): IpcMetricsPayload {
|
|
179
|
+
const metrics = this.cache.metrics();
|
|
180
|
+
const stats = typeof this.cache.stats === 'function' ? this.cache.stats() : undefined;
|
|
181
|
+
const hotKeys = typeof this.cache.hotKeys === 'function' ? this.cache.hotKeys(10) : undefined;
|
|
182
|
+
const health = typeof this.cache.health === 'function' ? this.cache.health() : undefined;
|
|
183
|
+
const l1MaxBytes = (this.cache.options?.l1MaxBytes as number | undefined) ?? metrics.l1?.maxBytes;
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
pid: process.pid,
|
|
187
|
+
uptimeMs: metrics.uptimeMs,
|
|
188
|
+
timestamp: Date.now(),
|
|
189
|
+
namespace: this.cache.options?.namespace || metrics.namespace,
|
|
190
|
+
l1MaxBytes,
|
|
191
|
+
metrics,
|
|
192
|
+
stats,
|
|
193
|
+
hotKeys,
|
|
194
|
+
health,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private _unlinkSocket(): void {
|
|
199
|
+
if (this._closed) return;
|
|
200
|
+
this._closed = true;
|
|
201
|
+
try {
|
|
202
|
+
this.server?.close();
|
|
203
|
+
} catch {
|
|
204
|
+
// Ignore close errors
|
|
205
|
+
}
|
|
206
|
+
if (process.platform !== 'win32') {
|
|
207
|
+
try {
|
|
208
|
+
if (fs.existsSync(this.socketPath)) {
|
|
209
|
+
fs.unlinkSync(this.socketPath);
|
|
210
|
+
}
|
|
211
|
+
} catch {
|
|
212
|
+
// Ignore unlink errors during teardown
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
219
|
+
*/
|
|
220
|
+
async close(): Promise<void> {
|
|
221
|
+
if (this._exitHandler) {
|
|
222
|
+
process.removeListener('exit', this._exitHandler);
|
|
223
|
+
this._exitHandler = null;
|
|
224
|
+
}
|
|
225
|
+
if (this._sigintHandler) {
|
|
226
|
+
process.removeListener('SIGINT', this._sigintHandler);
|
|
227
|
+
this._sigintHandler = null;
|
|
228
|
+
}
|
|
229
|
+
if (this._sigtermHandler) {
|
|
230
|
+
process.removeListener('SIGTERM', this._sigtermHandler);
|
|
231
|
+
this._sigtermHandler = null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
this._unlinkSocket();
|
|
235
|
+
|
|
236
|
+
return new Promise<void>((resolve) => {
|
|
237
|
+
if (!this.server || !this.server.listening) {
|
|
238
|
+
resolve();
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
this.server.close(() => resolve());
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
get isListening(): boolean {
|
|
246
|
+
return Boolean(this.server && this.server.listening);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* IPC Telemetry Client for connecting to and querying a running TriCache instance.
|
|
252
|
+
*/
|
|
253
|
+
export class IpcTelemetryClient {
|
|
254
|
+
public readonly socketPath: string;
|
|
255
|
+
|
|
256
|
+
constructor(socketPath?: string) {
|
|
257
|
+
this.socketPath = socketPath || resolveIpcSocketPath();
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Fetch a live metrics snapshot from the IPC server.
|
|
262
|
+
*/
|
|
263
|
+
async getMetrics(timeoutMs = 3000): Promise<IpcMetricsPayload> {
|
|
264
|
+
return new Promise((resolve, reject) => {
|
|
265
|
+
const socket = net.createConnection(this.socketPath);
|
|
266
|
+
let buffer = '';
|
|
267
|
+
let timer: NodeJS.Timeout | null = setTimeout(() => {
|
|
268
|
+
socket.destroy();
|
|
269
|
+
reject(new Error(`IPC connection timeout (${timeoutMs}ms) to ${this.socketPath}`));
|
|
270
|
+
}, timeoutMs);
|
|
271
|
+
|
|
272
|
+
socket.once('connect', () => {
|
|
273
|
+
socket.write('GET_METRICS\n');
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
socket.on('data', (chunk) => {
|
|
277
|
+
buffer += chunk.toString('utf8');
|
|
278
|
+
const newlineIdx = buffer.indexOf('\n');
|
|
279
|
+
if (newlineIdx !== -1) {
|
|
280
|
+
if (timer) {
|
|
281
|
+
clearTimeout(timer);
|
|
282
|
+
timer = null;
|
|
283
|
+
}
|
|
284
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
285
|
+
socket.end();
|
|
286
|
+
try {
|
|
287
|
+
const data = JSON.parse(line);
|
|
288
|
+
if (data.error) {
|
|
289
|
+
reject(new Error(data.error));
|
|
290
|
+
} else {
|
|
291
|
+
resolve(data as IpcMetricsPayload);
|
|
292
|
+
}
|
|
293
|
+
} catch (e) {
|
|
294
|
+
reject(new Error(`Failed to parse IPC payload: ${(e as Error).message}`));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
socket.once('error', (err) => {
|
|
300
|
+
if (timer) {
|
|
301
|
+
clearTimeout(timer);
|
|
302
|
+
timer = null;
|
|
303
|
+
}
|
|
304
|
+
reject(err);
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Send a ping over the IPC bridge and measure round-trip latency.
|
|
311
|
+
*/
|
|
312
|
+
async ping(timeoutMs = 1000): Promise<number> {
|
|
313
|
+
const start = Date.now();
|
|
314
|
+
return new Promise((resolve, reject) => {
|
|
315
|
+
const socket = net.createConnection(this.socketPath);
|
|
316
|
+
let timer: NodeJS.Timeout | null = setTimeout(() => {
|
|
317
|
+
socket.destroy();
|
|
318
|
+
reject(new Error(`IPC ping timeout (${timeoutMs}ms)`));
|
|
319
|
+
}, timeoutMs);
|
|
320
|
+
|
|
321
|
+
socket.once('connect', () => {
|
|
322
|
+
socket.write('PING\n');
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
socket.on('data', () => {
|
|
326
|
+
if (timer) {
|
|
327
|
+
clearTimeout(timer);
|
|
328
|
+
timer = null;
|
|
329
|
+
}
|
|
330
|
+
socket.end();
|
|
331
|
+
resolve(Date.now() - start);
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
socket.once('error', (err) => {
|
|
335
|
+
if (timer) {
|
|
336
|
+
clearTimeout(timer);
|
|
337
|
+
timer = null;
|
|
338
|
+
}
|
|
339
|
+
reject(err);
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Probe local system for active TriCache IPC sockets.
|
|
347
|
+
*/
|
|
348
|
+
export async function findActiveSockets(): Promise<string[]> {
|
|
349
|
+
const active: string[] = [];
|
|
350
|
+
|
|
351
|
+
if (process.platform === 'win32') {
|
|
352
|
+
const currentPipe = resolveIpcSocketPath(process.pid);
|
|
353
|
+
const client = new IpcTelemetryClient(currentPipe);
|
|
354
|
+
try {
|
|
355
|
+
await client.ping(100);
|
|
356
|
+
active.push(currentPipe);
|
|
357
|
+
} catch {
|
|
358
|
+
// Pipe not present or not active
|
|
359
|
+
}
|
|
360
|
+
return active;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const dir = process.env.TMPDIR || '/tmp';
|
|
364
|
+
try {
|
|
365
|
+
if (!fs.existsSync(dir)) return active;
|
|
366
|
+
const entries = fs.readdirSync(dir);
|
|
367
|
+
const candidates = entries
|
|
368
|
+
.filter((name) => name.startsWith('tricache-') && name.endsWith('.sock'))
|
|
369
|
+
.map((name) => path.join(dir, name));
|
|
370
|
+
|
|
371
|
+
await Promise.all(
|
|
372
|
+
candidates.map(async (sockPath) => {
|
|
373
|
+
const client = new IpcTelemetryClient(sockPath);
|
|
374
|
+
try {
|
|
375
|
+
await client.ping(100);
|
|
376
|
+
active.push(sockPath);
|
|
377
|
+
} catch {
|
|
378
|
+
// Stale socket
|
|
379
|
+
}
|
|
380
|
+
}),
|
|
381
|
+
);
|
|
382
|
+
} catch {
|
|
383
|
+
// Directory scan error
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
return active;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// ── Rendering Utilities for CLI Top ──────────────────────────────────────────
|
|
390
|
+
|
|
391
|
+
export function renderProgressBar(ratio: number, width = 18): string {
|
|
392
|
+
const clamped = Math.max(0, Math.min(1, isNaN(ratio) ? 0 : ratio));
|
|
393
|
+
const filled = Math.round(clamped * width);
|
|
394
|
+
const empty = width - filled;
|
|
395
|
+
return '█'.repeat(filled) + '░'.repeat(empty);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export function formatBytes(bytes: number): string {
|
|
399
|
+
if (!bytes || isNaN(bytes) || bytes < 0) return '0 B';
|
|
400
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
401
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
402
|
+
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
403
|
+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export function formatNumber(n: number): string {
|
|
407
|
+
return (n ?? 0).toLocaleString();
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export function formatDuration(ms: number): string {
|
|
411
|
+
if (ms < 1000) return `${ms}ms`;
|
|
412
|
+
const s = Math.floor(ms / 1000);
|
|
413
|
+
if (s < 60) return `${s}s`;
|
|
414
|
+
const m = Math.floor(s / 60);
|
|
415
|
+
const remS = s % 60;
|
|
416
|
+
if (m < 60) return `${m}m ${remS}s`;
|
|
417
|
+
const h = Math.floor(m / 60);
|
|
418
|
+
const remM = m % 60;
|
|
419
|
+
return `${h}h ${remM}m`;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Render an ANSI/ASCII dashboard representation of the cache metrics.
|
|
424
|
+
*/
|
|
425
|
+
export function renderTopDashboard(payload: IpcMetricsPayload): string {
|
|
426
|
+
const m = payload.metrics;
|
|
427
|
+
const gets = m.gets;
|
|
428
|
+
const l1Max = payload.l1MaxBytes || 200 * 1024 * 1024;
|
|
429
|
+
const l1Used = m.l1.sizeBytes;
|
|
430
|
+
const l1Pct = l1Max > 0 ? l1Used / l1Max : 0;
|
|
431
|
+
const uptime = formatDuration(payload.uptimeMs);
|
|
432
|
+
const ns = payload.namespace || '(default)';
|
|
433
|
+
const pct = (r: number) => `${((r || 0) * 100).toFixed(1)}%`;
|
|
434
|
+
|
|
435
|
+
const lines: string[] = [];
|
|
436
|
+
lines.push('╔══════════════════════════════════════════════════════════════════════════════════════╗');
|
|
437
|
+
lines.push(`║ TriCache Monitor [PID: ${String(payload.pid).padEnd(6)}] Uptime: ${uptime.padEnd(8)} Namespace: ${ns.padEnd(16)}║`);
|
|
438
|
+
lines.push('╠══════════════════════════════════════════════════════════════════════════════════════╣');
|
|
439
|
+
lines.push(`║ Hit Ratios & Tier Breakdown (Total Gets: ${formatNumber(gets.total).padEnd(12)}) ║`);
|
|
440
|
+
lines.push(`║ L1 (RAM): [${renderProgressBar(gets.l1HitRate)}] ${pct(gets.l1HitRate).padStart(6)} (${formatNumber(gets.l1Hits).padStart(8)} hits) ║`);
|
|
441
|
+
lines.push(`║ L1.5(Disk): [${renderProgressBar(gets.diskHitRate)}] ${pct(gets.diskHitRate).padStart(6)} (${formatNumber(gets.diskHits).padStart(8)} hits) ║`);
|
|
442
|
+
lines.push(`║ L2 (Redis): [${renderProgressBar(gets.l2HitRate)}] ${pct(gets.l2HitRate).padStart(6)} (${formatNumber(gets.l2Hits).padStart(8)} hits) ║`);
|
|
443
|
+
lines.push(`║ Misses: [${renderProgressBar(gets.fetchRate)}] ${pct(gets.fetchRate).padStart(6)} (${formatNumber(gets.fetches).padStart(8)} fetches) ║`);
|
|
444
|
+
lines.push(`║ Stampedes Saved: ${formatNumber(gets.stampedePrevented).padEnd(8)} coalesced concurrent requests ║`);
|
|
445
|
+
lines.push('╠══════════════════════════════════════════════════════════════════════════════════════╣');
|
|
446
|
+
lines.push(`║ Memory & Storage Headroom ║`);
|
|
447
|
+
lines.push(`║ L1 Memory: [${renderProgressBar(l1Pct)}] ${formatBytes(l1Used).padStart(8)} / ${formatBytes(l1Max).padEnd(8)} (${formatNumber(m.l1.entries).padStart(6)} entries) ║`);
|
|
448
|
+
const diskFiles = m.disk?.files ?? 0;
|
|
449
|
+
const diskKB = m.disk?.sizeKB ?? 0;
|
|
450
|
+
const diskMaxKB = m.disk?.maxKB ?? 0;
|
|
451
|
+
lines.push(`║ Disk Spill: ${formatBytes(diskKB * 1024).padStart(8)} / ${formatBytes(diskMaxKB * 1024).padEnd(8)} (${formatNumber(diskFiles).padStart(6)} files) ║`);
|
|
452
|
+
lines.push('╠══════════════════════════════════════════════════════════════════════════════════════╣');
|
|
453
|
+
lines.push(`║ Protection & Health Diagnostics ║`);
|
|
454
|
+
const watchdog = m.disk?.latencyWatchdog;
|
|
455
|
+
const bypassStage = watchdog ? `Stage ${watchdog.bypassStage} (${watchdog.bypassActive ? 'ACTIVE' : 'Normal'})` : 'Stage 0 (Normal)';
|
|
456
|
+
const cbState = m.l2CircuitBreaker?.state || 'closed';
|
|
457
|
+
lines.push(`║ Watchdog: ${bypassStage.padEnd(20)} L2 Circuit Breaker: ${cbState.padEnd(20)}║`);
|
|
458
|
+
if (watchdog) {
|
|
459
|
+
const diskP95 = `${watchdog.diskP95Ms.toFixed(2)}ms`;
|
|
460
|
+
const redisP95 = `${watchdog.redisP95Ms.toFixed(2)}ms`;
|
|
461
|
+
lines.push(`║ Disk p95: ${diskP95.padEnd(10)} Redis p95: ${redisP95.padEnd(10)} Bypassed: ${formatNumber(watchdog.bypassedTotal).padEnd(16)}║`);
|
|
462
|
+
}
|
|
463
|
+
const oomEvict = m.oom?.evictions ?? 0;
|
|
464
|
+
lines.push(`║ OOM Evictions: ${formatNumber(oomEvict).padEnd(6)} SWR Revalidations: ${formatNumber(m.revalidations?.total ?? 0).padEnd(14)} ║`);
|
|
465
|
+
lines.push('╠══════════════════════════════════════════════════════════════════════════════════════╣');
|
|
466
|
+
lines.push(`║ 🔥 Top Hot Keys (Count-Min Sketch) ║`);
|
|
467
|
+
|
|
468
|
+
if (!payload.hotKeys || payload.hotKeys.length === 0) {
|
|
469
|
+
lines.push('║ (no hot keys recorded yet) ║');
|
|
470
|
+
} else {
|
|
471
|
+
payload.hotKeys.slice(0, 5).forEach(({ key, hits, sizeBytes }, idx) => {
|
|
472
|
+
const displayKey = key.length > 34 ? `${key.slice(0, 31)}...` : key;
|
|
473
|
+
const hitStr = `${formatNumber(hits)} hits`;
|
|
474
|
+
const sizeStr = formatBytes(sizeBytes);
|
|
475
|
+
const row = ` ${idx + 1}. ${displayKey.padEnd(36)} ${hitStr.padStart(14)} (${sizeStr})`;
|
|
476
|
+
lines.push(`║${row.padEnd(86)}║`);
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
lines.push('╚══════════════════════════════════════════════════════════════════════════════════════╝');
|
|
480
|
+
return lines.join('\n');
|
|
481
|
+
}
|