tricache 1.0.1 → 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.
- package/README.md +89 -93
- package/dashboards/tricache-alerts.yaml +80 -4
- package/dashboards/tricache-grafana.json +54 -1
- package/dashboards/tricache-inventory.rules.yml +21 -0
- package/dist/cache-service-BV5T8-20.d.cts +1064 -0
- package/dist/cache-service-UZXOQGEY.js +14 -0
- package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
- package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
- package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
- package/dist/chunk-RBJRTGFK.js +94 -0
- package/dist/chunk-S5N65I45.js +17 -0
- package/dist/cli.cjs +3694 -1070
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +210 -14
- 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 +3578 -1068
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +6 -2
- package/dist/edge/index.cjs +368 -162
- package/dist/edge/index.d.cts +134 -0
- package/dist/edge/index.d.ts +11 -4
- package/dist/edge/index.js +314 -155
- package/dist/hono/index.cjs +3614 -1087
- 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-CMv2VdQ6.d.cts +404 -0
- package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
- package/dist/http/index.cjs +3712 -1124
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +92 -43
- package/dist/index.cjs +4067 -1252
- package/dist/index.d.cts +1071 -0
- package/dist/index.d.ts +123 -27
- package/dist/index.js +878 -21
- package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
- package/dist/murmur3-DF8BFRnu.d.ts +99 -0
- package/dist/nestjs/index.cjs +3635 -1112
- package/dist/nestjs/index.d.cts +299 -0
- package/dist/nestjs/index.d.ts +120 -33
- package/dist/nestjs/index.js +132 -43
- package/dist/next/index.cjs +3704 -1175
- package/dist/next/index.d.cts +238 -0
- package/dist/next/index.d.ts +39 -11
- package/dist/next/index.js +202 -102
- package/dist/prisma/index.cjs +29 -18
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +17 -18
- package/dist/serialize-worker.cjs +162 -39
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.js +9 -7
- package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
- package/dist/types-F8vRWMrE.d.ts +1636 -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 +116 -37
- package/src/adapters/auto-pipeliner.ts +150 -26
- package/src/adapters/node-redis.ts +106 -27
- package/src/cache-service.ts +2215 -793
- package/src/cli.ts +25 -14
- package/src/codec.ts +3 -3
- package/src/compression.ts +39 -16
- package/src/cross-region.ts +22 -4
- 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 +448 -102
- package/src/drizzle/index.ts +2 -1
- package/src/edge/adapters/cloudflare-do.ts +25 -10
- package/src/edge/adapters/cloudflare-kv.ts +12 -9
- package/src/edge/adapters/upstash.ts +27 -11
- package/src/edge/cache.ts +200 -110
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +17 -5
- package/src/encryption.ts +50 -18
- package/src/env.d.ts +1 -1
- package/src/errors.ts +12 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +62 -17
- package/src/http/fastify.ts +35 -21
- package/src/http/utils.ts +60 -20
- package/src/index.ts +6 -0
- package/src/ipc-telemetry.ts +35 -9
- package/src/latency-watchdog.ts +5 -1
- package/src/nestjs/decorators.ts +11 -6
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +15 -12
- package/src/nestjs/tricache.store.ts +69 -26
- package/src/nestjs/types.ts +30 -16
- package/src/next/cache-handler.ts +151 -53
- package/src/next/index.ts +1 -0
- package/src/next/types.ts +25 -0
- package/src/origin-capacity.ts +134 -0
- package/src/prisma/index.ts +17 -24
- package/src/remote-snapshot.ts +37 -27
- package/src/serialize-worker.ts +8 -5
- package/src/sigv4-snapshot-adapter.ts +37 -27
- package/src/smart-memory-cache.ts +121 -44
- package/src/types.ts +117 -37
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/config-comparison.ts +29 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/lz4-size.ts +74 -0
- package/src/utils/namespace-key.ts +48 -0
- package/src/utils/query-key.ts +13 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/utils/snapshot-transfer.ts +83 -0
- package/src/utils/work-limits.ts +73 -0
- package/src/utils/write-revision.ts +4 -0
- package/src/wasm/bloom-filter-wasm.ts +25 -5
- package/src/worker-pool.ts +44 -15
- package/src/wtiny-lfu.ts +82 -20
- package/dist/cache-service-MG7PN6MX.js +0 -12
- package/dist/chunk-3I5L7K6I.js +0 -704
- package/dist/chunk-BQRURGGD.js +0 -60
package/src/types.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { RemoteSnapshotOptions } from './remote-snapshot';
|
|
2
2
|
import type { CrossRegionRelayOptions } from './cross-region';
|
|
3
3
|
import type { CompressionAlgorithm, CustomCompressor } from './compression';
|
|
4
|
+
import type { OriginCapacityLimiter, OriginCapacityMetrics } from './origin-capacity';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* tricache — shared types and interfaces
|
|
@@ -25,7 +26,7 @@ export interface ICacheSpanLink {
|
|
|
25
26
|
export interface ICacheSpan {
|
|
26
27
|
setAttribute(key: string, value: string | number | boolean): this;
|
|
27
28
|
setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
|
|
28
|
-
recordException?(err:
|
|
29
|
+
recordException?(err: unknown): void;
|
|
29
30
|
end(): void;
|
|
30
31
|
}
|
|
31
32
|
|
|
@@ -125,8 +126,13 @@ export interface SmartCacheEntry {
|
|
|
125
126
|
* Optional for backward compatibility with snapshots written by older versions.
|
|
126
127
|
*/
|
|
127
128
|
setAt?: number;
|
|
129
|
+
/** Opaque identity of this write, preserved across tiers and snapshots. */
|
|
130
|
+
revision?: string;
|
|
128
131
|
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
129
132
|
tagVersions?: Record<string, number>;
|
|
133
|
+
/** Set-based tags and dependency patterns preserved through disk/snapshot promotion. */
|
|
134
|
+
tags?: string[];
|
|
135
|
+
dependsOn?: string[];
|
|
130
136
|
}
|
|
131
137
|
|
|
132
138
|
/** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
|
|
@@ -148,6 +154,9 @@ export interface CacheHit {
|
|
|
148
154
|
tagVersions?: Record<string, number>;
|
|
149
155
|
/** Timestamp (ms) when this entry was written into memory */
|
|
150
156
|
setAt?: number;
|
|
157
|
+
revision?: string;
|
|
158
|
+
tags?: string[];
|
|
159
|
+
dependsOn?: string[];
|
|
151
160
|
}
|
|
152
161
|
|
|
153
162
|
// ─── Disk tier ───────────────────────────────────────────────────────────────
|
|
@@ -165,6 +174,13 @@ export interface DiskCacheEntry {
|
|
|
165
174
|
priority: number;
|
|
166
175
|
/** Active tag versions at write time (used when tagStrategy === 'generational') */
|
|
167
176
|
tagVersions?: Record<string, number>;
|
|
177
|
+
/** Original write time and TTL, preserved on spill and promotion. */
|
|
178
|
+
setAt?: number;
|
|
179
|
+
revision?: string;
|
|
180
|
+
ttlMs?: number;
|
|
181
|
+
delta?: number;
|
|
182
|
+
tags?: string[];
|
|
183
|
+
dependsOn?: string[];
|
|
168
184
|
}
|
|
169
185
|
|
|
170
186
|
// ─── Metrics snapshot ────────────────────────────────────────────────────────
|
|
@@ -180,6 +196,14 @@ export interface CacheMetrics {
|
|
|
180
196
|
/** Milliseconds since the CacheService instance was constructed */
|
|
181
197
|
uptimeMs: number;
|
|
182
198
|
|
|
199
|
+
/** Per-cache admission accounting; active origin work remains reserved until its physical promise settles. */
|
|
200
|
+
work?: {
|
|
201
|
+
origin: { active: number; capacity: number; rejected: number };
|
|
202
|
+
background: { active: number; capacity: number; rejected: number };
|
|
203
|
+
};
|
|
204
|
+
/** Process-shared physical origin budget, when an OriginCapacityLimiter is configured. */
|
|
205
|
+
originCapacity?: OriginCapacityMetrics;
|
|
206
|
+
|
|
183
207
|
gets: {
|
|
184
208
|
total: number;
|
|
185
209
|
l1Hits: number;
|
|
@@ -209,6 +233,8 @@ export interface CacheMetrics {
|
|
|
209
233
|
errors: number;
|
|
210
234
|
/** Times a later `create(ns)` call passed options diverging from the live singleton. */
|
|
211
235
|
singletonDivergences: number;
|
|
236
|
+
/** Cached reads rejected because strict invalidation protection was active. */
|
|
237
|
+
invalidationReadRejections?: number;
|
|
212
238
|
};
|
|
213
239
|
|
|
214
240
|
bloom: {
|
|
@@ -234,6 +260,18 @@ export interface CacheMetrics {
|
|
|
234
260
|
backplane: {
|
|
235
261
|
enabled: boolean;
|
|
236
262
|
mode: 'pubsub' | 'stream';
|
|
263
|
+
/** True when cached values are rejected while the invalidation consumer is unavailable. */
|
|
264
|
+
readProtectionEnabled?: boolean;
|
|
265
|
+
/** Current strict-read protection state. */
|
|
266
|
+
readProtectionActive?: boolean;
|
|
267
|
+
/** Sanitized reason for the current protection state, when active. */
|
|
268
|
+
readProtectionReason?: string;
|
|
269
|
+
/** Date.now() timestamp when the current protection state began. */
|
|
270
|
+
readProtectionSince?: number | null;
|
|
271
|
+
/** Monotonic elapsed milliseconds while the read gate is closed (zero when open). */
|
|
272
|
+
readProtectionDurationMs?: number;
|
|
273
|
+
/** Configured consumer proof deadline when strict protection is enabled. */
|
|
274
|
+
readProtectionDeadlineMs?: number;
|
|
237
275
|
/** Invalidation messages published to other instances */
|
|
238
276
|
sent: number;
|
|
239
277
|
/** Invalidation messages received from other instances */
|
|
@@ -360,6 +398,18 @@ export type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterp
|
|
|
360
398
|
* All fields are optional — sensible defaults are used when omitted.
|
|
361
399
|
*/
|
|
362
400
|
export interface CacheOptions {
|
|
401
|
+
/** Optional process-wide origin budget shared with other caches and direct-origin fallback. */
|
|
402
|
+
originCapacityLimiter?: OriginCapacityLimiter;
|
|
403
|
+
/** Maximum concurrent origin invocations (batch calls reserve one slot per owned key). Default: 1024. Saturated misses reject; no queue. */
|
|
404
|
+
maxConcurrentFetches?: number;
|
|
405
|
+
/** Maximum concurrent background refreshes, also subject to maxConcurrentFetches. Default: 64. */
|
|
406
|
+
maxBackgroundRefreshes?: number;
|
|
407
|
+
/** Maximum unique stored/pending dependency edges per instance. Default: 100000. */
|
|
408
|
+
maxDependencyEdges?: number;
|
|
409
|
+
/** Maximum outstanding serialization tasks, including pools draining during rotation. Default: 256. */
|
|
410
|
+
workerMaxPendingTasks?: number;
|
|
411
|
+
/** Outstanding worker input/context admission across rotation. Default: 64 MiB; not total process memory. */
|
|
412
|
+
workerMaxPendingBytes?: number;
|
|
363
413
|
/**
|
|
364
414
|
* Plug in your own logger (pino, winston, bunyan, …).
|
|
365
415
|
* Defaults to a minimal console logger that only prints warn/error.
|
|
@@ -392,7 +442,7 @@ export interface CacheOptions {
|
|
|
392
442
|
* - `'wtinylfu'`: Window TinyLFU admission policy (popularized by Caffeine) providing
|
|
393
443
|
* mathematical scan resistance and burst recency absorption.
|
|
394
444
|
* - `'adaptive'`: Adaptive LFU x LRU x priority reservoir sampling.
|
|
395
|
-
* Default: `'wtinylfu'
|
|
445
|
+
* Default: `'adaptive'`; all built-in presets explicitly select `'wtinylfu'`.
|
|
396
446
|
*/
|
|
397
447
|
l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
|
|
398
448
|
|
|
@@ -477,7 +527,7 @@ export interface CacheOptions {
|
|
|
477
527
|
/**
|
|
478
528
|
* Coalesce Redis operations executed within the identical synchronous tick into a single pipeline round-trip via queueMicrotask.
|
|
479
529
|
* Eliminates syscall and network overhead under heavy concurrent traffic with 0ms event-loop delay.
|
|
480
|
-
* Default:
|
|
530
|
+
* Default: true
|
|
481
531
|
*/
|
|
482
532
|
autoPipeline?: boolean;
|
|
483
533
|
/**
|
|
@@ -558,9 +608,12 @@ export interface CacheOptions {
|
|
|
558
608
|
*/
|
|
559
609
|
strictKeyValidation?: boolean;
|
|
560
610
|
|
|
611
|
+
/** Permit legacy context-free ciphertext/plaintext reads during a deliberate migration. Default: false. */
|
|
612
|
+
allowLegacyPlaintextRead?: boolean;
|
|
613
|
+
|
|
561
614
|
// ── Serialization & Codec (msgpackr) ────────────────────────────────────
|
|
562
615
|
/**
|
|
563
|
-
* Whether to call `.toJSON()` when serializing objects
|
|
616
|
+
* Whether to call `.toJSON()` when serializing objects for packed buffers and Redis.
|
|
564
617
|
* - `true` (default): Honors `.toJSON()`, matching standard JSON serialization conventions.
|
|
565
618
|
* - `false`: Preserves the object's own internal properties (msgpackr 2.1.0+ durable state feature),
|
|
566
619
|
* avoiding accidental API response projections on cached domain entities.
|
|
@@ -595,7 +648,7 @@ export interface CacheOptions {
|
|
|
595
648
|
// ── Snapshot ────────────────────────────────────────────────────────────
|
|
596
649
|
/**
|
|
597
650
|
* Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
|
|
598
|
-
* on startup. Default: os.tmpdir()/tricache-snapshot
|
|
651
|
+
* on startup. Default: os.tmpdir()/tricache-snapshot-v3-<namespace-hex>.msgpack
|
|
599
652
|
*/
|
|
600
653
|
snapshotPath?: string;
|
|
601
654
|
/**
|
|
@@ -609,24 +662,16 @@ export interface CacheOptions {
|
|
|
609
662
|
remoteSnapshot?: RemoteSnapshotOptions;
|
|
610
663
|
|
|
611
664
|
/**
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
*
|
|
615
|
-
* L1, L1.5 (disk), and L2 (Redis). This enables:
|
|
616
|
-
* - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
|
|
617
|
-
* — tenants sharing the same Redis instance or disk dir are fully isolated.
|
|
618
|
-
* - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
|
|
619
|
-
* - **Service-level scoping**: microservices sharing one Redis without key collisions.
|
|
665
|
+
* Namespace identifier used to derive collision-free, versioned storage keys
|
|
666
|
+
* across L1, disk, Redis, invalidation, and snapshots. The identifier is trimmed.
|
|
667
|
+
* Consumers continue to use logical keys such as `get('user:1')`.
|
|
620
668
|
*
|
|
621
|
-
*
|
|
622
|
-
*
|
|
623
|
-
*
|
|
669
|
+
* The v3 format separates data, tag sets, tag versions, and locks. It does not
|
|
670
|
+
* read earlier raw/colon-prefixed or v2 entries as a fallback. Upgrades start
|
|
671
|
+
* cold; coordinate all writers onto v3 or isolate storage during rollout.
|
|
624
672
|
*
|
|
625
|
-
*
|
|
626
|
-
*
|
|
627
|
-
* with different namespaces return completely independent instances.
|
|
628
|
-
*
|
|
629
|
-
* Default: `''` (no prefix)
|
|
673
|
+
* Use separate Node and Edge namespaces: their value formats are not interoperable.
|
|
674
|
+
* Default: `''` (the default namespace, also stored under the v3 format).
|
|
630
675
|
*/
|
|
631
676
|
namespace?: string;
|
|
632
677
|
|
|
@@ -695,6 +740,18 @@ export interface CacheOptions {
|
|
|
695
740
|
*/
|
|
696
741
|
awaitInvalidationBackplane?: boolean;
|
|
697
742
|
|
|
743
|
+
/**
|
|
744
|
+
* Reject cached reads while the invalidation consumer is unavailable or has
|
|
745
|
+
* missed its heartbeat deadline. The caller can catch
|
|
746
|
+
* `CacheInvalidationUnavailableError` and use an authoritative origin route.
|
|
747
|
+
* This is opt-in; `false` preserves the default availability-first behavior.
|
|
748
|
+
* Requires active Redis/invalidation, a supported dedicated subscriber, and a
|
|
749
|
+
* finite positive `backplaneMaxStalenessMs` detection deadline. Reads/fills
|
|
750
|
+
* spanning a gate closure reject even if the consumer recovers meanwhile.
|
|
751
|
+
* Strict startup skips snapshot hydration and discards existing local spill.
|
|
752
|
+
*/
|
|
753
|
+
rejectCachedReadsOnInvalidationLoss?: boolean;
|
|
754
|
+
|
|
698
755
|
/**
|
|
699
756
|
* If `true`, `cache.lock()` operations fail closed (throw an Error) if Redis
|
|
700
757
|
* encounters a connection or runtime error during lock acquisition, preventing
|
|
@@ -849,17 +906,19 @@ export interface CacheOptions {
|
|
|
849
906
|
|
|
850
907
|
/**
|
|
851
908
|
* When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
|
|
852
|
-
* and
|
|
909
|
+
* and derives a cost-based TTL from the p95 fetch duration:
|
|
853
910
|
*
|
|
854
911
|
* ```
|
|
855
|
-
*
|
|
912
|
+
* adaptedTtlMs = clamp(round(p95LatencyMs × adaptiveTtlMultiplier),
|
|
913
|
+
* adaptiveTtlMin × 1000, adaptiveTtlMax × 1000)
|
|
856
914
|
* ```
|
|
857
915
|
*
|
|
858
916
|
* The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
|
|
859
917
|
* for a key, then the library takes over TTL management autonomously.
|
|
860
918
|
*
|
|
861
|
-
*
|
|
862
|
-
*
|
|
919
|
+
* More expensive keys receive longer derived TTLs than cheaper keys, subject
|
|
920
|
+
* to the configured bounds. Fetch latency does not establish data freshness:
|
|
921
|
+
* choose adaptiveTtlMin/Max to match your application's stale-data tolerance.
|
|
863
922
|
*
|
|
864
923
|
* Default: `false`.
|
|
865
924
|
*/
|
|
@@ -880,11 +939,13 @@ export interface CacheOptions {
|
|
|
880
939
|
adaptiveTtlMax?: number;
|
|
881
940
|
|
|
882
941
|
/**
|
|
883
|
-
* `p95FetchLatencyMs × adaptiveTtlMultiplier =
|
|
942
|
+
* Dimensionless factor: `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlMs`
|
|
943
|
+
* before applying the minimum and maximum (configured in seconds).
|
|
884
944
|
*
|
|
885
945
|
* Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
|
|
886
|
-
* 4-second TTL
|
|
887
|
-
*
|
|
946
|
+
* 4-second derived TTL, raised to 10 seconds by the default minimum.
|
|
947
|
+
* A 2 000 ms fetch yields 40 seconds. Increase the multiplier if you want
|
|
948
|
+
* the cache to absorb more upstream pressure, within your freshness bounds.
|
|
888
949
|
*
|
|
889
950
|
* Default: `20`.
|
|
890
951
|
*/
|
|
@@ -908,12 +969,11 @@ export interface CacheOptions {
|
|
|
908
969
|
|
|
909
970
|
// ── Worker-thread serialization offload ────────────────────────────────────
|
|
910
971
|
/**
|
|
911
|
-
* When `true`, tricache spawns a pool of worker threads and offloads
|
|
912
|
-
*
|
|
913
|
-
* V8 main event loop free for concurrent HTTP requests.
|
|
972
|
+
* When `true`, tricache spawns a pool of worker threads and offloads
|
|
973
|
+
* compression and encryption/decryption of large Redis payloads.
|
|
914
974
|
*
|
|
915
|
-
*
|
|
916
|
-
*
|
|
975
|
+
* MessagePack encode/decode remains on the calling thread. Compression can
|
|
976
|
+
* run in workers even without encryption; custom compressors run locally.
|
|
917
977
|
*
|
|
918
978
|
* Default: `false`. Enable in long-running servers that write multi-megabyte
|
|
919
979
|
* encrypted payloads and observe event-loop latency spikes.
|
|
@@ -944,6 +1004,9 @@ export interface CacheOptions {
|
|
|
944
1004
|
*
|
|
945
1005
|
* Set to `0` to disable the fence entirely (accept eventual-consistency drift).
|
|
946
1006
|
* Default: `5000` (5 seconds).
|
|
1007
|
+
* With `rejectCachedReadsOnInvalidationLoss`, this also bounds silent loss
|
|
1008
|
+
* detection since the send time of the last acknowledged consumer challenge.
|
|
1009
|
+
* Strict mode requires a finite positive value and uses monotonic elapsed time.
|
|
947
1010
|
*/
|
|
948
1011
|
backplaneMaxStalenessMs?: number;
|
|
949
1012
|
|
|
@@ -1089,8 +1152,8 @@ export interface CacheOptions {
|
|
|
1089
1152
|
backplaneStreamBlockMs?: number;
|
|
1090
1153
|
|
|
1091
1154
|
/**
|
|
1092
|
-
* Custom Redis Stream key
|
|
1093
|
-
*
|
|
1155
|
+
* Custom Redis Stream key base. TriCache adds a namespace-specific suffix so
|
|
1156
|
+
* streams remain isolated. The default is hash-tagged for Redis Cluster routing.
|
|
1094
1157
|
*/
|
|
1095
1158
|
backplaneStreamKey?: string;
|
|
1096
1159
|
|
|
@@ -1125,7 +1188,11 @@ export interface WrapOptions {
|
|
|
1125
1188
|
priority?: CachePriority;
|
|
1126
1189
|
/** Semantic tags for invalidation. */
|
|
1127
1190
|
tags?: string[];
|
|
1128
|
-
/**
|
|
1191
|
+
/**
|
|
1192
|
+
* Logical source-key patterns (e.g. `['user:*']`) for transitive exact-key
|
|
1193
|
+
* invalidation. Discovery uses process-local entry metadata and active writers;
|
|
1194
|
+
* it is not a shared fleet-wide dependency index.
|
|
1195
|
+
*/
|
|
1129
1196
|
dependsOn?: string[];
|
|
1130
1197
|
/** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
|
|
1131
1198
|
refreshAhead?: number;
|
|
@@ -1169,8 +1236,13 @@ export interface ICacheCounter {
|
|
|
1169
1236
|
add(value: number, attributes?: Record<string, string | number | boolean>): void;
|
|
1170
1237
|
}
|
|
1171
1238
|
|
|
1239
|
+
export type ICacheObservableCallback = (result: {
|
|
1240
|
+
observe(value: number, attributes?: Record<string, string | number | boolean>): void;
|
|
1241
|
+
}) => void | Promise<void>;
|
|
1242
|
+
|
|
1172
1243
|
export interface ICacheObservableGauge {
|
|
1173
|
-
|
|
1244
|
+
addCallback(callback: ICacheObservableCallback): void;
|
|
1245
|
+
removeCallback(callback: ICacheObservableCallback): void;
|
|
1174
1246
|
}
|
|
1175
1247
|
|
|
1176
1248
|
export interface ICacheBatchObservableCallback {
|
|
@@ -1183,6 +1255,7 @@ export interface ICacheMeter {
|
|
|
1183
1255
|
createCounter(name: string, options?: { description?: string; unit?: string }): ICacheCounter;
|
|
1184
1256
|
createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
|
|
1185
1257
|
addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
1258
|
+
removeBatchObservableCallback?(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
|
|
1186
1259
|
}
|
|
1187
1260
|
|
|
1188
1261
|
/**
|
|
@@ -1199,6 +1272,9 @@ export interface IRedisPipeline {
|
|
|
1199
1272
|
smembers(key: string): this;
|
|
1200
1273
|
hset(key: string, value: Record<string, string>): this;
|
|
1201
1274
|
hgetall?(key: string): this;
|
|
1275
|
+
/** Remaining TTL in milliseconds; enables atomic value + expiry reads. */
|
|
1276
|
+
pttl?(key: string): this;
|
|
1277
|
+
eval?(script: string, numkeys: number, ...args: (string | number)[]): this;
|
|
1202
1278
|
exec(): Promise<Array<[Error | null, any]> | null>;
|
|
1203
1279
|
}
|
|
1204
1280
|
|
|
@@ -1212,6 +1288,7 @@ export interface IRedisDriver {
|
|
|
1212
1288
|
setex?(key: string, seconds: number, value: string): Promise<unknown>;
|
|
1213
1289
|
del(...keys: string[]): Promise<number>;
|
|
1214
1290
|
ping(): Promise<string>;
|
|
1291
|
+
pttl?(key: string): Promise<number>;
|
|
1215
1292
|
expire(key: string, seconds: number): Promise<number | boolean>;
|
|
1216
1293
|
incr(key: string): Promise<number>;
|
|
1217
1294
|
eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
@@ -1222,9 +1299,12 @@ export interface IRedisDriver {
|
|
|
1222
1299
|
scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
|
|
1223
1300
|
scanStream?(options?: { match?: string; count?: number }): any;
|
|
1224
1301
|
hset?(key: string, value: Record<string, string>): Promise<unknown>;
|
|
1302
|
+
/** Enables tagged hash envelopes, preserving tags/deadlines on cold reads and touch(). */
|
|
1225
1303
|
hgetall?(key: string): Promise<Record<string, string>>;
|
|
1226
1304
|
publish?(channel: string, message: string): Promise<number>;
|
|
1227
1305
|
subscribe?(...channels: string[]): Promise<unknown>;
|
|
1306
|
+
unsubscribe?(...channels: string[]): Promise<unknown>;
|
|
1307
|
+
removeListener?(event: string, listener: (...args: any[]) => void): this | unknown;
|
|
1228
1308
|
disconnect(): Promise<void> | void;
|
|
1229
1309
|
quit?(): Promise<void> | void;
|
|
1230
1310
|
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,29 @@
|
|
|
1
|
+
// Opaque resources retain identity. Plain configuration containers are copied so
|
|
2
|
+
// mutating the caller's object later cannot rewrite the singleton's baseline.
|
|
3
|
+
const IDENTITY_KEYS = new Set(['redisClient', 'redisSubClient', 'originCapacityLimiter', 'logger', 'tracer', 'meter', 'adapter', 'relay']);
|
|
4
|
+
|
|
5
|
+
export function captureConfiguration(value: unknown, key = '', seen = new WeakMap<object, unknown>()): any {
|
|
6
|
+
if (value === null || typeof value !== 'object' || IDENTITY_KEYS.has(key)) return value;
|
|
7
|
+
const prototype = Object.getPrototypeOf(value);
|
|
8
|
+
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return value;
|
|
9
|
+
if (seen.has(value)) return seen.get(value);
|
|
10
|
+
const result: any = Array.isArray(value) ? [] : Object.create(null);
|
|
11
|
+
seen.set(value, result);
|
|
12
|
+
for (const field of Object.keys(value)) result[field] = captureConfiguration((value as any)[field], field, seen);
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function sameConfiguration(a: unknown, b: unknown, key = '', seen = new WeakMap<object, WeakSet<object>>()): boolean {
|
|
17
|
+
if (Object.is(a, b)) return true;
|
|
18
|
+
if (IDENTITY_KEYS.has(key) || a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
|
|
19
|
+
const plain = (value: object) => Array.isArray(value) || [null, Object.prototype].includes(Object.getPrototypeOf(value));
|
|
20
|
+
if (!plain(a) || !plain(b) || Array.isArray(a) !== Array.isArray(b)) return false;
|
|
21
|
+
if (Array.isArray(a) && a.length !== (b as unknown[]).length) return false;
|
|
22
|
+
const pairs = seen.get(a) ?? new WeakSet<object>();
|
|
23
|
+
if (pairs.has(b)) return true;
|
|
24
|
+
pairs.add(b);
|
|
25
|
+
seen.set(a, pairs);
|
|
26
|
+
const keys = Object.keys(a).sort(), other = Object.keys(b).sort();
|
|
27
|
+
return keys.length === other.length && keys.every((field, index) => field === other[index] &&
|
|
28
|
+
sameConfiguration((a as any)[field], (b as any)[field], field, seen));
|
|
29
|
+
}
|
|
@@ -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,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,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
|
+
}
|