tricache 0.7.1 → 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 (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
package/src/index.ts CHANGED
@@ -1,47 +1,149 @@
1
- /**
2
- * tricache — three-tier cache for Node.js
3
- *
4
- * L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
5
- *
6
- * Quick start:
7
- * import { CacheService, CachePriority } from 'tricache';
8
- *
9
- * const cache = CacheService.create({ redisHost: 'localhost' });
10
- *
11
- * const user = await cache.get(
12
- * `user:${userId}`,
13
- * () => db.users.findById(userId),
14
- * 300, // 5-minute TTL
15
- * );
16
- *
17
- * await cache.delete(`user:${userId}`);
18
- */
19
-
20
- export { CacheService } from './cache-service';
21
- export { CacheEncryption, type EncryptionMode } from './encryption';
22
- export { SmartMemoryCache } from './smart-memory-cache';
23
- export { DiskTier } from './disk-tier';
24
- export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
25
- export { type CompressionAlgorithm } from './compression';
26
-
27
- export {
28
- CachePriority,
29
- consoleLogger,
30
- type ILogger,
31
- type CacheOptions,
32
- type CacheMetrics,
33
- type CategoryLimit,
34
- type SmartCacheEntry,
35
- type DiskCacheEntry,
36
- type CacheHit,
37
- type EvictionReason,
38
- type CachePingResult,
39
- type ICacheTracer,
40
- type ICacheSpan,
41
- type WrapOptions,
42
- type LockOptions,
43
- type ICacheCounter,
44
- type ICacheObservableGauge,
45
- type ICacheBatchObservableCallback,
46
- type ICacheMeter,
47
- } from './types';
1
+ /**
2
+ * tricache — three-tier cache for Node.js
3
+ *
4
+ * L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
5
+ *
6
+ * Quick start:
7
+ * import { CacheService, CachePriority } from 'tricache';
8
+ *
9
+ * const cache = CacheService.create({ redisHost: 'localhost' });
10
+ *
11
+ * const user = await cache.get(
12
+ * `user:${userId}`,
13
+ * () => db.users.findById(userId),
14
+ * 300, // 5-minute TTL
15
+ * );
16
+ *
17
+ * await cache.delete(`user:${userId}`);
18
+ */
19
+
20
+ export { CacheService, ProcessTerminationBus, deepMergeOptions } from './cache-service';
21
+ export {
22
+ CacheEncryption,
23
+ EnvelopeEncryption,
24
+ type EncryptionMode,
25
+ type EnvelopeEncryptionOptions,
26
+ } from './encryption';
27
+ export { SmartMemoryCache } from './smart-memory-cache';
28
+ export {
29
+ WTinyLfuCache,
30
+ WTinyLfuPolicy,
31
+ TinyLfuSketch,
32
+ type WTinyLfuOptions,
33
+ type WTinyLfuStats,
34
+ type EvictionResult,
35
+ } from './wtiny-lfu';
36
+ export { DiskTier, resolveDefaultDiskDir } from './disk-tier';
37
+ export { TierLatencyWatchdog, type LatencyWatchdogOptions, type LatencyWatchdogTelemetry } from './latency-watchdog';
38
+ export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
39
+ export { type CompressionAlgorithm } from './compression';
40
+ export { CacheCodec, defaultCodec, type CacheCodecOptions } from './codec';
41
+ export {
42
+ createHttpSnapshotAdapter,
43
+ createCustomSnapshotAdapter,
44
+ createMemorySnapshotAdapter,
45
+ createSigV4SnapshotAdapter,
46
+ createS3SnapshotAdapter,
47
+ createR2SnapshotAdapter,
48
+ SigV4SnapshotAdapter,
49
+ type IRemoteSnapshotAdapter,
50
+ type RemoteSnapshotOptions,
51
+ type HttpSnapshotAdapterOptions,
52
+ type SigV4SnapshotAdapterOptions,
53
+ } from './remote-snapshot';
54
+ export {
55
+ createHttpMeshRelay,
56
+ createCustomCrossRegionRelay,
57
+ createMemoryCrossRegionRelay,
58
+ createCrossRegionWebhookHandler,
59
+ type CrossRegionInvalidationEvent,
60
+ type ICrossRegionRelay,
61
+ type CrossRegionRelayOptions,
62
+ type HttpMeshRelayOptions,
63
+ type WebhookRequestLike,
64
+ type WebhookResponseLike,
65
+ } from './cross-region';
66
+
67
+ export {
68
+ NodeRedisAdapter,
69
+ createNodeRedisAdapter,
70
+ type IRedisDriver,
71
+ type IRedisPipeline,
72
+ } from './adapters/node-redis';
73
+
74
+ export {
75
+ AutoPipeliner,
76
+ type AutoPipelinerOptions,
77
+ } from './adapters/auto-pipeliner';
78
+
79
+ export {
80
+ resolveAutonomousL1MaxBytes,
81
+ readCgroupMemoryLimit,
82
+ getV8HeapLimit,
83
+ type AutonomousL1Options,
84
+ DEFAULT_AUTONOMOUS_L1_CEILING_BYTES,
85
+ MIN_AUTONOMOUS_L1_FLOOR_BYTES,
86
+ } from './utils/cgroup';
87
+
88
+ export {
89
+ Murmur3BloomFilter,
90
+ murmur3_32,
91
+ type BloomFilterStats,
92
+ } from './edge/utils/murmur3';
93
+
94
+ export {
95
+ CachePriority,
96
+ consoleLogger,
97
+ type ILogger,
98
+ type CachePresetType,
99
+ type CacheOptions,
100
+ type CacheMetrics,
101
+ type CategoryLimit,
102
+ type SmartCacheEntry,
103
+ type DiskCacheEntry,
104
+ type CacheHit,
105
+ type EvictionReason,
106
+ type CachePingResult,
107
+ type ICacheTracer,
108
+ type ICacheSpan,
109
+ type ICacheSpanLink,
110
+ type WrapOptions,
111
+ type LockOptions,
112
+ type ICacheCounter,
113
+ type ICacheObservableGauge,
114
+ type ICacheBatchObservableCallback,
115
+ type ICacheMeter,
116
+ type CacheHealthStatus,
117
+ } from './types';
118
+
119
+ export {
120
+ parseTraceParent,
121
+ formatTraceParent,
122
+ type ParsedTraceParent,
123
+ } from './utils/tracing';
124
+
125
+ export {
126
+ tricacheDashboard,
127
+ createNextDashboardHandlers,
128
+ startDashboardServer,
129
+ handleDashboardRequest,
130
+ type DashboardOptions,
131
+ type StandaloneDashboardOptions,
132
+ type DashboardPeerInstance,
133
+ type DashboardActionEvent,
134
+ } from './dashboard/index';
135
+
136
+ export {
137
+ IpcTelemetryServer,
138
+ IpcTelemetryClient,
139
+ resolveIpcSocketPath,
140
+ findActiveSockets,
141
+ renderTopDashboard,
142
+ renderProgressBar,
143
+ formatBytes,
144
+ formatDuration,
145
+ formatNumber,
146
+ type IpcMetricsPayload,
147
+ type IIpcCacheProvider,
148
+ } from './ipc-telemetry';
149
+
@@ -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
+ }