tricache 0.7.1 → 0.9.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 +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -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 +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- 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 +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -2
- package/src/codec.ts +72 -0
- 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 +449 -47
- 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 +284 -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 +127 -5
- package/src/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -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 +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- 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 +91 -8
- package/src/types.ts +315 -2
- 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-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
package/src/disk-tier.ts
CHANGED
|
@@ -17,8 +17,9 @@
|
|
|
17
17
|
import fs from 'fs';
|
|
18
18
|
import path from 'path';
|
|
19
19
|
import crypto from 'crypto';
|
|
20
|
-
import
|
|
21
|
-
import
|
|
20
|
+
import os from 'os';
|
|
21
|
+
import { CacheCodec, defaultCodec } from './codec.js';
|
|
22
|
+
import type { DiskCacheEntry, ILogger, DiskBackpressureStats } from './types.js';
|
|
22
23
|
import type { CacheEncryption } from './encryption.js';
|
|
23
24
|
import {
|
|
24
25
|
compressWithHeader,
|
|
@@ -26,6 +27,117 @@ import {
|
|
|
26
27
|
type CompressionAlgorithm,
|
|
27
28
|
} from './compression.js';
|
|
28
29
|
|
|
30
|
+
export type { DiskBackpressureStats };
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* BoundedDiskQueue — Concurrency-controlled write spooler with circuit breaking.
|
|
34
|
+
*
|
|
35
|
+
* Prevents libuv threadpool (UV_THREADPOOL_SIZE=4) starvation during cloud NVMe / EBS
|
|
36
|
+
* latency spikes (e.g. 450ms multi-tenant throttle) by limiting active async fs operations,
|
|
37
|
+
* bounding in-memory pending queues, and fast-shedding spills via a 3-state circuit breaker
|
|
38
|
+
* (CLOSED -> OPEN -> HALF-OPEN canary).
|
|
39
|
+
*/
|
|
40
|
+
export class BoundedDiskQueue {
|
|
41
|
+
private active = 0;
|
|
42
|
+
private queue: Array<() => void> = [];
|
|
43
|
+
private spillsDropped = 0;
|
|
44
|
+
private consecutiveFailures = 0;
|
|
45
|
+
private circuitState: 'closed' | 'open' | 'half-open' = 'closed';
|
|
46
|
+
private lastStateChangeMonotonic = performance.now();
|
|
47
|
+
|
|
48
|
+
constructor(
|
|
49
|
+
private readonly maxConcurrent: number = Math.min(4, Math.max(1, Math.floor((os?.availableParallelism?.() ?? 4) / 4))),
|
|
50
|
+
private readonly maxPending: number = 512,
|
|
51
|
+
private readonly writeTimeoutMs: number = 500,
|
|
52
|
+
private readonly failureThreshold: number = 5,
|
|
53
|
+
private readonly cooldownMs: number = 5000,
|
|
54
|
+
) {}
|
|
55
|
+
|
|
56
|
+
public async schedule<T>(task: () => Promise<T>): Promise<T | null> {
|
|
57
|
+
const now = performance.now();
|
|
58
|
+
|
|
59
|
+
// Check circuit breaker state
|
|
60
|
+
if (this.circuitState === 'open') {
|
|
61
|
+
if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
|
|
62
|
+
this.circuitState = 'half-open';
|
|
63
|
+
this.lastStateChangeMonotonic = now;
|
|
64
|
+
} else {
|
|
65
|
+
this.spillsDropped++;
|
|
66
|
+
return null; // Fast-drop spill without touching libuv
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (this.circuitState === 'half-open' && this.active > 0) {
|
|
71
|
+
// In half-open mode, only allow 1 canary write
|
|
72
|
+
this.spillsDropped++;
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (this.queue.length >= this.maxPending) {
|
|
77
|
+
this.spillsDropped++;
|
|
78
|
+
return null; // Bounded memory queue: drop spill to preserve main thread
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Wait for slot in concurrency pool
|
|
82
|
+
if (this.active >= this.maxConcurrent) {
|
|
83
|
+
await new Promise<void>((resolve) => this.queue.push(resolve));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
this.active++;
|
|
87
|
+
let timeoutId: NodeJS.Timeout | null = null;
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const result = await Promise.race([
|
|
91
|
+
task(),
|
|
92
|
+
new Promise<never>((_, reject) => {
|
|
93
|
+
timeoutId = setTimeout(
|
|
94
|
+
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
95
|
+
this.writeTimeoutMs,
|
|
96
|
+
);
|
|
97
|
+
}),
|
|
98
|
+
]);
|
|
99
|
+
|
|
100
|
+
// Success: reset breaker
|
|
101
|
+
this.consecutiveFailures = 0;
|
|
102
|
+
if (this.circuitState === 'half-open') {
|
|
103
|
+
this.circuitState = 'closed';
|
|
104
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return result;
|
|
108
|
+
} catch {
|
|
109
|
+
this.consecutiveFailures++;
|
|
110
|
+
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === 'half-open') {
|
|
111
|
+
this.circuitState = 'open';
|
|
112
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
113
|
+
}
|
|
114
|
+
this.spillsDropped++;
|
|
115
|
+
return null;
|
|
116
|
+
} finally {
|
|
117
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
118
|
+
this.active--;
|
|
119
|
+
const next = this.queue.shift();
|
|
120
|
+
if (next) next();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
public getStats(): DiskBackpressureStats {
|
|
125
|
+
return {
|
|
126
|
+
activeWrites: this.active,
|
|
127
|
+
pendingWrites: this.queue.length,
|
|
128
|
+
spillsDropped: this.spillsDropped,
|
|
129
|
+
circuitState: this.circuitState,
|
|
130
|
+
lastTripTimestamp: this.lastStateChangeMonotonic,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
public reset(): void {
|
|
135
|
+
this.consecutiveFailures = 0;
|
|
136
|
+
this.circuitState = 'closed';
|
|
137
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
29
141
|
// ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
|
|
30
142
|
// Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
|
|
31
143
|
// Falls back to file-only mode silently when unavailable (edge runtimes, etc.).
|
|
@@ -42,11 +154,13 @@ type _SqliteDB = {
|
|
|
42
154
|
};
|
|
43
155
|
let _SqliteDB: (new (p: string) => _SqliteDB) | null = null;
|
|
44
156
|
try {
|
|
45
|
-
// process.getBuiltinModule is available in Node >= 22.3.0
|
|
46
|
-
//
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
157
|
+
// process.getBuiltinModule is available in Node >= 22.3.0.
|
|
158
|
+
// In Node 20 LTS or environments without node:sqlite, this safely falls back to file-only mode.
|
|
159
|
+
const proc = process as unknown as { getBuiltinModule?: (m: string) => unknown };
|
|
160
|
+
if (typeof proc.getBuiltinModule === 'function') {
|
|
161
|
+
const sqlite = proc.getBuiltinModule('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB } | undefined;
|
|
162
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
163
|
+
}
|
|
50
164
|
} catch { /* node:sqlite unavailable — file-only mode */ }
|
|
51
165
|
// ── Encryption (delegates to CacheEncryption — mode-aware, no reimplementation) ──
|
|
52
166
|
// DiskTier keeps its own V2 envelope (magic | plaintext expiresAt | payload) but
|
|
@@ -75,13 +189,61 @@ interface DiskPayload {
|
|
|
75
189
|
|
|
76
190
|
const DISK_TIER_VERSION = 1;
|
|
77
191
|
|
|
192
|
+
/**
|
|
193
|
+
* Resolves the default directory for DiskTier storage.
|
|
194
|
+
*
|
|
195
|
+
* In Linux container environments, checks if `/dev/shm` (POSIX shared memory tmpfs)
|
|
196
|
+
* is writable and has adequate capacity (total >= 256MB AND free >= 128MB).
|
|
197
|
+
* When valid, targets `/dev/shm` to provide an off-heap, zero-GC RAM extension
|
|
198
|
+
* that runs at memory speeds (~20µs) and burns zero cloud/EBS IOPS.
|
|
199
|
+
* If capacity or free space is insufficient, or on non-Linux platforms,
|
|
200
|
+
* gracefully falls back to `os.tmpdir()`.
|
|
201
|
+
*/
|
|
202
|
+
export function resolveDefaultDiskDir(namespace?: string, logger?: ILogger): { dir: string; isShm: boolean } {
|
|
203
|
+
const ns = namespace?.trim() ?? '';
|
|
204
|
+
const nsDir = ns ? `tricache-disk-${ns}` : 'tricache-disk';
|
|
205
|
+
|
|
206
|
+
if (process.platform === 'linux') {
|
|
207
|
+
const shmPath = '/dev/shm';
|
|
208
|
+
try {
|
|
209
|
+
fs.accessSync(shmPath, fs.constants.W_OK | fs.constants.R_OK);
|
|
210
|
+
if (typeof fs.statfsSync === 'function') {
|
|
211
|
+
const stats = fs.statfsSync(shmPath);
|
|
212
|
+
const totalBytes = Number(stats.blocks) * Number(stats.bsize);
|
|
213
|
+
const freeBytes = Number(stats.bavail) * Number(stats.bsize);
|
|
214
|
+
|
|
215
|
+
if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
|
|
216
|
+
const targetDir = path.join(shmPath, nsDir);
|
|
217
|
+
logger?.info?.('DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage', {
|
|
218
|
+
path: targetDir,
|
|
219
|
+
totalBytes,
|
|
220
|
+
freeBytes,
|
|
221
|
+
});
|
|
222
|
+
return { dir: targetDir, isShm: true };
|
|
223
|
+
} else {
|
|
224
|
+
logger?.info?.('DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir', {
|
|
225
|
+
totalBytes,
|
|
226
|
+
freeBytes,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch (err) {
|
|
231
|
+
logger?.debug?.('DiskTier: /dev/shm not usable, falling back to tmpdir', {
|
|
232
|
+
error: (err as Error).message,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
return { dir: path.join(os.tmpdir(), nsDir), isShm: false };
|
|
238
|
+
}
|
|
239
|
+
|
|
78
240
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
79
241
|
|
|
80
242
|
export interface DiskTierOptions {
|
|
81
243
|
dir: string;
|
|
82
244
|
maxBytes: number;
|
|
83
245
|
entryMaxBytes: number;
|
|
84
|
-
forbiddenPrefixes
|
|
246
|
+
forbiddenPrefixes?: readonly string[];
|
|
85
247
|
/** Mode-aware encryption instance. When set, disk files are encrypted with the
|
|
86
248
|
* same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
|
|
87
249
|
* When null, files are written unencrypted. Pass `cache.encryption` here. */
|
|
@@ -89,10 +251,18 @@ export interface DiskTierOptions {
|
|
|
89
251
|
compression?: CompressionAlgorithm;
|
|
90
252
|
compressionThresholdBytes?: number;
|
|
91
253
|
logger: ILogger;
|
|
254
|
+
codec?: CacheCodec;
|
|
255
|
+
diskMaxConcurrentWrites?: number;
|
|
256
|
+
diskMaxPendingWrites?: number;
|
|
257
|
+
diskWriteTimeoutMs?: number;
|
|
258
|
+
diskCircuitBreakerThreshold?: number;
|
|
259
|
+
diskCircuitBreakerCooldownMs?: number;
|
|
92
260
|
}
|
|
93
261
|
|
|
94
262
|
export class DiskTier {
|
|
95
263
|
private readonly opts: DiskTierOptions;
|
|
264
|
+
private readonly codec: CacheCodec;
|
|
265
|
+
private readonly diskQueue: BoundedDiskQueue;
|
|
96
266
|
private dirReady = false;
|
|
97
267
|
private diskUsageBytes = 0;
|
|
98
268
|
private usageCounted = false;
|
|
@@ -100,6 +270,15 @@ export class DiskTier {
|
|
|
100
270
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
101
271
|
private _nextJanitorBucket = 0;
|
|
102
272
|
|
|
273
|
+
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
274
|
+
private _isPruning = false;
|
|
275
|
+
private _pruneRounds = 0;
|
|
276
|
+
private _entriesPruned = 0;
|
|
277
|
+
private _spillsShedTotal = 0;
|
|
278
|
+
private _hostVolumeLowSpace = false;
|
|
279
|
+
private _hostVolumeLowSpacePauses = 0;
|
|
280
|
+
private _writeCounter = 0;
|
|
281
|
+
|
|
103
282
|
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
104
283
|
private _db: _SqliteDB | null = null;
|
|
105
284
|
private _stmtInsert: _SqliteStmt | null = null; // INSERT OR REPLACE
|
|
@@ -108,9 +287,19 @@ export class DiskTier {
|
|
|
108
287
|
private _stmtExpire: _SqliteStmt | null = null; // SELECT expired rows
|
|
109
288
|
private _stmtDelExp: _SqliteStmt | null = null; // DELETE expired rows
|
|
110
289
|
private _stmtStats: _SqliteStmt | null = null; // COUNT + SUM(size)
|
|
290
|
+
private _stmtPruneChunk: _SqliteStmt | null = null; // SELECT chunk for watermark pruning
|
|
111
291
|
|
|
112
292
|
constructor(opts: DiskTierOptions) {
|
|
113
|
-
this.opts
|
|
293
|
+
this.opts = opts;
|
|
294
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
295
|
+
const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((os?.availableParallelism?.() ?? 4) / 4)));
|
|
296
|
+
this.diskQueue = new BoundedDiskQueue(
|
|
297
|
+
opts.diskMaxConcurrentWrites ?? defaultConcurrent,
|
|
298
|
+
opts.diskMaxPendingWrites ?? 512,
|
|
299
|
+
opts.diskWriteTimeoutMs ?? 500,
|
|
300
|
+
opts.diskCircuitBreakerThreshold ?? 5,
|
|
301
|
+
opts.diskCircuitBreakerCooldownMs ?? 5000,
|
|
302
|
+
);
|
|
114
303
|
}
|
|
115
304
|
|
|
116
305
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
@@ -148,15 +337,30 @@ export class DiskTier {
|
|
|
148
337
|
PRAGMA synchronous = NORMAL;
|
|
149
338
|
PRAGMA temp_store = MEMORY;
|
|
150
339
|
CREATE TABLE IF NOT EXISTS meta (
|
|
151
|
-
key_hash
|
|
152
|
-
file_path
|
|
153
|
-
expires_at
|
|
154
|
-
size
|
|
340
|
+
key_hash TEXT PRIMARY KEY,
|
|
341
|
+
file_path TEXT NOT NULL,
|
|
342
|
+
expires_at INTEGER NOT NULL,
|
|
343
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
344
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
345
|
+
last_accessed_at INTEGER NOT NULL DEFAULT 0
|
|
155
346
|
);
|
|
156
347
|
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
348
|
+
CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
|
|
157
349
|
`);
|
|
350
|
+
|
|
351
|
+
// Migration guards for pre-existing databases without priority or last_accessed_at columns
|
|
352
|
+
try {
|
|
353
|
+
this._db.exec('ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;');
|
|
354
|
+
} catch { /* column already present */ }
|
|
355
|
+
try {
|
|
356
|
+
this._db.exec('ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;');
|
|
357
|
+
} catch { /* column already present */ }
|
|
358
|
+
try {
|
|
359
|
+
this._db.exec('CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);');
|
|
360
|
+
} catch { /* index already present */ }
|
|
361
|
+
|
|
158
362
|
this._stmtInsert = this._db.prepare(
|
|
159
|
-
'INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (
|
|
363
|
+
'INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)',
|
|
160
364
|
);
|
|
161
365
|
this._stmtSelect = this._db.prepare(
|
|
162
366
|
'SELECT file_path, expires_at FROM meta WHERE key_hash = ?',
|
|
@@ -169,6 +373,9 @@ export class DiskTier {
|
|
|
169
373
|
this._stmtStats = this._db.prepare(
|
|
170
374
|
'SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta',
|
|
171
375
|
);
|
|
376
|
+
this._stmtPruneChunk = this._db.prepare(
|
|
377
|
+
'SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500',
|
|
378
|
+
);
|
|
172
379
|
// Seed in-memory counters from the index — avoids startup walkCacheFiles().
|
|
173
380
|
const row = this._stmtStats.get() as { cnt: number; bytes: number };
|
|
174
381
|
this.fileCount = row.cnt;
|
|
@@ -177,7 +384,7 @@ export class DiskTier {
|
|
|
177
384
|
this.opts.logger.debug('DiskTier: SQLite index ready', { entries: row.cnt });
|
|
178
385
|
} catch (err) {
|
|
179
386
|
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
180
|
-
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
387
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
181
388
|
this.opts.logger.warn('DiskTier: SQLite init failed, using file-only mode', {
|
|
182
389
|
error: (err as Error).message,
|
|
183
390
|
});
|
|
@@ -269,7 +476,7 @@ export class DiskTier {
|
|
|
269
476
|
}
|
|
270
477
|
|
|
271
478
|
private isForbidden(key: string): boolean {
|
|
272
|
-
return this.opts.forbiddenPrefixes
|
|
479
|
+
return this.opts.forbiddenPrefixes?.some(p => key.startsWith(p)) ?? false;
|
|
273
480
|
}
|
|
274
481
|
|
|
275
482
|
private encrypt(data: Buffer): Buffer {
|
|
@@ -329,7 +536,22 @@ export class DiskTier {
|
|
|
329
536
|
this.ensureDir();
|
|
330
537
|
if (!this.dirReady) return;
|
|
331
538
|
this.ensureUsageCounted();
|
|
332
|
-
|
|
539
|
+
|
|
540
|
+
// Periodic host volume check every 2000 writes
|
|
541
|
+
if (++this._writeCounter % 2000 === 0) {
|
|
542
|
+
this.checkHostVolumeHealth();
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// Fast-shed incoming spills while host volume is low (<10%), pruning is active, or quota is reached
|
|
546
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
547
|
+
this._spillsShedTotal++;
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// High-watermark trigger (80%): fire non-blocking chunked prune down to 60%
|
|
552
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.80 && !this._isPruning) {
|
|
553
|
+
void this.triggerChunkedPrune();
|
|
554
|
+
}
|
|
333
555
|
|
|
334
556
|
// ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
|
|
335
557
|
let final: Buffer;
|
|
@@ -345,7 +567,7 @@ export class DiskTier {
|
|
|
345
567
|
},
|
|
346
568
|
writtenAt: Date.now(),
|
|
347
569
|
};
|
|
348
|
-
const packed =
|
|
570
|
+
const packed = this.codec.encode(payload);
|
|
349
571
|
if (packed.length > this.opts.entryMaxBytes) return;
|
|
350
572
|
let toEncrypt = packed;
|
|
351
573
|
if (this.opts.compression && this.opts.compression !== 'none' && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
@@ -366,37 +588,55 @@ export class DiskTier {
|
|
|
366
588
|
// ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
|
|
367
589
|
const hash = this.keyToHash(key);
|
|
368
590
|
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
369
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${
|
|
370
|
-
|
|
591
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
592
|
+
|
|
593
|
+
// Optimistically reserve quota before queuing so concurrent spills respect the cap
|
|
594
|
+
this.diskUsageBytes += final.length;
|
|
371
595
|
this.fileCount++;
|
|
372
596
|
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
597
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.80 && !this._isPruning) {
|
|
598
|
+
void this.triggerChunkedPrune();
|
|
599
|
+
}
|
|
376
600
|
|
|
377
|
-
|
|
601
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
378
602
|
try {
|
|
379
|
-
await fs.promises.
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
603
|
+
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
604
|
+
await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
|
|
605
|
+
|
|
606
|
+
// Atomic rename with micro-retry loop for Windows NTFS handle release
|
|
607
|
+
try {
|
|
384
608
|
await fs.promises.rename(tmpPath, filePath);
|
|
385
|
-
}
|
|
386
|
-
|
|
609
|
+
} catch (renameErr: unknown) {
|
|
610
|
+
const code = (renameErr as { code?: string })?.code;
|
|
611
|
+
if (code === 'EBUSY' || code === 'EPERM') {
|
|
612
|
+
await new Promise<void>(resolve => setTimeout(resolve, 5));
|
|
613
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
614
|
+
} else {
|
|
615
|
+
throw renameErr;
|
|
616
|
+
}
|
|
387
617
|
}
|
|
388
|
-
}
|
|
389
618
|
|
|
390
|
-
|
|
391
|
-
|
|
619
|
+
if (this._db) {
|
|
620
|
+
const priority = typeof entry.priority === 'number' ? entry.priority : 2;
|
|
621
|
+
const lastAccess = typeof entry.lastAccess === 'number' ? entry.lastAccess : Date.now();
|
|
622
|
+
this._stmtInsert!.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
|
|
623
|
+
}
|
|
624
|
+
this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
|
|
625
|
+
return true;
|
|
626
|
+
} catch (err) {
|
|
627
|
+
try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
|
|
628
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
|
|
629
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
630
|
+
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
631
|
+
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
632
|
+
throw err;
|
|
392
633
|
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
if (result === null) {
|
|
637
|
+
// Fast-dropped by BoundedDiskQueue backpressure / circuit breaker: rollback reservation
|
|
638
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
397
639
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
398
|
-
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
399
|
-
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
400
640
|
}
|
|
401
641
|
}
|
|
402
642
|
|
|
@@ -477,7 +717,7 @@ export class DiskTier {
|
|
|
477
717
|
}
|
|
478
718
|
|
|
479
719
|
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
|
|
480
|
-
const payload =
|
|
720
|
+
const payload = this.codec.decode(uncompressed) as DiskPayload;
|
|
481
721
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
482
722
|
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
483
723
|
|
|
@@ -568,6 +808,10 @@ export class DiskTier {
|
|
|
568
808
|
}
|
|
569
809
|
|
|
570
810
|
// ── V2 header fast path: read only the 16-byte plaintext header ────────
|
|
811
|
+
// NOTE: Modern TriCache disk files never read full payload data during eviction.
|
|
812
|
+
// The 16-byte plaintext header (magic + expiresAt) allows checking TTL and unlinking
|
|
813
|
+
// expired files with near-zero I/O overhead. Full readFileSync below is exclusively
|
|
814
|
+
// for backward compatibility with ancient V1 files lacking the magic header.
|
|
571
815
|
let fd = -1;
|
|
572
816
|
try {
|
|
573
817
|
fd = fs.openSync(filePath, 'r');
|
|
@@ -588,7 +832,7 @@ export class DiskTier {
|
|
|
588
832
|
continue;
|
|
589
833
|
}
|
|
590
834
|
|
|
591
|
-
// ── Legacy path: V1 encrypted or pre-magic unencrypted
|
|
835
|
+
// ── Legacy fallback path: V1 encrypted or pre-magic unencrypted ────────
|
|
592
836
|
const stat = fs.statSync(filePath);
|
|
593
837
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
594
838
|
fs.unlinkSync(filePath);
|
|
@@ -600,7 +844,7 @@ export class DiskTier {
|
|
|
600
844
|
const raw = fs.readFileSync(filePath);
|
|
601
845
|
let dec: Buffer;
|
|
602
846
|
try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
|
|
603
|
-
const payload =
|
|
847
|
+
const payload = this.codec.decode(dec) as DiskPayload;
|
|
604
848
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
605
849
|
fs.unlinkSync(filePath);
|
|
606
850
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -759,7 +1003,7 @@ export class DiskTier {
|
|
|
759
1003
|
const raw = fs.readFileSync(filePath);
|
|
760
1004
|
let dec: Buffer;
|
|
761
1005
|
try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
|
|
762
|
-
const payload =
|
|
1006
|
+
const payload = this.codec.decode(dec) as DiskPayload;
|
|
763
1007
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
764
1008
|
fs.unlinkSync(filePath);
|
|
765
1009
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -795,14 +1039,172 @@ export class DiskTier {
|
|
|
795
1039
|
return cleared;
|
|
796
1040
|
}
|
|
797
1041
|
|
|
798
|
-
|
|
1042
|
+
/**
|
|
1043
|
+
* Proactively checks host volume free space via statfsSync.
|
|
1044
|
+
* If free space on the volume drops below 10%, pauses spills to prevent
|
|
1045
|
+
* Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
|
|
1046
|
+
*/
|
|
1047
|
+
public checkHostVolumeHealth(): boolean {
|
|
1048
|
+
try {
|
|
1049
|
+
if (typeof fs.statfsSync === 'function') {
|
|
1050
|
+
const stats = fs.statfsSync(this.opts.dir);
|
|
1051
|
+
const total = Number(stats.blocks);
|
|
1052
|
+
const avail = Number(stats.bavail);
|
|
1053
|
+
if (total > 0) {
|
|
1054
|
+
const freeRatio = avail / total;
|
|
1055
|
+
if (freeRatio < 0.10) {
|
|
1056
|
+
if (!this._hostVolumeLowSpace) {
|
|
1057
|
+
this._hostVolumeLowSpace = true;
|
|
1058
|
+
this._hostVolumeLowSpacePauses++;
|
|
1059
|
+
this.opts.logger.warn(
|
|
1060
|
+
'DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.',
|
|
1061
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) },
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
return false;
|
|
1065
|
+
} else if (this._hostVolumeLowSpace) {
|
|
1066
|
+
this._hostVolumeLowSpace = false;
|
|
1067
|
+
this.opts.logger.info(
|
|
1068
|
+
'DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.',
|
|
1069
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) },
|
|
1070
|
+
);
|
|
1071
|
+
return true;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
} catch {
|
|
1076
|
+
// statfs may fail if directory does not yet exist or is unmounted
|
|
1077
|
+
}
|
|
1078
|
+
return true;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/**
|
|
1082
|
+
* Non-blocking chunked pruning:
|
|
1083
|
+
* Evicts oldest entries in 500-entry chunks down to 60% watermark,
|
|
1084
|
+
* yielding to the event loop via setImmediate between chunks.
|
|
1085
|
+
*/
|
|
1086
|
+
public async triggerChunkedPrune(): Promise<number> {
|
|
1087
|
+
if (this._isPruning) return 0;
|
|
1088
|
+
this._isPruning = true;
|
|
1089
|
+
this._pruneRounds++;
|
|
1090
|
+
let prunedInThisRound = 0;
|
|
1091
|
+
|
|
1092
|
+
try {
|
|
1093
|
+
this.ensureUsageCounted();
|
|
1094
|
+
const targetBytes = Math.floor(this.opts.maxBytes * 0.60);
|
|
1095
|
+
|
|
1096
|
+
if (this._db && this._stmtPruneChunk) {
|
|
1097
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
1098
|
+
const rows = this._stmtPruneChunk.all() as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
1099
|
+
if (!rows || rows.length === 0) break;
|
|
1100
|
+
|
|
1101
|
+
for (const row of rows) {
|
|
1102
|
+
try {
|
|
1103
|
+
fs.unlinkSync(row.file_path);
|
|
1104
|
+
} catch { /* already gone */ }
|
|
1105
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1106
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1107
|
+
this._entriesPruned++;
|
|
1108
|
+
prunedInThisRound++;
|
|
1109
|
+
try { this._stmtDelete!.run(row.key_hash); } catch { /* ok */ }
|
|
1110
|
+
|
|
1111
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
1115
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
} else {
|
|
1119
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
1120
|
+
const files = this.walkCacheFiles();
|
|
1121
|
+
if (files.length === 0) break;
|
|
1122
|
+
const chunk = files.slice(0, 500);
|
|
1123
|
+
|
|
1124
|
+
for (const filePath of chunk) {
|
|
1125
|
+
try {
|
|
1126
|
+
const stat = fs.statSync(filePath);
|
|
1127
|
+
fs.unlinkSync(filePath);
|
|
1128
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1129
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1130
|
+
this._entriesPruned++;
|
|
1131
|
+
prunedInThisRound++;
|
|
1132
|
+
} catch { /* already gone */ }
|
|
1133
|
+
|
|
1134
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
1138
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
} finally {
|
|
1143
|
+
this._isPruning = false;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
return prunedInThisRound;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
get isPruning(): boolean {
|
|
1150
|
+
return this._isPruning;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
get hostVolumeLowSpace(): boolean {
|
|
1154
|
+
return this._hostVolumeLowSpace;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
get spillsShedTotal(): number {
|
|
1158
|
+
return this._spillsShedTotal;
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
getPruningStats(): {
|
|
1162
|
+
active: boolean;
|
|
1163
|
+
pruneRounds: number;
|
|
1164
|
+
entriesPruned: number;
|
|
1165
|
+
spillsShedTotal: number;
|
|
1166
|
+
hostVolumeLowSpacePauses: number;
|
|
1167
|
+
} {
|
|
1168
|
+
return {
|
|
1169
|
+
active: this._isPruning,
|
|
1170
|
+
pruneRounds: this._pruneRounds,
|
|
1171
|
+
entriesPruned: this._entriesPruned,
|
|
1172
|
+
spillsShedTotal: this._spillsShedTotal,
|
|
1173
|
+
hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses,
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
get stats(): {
|
|
1178
|
+
files: number;
|
|
1179
|
+
sizeKB: number;
|
|
1180
|
+
maxKB: number;
|
|
1181
|
+
backpressure?: DiskBackpressureStats;
|
|
1182
|
+
pruning?: {
|
|
1183
|
+
active: boolean;
|
|
1184
|
+
pruneRounds: number;
|
|
1185
|
+
entriesPruned: number;
|
|
1186
|
+
spillsShedTotal: number;
|
|
1187
|
+
hostVolumeLowSpacePauses: number;
|
|
1188
|
+
};
|
|
1189
|
+
} {
|
|
799
1190
|
if (this._db) {
|
|
800
1191
|
// Query the index for authoritative counts — O(1) SQLite aggregate.
|
|
801
1192
|
const row = this._stmtStats!.get() as { cnt: number; bytes: number };
|
|
802
1193
|
this.fileCount = row.cnt;
|
|
803
1194
|
this.diskUsageBytes = row.bytes;
|
|
804
1195
|
}
|
|
805
|
-
return {
|
|
1196
|
+
return {
|
|
1197
|
+
files: this.fileCount,
|
|
1198
|
+
sizeKB: Math.round(this.diskUsageBytes / 1024),
|
|
1199
|
+
maxKB: Math.round(this.opts.maxBytes / 1024),
|
|
1200
|
+
backpressure: this.diskQueue.getStats(),
|
|
1201
|
+
pruning: this.getPruningStats(),
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
|
|
1206
|
+
get backpressure(): BoundedDiskQueue {
|
|
1207
|
+
return this.diskQueue;
|
|
806
1208
|
}
|
|
807
1209
|
|
|
808
1210
|
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
@@ -815,7 +1217,7 @@ export class DiskTier {
|
|
|
815
1217
|
if (this._db) {
|
|
816
1218
|
try { this._db.close(); } catch { /* ok */ }
|
|
817
1219
|
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
818
|
-
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
1220
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
819
1221
|
}
|
|
820
1222
|
}
|
|
821
1223
|
}
|