tricache 1.0.2 → 2.0.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 (101) hide show
  1. package/README.md +78 -90
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/{cache-service-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
@@ -0,0 +1,74 @@
1
+ /** Validate the pinned lz4js-supported frame subset and count output before allocation.
2
+ * Checksums are not authenticity: use GCM for hostile storage. Dictionary and
3
+ * block-checksum frames are rejected because lz4js 0.2 does not decode them safely.
4
+ */
5
+ export function lz4DecodedSize(source: Buffer, maximum: number): number {
6
+ const malformed = () => new Error('tricache: malformed or unsupported LZ4 frame');
7
+ const oversized = () => new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${maximum} bytes`);
8
+ if (source.length < 11 || source.readUInt32LE(0) !== 0x184d2204) throw malformed();
9
+ const flags = source[4];
10
+ const descriptor = source[5];
11
+ const blockMaximum = [0, 0, 0, 0, 65536, 262144, 1048576, 4194304][descriptor >> 4];
12
+ if ((flags & 0xc0) !== 0x40 || (flags & 0x13) !== 0 || (descriptor & 0x8f) !== 0 || !blockMaximum) throw malformed();
13
+ let cursor = 6;
14
+ let declared: number | undefined;
15
+ if (flags & 8) {
16
+ if (cursor + 9 > source.length) throw malformed();
17
+ const size = source.readBigUInt64LE(cursor);
18
+ if (size > BigInt(maximum)) throw oversized();
19
+ declared = Number(size);
20
+ cursor += 8;
21
+ }
22
+ cursor++; // Header checksum is consumed by the codec; not an authentication claim.
23
+ let total = 0;
24
+ const grow = (amount: number) => {
25
+ if (amount > maximum - total) throw oversized();
26
+ total += amount;
27
+ };
28
+ while (true) {
29
+ if (cursor + 4 > source.length) throw malformed();
30
+ const rawLength = source.readUInt32LE(cursor);
31
+ cursor += 4;
32
+ if (rawLength === 0) break;
33
+ const length = rawLength & 0x7fffffff;
34
+ if (length > blockMaximum || length > source.length - cursor) throw malformed();
35
+ const end = cursor + length;
36
+ const blockStart = total;
37
+ if (rawLength & 0x80000000) {
38
+ grow(length);
39
+ cursor = end;
40
+ } else {
41
+ const readLength = (initial: number) => {
42
+ let count = initial;
43
+ if (initial === 15) {
44
+ let extra: number;
45
+ do {
46
+ if (cursor >= end) throw malformed();
47
+ extra = source[cursor++];
48
+ count += extra;
49
+ if (count > maximum) throw oversized();
50
+ } while (extra === 255);
51
+ }
52
+ return count;
53
+ };
54
+ while (cursor < end) {
55
+ const token = source[cursor++];
56
+ const literals = readLength(token >>> 4);
57
+ if (literals > end - cursor) throw malformed();
58
+ grow(literals);
59
+ cursor += literals;
60
+ if (cursor === end) break;
61
+ if (cursor + 2 > end) throw malformed();
62
+ const offset = source.readUInt16LE(cursor);
63
+ cursor += 2;
64
+ const history = flags & 0x20 ? total - blockStart : total;
65
+ if (offset === 0 || offset > history) throw malformed();
66
+ grow(readLength(token & 15) + 4);
67
+ }
68
+ }
69
+ if (total - blockStart > blockMaximum) throw malformed();
70
+ }
71
+ if (flags & 4) cursor += 4; // Content checksum is not verified by the pinned codec.
72
+ if (cursor !== source.length || declared !== undefined && declared !== total) throw malformed();
73
+ return total;
74
+ }
@@ -0,0 +1,48 @@
1
+ const NAMESPACE_KEY_VERSION = 'tricache:v3:';
2
+
3
+ /** Domains are fixed protocol tokens; caller-provided identifiers follow them. */
4
+ export type CacheKeyDomain = 'data' | 'tag-set' | 'tag-version' | 'tag-registry' | 'lock';
5
+
6
+ /** Fixed-width UTF-16 hex preserves every JS string, including lone surrogates.
7
+ * Hex contains no glob, path, delimiter, or Redis hash-tag metacharacters.
8
+ * The terminating ':' makes namespace prefixes disjoint even for empty names.
9
+ */
10
+ export function encodeNamespaceSegment(namespace: string): string {
11
+ let encoded = '';
12
+ for (let index = 0; index < namespace.length; index++) {
13
+ encoded += namespace.charCodeAt(index).toString(16).padStart(4, '0');
14
+ }
15
+ return encoded;
16
+ }
17
+
18
+ export function namespaceKeyPrefix(namespace: string): string {
19
+ return `${NAMESPACE_KEY_VERSION}${encodeNamespaceSegment(namespace)}:`;
20
+ }
21
+
22
+ export function namespaceKey(namespace: string, key: string): string {
23
+ return namespaceDomainKey(namespace, 'data', key);
24
+ }
25
+
26
+ export function namespaceDomainPrefix(namespace: string, domain: CacheKeyDomain): string {
27
+ return `${namespaceKeyPrefix(namespace)}${domain}:`;
28
+ }
29
+
30
+ export function namespaceDomainKey(namespace: string, domain: CacheKeyDomain, identifier: string): string {
31
+ return `${namespaceDomainPrefix(namespace, domain)}${identifier}`;
32
+ }
33
+
34
+ export function namespaceStreamKey(namespace: string, customBase?: string): string {
35
+ const namespaceTag = `ns-${encodeNamespaceSegment(namespace)}`;
36
+ const streamName = customBase === undefined
37
+ ? 'default'
38
+ : `custom-${encodeNamespaceSegment(customBase)}`;
39
+ return `${NAMESPACE_KEY_VERSION}stream:{${namespaceTag}}:${streamName}`;
40
+ }
41
+
42
+ export function namespaceBackplaneChannel(namespace: string): string {
43
+ return `${NAMESPACE_KEY_VERSION}inv:${encodeNamespaceSegment(namespace)}`;
44
+ }
45
+
46
+ export function namespaceSingletonKey(namespace: string): string {
47
+ return `__tricache_v3_ns_${encodeNamespaceSegment(namespace)}__`;
48
+ }
@@ -0,0 +1,13 @@
1
+ /** Stable typed serialization for ORM query keys; object property order is immaterial. */
2
+ export function deterministicStringify(val: unknown): string {
3
+ if (val instanceof Date) return `date:${JSON.stringify(val.toISOString())}`;
4
+ if (typeof val === 'bigint') return `bigint:${val}`;
5
+ if (val instanceof Uint8Array) return `binary:${Buffer.from(val.buffer, val.byteOffset, val.byteLength).toString('base64')}`;
6
+ if (val && typeof val === 'object' && typeof (val as { toJSON?: unknown }).toJSON === 'function') {
7
+ return deterministicStringify((val as { toJSON(): unknown }).toJSON());
8
+ }
9
+ if (val === null || typeof val !== 'object') return JSON.stringify(val) ?? 'undefined';
10
+ if (Array.isArray(val)) return `[${val.map(deterministicStringify).join(',')}]`;
11
+ const obj = val as Record<string, unknown>;
12
+ return `{${Object.keys(obj).sort().map(key => `${JSON.stringify(key)}:${deterministicStringify(obj[key])}`).join(',')}}`;
13
+ }
@@ -0,0 +1,83 @@
1
+ import { positiveLimit } from './work-limits.js';
2
+
3
+ export interface SnapshotTransferOptions {
4
+ /** Maximum downloaded snapshot bytes, enforced while streaming. Default: 220 MiB. */
5
+ maxBytes?: number;
6
+ /** Deadline covering the request and response body. Default: 30 seconds. */
7
+ timeoutMs?: number;
8
+ }
9
+
10
+ export interface SnapshotRequestOptions {
11
+ /** Cancel transport work, for example when the owning cache is destroyed. */
12
+ signal?: AbortSignal;
13
+ }
14
+
15
+ export async function snapshotRequest<T>(
16
+ options: SnapshotTransferOptions,
17
+ request: SnapshotRequestOptions | undefined,
18
+ work: (signal: AbortSignal, maxBytes: number) => Promise<T>,
19
+ ): Promise<T> {
20
+ const maxBytes = positiveLimit(options.maxBytes, 220 * 1024 * 1024, 'maxBytes');
21
+ const timeoutMs = positiveLimit(options.timeoutMs, 30_000, 'timeoutMs');
22
+ const controller = new AbortController();
23
+ const abort = () => controller.abort(request?.signal?.reason);
24
+ request?.signal?.addEventListener('abort', abort, { once: true });
25
+ if (request?.signal?.aborted) abort();
26
+ const timer = setTimeout(() => controller.abort(new Error('Snapshot request timed out')), timeoutMs);
27
+ let stopWaiting!: () => void;
28
+ const cancelled = new Promise<never>((_resolve, reject) => {
29
+ stopWaiting = () => reject(controller.signal.reason);
30
+ controller.signal.addEventListener('abort', stopWaiting, { once: true });
31
+ });
32
+ try {
33
+ controller.signal.throwIfAborted();
34
+ return await Promise.race([work(controller.signal, maxBytes), cancelled]);
35
+ } finally {
36
+ clearTimeout(timer);
37
+ request?.signal?.removeEventListener('abort', abort);
38
+ controller.signal.removeEventListener('abort', stopWaiting);
39
+ }
40
+ }
41
+
42
+ /** Cancel unused error/404/upload bodies without buffering them. */
43
+ export function discardSnapshotResponse(response: Response): void {
44
+ void response.body?.cancel().catch(() => {});
45
+ }
46
+
47
+ export async function readSnapshotResponse(response: Response, signal: AbortSignal, maxBytes: number): Promise<Buffer> {
48
+ const advertised = response.headers.get('content-length');
49
+ if (advertised !== null && Number(advertised) > maxBytes) {
50
+ discardSnapshotResponse(response);
51
+ throw new Error('Snapshot exceeds size limit');
52
+ }
53
+ // The deadline can expire after fetch resolves but before this body is read.
54
+ // Release the already-received body instead of leaking it uncancelled.
55
+ if (signal.aborted) {
56
+ discardSnapshotResponse(response);
57
+ signal.throwIfAborted();
58
+ }
59
+ if (!response.body) return Buffer.alloc(0);
60
+ const reader = response.body.getReader();
61
+ const cancel = () => { void reader.cancel(signal.reason).catch(() => {}); };
62
+ signal.addEventListener('abort', cancel, { once: true });
63
+ const chunks: Buffer[] = [];
64
+ let size = 0;
65
+ try {
66
+ while (true) {
67
+ signal.throwIfAborted();
68
+ const { done, value } = await reader.read();
69
+ signal.throwIfAborted();
70
+ if (done) break;
71
+ size += value.byteLength;
72
+ if (size > maxBytes) throw new Error('Snapshot exceeds size limit');
73
+ chunks.push(Buffer.from(value));
74
+ }
75
+ return Buffer.concat(chunks, size);
76
+ } catch (error) {
77
+ void reader.cancel(error).catch(() => {});
78
+ throw error;
79
+ } finally {
80
+ signal.removeEventListener('abort', cancel);
81
+ reader.releaseLock();
82
+ }
83
+ }
@@ -0,0 +1,73 @@
1
+ /** Fail before allocating queues or starting user work. No implicit retry. */
2
+ export class CacheCapacityError extends Error {
3
+ constructor(resource: string) {
4
+ super(`TriCache capacity exceeded: ${resource}`);
5
+ this.name = 'CacheCapacityError';
6
+ }
7
+ }
8
+
9
+ export function positiveLimit(value: number | undefined, fallback: number, name: string): number {
10
+ const limit = value ?? fallback;
11
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new RangeError(`${name} must be a positive safe integer`);
12
+ return limit;
13
+ }
14
+
15
+ export class WorkLimit {
16
+ private active = 0;
17
+ private rejected = 0;
18
+ constructor(readonly maximum: number, private readonly name: string) {}
19
+ acquire(weight = 1): () => void {
20
+ if (!Number.isSafeInteger(weight) || weight < 1) throw new RangeError('Work weight must be a positive safe integer');
21
+ if (weight > this.maximum - this.active) { this.rejected++; throw new CacheCapacityError(this.name); }
22
+ this.active += weight;
23
+ let released = false;
24
+ return () => { if (!released) { released = true; this.active -= weight; } };
25
+ }
26
+
27
+ metrics(): { active: number; capacity: number; rejected: number } {
28
+ return { active: this.active, capacity: this.maximum, rejected: this.rejected };
29
+ }
30
+
31
+ /** Grow one reservation without retaining one release closure per stream chunk. */
32
+ reservation(): { grow(weight: number): void; release(): void } {
33
+ let weight = 0;
34
+ let released = false;
35
+ return {
36
+ grow: (extra: number) => {
37
+ if (released) throw new Error('Cannot grow a released reservation');
38
+ if (!Number.isSafeInteger(extra) || extra < 1) throw new RangeError('Work weight must be a positive safe integer');
39
+ if (extra > this.maximum - this.active) { this.rejected++; throw new CacheCapacityError(this.name); }
40
+ this.active += extra;
41
+ weight += extra;
42
+ },
43
+ release: () => { if (!released) { released = true; this.active -= weight; } },
44
+ };
45
+ }
46
+ }
47
+
48
+ /** Count unique key/pattern edges shared by stored and pending registrations. */
49
+ export class DependencyBudget {
50
+ private edges = 0;
51
+ private readonly keys = new Map<string, Map<string, number>>();
52
+ constructor(private readonly maximum: number) {}
53
+ reserve(key: string, patterns: string[]): () => void {
54
+ const unique = [...new Set(patterns)];
55
+ const refs = this.keys.get(key) ?? new Map<string, number>();
56
+ const extra = unique.filter(pattern => !refs.has(pattern)).length;
57
+ if (extra > this.maximum - this.edges) throw new CacheCapacityError('dependency edges');
58
+ this.edges += extra;
59
+ if (unique.length) this.keys.set(key, refs);
60
+ for (const pattern of unique) refs.set(pattern, (refs.get(pattern) ?? 0) + 1);
61
+ let released = false;
62
+ return () => {
63
+ if (released) return;
64
+ released = true;
65
+ for (const pattern of unique) {
66
+ const count = refs.get(pattern)! - 1;
67
+ if (count > 0) refs.set(pattern, count);
68
+ else { refs.delete(pattern); this.edges--; }
69
+ }
70
+ if (!refs.size && this.keys.get(key) === refs) this.keys.delete(key);
71
+ };
72
+ }
73
+ }
@@ -0,0 +1,4 @@
1
+ /** Bound externally restored metadata; revisions are opaque equality identities. */
2
+ export function isWriteRevision(value: unknown): value is string {
3
+ return typeof value === 'string' && value.length > 0 && value.length <= 128;
4
+ }
@@ -56,6 +56,7 @@ export class WasmBloomFilter {
56
56
  private readonly exports: BloomWasmExports;
57
57
  private readonly mem: Uint8Array;
58
58
  private readonly stagingTarget: Uint8Array;
59
+ private readonly stagingView: DataView;
59
60
  private readonly encoder = new TextEncoder();
60
61
  private readonly numBits = 100_000;
61
62
  /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
@@ -68,13 +69,27 @@ export class WasmBloomFilter {
68
69
  this.exports = instance.exports as unknown as BloomWasmExports;
69
70
  this.mem = new Uint8Array(this.exports.memory.buffer);
70
71
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
72
+ this.stagingView = new DataView(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
71
73
  const k = 7, p = 0.01;
72
74
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
73
75
  }
74
76
 
75
77
  private writeKey(key: string): number {
76
78
  if (key.length === 0) return 0;
77
- return this.encoder.encodeInto(key, this.stagingTarget).written;
79
+ const encoded = this.encoder.encodeInto(key, this.stagingTarget);
80
+ if (encoded.read === key.length) return encoded.written;
81
+ // Hash the complete key when UTF-8 does not fit. 0xff cannot occur in valid
82
+ // UTF-8, so digests cannot alias a short key's staging representation.
83
+ let first = 0x811c9dc5, second = 5381;
84
+ for (let index = 0; index < key.length; index++) {
85
+ const unit = key.charCodeAt(index);
86
+ first = Math.imul(first ^ unit, 0x01000193) >>> 0;
87
+ second = (Math.imul(second, 33) ^ unit) >>> 0;
88
+ }
89
+ this.stagingTarget[0] = 0xff;
90
+ this.stagingView.setUint32(1, first, true);
91
+ this.stagingView.setUint32(5, second, true);
92
+ return 9;
78
93
  }
79
94
 
80
95
  add(key: string): void {
@@ -29,6 +29,7 @@ import { dirname, join } from 'path';
29
29
  import os from 'os';
30
30
  import type { EncryptionMode } from './encryption.js';
31
31
  import type { CompressionAlgorithm } from './compression.js';
32
+ import { positiveLimit, WorkLimit } from './utils/work-limits.js';
32
33
 
33
34
  // Locate the serialize-worker entry point.
34
35
  // Production: tsup emits compile .js files as flat siblings → use .js path.
@@ -70,10 +71,15 @@ export interface WorkerPoolOptions {
70
71
  mode: EncryptionMode;
71
72
  prevKeyBase64?: string;
72
73
  prevMode?: EncryptionMode;
74
+ allowLegacyPlaintextRead?: boolean;
73
75
  compression?: CompressionAlgorithm;
74
76
  compressionThresholdBytes?: number;
75
77
  /** Number of worker threads. Default: min(4, availableCPUs). */
76
78
  size?: number;
79
+ /** Bound all outstanding tasks, including retiring workers during key rotation. Default: 256. */
80
+ maxPendingTasks?: number;
81
+ /** Outstanding input/context byte admission, shared across rotations. Default: 64 MiB. Not an RSS ceiling. */
82
+ maxPendingBytes?: number;
77
83
  }
78
84
 
79
85
  type PendingEntry = { resolve: (v: string) => void; reject: (e: Error) => void };
@@ -105,6 +111,8 @@ export function getTransferableArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffe
105
111
  }
106
112
 
107
113
  export class WorkerPool {
114
+ private readonly limit: WorkLimit;
115
+ private readonly byteLimit: WorkLimit;
108
116
  private workers: Worker[] = [];
109
117
  private pending: Map<number, PendingEntry>[] = [];
110
118
  private _nextId = 0;
@@ -112,6 +120,8 @@ export class WorkerPool {
112
120
  private _available = false;
113
121
 
114
122
  constructor(opts: WorkerPoolOptions) {
123
+ this.limit = new WorkLimit(positiveLimit(opts.maxPendingTasks, 256, 'maxPendingTasks'), 'worker tasks');
124
+ this.byteLimit = new WorkLimit(positiveLimit(opts.maxPendingBytes, 64 * 1024 * 1024, 'maxPendingBytes'), 'worker input bytes');
115
125
  try {
116
126
  const { workers, pending } = this._spawnWorkers(opts);
117
127
  this.workers = workers;
@@ -132,6 +142,7 @@ export class WorkerPool {
132
142
  mode: opts.mode,
133
143
  prevKeyBase64: opts.prevKeyBase64 ?? '',
134
144
  prevMode: opts.prevMode,
145
+ allowLegacyPlaintextRead: opts.allowLegacyPlaintextRead,
135
146
  compression: opts.compression ?? 'none',
136
147
  compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024,
137
148
  };
@@ -234,25 +245,35 @@ export class WorkerPool {
234
245
  get isAvailable(): boolean { return this._available; }
235
246
 
236
247
  /** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
237
- encrypt(payload: string | Buffer | Uint8Array): Promise<string> {
238
- return this._dispatch('encrypt', payload);
248
+ encrypt(payload: string | Buffer | Uint8Array, context?: string): Promise<string> {
249
+ return this._dispatch('encrypt', payload, context);
239
250
  }
240
251
 
241
252
  /** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
242
- decrypt(payload: string | Buffer | Uint8Array): Promise<string> {
243
- return this._dispatch('decrypt', payload);
253
+ decrypt(payload: string | Buffer | Uint8Array, context?: string): Promise<string> {
254
+ return this._dispatch('decrypt', payload, context);
244
255
  }
245
256
 
246
- private _dispatch(type: 'encrypt' | 'decrypt', payload: string | Buffer | Uint8Array): Promise<string> {
257
+ private _dispatch(type: 'encrypt' | 'decrypt', payload: string | Buffer | Uint8Array, context?: string): Promise<string> {
247
258
  if (!this._available || this.workers.length === 0) {
248
259
  return Promise.reject(new Error('WorkerPool is not available'));
249
260
  }
261
+ let release: () => void;
262
+ try { release = this.limit.acquire(); }
263
+ catch (error) { return Promise.reject(error); }
264
+ let releaseBytes: () => void;
265
+ try {
266
+ const stringBytes = (value: string) => Math.max(Buffer.byteLength(value, 'utf8'), value.length * 2);
267
+ const bytes = (typeof payload === 'string' ? stringBytes(payload) : payload.byteLength) + (context ? stringBytes(context) : 0);
268
+ releaseBytes = this.byteLimit.acquire(Math.max(1, bytes));
269
+ } catch (error) { release(); return Promise.reject(error); }
250
270
  const id = this._nextId++;
251
271
  const idx = this._robin;
252
272
  const worker = this.workers[idx];
253
273
  const pending = this.pending[idx];
254
274
  this._robin = (this._robin + 1) % this.workers.length;
255
275
 
276
+ return new Promise<string>((resolve, reject) => {
256
277
  let transferable: ArrayBuffer | null = null;
257
278
  let dataToSend: string | Uint8Array = typeof payload === 'string' ? payload : payload;
258
279
 
@@ -271,18 +292,17 @@ export class WorkerPool {
271
292
 
272
293
  const transferList = transferable ? [transferable] : [];
273
294
 
274
- return new Promise<string>((resolve, reject) => {
275
295
  pending.set(id, { resolve, reject });
276
296
  // Re-ref the worker while this request is in flight so the event loop
277
297
  // stays alive even in short-lived scripts (benchmarks, CLI tools).
278
298
  worker.ref();
279
- try { worker.postMessage({ id, type, payload: dataToSend }, transferList); }
299
+ try { worker.postMessage({ id, type, payload: dataToSend, context }, transferList); }
280
300
  catch (error) {
281
301
  pending.delete(id);
282
302
  if (pending.size === 0) worker.unref();
283
303
  reject(error);
284
304
  }
285
- });
305
+ }).finally(() => { release(); releaseBytes(); });
286
306
  }
287
307
 
288
308
  /** Terminate all worker threads. In-flight promises are rejected. */
package/src/wtiny-lfu.ts CHANGED
@@ -65,6 +65,36 @@ export interface EvictionResult<K, V> {
65
65
  rejected?: { key: K; value: V; segment: 'window' };
66
66
  }
67
67
 
68
+ interface SegmentCapacities {
69
+ total: number;
70
+ window: number;
71
+ probation: number;
72
+ protected: number;
73
+ }
74
+
75
+ /**
76
+ * Normalize W-TinyLFU's integer segment budgets without allowing minimum
77
+ * segment sizes to exceed the configured total. Small caches cannot always
78
+ * have a non-empty window, probation, and protected segment simultaneously.
79
+ */
80
+ function segmentCapacities(capacity: number, windowPercent = 0.01, protectedPercent = 0.80): SegmentCapacities {
81
+ const total = Number.isFinite(capacity) && capacity > 0 ? Math.floor(capacity) : 0;
82
+ if (total === 0) return { total: 0, window: 0, probation: 0, protected: 0 };
83
+
84
+ const windowRatio = Number.isFinite(windowPercent) ? Math.min(1, Math.max(0, windowPercent)) : 0.01;
85
+ const protectedRatio = Number.isFinite(protectedPercent) ? Math.min(1, Math.max(0, protectedPercent)) : 0.80;
86
+ const window = Math.min(total, Math.max(1, Math.floor(total * windowRatio)));
87
+ const main = total - window;
88
+ if (main === 0) return { total, window, probation: 0, protected: 0 };
89
+
90
+ // Keep both main segments alive when there is room, while reserving the
91
+ // sole main slot for protected entries when main capacity is one.
92
+ const protectedCapacity = main === 1
93
+ ? 1
94
+ : Math.min(main - 1, Math.max(1, Math.floor(main * protectedRatio)));
95
+ return { total, window, probation: main - protectedCapacity, protected: protectedCapacity };
96
+ }
97
+
68
98
  /**
69
99
  * 4-row Count-Min Sketch for TinyLFU frequency estimation.
70
100
  * Uses Murmur3-style bit-mixes of FNV-1a digests with periodic halving decay.
@@ -178,15 +208,11 @@ export class WTinyLfuCache<K = string, V = unknown> {
178
208
  private demotionCount = 0;
179
209
 
180
210
  constructor(options: WTinyLfuOptions) {
181
- this.maxTotal = Math.max(2, options.capacity);
182
-
183
- const winPercent = options.windowPercent ?? 0.01;
184
- this.maxWindow = Math.max(1, Math.floor(this.maxTotal * winPercent));
185
-
186
- const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
187
- const protPercent = options.protectedPercent ?? 0.80;
188
- this.maxProtected = Math.max(1, Math.floor(mainCapacity * protPercent));
189
- this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
211
+ const segments = segmentCapacities(options.capacity, options.windowPercent, options.protectedPercent);
212
+ this.maxTotal = segments.total;
213
+ this.maxWindow = segments.window;
214
+ this.maxProtected = segments.protected;
215
+ this.maxProbation = segments.probation;
190
216
 
191
217
  this.sketch = new TinyLfuSketch(options.sketchWidth ?? 1024);
192
218
  }
@@ -272,6 +298,12 @@ export class WTinyLfuCache<K = string, V = unknown> {
272
298
 
273
299
  const result: EvictionResult<K, V> = {};
274
300
 
301
+ if (this.maxTotal === 0) {
302
+ result.rejected = { key, value, segment: 'window' };
303
+ this.rejectionCount++;
304
+ return result;
305
+ }
306
+
275
307
  // ── 1. Update existing key if present in any segment ────────────────────
276
308
  if (this.window.has(key)) {
277
309
  this.window.delete(key);
@@ -305,6 +337,12 @@ export class WTinyLfuCache<K = string, V = unknown> {
305
337
  const candVal = this.window.get(candKey)!;
306
338
  this.window.delete(candKey);
307
339
 
340
+ if (this.maxProbation + this.maxProtected === 0) {
341
+ this.rejectionCount++;
342
+ result.rejected = { key: candKey, value: candVal, segment: 'window' };
343
+ return result;
344
+ }
345
+
308
346
  // If Main cache has headroom, admit candidate directly to Probation
309
347
  if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
310
348
  this.probation.set(candKey, candVal);
@@ -462,11 +500,11 @@ export class WTinyLfuPolicy {
462
500
  protectedPercent = 0.80,
463
501
  private readonly canEvict?: (key: string) => boolean,
464
502
  ) {
465
- this.maxTotal = Math.max(2, capacity);
466
- this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
467
- const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
468
- this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
469
- this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
503
+ const segments = segmentCapacities(capacity, windowPercent, protectedPercent);
504
+ this.maxTotal = segments.total;
505
+ this.maxWindow = segments.window;
506
+ this.maxProtected = segments.protected;
507
+ this.maxProbation = segments.probation;
470
508
  }
471
509
 
472
510
  get windowSize(): number {
@@ -516,6 +554,11 @@ export class WTinyLfuPolicy {
516
554
  }
517
555
 
518
556
  onSet(key: string, isUpdate: boolean): WTinyLfuAdmissionDecision {
557
+ if (this.maxTotal === 0) {
558
+ this.rejectionCount++;
559
+ return { admit: false, candidateKey: key };
560
+ }
561
+
519
562
  if (isUpdate) {
520
563
  if (this.window.has(key)) {
521
564
  this.window.delete(key);
@@ -542,6 +585,11 @@ export class WTinyLfuPolicy {
542
585
  const candKey = this.window.values().next().value!;
543
586
  this.window.delete(candKey);
544
587
 
588
+ if (this.maxProbation + this.maxProtected === 0) {
589
+ this.rejectionCount++;
590
+ return { admit: false, candidateKey: candKey };
591
+ }
592
+
545
593
  // If main cache has headroom, admit to Probation
546
594
  if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
547
595
  this.probation.add(candKey);
@@ -1,12 +0,0 @@
1
- import {
2
- CacheService,
3
- ProcessTerminationBus,
4
- deepMergeOptions
5
- } from "./chunk-WYF7NOAT.js";
6
- import "./chunk-UBWLPKTI.js";
7
- import "./chunk-H4GFLQ26.js";
8
- export {
9
- CacheService,
10
- ProcessTerminationBus,
11
- deepMergeOptions
12
- };