tricache 0.6.3 → 0.6.5
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/dist/{chunk-F24NEZGQ.js → chunk-IB4HMBA2.js} +0 -8
- package/dist/index.cjs +25 -23
- package/dist/index.d.ts +16 -5
- package/dist/index.js +27 -25
- package/dist/serialize-worker.js +1 -1
- package/package.json +2 -1
- package/src/cache-service.ts +1 -1
- package/src/disk-tier.ts +5 -3
- package/src/smart-memory-cache.ts +35 -14
- package/src/types.ts +7 -0
- package/src/worker-pool.ts +3 -8
- package/dist/index.d.cts +0 -1559
- package/dist/serialize-worker.d.cts +0 -2
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
-
}) : x)(function(x) {
|
|
4
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
-
});
|
|
7
|
-
|
|
8
1
|
// src/encryption.ts
|
|
9
2
|
import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync } from "crypto";
|
|
10
3
|
var IV_BYTES = 12;
|
|
@@ -337,6 +330,5 @@ var CacheEncryption = class {
|
|
|
337
330
|
};
|
|
338
331
|
|
|
339
332
|
export {
|
|
340
|
-
__require,
|
|
341
333
|
CacheEncryption
|
|
342
334
|
};
|
package/dist/index.cjs
CHANGED
|
@@ -44,12 +44,13 @@ module.exports = __toCommonJS(index_exports);
|
|
|
44
44
|
var import_ioredis = require("ioredis");
|
|
45
45
|
var import_msgpackr3 = require("msgpackr");
|
|
46
46
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
47
|
-
var
|
|
47
|
+
var import_os2 = __toESM(require("os"), 1);
|
|
48
48
|
|
|
49
49
|
// src/worker-pool.ts
|
|
50
50
|
var import_worker_threads = require("worker_threads");
|
|
51
51
|
var import_url = require("url");
|
|
52
52
|
var import_path = require("path");
|
|
53
|
+
var import_os = __toESM(require("os"), 1);
|
|
53
54
|
var import_fs = require("fs");
|
|
54
55
|
var import_meta = {};
|
|
55
56
|
var _workerFile;
|
|
@@ -155,12 +156,7 @@ var WorkerPool = class {
|
|
|
155
156
|
}
|
|
156
157
|
};
|
|
157
158
|
function availableCpus() {
|
|
158
|
-
|
|
159
|
-
const os2 = require("os");
|
|
160
|
-
return os2.availableParallelism?.() ?? os2.cpus().length;
|
|
161
|
-
} catch {
|
|
162
|
-
return 2;
|
|
163
|
-
}
|
|
159
|
+
return import_os.default.availableParallelism?.() ?? import_os.default.cpus().length;
|
|
164
160
|
}
|
|
165
161
|
|
|
166
162
|
// src/cache-service.ts
|
|
@@ -583,6 +579,7 @@ var WasmBloomFilter = class {
|
|
|
583
579
|
|
|
584
580
|
// src/smart-memory-cache.ts
|
|
585
581
|
var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
|
|
582
|
+
var LARGE_VALUE_BYTES = 16384;
|
|
586
583
|
var EVICTION_BATCH_PERCENT = 0.2;
|
|
587
584
|
var EVICTION_SAMPLE = 16;
|
|
588
585
|
var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
|
|
@@ -1002,7 +999,8 @@ var SmartMemoryCache = class {
|
|
|
1002
999
|
}
|
|
1003
1000
|
this.ensureCapacity(cat, size);
|
|
1004
1001
|
const now = Date.now();
|
|
1005
|
-
|
|
1002
|
+
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1003
|
+
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now });
|
|
1006
1004
|
if (!existingEntry) this.bloom.add(key);
|
|
1007
1005
|
this.maybeRebuildBloom();
|
|
1008
1006
|
this.totalSize += size;
|
|
@@ -1167,9 +1165,9 @@ var SmartMemoryCache = class {
|
|
|
1167
1165
|
* peers while the backplane was down; evicting them forces a controlled
|
|
1168
1166
|
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
1169
1167
|
*
|
|
1170
|
-
* Write-time is
|
|
1171
|
-
*
|
|
1172
|
-
* conservatively.
|
|
1168
|
+
* Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
|
|
1169
|
+
* Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
|
|
1170
|
+
* entries with neither field are treated as potentially stale and evicted conservatively.
|
|
1173
1171
|
*
|
|
1174
1172
|
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
1175
1173
|
* this time are evicted.
|
|
@@ -1179,7 +1177,7 @@ var SmartMemoryCache = class {
|
|
|
1179
1177
|
let evicted = 0;
|
|
1180
1178
|
for (const [key, entry] of this.cache) {
|
|
1181
1179
|
if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
|
|
1182
|
-
const setAt = entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0;
|
|
1180
|
+
const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
|
|
1183
1181
|
if (setAt < cutoffMs) {
|
|
1184
1182
|
this._delete(key, "manual");
|
|
1185
1183
|
evicted++;
|
|
@@ -1211,7 +1209,7 @@ var SmartMemoryCache = class {
|
|
|
1211
1209
|
if (this.cache.has(key)) continue;
|
|
1212
1210
|
const rawData = entry.data;
|
|
1213
1211
|
const data = !entry.isCompressed ? (0, import_msgpackr.pack)(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
1214
|
-
const value = (0, import_msgpackr.unpack)(data);
|
|
1212
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? (0, import_msgpackr.unpack)(data) : void 0;
|
|
1215
1213
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
1216
1214
|
this.bloom.add(key);
|
|
1217
1215
|
loaded++;
|
|
@@ -1268,16 +1266,22 @@ var SmartMemoryCache = class {
|
|
|
1268
1266
|
/**
|
|
1269
1267
|
* Yields only the resolved values of live entries.
|
|
1270
1268
|
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
1271
|
-
* Returns the
|
|
1272
|
-
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
1269
|
+
* Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
|
|
1273
1270
|
*/
|
|
1274
1271
|
*liveValues() {
|
|
1275
1272
|
const now = Date.now();
|
|
1276
1273
|
for (const entry of this.cache.values()) {
|
|
1277
1274
|
if (entry.expiresAt > now)
|
|
1278
|
-
yield
|
|
1275
|
+
yield this.resolveValue(entry);
|
|
1279
1276
|
}
|
|
1280
1277
|
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Returns the deserialized value for an entry, unpacking from the msgpackr buffer
|
|
1280
|
+
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1281
|
+
*/
|
|
1282
|
+
resolveValue(entry) {
|
|
1283
|
+
return entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
|
|
1284
|
+
}
|
|
1281
1285
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1282
1286
|
get size() {
|
|
1283
1287
|
return this.cache.size;
|
|
@@ -1387,13 +1391,11 @@ var SmartMemoryCache = class {
|
|
|
1387
1391
|
var import_fs2 = __toESM(require("fs"), 1);
|
|
1388
1392
|
var import_path2 = __toESM(require("path"), 1);
|
|
1389
1393
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1390
|
-
var import_module = require("module");
|
|
1391
1394
|
var import_msgpackr2 = require("msgpackr");
|
|
1392
|
-
var import_meta2 = {};
|
|
1393
1395
|
var _SqliteDB = null;
|
|
1394
1396
|
try {
|
|
1395
|
-
const
|
|
1396
|
-
_SqliteDB =
|
|
1397
|
+
const sqlite = process.getBuiltinModule("node:sqlite");
|
|
1398
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
1397
1399
|
} catch {
|
|
1398
1400
|
}
|
|
1399
1401
|
var AES_ALGO = "aes-256-gcm";
|
|
@@ -2325,7 +2327,7 @@ var CacheService = class _CacheService {
|
|
|
2325
2327
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2326
2328
|
// two instances with different namespaces never share cache files.
|
|
2327
2329
|
diskCacheDir: options.diskCacheDir ?? import_path3.default.join(
|
|
2328
|
-
|
|
2330
|
+
import_os2.default.tmpdir(),
|
|
2329
2331
|
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2330
2332
|
),
|
|
2331
2333
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
@@ -2336,7 +2338,7 @@ var CacheService = class _CacheService {
|
|
|
2336
2338
|
disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
|
|
2337
2339
|
encryptionKey: encKeyRaw,
|
|
2338
2340
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2339
|
-
|
|
2341
|
+
import_os2.default.tmpdir(),
|
|
2340
2342
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2341
2343
|
),
|
|
2342
2344
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
@@ -3289,7 +3291,7 @@ var CacheService = class _CacheService {
|
|
|
3289
3291
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
3290
3292
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
3291
3293
|
const k = prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
3292
|
-
yield [k,
|
|
3294
|
+
yield [k, this.l1.resolveValue(entry)];
|
|
3293
3295
|
}
|
|
3294
3296
|
}
|
|
3295
3297
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -83,6 +83,13 @@ interface SmartCacheEntry {
|
|
|
83
83
|
ttlMs?: number;
|
|
84
84
|
/** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
|
|
85
85
|
delta?: number;
|
|
86
|
+
/**
|
|
87
|
+
* Unix timestamp (ms) when this entry was written.
|
|
88
|
+
* Stored explicitly so staleness-fence eviction (`evictSetBefore`) is precise
|
|
89
|
+
* instead of approximating via `expiresAt - ttlMs`.
|
|
90
|
+
* Optional for backward compatibility with snapshots written by older versions.
|
|
91
|
+
*/
|
|
92
|
+
setAt?: number;
|
|
86
93
|
}
|
|
87
94
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
88
95
|
interface CacheHit {
|
|
@@ -1261,9 +1268,9 @@ declare class SmartMemoryCache {
|
|
|
1261
1268
|
* peers while the backplane was down; evicting them forces a controlled
|
|
1262
1269
|
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
1263
1270
|
*
|
|
1264
|
-
* Write-time is
|
|
1265
|
-
*
|
|
1266
|
-
* conservatively.
|
|
1271
|
+
* Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
|
|
1272
|
+
* Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
|
|
1273
|
+
* entries with neither field are treated as potentially stale and evicted conservatively.
|
|
1267
1274
|
*
|
|
1268
1275
|
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
1269
1276
|
* this time are evicted.
|
|
@@ -1311,10 +1318,14 @@ declare class SmartMemoryCache {
|
|
|
1311
1318
|
/**
|
|
1312
1319
|
* Yields only the resolved values of live entries.
|
|
1313
1320
|
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
1314
|
-
* Returns the
|
|
1315
|
-
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
1321
|
+
* Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
|
|
1316
1322
|
*/
|
|
1317
1323
|
liveValues(): Generator<unknown>;
|
|
1324
|
+
/**
|
|
1325
|
+
* Returns the deserialized value for an entry, unpacking from the msgpackr buffer
|
|
1326
|
+
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1327
|
+
*/
|
|
1328
|
+
resolveValue(entry: SmartCacheEntry): unknown;
|
|
1318
1329
|
get size(): number;
|
|
1319
1330
|
get memoryUsage(): number;
|
|
1320
1331
|
getStats(): {
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
-
CacheEncryption
|
|
3
|
-
|
|
4
|
-
} from "./chunk-F24NEZGQ.js";
|
|
2
|
+
CacheEncryption
|
|
3
|
+
} from "./chunk-IB4HMBA2.js";
|
|
5
4
|
|
|
6
5
|
// src/cache-service.ts
|
|
7
6
|
import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
|
|
8
7
|
import { pack as pack3, unpack as unpack3 } from "msgpackr";
|
|
9
8
|
import crypto2 from "crypto";
|
|
10
|
-
import
|
|
9
|
+
import os2 from "os";
|
|
11
10
|
|
|
12
11
|
// src/worker-pool.ts
|
|
13
12
|
import { Worker } from "worker_threads";
|
|
14
13
|
import { fileURLToPath } from "url";
|
|
15
14
|
import { dirname, join } from "path";
|
|
15
|
+
import os from "os";
|
|
16
16
|
import { existsSync } from "fs";
|
|
17
17
|
var _workerFile;
|
|
18
18
|
var _workerExecArgv = [];
|
|
@@ -117,12 +117,7 @@ var WorkerPool = class {
|
|
|
117
117
|
}
|
|
118
118
|
};
|
|
119
119
|
function availableCpus() {
|
|
120
|
-
|
|
121
|
-
const os2 = __require("os");
|
|
122
|
-
return os2.availableParallelism?.() ?? os2.cpus().length;
|
|
123
|
-
} catch {
|
|
124
|
-
return 2;
|
|
125
|
-
}
|
|
120
|
+
return os.availableParallelism?.() ?? os.cpus().length;
|
|
126
121
|
}
|
|
127
122
|
|
|
128
123
|
// src/cache-service.ts
|
|
@@ -214,6 +209,7 @@ var WasmBloomFilter = class {
|
|
|
214
209
|
|
|
215
210
|
// src/smart-memory-cache.ts
|
|
216
211
|
var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
|
|
212
|
+
var LARGE_VALUE_BYTES = 16384;
|
|
217
213
|
var EVICTION_BATCH_PERCENT = 0.2;
|
|
218
214
|
var EVICTION_SAMPLE = 16;
|
|
219
215
|
var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
|
|
@@ -633,7 +629,8 @@ var SmartMemoryCache = class {
|
|
|
633
629
|
}
|
|
634
630
|
this.ensureCapacity(cat, size);
|
|
635
631
|
const now = Date.now();
|
|
636
|
-
|
|
632
|
+
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
633
|
+
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now });
|
|
637
634
|
if (!existingEntry) this.bloom.add(key);
|
|
638
635
|
this.maybeRebuildBloom();
|
|
639
636
|
this.totalSize += size;
|
|
@@ -798,9 +795,9 @@ var SmartMemoryCache = class {
|
|
|
798
795
|
* peers while the backplane was down; evicting them forces a controlled
|
|
799
796
|
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
800
797
|
*
|
|
801
|
-
* Write-time is
|
|
802
|
-
*
|
|
803
|
-
* conservatively.
|
|
798
|
+
* Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
|
|
799
|
+
* Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
|
|
800
|
+
* entries with neither field are treated as potentially stale and evicted conservatively.
|
|
804
801
|
*
|
|
805
802
|
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
806
803
|
* this time are evicted.
|
|
@@ -810,7 +807,7 @@ var SmartMemoryCache = class {
|
|
|
810
807
|
let evicted = 0;
|
|
811
808
|
for (const [key, entry] of this.cache) {
|
|
812
809
|
if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
|
|
813
|
-
const setAt = entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0;
|
|
810
|
+
const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
|
|
814
811
|
if (setAt < cutoffMs) {
|
|
815
812
|
this._delete(key, "manual");
|
|
816
813
|
evicted++;
|
|
@@ -842,7 +839,7 @@ var SmartMemoryCache = class {
|
|
|
842
839
|
if (this.cache.has(key)) continue;
|
|
843
840
|
const rawData = entry.data;
|
|
844
841
|
const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
845
|
-
const value = unpack(data);
|
|
842
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : void 0;
|
|
846
843
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
847
844
|
this.bloom.add(key);
|
|
848
845
|
loaded++;
|
|
@@ -899,16 +896,22 @@ var SmartMemoryCache = class {
|
|
|
899
896
|
/**
|
|
900
897
|
* Yields only the resolved values of live entries.
|
|
901
898
|
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
902
|
-
* Returns the
|
|
903
|
-
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
899
|
+
* Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
|
|
904
900
|
*/
|
|
905
901
|
*liveValues() {
|
|
906
902
|
const now = Date.now();
|
|
907
903
|
for (const entry of this.cache.values()) {
|
|
908
904
|
if (entry.expiresAt > now)
|
|
909
|
-
yield
|
|
905
|
+
yield this.resolveValue(entry);
|
|
910
906
|
}
|
|
911
907
|
}
|
|
908
|
+
/**
|
|
909
|
+
* Returns the deserialized value for an entry, unpacking from the msgpackr buffer
|
|
910
|
+
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
911
|
+
*/
|
|
912
|
+
resolveValue(entry) {
|
|
913
|
+
return entry.value !== void 0 ? entry.value : unpack(entry.data);
|
|
914
|
+
}
|
|
912
915
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
913
916
|
get size() {
|
|
914
917
|
return this.cache.size;
|
|
@@ -1018,12 +1021,11 @@ var SmartMemoryCache = class {
|
|
|
1018
1021
|
import fs from "fs";
|
|
1019
1022
|
import path from "path";
|
|
1020
1023
|
import crypto from "crypto";
|
|
1021
|
-
import { createRequire } from "module";
|
|
1022
1024
|
import { pack as pack2, unpack as unpack2 } from "msgpackr";
|
|
1023
1025
|
var _SqliteDB = null;
|
|
1024
1026
|
try {
|
|
1025
|
-
const
|
|
1026
|
-
_SqliteDB =
|
|
1027
|
+
const sqlite = process.getBuiltinModule("node:sqlite");
|
|
1028
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
1027
1029
|
} catch {
|
|
1028
1030
|
}
|
|
1029
1031
|
var AES_ALGO = "aes-256-gcm";
|
|
@@ -1955,7 +1957,7 @@ var CacheService = class _CacheService {
|
|
|
1955
1957
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
1956
1958
|
// two instances with different namespaces never share cache files.
|
|
1957
1959
|
diskCacheDir: options.diskCacheDir ?? path2.join(
|
|
1958
|
-
|
|
1960
|
+
os2.tmpdir(),
|
|
1959
1961
|
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
1960
1962
|
),
|
|
1961
1963
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
@@ -1966,7 +1968,7 @@ var CacheService = class _CacheService {
|
|
|
1966
1968
|
disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
|
|
1967
1969
|
encryptionKey: encKeyRaw,
|
|
1968
1970
|
snapshotPath: options.snapshotPath ?? path2.join(
|
|
1969
|
-
|
|
1971
|
+
os2.tmpdir(),
|
|
1970
1972
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
1971
1973
|
),
|
|
1972
1974
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
@@ -2919,7 +2921,7 @@ var CacheService = class _CacheService {
|
|
|
2919
2921
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2920
2922
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
2921
2923
|
const k = prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2922
|
-
yield [k,
|
|
2924
|
+
yield [k, this.l1.resolveValue(entry)];
|
|
2923
2925
|
}
|
|
2924
2926
|
}
|
|
2925
2927
|
/**
|
package/dist/serialize-worker.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tricache",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.5",
|
|
4
4
|
"description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cache",
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
],
|
|
39
39
|
"scripts": {
|
|
40
40
|
"build": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --clean",
|
|
41
|
+
"postbuild": "node --input-type=module -e \"import{rmSync}from'fs';['dist/index.d.cts','dist/serialize-worker.d.cts'].forEach(f=>rmSync(f,{force:true}));\"",
|
|
41
42
|
"dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
|
|
42
43
|
"typecheck": "tsc --noEmit",
|
|
43
44
|
"test": "vitest run",
|
package/src/cache-service.ts
CHANGED
|
@@ -1555,7 +1555,7 @@ export class CacheService {
|
|
|
1555
1555
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
1556
1556
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
1557
1557
|
const k = prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
1558
|
-
yield [k,
|
|
1558
|
+
yield [k, this.l1.resolveValue(entry) as T];
|
|
1559
1559
|
}
|
|
1560
1560
|
}
|
|
1561
1561
|
|
package/src/disk-tier.ts
CHANGED
|
@@ -17,7 +17,6 @@
|
|
|
17
17
|
import fs from 'fs';
|
|
18
18
|
import path from 'path';
|
|
19
19
|
import crypto from 'crypto';
|
|
20
|
-
import { createRequire } from 'module';
|
|
21
20
|
import { pack, unpack } from 'msgpackr';
|
|
22
21
|
import { DiskCacheEntry, ILogger } from './types.js';
|
|
23
22
|
|
|
@@ -37,8 +36,11 @@ type _SqliteDB = {
|
|
|
37
36
|
};
|
|
38
37
|
let _SqliteDB: (new (p: string) => _SqliteDB) | null = null;
|
|
39
38
|
try {
|
|
40
|
-
|
|
41
|
-
|
|
39
|
+
// process.getBuiltinModule is available in Node >= 22.3.0 (within our >=22.13.0 engine
|
|
40
|
+
// requirement). It's synchronous and does not require the esbuild __require shim.
|
|
41
|
+
const sqlite = (process as unknown as { getBuiltinModule(m: string): unknown })
|
|
42
|
+
.getBuiltinModule('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB } | undefined;
|
|
43
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
42
44
|
} catch { /* node:sqlite unavailable — file-only mode */ }
|
|
43
45
|
// ── Encryption (self-contained to avoid circular import) ─────────────────────
|
|
44
46
|
|
|
@@ -18,6 +18,19 @@ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger,
|
|
|
18
18
|
// Reusable return object for get() — eliminates one heap allocation per hot read.
|
|
19
19
|
// Safe because JS is single-threaded: callers consume all fields before the next get().
|
|
20
20
|
const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined, fetchedAt: 0 };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Packed-byte threshold above which the live JS object is NOT stored alongside the
|
|
24
|
+
* serialised buffer. For entries above this size, the double-heap overhead (both the
|
|
25
|
+
* msgpackr Buffer and the deserialized object resident simultaneously) outweighs the
|
|
26
|
+
* latency saved by skipping unpack on read. Below the threshold the live object is
|
|
27
|
+
* stored so hot reads skip deserialization entirely.
|
|
28
|
+
*
|
|
29
|
+
* 16 KiB is a conservative default: msgpackr unpacks a 16 KiB buffer in ~0.03 ms,
|
|
30
|
+
* while storing the deserialized form of a 16 KiB payload typically costs 32–64 KiB
|
|
31
|
+
* of additional heap depending on object shape.
|
|
32
|
+
*/
|
|
33
|
+
const LARGE_VALUE_BYTES = 16_384;
|
|
21
34
|
import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
22
35
|
|
|
23
36
|
|
|
@@ -551,7 +564,11 @@ export class SmartMemoryCache {
|
|
|
551
564
|
this.ensureCapacity(cat, size);
|
|
552
565
|
|
|
553
566
|
const now = Date.now();
|
|
554
|
-
|
|
567
|
+
// Only cache the live object for small entries — large entries would store the packed
|
|
568
|
+
// buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
|
|
569
|
+
// For large entries, get() falls back to the unpack() path transparently.
|
|
570
|
+
const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
|
|
571
|
+
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now });
|
|
555
572
|
// Only add new keys to the bloom — overwrites already have their bits set.
|
|
556
573
|
// Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
|
|
557
574
|
if (!existingEntry) this.bloom.add(key);
|
|
@@ -738,9 +755,9 @@ export class SmartMemoryCache {
|
|
|
738
755
|
* peers while the backplane was down; evicting them forces a controlled
|
|
739
756
|
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
740
757
|
*
|
|
741
|
-
* Write-time is
|
|
742
|
-
*
|
|
743
|
-
* conservatively.
|
|
758
|
+
* Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
|
|
759
|
+
* Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
|
|
760
|
+
* entries with neither field are treated as potentially stale and evicted conservatively.
|
|
744
761
|
*
|
|
745
762
|
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
746
763
|
* this time are evicted.
|
|
@@ -752,11 +769,8 @@ export class SmartMemoryCache {
|
|
|
752
769
|
// Never evict live CRITICAL entries — auth tokens, active sessions, etc.
|
|
753
770
|
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > Date.now()) continue;
|
|
754
771
|
|
|
755
|
-
//
|
|
756
|
-
|
|
757
|
-
const setAt = (entry.ttlMs != null)
|
|
758
|
-
? entry.expiresAt - entry.ttlMs
|
|
759
|
-
: 0; // unknown → assume stale
|
|
772
|
+
// Prefer the explicit setAt timestamp; fall back to approximation for older entries.
|
|
773
|
+
const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
|
|
760
774
|
|
|
761
775
|
if (setAt < cutoffMs) {
|
|
762
776
|
this._delete(key, 'manual');
|
|
@@ -798,8 +812,8 @@ export class SmartMemoryCache {
|
|
|
798
812
|
: rawData instanceof Uint8Array
|
|
799
813
|
? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
|
|
800
814
|
: rawData as Buffer; // already a Buffer
|
|
801
|
-
//
|
|
802
|
-
const value = unpack(data);
|
|
815
|
+
// Cache the live object for small entries only — large entries skip double-heap storage.
|
|
816
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : undefined;
|
|
803
817
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
804
818
|
this.bloom.add(key);
|
|
805
819
|
loaded++;
|
|
@@ -861,17 +875,24 @@ export class SmartMemoryCache {
|
|
|
861
875
|
/**
|
|
862
876
|
* Yields only the resolved values of live entries.
|
|
863
877
|
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
864
|
-
* Returns the
|
|
865
|
-
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
878
|
+
* Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
|
|
866
879
|
*/
|
|
867
880
|
*liveValues(): Generator<unknown> {
|
|
868
881
|
const now = Date.now();
|
|
869
882
|
for (const entry of this.cache.values()) {
|
|
870
883
|
if (entry.expiresAt > now)
|
|
871
|
-
yield
|
|
884
|
+
yield this.resolveValue(entry);
|
|
872
885
|
}
|
|
873
886
|
}
|
|
874
887
|
|
|
888
|
+
/**
|
|
889
|
+
* Returns the deserialized value for an entry, unpacking from the msgpackr buffer
|
|
890
|
+
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
891
|
+
*/
|
|
892
|
+
resolveValue(entry: SmartCacheEntry): unknown {
|
|
893
|
+
return entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
|
|
894
|
+
}
|
|
895
|
+
|
|
875
896
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
876
897
|
|
|
877
898
|
get size(): number { return this.cache.size; }
|
package/src/types.ts
CHANGED
|
@@ -105,6 +105,13 @@ export interface SmartCacheEntry {
|
|
|
105
105
|
ttlMs?: number;
|
|
106
106
|
/** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
|
|
107
107
|
delta?: number;
|
|
108
|
+
/**
|
|
109
|
+
* Unix timestamp (ms) when this entry was written.
|
|
110
|
+
* Stored explicitly so staleness-fence eviction (`evictSetBefore`) is precise
|
|
111
|
+
* instead of approximating via `expiresAt - ttlMs`.
|
|
112
|
+
* Optional for backward compatibility with snapshots written by older versions.
|
|
113
|
+
*/
|
|
114
|
+
setAt?: number;
|
|
108
115
|
}
|
|
109
116
|
|
|
110
117
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
package/src/worker-pool.ts
CHANGED
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
import { Worker } from 'worker_threads';
|
|
27
27
|
import { fileURLToPath } from 'url';
|
|
28
28
|
import { dirname, join } from 'path';
|
|
29
|
+
import os from 'os';
|
|
29
30
|
import type { EncryptionMode } from './encryption.js';
|
|
30
31
|
|
|
31
32
|
// Locate the serialize-worker entry point.
|
|
@@ -179,12 +180,6 @@ export class WorkerPool {
|
|
|
179
180
|
}
|
|
180
181
|
|
|
181
182
|
function availableCpus(): number {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
185
|
-
const os = require('os') as typeof import('os');
|
|
186
|
-
return (os as unknown as { availableParallelism?: () => number }).availableParallelism?.() ?? os.cpus().length;
|
|
187
|
-
} catch {
|
|
188
|
-
return 2;
|
|
189
|
-
}
|
|
183
|
+
// Node >= 22.13.0 (engines constraint) always has availableParallelism.
|
|
184
|
+
return os.availableParallelism?.() ?? os.cpus().length;
|
|
190
185
|
}
|