tricache 1.0.0 → 1.0.2
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/README.md +36 -28
- package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
- package/dist/cache-service-CWI4jkS7.d.cts +963 -0
- package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/chunk-OYDU3SMI.js +89 -0
- package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
- package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
- package/dist/cli.cjs +1757 -777
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +27 -6
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +1757 -773
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +280 -153
- package/dist/edge/index.d.cts +127 -0
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +254 -147
- package/dist/hono/index.cjs +1805 -793
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
- package/dist/hono-C886ok3X.d.cts +391 -0
- package/dist/http/index.cjs +1946 -842
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +137 -57
- package/dist/index.cjs +2073 -937
- package/dist/index.d.cts +1006 -0
- package/dist/index.d.ts +40 -8
- package/dist/index.js +8 -8
- package/dist/murmur3-CMGw9PbV.d.cts +98 -0
- package/dist/nestjs/index.cjs +1849 -806
- package/dist/nestjs/index.d.cts +285 -0
- package/dist/nestjs/index.d.ts +103 -30
- package/dist/nestjs/index.js +115 -32
- package/dist/next/index.cjs +1913 -887
- package/dist/next/index.d.cts +232 -0
- package/dist/next/index.d.ts +33 -11
- package/dist/next/index.js +174 -107
- package/dist/prisma/index.cjs +11 -1
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +11 -1
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
- package/dist/types-BA4pz1A0.d.ts +1519 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +96 -36
- package/src/adapters/auto-pipeliner.ts +107 -24
- package/src/adapters/node-redis.ts +123 -25
- package/src/cache-service.ts +1238 -659
- package/src/cli.ts +24 -6
- package/src/cross-region.ts +21 -3
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +171 -65
- package/src/edge/cache.ts +202 -129
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +2 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +110 -26
- package/src/http/fastify.ts +38 -28
- package/src/http/utils.ts +54 -20
- package/src/ipc-telemetry.ts +35 -9
- package/src/nestjs/decorators.ts +1 -1
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +13 -11
- package/src/nestjs/tricache.store.ts +51 -20
- package/src/nestjs/types.ts +29 -15
- package/src/next/cache-handler.ts +132 -57
- package/src/next/index.ts +1 -0
- package/src/next/isr-handler.ts +1 -4
- package/src/next/types.ts +21 -0
- package/src/prisma/index.ts +12 -1
- package/src/smart-memory-cache.ts +65 -27
- package/src/types.ts +27 -2
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/wasm/bloom-filter-wasm.ts +9 -4
- package/src/worker-pool.ts +17 -8
- package/src/wtiny-lfu.ts +20 -6
- package/dist/chunk-BQRURGGD.js +0 -60
package/src/types.ts
CHANGED
|
@@ -25,7 +25,7 @@ export interface ICacheSpanLink {
|
|
|
25
25
|
export interface ICacheSpan {
|
|
26
26
|
setAttribute(key: string, value: string | number | boolean): this;
|
|
27
27
|
setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
|
|
28
|
-
recordException?(err:
|
|
28
|
+
recordException?(err: unknown): void;
|
|
29
29
|
end(): void;
|
|
30
30
|
}
|
|
31
31
|
|
|
@@ -127,6 +127,9 @@ export interface SmartCacheEntry {
|
|
|
127
127
|
setAt?: number;
|
|
128
128
|
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
129
129
|
tagVersions?: Record<string, number>;
|
|
130
|
+
/** Set-based tags and dependency patterns preserved through disk/snapshot promotion. */
|
|
131
|
+
tags?: string[];
|
|
132
|
+
dependsOn?: string[];
|
|
130
133
|
}
|
|
131
134
|
|
|
132
135
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
@@ -148,6 +151,8 @@ export interface CacheHit {
|
|
|
148
151
|
tagVersions?: Record<string, number>;
|
|
149
152
|
/** Timestamp (ms) when this entry was written into memory */
|
|
150
153
|
setAt?: number;
|
|
154
|
+
tags?: string[];
|
|
155
|
+
dependsOn?: string[];
|
|
151
156
|
}
|
|
152
157
|
|
|
153
158
|
// ─── Disk tier ───────────────────────────────────────────────────────────────
|
|
@@ -165,6 +170,12 @@ export interface DiskCacheEntry {
|
|
|
165
170
|
priority: number;
|
|
166
171
|
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
167
172
|
tagVersions?: Record<string, number>;
|
|
173
|
+
/** Original write time and TTL, preserved on spill and promotion. */
|
|
174
|
+
setAt?: number;
|
|
175
|
+
ttlMs?: number;
|
|
176
|
+
delta?: number;
|
|
177
|
+
tags?: string[];
|
|
178
|
+
dependsOn?: string[];
|
|
168
179
|
}
|
|
169
180
|
|
|
170
181
|
// ─── Metrics snapshot ────────────────────────────────────────────────────────
|
|
@@ -1169,8 +1180,13 @@ export interface ICacheCounter {
|
|
|
1169
1180
|
add(value: number, attributes?: Record<string, string | number | boolean>): void;
|
|
1170
1181
|
}
|
|
1171
1182
|
|
|
1183
|
+
export type ICacheObservableCallback = (result: {
|
|
1184
|
+
observe(value: number, attributes?: Record<string, string | number | boolean>): void;
|
|
1185
|
+
}) => void | Promise<void>;
|
|
1186
|
+
|
|
1172
1187
|
export interface ICacheObservableGauge {
|
|
1173
|
-
|
|
1188
|
+
addCallback(callback: ICacheObservableCallback): void;
|
|
1189
|
+
removeCallback(callback: ICacheObservableCallback): void;
|
|
1174
1190
|
}
|
|
1175
1191
|
|
|
1176
1192
|
export interface ICacheBatchObservableCallback {
|
|
@@ -1183,6 +1199,7 @@ export interface ICacheMeter {
|
|
|
1183
1199
|
createCounter(name: string, options?: { description?: string; unit?: string }): ICacheCounter;
|
|
1184
1200
|
createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
|
|
1185
1201
|
addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
1202
|
+
removeBatchObservableCallback?(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
1186
1203
|
}
|
|
1187
1204
|
|
|
1188
1205
|
/**
|
|
@@ -1198,6 +1215,10 @@ export interface IRedisPipeline {
|
|
|
1198
1215
|
sadd(key: string, ...members: string[]): this;
|
|
1199
1216
|
smembers(key: string): this;
|
|
1200
1217
|
hset(key: string, value: Record<string, string>): this;
|
|
1218
|
+
hgetall?(key: string): this;
|
|
1219
|
+
/** Remaining TTL in milliseconds; enables atomic value + expiry reads. */
|
|
1220
|
+
pttl?(key: string): this;
|
|
1221
|
+
eval?(script: string, numkeys: number, ...args: (string | number)[]): this;
|
|
1201
1222
|
exec(): Promise<Array<[Error | null, any]> | null>;
|
|
1202
1223
|
}
|
|
1203
1224
|
|
|
@@ -1211,6 +1232,7 @@ export interface IRedisDriver {
|
|
|
1211
1232
|
setex?(key: string, seconds: number, value: string): Promise<unknown>;
|
|
1212
1233
|
del(...keys: string[]): Promise<number>;
|
|
1213
1234
|
ping(): Promise<string>;
|
|
1235
|
+
pttl?(key: string): Promise<number>;
|
|
1214
1236
|
expire(key: string, seconds: number): Promise<number | boolean>;
|
|
1215
1237
|
incr(key: string): Promise<number>;
|
|
1216
1238
|
eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
@@ -1221,8 +1243,11 @@ export interface IRedisDriver {
|
|
|
1221
1243
|
scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
|
|
1222
1244
|
scanStream?(options?: { match?: string; count?: number }): any;
|
|
1223
1245
|
hset?(key: string, value: Record<string, string>): Promise<unknown>;
|
|
1246
|
+
hgetall?(key: string): Promise<Record<string, string>>;
|
|
1224
1247
|
publish?(channel: string, message: string): Promise<number>;
|
|
1225
1248
|
subscribe?(...channels: string[]): Promise<unknown>;
|
|
1249
|
+
unsubscribe?(...channels: string[]): Promise<unknown>;
|
|
1250
|
+
removeListener?(event: string, listener: (...args: any[]) => void): this | unknown;
|
|
1226
1251
|
disconnect(): Promise<void> | void;
|
|
1227
1252
|
quit?(): Promise<void> | void;
|
|
1228
1253
|
duplicate?(): IRedisDriver;
|
package/src/utils/cgroup.ts
CHANGED
|
@@ -53,6 +53,18 @@ export function readCgroupMemoryLimit(): number {
|
|
|
53
53
|
return Infinity;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
/** Current cgroup usage includes tmpfs/page-cache charges that are absent from process RSS. */
|
|
57
|
+
export function readCgroupMemoryUsage(): number | null {
|
|
58
|
+
if (process.platform !== 'linux') return null;
|
|
59
|
+
for (const file of ['/sys/fs/cgroup/memory.current', '/sys/fs/cgroup/memory/memory.usage_in_bytes']) {
|
|
60
|
+
try {
|
|
61
|
+
const value = Number(fs.readFileSync(file, 'utf8').trim());
|
|
62
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
63
|
+
} catch { /* unavailable or unreadable */ }
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
56
68
|
/**
|
|
57
69
|
* Returns the V8 JavaScript heap size limit in bytes.
|
|
58
70
|
* Safely guards against missing or mock environments.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Bound library-owned I/O without leaking timeout handles after success or failure. */
|
|
2
|
+
export async function withDeadline<T>(operation: Promise<T>, timeoutMs: number, label: string): Promise<T> {
|
|
3
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
4
|
+
try {
|
|
5
|
+
return await Promise.race([
|
|
6
|
+
operation,
|
|
7
|
+
new Promise<never>((_resolve, reject) => {
|
|
8
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
9
|
+
}),
|
|
10
|
+
]);
|
|
11
|
+
} finally {
|
|
12
|
+
if (timer) clearTimeout(timer);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Produce a bounded, JSON-safe diagnostic view without retaining opaque credential holders. */
|
|
2
|
+
export function redactDiagnostics(value: unknown, seen = new WeakSet<object>(), depth = 0): unknown {
|
|
3
|
+
if (typeof value === 'string' && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
|
|
4
|
+
try {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (url.username) url.username = '[REDACTED]';
|
|
7
|
+
if (url.password) url.password = '[REDACTED]';
|
|
8
|
+
for (const key of url.searchParams.keys()) {
|
|
9
|
+
if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, '[REDACTED]');
|
|
10
|
+
}
|
|
11
|
+
return url.toString();
|
|
12
|
+
} catch { return '[REDACTED URL]'; }
|
|
13
|
+
}
|
|
14
|
+
if (value == null || typeof value !== 'object') return typeof value === 'function' ? undefined : value;
|
|
15
|
+
if (depth >= 8) return '[OMITTED]';
|
|
16
|
+
if (seen.has(value)) return '[CIRCULAR]';
|
|
17
|
+
seen.add(value);
|
|
18
|
+
if (Array.isArray(value)) return value.map(item => redactDiagnostics(item, seen, depth + 1));
|
|
19
|
+
const result: Record<string, unknown> = {};
|
|
20
|
+
for (const [key, item] of Object.entries(value)) {
|
|
21
|
+
if (typeof item === 'function') continue; // In particular, never preserve an opaque toJSON().
|
|
22
|
+
result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key)
|
|
23
|
+
? item == null ? item : '[REDACTED]'
|
|
24
|
+
: redactDiagnostics(item, seen, depth + 1);
|
|
25
|
+
}
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Redis Cluster CRC16/XMODEM hash slots, including the first non-empty hash tag. */
|
|
2
|
+
export function redisHashSlot(key: string): number {
|
|
3
|
+
const open = key.indexOf('{');
|
|
4
|
+
const close = open < 0 ? -1 : key.indexOf('}', open + 1);
|
|
5
|
+
const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, 'utf8');
|
|
6
|
+
let crc = 0;
|
|
7
|
+
for (const byte of bytes) {
|
|
8
|
+
crc ^= byte << 8;
|
|
9
|
+
for (let bit = 0; bit < 8; bit++) crc = (crc << 1) ^ ((crc & 0x8000) ? 0x1021 : 0);
|
|
10
|
+
crc &= 0xffff;
|
|
11
|
+
}
|
|
12
|
+
return crc & 0x3fff;
|
|
13
|
+
}
|
|
@@ -40,9 +40,14 @@ interface BloomWasmExports {
|
|
|
40
40
|
|
|
41
41
|
import { base64ToUint8Array } from '../edge/utils/base64';
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
)
|
|
43
|
+
let bloomWasmModule: WebAssembly.Module | undefined;
|
|
44
|
+
|
|
45
|
+
function getBloomWasmModule(): WebAssembly.Module {
|
|
46
|
+
// Compile lazily so importing an edge bundle does not bypass the JS fallback.
|
|
47
|
+
return bloomWasmModule ??= new WebAssembly.Module(
|
|
48
|
+
base64ToUint8Array(BLOOM_WASM_BASE64) as unknown as BufferSource,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
46
51
|
|
|
47
52
|
// NOTE: WasmBloomFilter initializes 100% synchronously in its constructor from
|
|
48
53
|
// pre-compiled WebAssembly bytecode (BLOOM_WASM_MODULE). There is no async init() promise,
|
|
@@ -59,7 +64,7 @@ export class WasmBloomFilter {
|
|
|
59
64
|
private _insertionCount = 0;
|
|
60
65
|
|
|
61
66
|
constructor() {
|
|
62
|
-
const instance = new WebAssembly.Instance(
|
|
67
|
+
const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
|
|
63
68
|
this.exports = instance.exports as unknown as BloomWasmExports;
|
|
64
69
|
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
65
70
|
this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
|
package/src/worker-pool.ts
CHANGED
|
@@ -60,7 +60,8 @@ try {
|
|
|
60
60
|
}
|
|
61
61
|
} catch {
|
|
62
62
|
// CJS fallback — __dirname is available natively in CJS (and shimmed by tsup for ESM).
|
|
63
|
-
|
|
63
|
+
const sibling = join(__dirname, 'serialize-worker.js');
|
|
64
|
+
_workerFile = existsSync(sibling) ? sibling : join(dirname(__dirname), 'serialize-worker.js');
|
|
64
65
|
}
|
|
65
66
|
|
|
66
67
|
export interface WorkerPoolOptions {
|
|
@@ -125,6 +126,7 @@ export class WorkerPool {
|
|
|
125
126
|
|
|
126
127
|
private _spawnWorkers(opts: WorkerPoolOptions): { workers: Worker[]; pending: Map<number, PendingEntry>[] } {
|
|
127
128
|
const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
|
|
129
|
+
if (!Number.isInteger(size) || size > 32 || !existsSync(_workerFile)) throw new Error('Worker pool unavailable or invalid worker count');
|
|
128
130
|
const workerData = {
|
|
129
131
|
keyBase64: opts.keyBase64,
|
|
130
132
|
mode: opts.mode,
|
|
@@ -140,7 +142,7 @@ export class WorkerPool {
|
|
|
140
142
|
const createWorker = (index: number): Worker => {
|
|
141
143
|
const worker = new Worker(_workerFile, {
|
|
142
144
|
workerData,
|
|
143
|
-
execArgv: _workerExecArgv
|
|
145
|
+
execArgv: _workerExecArgv, // Do not inherit --input-type/eval or application loader flags.
|
|
144
146
|
});
|
|
145
147
|
const pending = pendingList[index] ?? new Map<number, PendingEntry>();
|
|
146
148
|
if (!pendingList[index]) pendingList[index] = pending;
|
|
@@ -175,7 +177,7 @@ export class WorkerPool {
|
|
|
175
177
|
worker.unref();
|
|
176
178
|
|
|
177
179
|
// If pool is still active and worker exited with non-zero code, auto-replace
|
|
178
|
-
if (this._available &&
|
|
180
|
+
if (this._available && this.workers === workers && workers[index] === worker) {
|
|
179
181
|
try {
|
|
180
182
|
workers[index] = createWorker(index);
|
|
181
183
|
} catch { /* ok */ }
|
|
@@ -186,9 +188,11 @@ export class WorkerPool {
|
|
|
186
188
|
return worker;
|
|
187
189
|
};
|
|
188
190
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
191
|
+
try {
|
|
192
|
+
for (let i = 0; i < size; i++) workers.push(createWorker(i));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
for (const worker of workers) void worker.terminate().catch(() => {});
|
|
195
|
+
throw error;
|
|
192
196
|
}
|
|
193
197
|
|
|
194
198
|
return { workers, pending: pendingList };
|
|
@@ -223,7 +227,7 @@ export class WorkerPool {
|
|
|
223
227
|
entry.reject(new Error('WorkerPool replaced during key rotation'));
|
|
224
228
|
}
|
|
225
229
|
oldPending[i]?.clear();
|
|
226
|
-
oldWorkers[i]?.terminate().catch(() => {});
|
|
230
|
+
await oldWorkers[i]?.terminate().catch(() => {});
|
|
227
231
|
}
|
|
228
232
|
}
|
|
229
233
|
|
|
@@ -272,7 +276,12 @@ export class WorkerPool {
|
|
|
272
276
|
// Re-ref the worker while this request is in flight so the event loop
|
|
273
277
|
// stays alive even in short-lived scripts (benchmarks, CLI tools).
|
|
274
278
|
worker.ref();
|
|
275
|
-
worker.postMessage({ id, type, payload: dataToSend }, transferList);
|
|
279
|
+
try { worker.postMessage({ id, type, payload: dataToSend }, transferList); }
|
|
280
|
+
catch (error) {
|
|
281
|
+
pending.delete(id);
|
|
282
|
+
if (pending.size === 0) worker.unref();
|
|
283
|
+
reject(error);
|
|
284
|
+
}
|
|
276
285
|
});
|
|
277
286
|
}
|
|
278
287
|
|
package/src/wtiny-lfu.ts
CHANGED
|
@@ -460,6 +460,7 @@ export class WTinyLfuPolicy {
|
|
|
460
460
|
private readonly sketch: { estimate(key: string): number; increment(key: string): void },
|
|
461
461
|
windowPercent = 0.01,
|
|
462
462
|
protectedPercent = 0.80,
|
|
463
|
+
private readonly canEvict?: (key: string) => boolean,
|
|
463
464
|
) {
|
|
464
465
|
this.maxTotal = Math.max(2, capacity);
|
|
465
466
|
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
@@ -549,20 +550,33 @@ export class WTinyLfuPolicy {
|
|
|
549
550
|
}
|
|
550
551
|
|
|
551
552
|
// Main space full: TinyLFU gate
|
|
552
|
-
let victimKey: string;
|
|
553
|
+
let victimKey: string | undefined;
|
|
553
554
|
let victimIsProbation = true;
|
|
554
555
|
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
}
|
|
558
|
-
|
|
556
|
+
for (const candidate of this.probation) {
|
|
557
|
+
if (!this.canEvict || this.canEvict(candidate)) { victimKey = candidate; break; }
|
|
558
|
+
}
|
|
559
|
+
if (victimKey === undefined) {
|
|
560
|
+
for (const candidate of this.protected_) {
|
|
561
|
+
if (!this.canEvict || this.canEvict(candidate)) { victimKey = candidate; break; }
|
|
562
|
+
}
|
|
559
563
|
victimIsProbation = false;
|
|
560
564
|
}
|
|
561
565
|
|
|
566
|
+
if (victimKey === undefined) {
|
|
567
|
+
if (this.canEvict && !this.canEvict(candKey)) {
|
|
568
|
+
this.window.delete(key);
|
|
569
|
+
this.window.add(candKey);
|
|
570
|
+
return { admit: false, candidateKey: key };
|
|
571
|
+
}
|
|
572
|
+
this.rejectionCount++;
|
|
573
|
+
return { admit: false, candidateKey: candKey };
|
|
574
|
+
}
|
|
575
|
+
|
|
562
576
|
const candFreq = this.sketch.estimate(candKey);
|
|
563
577
|
const victimFreq = this.sketch.estimate(victimKey);
|
|
564
578
|
|
|
565
|
-
if (candFreq > victimFreq) {
|
|
579
|
+
if ((this.canEvict && !this.canEvict(candKey)) || candFreq > victimFreq) {
|
|
566
580
|
// Candidate wins: evict victim, admit candidate to Probation
|
|
567
581
|
if (victimIsProbation) {
|
|
568
582
|
this.probation.delete(victimKey);
|
package/dist/chunk-BQRURGGD.js
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
// src/http/utils.ts
|
|
2
|
-
import crypto from "crypto";
|
|
3
|
-
function buildDeterministicKey(req, options) {
|
|
4
|
-
if (options?.keyGenerator) {
|
|
5
|
-
return options.keyGenerator(req);
|
|
6
|
-
}
|
|
7
|
-
const method = (req.method || "GET").toUpperCase();
|
|
8
|
-
const rawUrl = req.originalUrl || req.url || "/";
|
|
9
|
-
const qIdx = rawUrl.indexOf("?");
|
|
10
|
-
const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
|
|
11
|
-
let queryString = "";
|
|
12
|
-
if (qIdx >= 0) {
|
|
13
|
-
const rawQuery = rawUrl.slice(qIdx + 1);
|
|
14
|
-
try {
|
|
15
|
-
const params = new URLSearchParams(rawQuery);
|
|
16
|
-
params.sort();
|
|
17
|
-
queryString = params.toString();
|
|
18
|
-
} catch {
|
|
19
|
-
queryString = rawQuery;
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
let key = `http:${method}:${path}`;
|
|
23
|
-
if (queryString) {
|
|
24
|
-
key += `?${queryString}`;
|
|
25
|
-
}
|
|
26
|
-
if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
|
|
27
|
-
const sortedHeaders = [...options.headerWhitelist].sort();
|
|
28
|
-
for (const h of sortedHeaders) {
|
|
29
|
-
const normalizedHeader = h.toLowerCase();
|
|
30
|
-
const val = req.headers[normalizedHeader];
|
|
31
|
-
if (val !== void 0 && val !== null && val !== "") {
|
|
32
|
-
const headerStr = Array.isArray(val) ? val.join(",") : String(val);
|
|
33
|
-
key += `|h:${normalizedHeader}=${headerStr}`;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return key;
|
|
38
|
-
}
|
|
39
|
-
function shouldSkipCache(req, customSkip) {
|
|
40
|
-
if (customSkip && customSkip(req)) return true;
|
|
41
|
-
const cc = req.headers ? req.headers["cache-control"] || req.headers["Cache-Control"] : void 0;
|
|
42
|
-
if (typeof cc === "string") {
|
|
43
|
-
const lower = cc.toLowerCase();
|
|
44
|
-
if (lower.includes("no-cache") || lower.includes("no-store")) {
|
|
45
|
-
return true;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
function generateETag(data) {
|
|
51
|
-
const str = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : JSON.stringify(data);
|
|
52
|
-
const hash = crypto.createHash("sha1").update(str).digest("hex").slice(0, 16);
|
|
53
|
-
return `W/"${str.length.toString(16)}-${hash}"`;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export {
|
|
57
|
-
buildDeterministicKey,
|
|
58
|
-
shouldSkipCache,
|
|
59
|
-
generateETag
|
|
60
|
-
};
|