tricache 0.8.0 → 1.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 +10 -4
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
- package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
- package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
- package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
- package/dist/cli.cjs +767 -133
- package/dist/cli.js +24 -6
- package/dist/dashboard/index.d.ts +2 -2
- package/dist/drizzle/index.cjs +734 -132
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +163 -46
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +42 -14
- package/dist/hono/index.cjs +8093 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
- package/dist/http/index.cjs +833 -170
- package/dist/http/index.d.ts +6 -30
- package/dist/http/index.js +9 -59
- package/dist/index.cjs +755 -130
- package/dist/index.d.ts +35 -6
- package/dist/index.js +16 -6
- package/dist/nestjs/index.cjs +725 -130
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +4 -4
- package/dist/next/index.cjs +725 -130
- package/dist/next/index.d.ts +2 -2
- package/dist/next/index.js +3 -3
- package/dist/prisma/index.d.ts +2 -2
- package/dist/serialize-worker.cjs +127 -9
- package/dist/serialize-worker.js +8 -4
- package/dist/{types-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +22 -9
- package/src/cache-service.ts +540 -68
- package/src/cli.ts +21 -4
- package/src/compression.ts +193 -15
- package/src/cross-region.ts +1 -1
- package/src/edge/cache.ts +38 -11
- package/src/edge/hono.ts +123 -42
- package/src/env.d.ts +13 -0
- package/src/hono/index.ts +316 -0
- package/src/http/index.ts +5 -0
- package/src/index.ts +9 -1
- package/src/ipc-telemetry.ts +29 -1
- package/src/serialize-worker.ts +6 -2
- package/src/types.ts +68 -5
- package/src/utils/tag-matcher.ts +90 -0
- package/dist/chunk-ZTSWCFYO.js +0 -135
- /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
|
@@ -7,11 +7,16 @@ import {
|
|
|
7
7
|
compressWithHeader,
|
|
8
8
|
consoleLogger,
|
|
9
9
|
decompressBuffer,
|
|
10
|
-
decompressWithHeader
|
|
11
|
-
|
|
10
|
+
decompressWithHeader,
|
|
11
|
+
initZstd
|
|
12
|
+
} from "./chunk-UBWLPKTI.js";
|
|
12
13
|
import {
|
|
13
|
-
WasmBloomFilter
|
|
14
|
-
|
|
14
|
+
WasmBloomFilter,
|
|
15
|
+
expandHierarchicalTags,
|
|
16
|
+
isChildTag,
|
|
17
|
+
isWildcardTag,
|
|
18
|
+
matchesTagPattern
|
|
19
|
+
} from "./chunk-2AJKEQMZ.js";
|
|
15
20
|
|
|
16
21
|
// src/cache-service.ts
|
|
17
22
|
import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
|
|
@@ -3306,6 +3311,26 @@ async function findActiveSockets() {
|
|
|
3306
3311
|
active.push(currentPipe);
|
|
3307
3312
|
} catch {
|
|
3308
3313
|
}
|
|
3314
|
+
try {
|
|
3315
|
+
const { execFileSync } = await import("child_process");
|
|
3316
|
+
const stdout = execFileSync(
|
|
3317
|
+
"powershell.exe",
|
|
3318
|
+
["-NoProfile", "-NonInteractive", "-Command", '[System.IO.Directory]::GetFiles("\\\\.\\pipe\\") | Where-Object { $_ -like "*tricache-*" }'],
|
|
3319
|
+
{ timeout: 1500, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
|
|
3320
|
+
);
|
|
3321
|
+
const candidates = stdout.split(/\r?\n/).map((name) => name.trim()).filter((name) => name.length > 0 && !active.includes(name));
|
|
3322
|
+
await Promise.all(
|
|
3323
|
+
candidates.map(async (pipePath) => {
|
|
3324
|
+
const testClient = new IpcTelemetryClient(pipePath);
|
|
3325
|
+
try {
|
|
3326
|
+
await testClient.ping(100);
|
|
3327
|
+
active.push(pipePath);
|
|
3328
|
+
} catch {
|
|
3329
|
+
}
|
|
3330
|
+
})
|
|
3331
|
+
);
|
|
3332
|
+
} catch {
|
|
3333
|
+
}
|
|
3309
3334
|
return active;
|
|
3310
3335
|
}
|
|
3311
3336
|
const dir = process.env.TMPDIR || "/tmp";
|
|
@@ -3696,6 +3721,7 @@ var CacheService = class _CacheService {
|
|
|
3696
3721
|
opts;
|
|
3697
3722
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
3698
3723
|
_namespace;
|
|
3724
|
+
prefixLen;
|
|
3699
3725
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
3700
3726
|
_redisDisabled;
|
|
3701
3727
|
watchdog;
|
|
@@ -3735,6 +3761,52 @@ var CacheService = class _CacheService {
|
|
|
3735
3761
|
streamClient = null;
|
|
3736
3762
|
_lastStreamId = "$";
|
|
3737
3763
|
_destroyed = false;
|
|
3764
|
+
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
3765
|
+
_globalEpoch = 0;
|
|
3766
|
+
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
3767
|
+
/**
|
|
3768
|
+
* Pattern tombstones for disk tier.
|
|
3769
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
3770
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
3771
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
3772
|
+
*/
|
|
3773
|
+
_patternTombstones = [];
|
|
3774
|
+
_addPatternTombstone(prefix) {
|
|
3775
|
+
const now = Date.now();
|
|
3776
|
+
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
3777
|
+
this._patternTombstones.shift();
|
|
3778
|
+
}
|
|
3779
|
+
if (this._patternTombstones.length >= 2e3) {
|
|
3780
|
+
this._patternTombstones.shift();
|
|
3781
|
+
}
|
|
3782
|
+
this._patternTombstones.push({ prefix, createdAt: now });
|
|
3783
|
+
}
|
|
3784
|
+
_isTombstonedByPattern(namespacedKey) {
|
|
3785
|
+
if (this._patternTombstones.length === 0) return false;
|
|
3786
|
+
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
3787
|
+
if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
|
|
3788
|
+
return true;
|
|
3789
|
+
}
|
|
3790
|
+
}
|
|
3791
|
+
return false;
|
|
3792
|
+
}
|
|
3793
|
+
_assertActive(operation) {
|
|
3794
|
+
if (this._destroyed) {
|
|
3795
|
+
throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
|
|
3796
|
+
}
|
|
3797
|
+
}
|
|
3798
|
+
_bumpKeyMutation(namespacedKey) {
|
|
3799
|
+
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
3800
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
3801
|
+
if (this._keyMutationEpochs.size > 5e4) {
|
|
3802
|
+
const oldest = this._keyMutationEpochs.keys().next().value;
|
|
3803
|
+
if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
|
|
3804
|
+
}
|
|
3805
|
+
return next;
|
|
3806
|
+
}
|
|
3807
|
+
_getKeyMutationEpoch(namespacedKey) {
|
|
3808
|
+
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
3809
|
+
}
|
|
3738
3810
|
_ipcServer;
|
|
3739
3811
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
3740
3812
|
_subDisconnectedAt = null;
|
|
@@ -3823,6 +3895,8 @@ var CacheService = class _CacheService {
|
|
|
3823
3895
|
),
|
|
3824
3896
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
3825
3897
|
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
3898
|
+
awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
|
|
3899
|
+
lockFailClosed: options.lockFailClosed ?? false,
|
|
3826
3900
|
oomProtection: options.oomProtection ?? true,
|
|
3827
3901
|
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
3828
3902
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
@@ -3856,12 +3930,15 @@ var CacheService = class _CacheService {
|
|
|
3856
3930
|
redisSentinel: options.redisSentinel,
|
|
3857
3931
|
redisProtocol: options.redisProtocol,
|
|
3858
3932
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
3859
|
-
compression: options.compression ?? "
|
|
3933
|
+
compression: options.compression ?? "zstd",
|
|
3934
|
+
customCompressor: options.customCompressor,
|
|
3860
3935
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
3861
3936
|
strictSingleton: options.strictSingleton ?? false,
|
|
3862
3937
|
failClosed: options.failClosed ?? false,
|
|
3863
3938
|
tagStrategy: options.tagStrategy ?? "set",
|
|
3864
3939
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
3940
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
3941
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
3865
3942
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
3866
3943
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
3867
3944
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -3934,6 +4011,7 @@ var CacheService = class _CacheService {
|
|
|
3934
4011
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
3935
4012
|
});
|
|
3936
4013
|
this._namespace = ns;
|
|
4014
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
3937
4015
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
3938
4016
|
this.watchdog = new TierLatencyWatchdog({
|
|
3939
4017
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4043,6 +4121,9 @@ var CacheService = class _CacheService {
|
|
|
4043
4121
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4044
4122
|
this.initBackplane();
|
|
4045
4123
|
const startupPromises = [];
|
|
4124
|
+
if (this.opts.compression === "zstd") {
|
|
4125
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
4126
|
+
}
|
|
4046
4127
|
if (this.opts.remoteSnapshot) {
|
|
4047
4128
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4048
4129
|
}
|
|
@@ -4188,7 +4269,9 @@ var CacheService = class _CacheService {
|
|
|
4188
4269
|
"adaptiveTtl",
|
|
4189
4270
|
"l2WriteMode",
|
|
4190
4271
|
"instanceName",
|
|
4191
|
-
"invalidationBackplane"
|
|
4272
|
+
"invalidationBackplane",
|
|
4273
|
+
"awaitInvalidationBackplane",
|
|
4274
|
+
"lockFailClosed"
|
|
4192
4275
|
];
|
|
4193
4276
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
4194
4277
|
static optionsDiff(a, b) {
|
|
@@ -4229,6 +4312,8 @@ var CacheService = class _CacheService {
|
|
|
4229
4312
|
frozen: o.frozen,
|
|
4230
4313
|
adaptiveTtl: o.adaptiveTtl,
|
|
4231
4314
|
invalidationBackplane: o.invalidationBackplane,
|
|
4315
|
+
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4316
|
+
lockFailClosed: o.lockFailClosed,
|
|
4232
4317
|
strictSingleton: o.strictSingleton,
|
|
4233
4318
|
remoteSnapshot: o.remoteSnapshot,
|
|
4234
4319
|
crossRegion: o.crossRegion
|
|
@@ -4514,16 +4599,80 @@ var CacheService = class _CacheService {
|
|
|
4514
4599
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
4515
4600
|
if (op === "del") {
|
|
4516
4601
|
this.l1.delete(key);
|
|
4602
|
+
this._bumpKeyMutation(key);
|
|
4603
|
+
this.inflight.delete(key);
|
|
4604
|
+
this._pendingDiskDeletes.add(key);
|
|
4517
4605
|
setImmediate(() => {
|
|
4518
|
-
|
|
4606
|
+
try {
|
|
4607
|
+
if (!this._diskDisabled) this.disk.delete(key);
|
|
4608
|
+
} finally {
|
|
4609
|
+
this._pendingDiskDeletes.delete(key);
|
|
4610
|
+
}
|
|
4519
4611
|
});
|
|
4520
4612
|
this._cascadeDependencies(key);
|
|
4521
4613
|
} else if (op === "del-glob") {
|
|
4522
4614
|
this.l1.deletePattern(key);
|
|
4615
|
+
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
4616
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
4617
|
+
if (liveKey.startsWith(pfx)) {
|
|
4618
|
+
this._bumpKeyMutation(liveKey);
|
|
4619
|
+
}
|
|
4620
|
+
}
|
|
4621
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
4622
|
+
if (inflightKey.startsWith(pfx)) {
|
|
4623
|
+
this._bumpKeyMutation(inflightKey);
|
|
4624
|
+
this.inflight.delete(inflightKey);
|
|
4625
|
+
}
|
|
4626
|
+
}
|
|
4627
|
+
this._addPatternTombstone(pfx);
|
|
4523
4628
|
} else if (op === "tag_incr") {
|
|
4524
4629
|
const tag = key;
|
|
4525
4630
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4526
|
-
this._setLocalTagVersion(tag, ver,
|
|
4631
|
+
this._setLocalTagVersion(tag, ver, performance.now());
|
|
4632
|
+
} else if (op === "tag_pattern_incr") {
|
|
4633
|
+
const pattern = key;
|
|
4634
|
+
const now = performance.now();
|
|
4635
|
+
for (const [tag, info] of this.tagVersions) {
|
|
4636
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4637
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
4638
|
+
}
|
|
4639
|
+
}
|
|
4640
|
+
this.l1.scan((k, entry) => {
|
|
4641
|
+
if (entry.tagVersions) {
|
|
4642
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
4643
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4644
|
+
this.l1.delete(k);
|
|
4645
|
+
this._bumpKeyMutation(k);
|
|
4646
|
+
break;
|
|
4647
|
+
}
|
|
4648
|
+
}
|
|
4649
|
+
}
|
|
4650
|
+
}, 0);
|
|
4651
|
+
} else if (op === "tag_pattern_del") {
|
|
4652
|
+
const pattern = key;
|
|
4653
|
+
const matchedTagKeys = [];
|
|
4654
|
+
const prefix = this.nk("_tag_:");
|
|
4655
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
4656
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
4657
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4658
|
+
matchedTagKeys.push(tagKey);
|
|
4659
|
+
for (const k of members) {
|
|
4660
|
+
this.l1.delete(k);
|
|
4661
|
+
this._bumpKeyMutation(k);
|
|
4662
|
+
this._pendingDiskDeletes.add(k);
|
|
4663
|
+
setImmediate(() => {
|
|
4664
|
+
try {
|
|
4665
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
4666
|
+
} finally {
|
|
4667
|
+
this._pendingDiskDeletes.delete(k);
|
|
4668
|
+
}
|
|
4669
|
+
});
|
|
4670
|
+
}
|
|
4671
|
+
}
|
|
4672
|
+
}
|
|
4673
|
+
for (const tagKey of matchedTagKeys) {
|
|
4674
|
+
this.tagIndex.delete(tagKey);
|
|
4675
|
+
}
|
|
4527
4676
|
}
|
|
4528
4677
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
4529
4678
|
}
|
|
@@ -4531,7 +4680,7 @@ var CacheService = class _CacheService {
|
|
|
4531
4680
|
_handleBackplaneMessage(message) {
|
|
4532
4681
|
try {
|
|
4533
4682
|
const msg = JSON.parse(message);
|
|
4534
|
-
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr") {
|
|
4683
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr" && msg.op !== "tag_pattern_incr" && msg.op !== "tag_pattern_del") {
|
|
4535
4684
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
4536
4685
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
4537
4686
|
});
|
|
@@ -4551,7 +4700,11 @@ var CacheService = class _CacheService {
|
|
|
4551
4700
|
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4552
4701
|
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4553
4702
|
if (shouldBroadcast) {
|
|
4554
|
-
|
|
4703
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
4704
|
+
await this._broadcastCrossRegion(op, key, tagVersion);
|
|
4705
|
+
} else {
|
|
4706
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
4707
|
+
}
|
|
4555
4708
|
}
|
|
4556
4709
|
}
|
|
4557
4710
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
@@ -4592,7 +4745,11 @@ var CacheService = class _CacheService {
|
|
|
4592
4745
|
);
|
|
4593
4746
|
}
|
|
4594
4747
|
this.counters.invSent++;
|
|
4595
|
-
} catch {
|
|
4748
|
+
} catch (err) {
|
|
4749
|
+
this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
|
|
4750
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
4751
|
+
throw err;
|
|
4752
|
+
}
|
|
4596
4753
|
}
|
|
4597
4754
|
}
|
|
4598
4755
|
_markCrossRegionEventSeen(id) {
|
|
@@ -4710,12 +4867,12 @@ var CacheService = class _CacheService {
|
|
|
4710
4867
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
4711
4868
|
*/
|
|
4712
4869
|
async _serializeAndEncrypt(serialized) {
|
|
4713
|
-
const isCompressed = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
4714
|
-
if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
|
|
4870
|
+
const isCompressed = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
4871
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
|
|
4715
4872
|
return this._workerPool.encrypt(serialized);
|
|
4716
4873
|
}
|
|
4717
4874
|
if (isCompressed) {
|
|
4718
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
4875
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
4719
4876
|
if (this.enc.isEnabled) {
|
|
4720
4877
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
4721
4878
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -4730,16 +4887,16 @@ var CacheService = class _CacheService {
|
|
|
4730
4887
|
*/
|
|
4731
4888
|
async _decryptAndDeserialize(raw) {
|
|
4732
4889
|
let plain;
|
|
4733
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
4890
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
4734
4891
|
plain = await this._workerPool.decrypt(raw);
|
|
4735
4892
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
4736
4893
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
4737
4894
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
4738
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
4895
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4739
4896
|
plain = decompressed.toString("utf8");
|
|
4740
4897
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
4741
4898
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
4742
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
4899
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4743
4900
|
plain = decompressed.toString("utf8");
|
|
4744
4901
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
4745
4902
|
plain = this.enc.decrypt(raw);
|
|
@@ -4796,6 +4953,7 @@ var CacheService = class _CacheService {
|
|
|
4796
4953
|
}
|
|
4797
4954
|
}
|
|
4798
4955
|
async getRedis() {
|
|
4956
|
+
this._assertActive("getRedis");
|
|
4799
4957
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
4800
4958
|
if (this.redis) return this.redis;
|
|
4801
4959
|
if (this.redisConnecting) return this.redisConnecting;
|
|
@@ -5124,6 +5282,7 @@ var CacheService = class _CacheService {
|
|
|
5124
5282
|
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
5125
5283
|
*/
|
|
5126
5284
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
5285
|
+
this._assertActive("get");
|
|
5127
5286
|
const span = this._startSpan("tricache.get");
|
|
5128
5287
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5129
5288
|
const k = this.nk(cacheKey);
|
|
@@ -5133,7 +5292,7 @@ var CacheService = class _CacheService {
|
|
|
5133
5292
|
const optRefreshAhead = opts.refreshAhead;
|
|
5134
5293
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5135
5294
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5136
|
-
const optTags = opts.tags;
|
|
5295
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5137
5296
|
const l1Hit = this.l1.get(k);
|
|
5138
5297
|
if (l1Hit !== null) {
|
|
5139
5298
|
let isGenerationalStale = false;
|
|
@@ -5155,7 +5314,14 @@ var CacheService = class _CacheService {
|
|
|
5155
5314
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
5156
5315
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
5157
5316
|
this.revalidating.add(k);
|
|
5158
|
-
void this._revalidate(
|
|
5317
|
+
void this._revalidate(
|
|
5318
|
+
k,
|
|
5319
|
+
fetchFn,
|
|
5320
|
+
ttlSeconds * 1e3,
|
|
5321
|
+
swrGraceMs2,
|
|
5322
|
+
priority2,
|
|
5323
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5324
|
+
);
|
|
5159
5325
|
this.counters.swrRevalidations++;
|
|
5160
5326
|
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
5161
5327
|
} else {
|
|
@@ -5174,7 +5340,14 @@ var CacheService = class _CacheService {
|
|
|
5174
5340
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
5175
5341
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
5176
5342
|
this.revalidating.add(k);
|
|
5177
|
-
void this._revalidate(
|
|
5343
|
+
void this._revalidate(
|
|
5344
|
+
k,
|
|
5345
|
+
fetchFn,
|
|
5346
|
+
entryTtl,
|
|
5347
|
+
optSwr * 1e3,
|
|
5348
|
+
priority2,
|
|
5349
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5350
|
+
);
|
|
5178
5351
|
this.counters.swrRevalidations++;
|
|
5179
5352
|
this.logger.debug(
|
|
5180
5353
|
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
@@ -5200,44 +5373,52 @@ var CacheService = class _CacheService {
|
|
|
5200
5373
|
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5201
5374
|
return existing;
|
|
5202
5375
|
}
|
|
5376
|
+
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5203
5377
|
const executionPromise = (async () => {
|
|
5204
5378
|
try {
|
|
5205
|
-
if (!this._diskDisabled) {
|
|
5206
|
-
|
|
5207
|
-
|
|
5208
|
-
|
|
5209
|
-
|
|
5210
|
-
|
|
5211
|
-
|
|
5212
|
-
this.watchdog.
|
|
5213
|
-
if (
|
|
5214
|
-
|
|
5215
|
-
|
|
5216
|
-
|
|
5217
|
-
|
|
5218
|
-
|
|
5219
|
-
|
|
5220
|
-
|
|
5221
|
-
|
|
5379
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
5380
|
+
if (this._isTombstonedByPattern(k)) {
|
|
5381
|
+
try {
|
|
5382
|
+
this.disk.delete(k);
|
|
5383
|
+
} catch {
|
|
5384
|
+
}
|
|
5385
|
+
} else {
|
|
5386
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5387
|
+
if (isDiskAllowed) {
|
|
5388
|
+
const diskStart = performance.now();
|
|
5389
|
+
const diskHit = this.disk.load(k);
|
|
5390
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5391
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5392
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5393
|
+
if (diskHit !== null) {
|
|
5394
|
+
let isDiskStale = false;
|
|
5395
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5396
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5397
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5398
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5399
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5400
|
+
isDiskStale = true;
|
|
5401
|
+
break;
|
|
5402
|
+
}
|
|
5222
5403
|
}
|
|
5223
5404
|
}
|
|
5224
|
-
|
|
5225
|
-
|
|
5226
|
-
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
|
|
5231
|
-
|
|
5232
|
-
|
|
5233
|
-
|
|
5234
|
-
|
|
5235
|
-
|
|
5236
|
-
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5405
|
+
if (isDiskStale) {
|
|
5406
|
+
this.disk.delete(k);
|
|
5407
|
+
} else {
|
|
5408
|
+
const promoted = this.l1.importEntries(
|
|
5409
|
+
[{ key: k, entry: diskHit }],
|
|
5410
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5411
|
+
);
|
|
5412
|
+
if (promoted > 0) {
|
|
5413
|
+
const l1Check = this.l1.get(k);
|
|
5414
|
+
if (l1Check !== null) {
|
|
5415
|
+
this.counters.diskHits++;
|
|
5416
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5417
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5418
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5419
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5420
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5421
|
+
}
|
|
5241
5422
|
}
|
|
5242
5423
|
}
|
|
5243
5424
|
}
|
|
@@ -5348,6 +5529,18 @@ var CacheService = class _CacheService {
|
|
|
5348
5529
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
5349
5530
|
}
|
|
5350
5531
|
}
|
|
5532
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5533
|
+
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5534
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5535
|
+
const current = this.l1.get(k);
|
|
5536
|
+
if (current && !current.isStale && current.value !== void 0) {
|
|
5537
|
+
const freshVal = current.value;
|
|
5538
|
+
if (this.opts.frozen) deepFreeze(freshVal);
|
|
5539
|
+
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
5540
|
+
}
|
|
5541
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
5542
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5543
|
+
}
|
|
5351
5544
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
|
|
5352
5545
|
if (!this._redisDisabled) {
|
|
5353
5546
|
try {
|
|
@@ -5464,22 +5657,40 @@ var CacheService = class _CacheService {
|
|
|
5464
5657
|
const ttl = options?.ttl ?? 300;
|
|
5465
5658
|
return this.get(cacheKey, fetchFn, ttl, options);
|
|
5466
5659
|
}
|
|
5467
|
-
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
5660
|
+
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
5661
|
+
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
5468
5662
|
try {
|
|
5469
5663
|
const fetchStart = Date.now();
|
|
5470
5664
|
const data = await fetchFn();
|
|
5471
5665
|
const delta = Date.now() - fetchStart;
|
|
5472
5666
|
const staleAt = Date.now() + ttlMs;
|
|
5667
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5668
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5669
|
+
return;
|
|
5670
|
+
}
|
|
5473
5671
|
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
5474
5672
|
let activeTagVersions;
|
|
5475
5673
|
const l1Existing = this.l1.get(cacheKey);
|
|
5476
|
-
|
|
5477
|
-
|
|
5674
|
+
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
5675
|
+
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
5676
|
+
const tags = Object.keys(tagVersionsSource);
|
|
5478
5677
|
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5479
5678
|
activeTagVersions = {};
|
|
5480
5679
|
for (let i = 0; i < tags.length; i++) {
|
|
5481
5680
|
activeTagVersions[tags[i]] = vers[i];
|
|
5482
5681
|
}
|
|
5682
|
+
if (knownTagVersions) {
|
|
5683
|
+
for (const t of tags) {
|
|
5684
|
+
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
5685
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
5686
|
+
return;
|
|
5687
|
+
}
|
|
5688
|
+
}
|
|
5689
|
+
}
|
|
5690
|
+
}
|
|
5691
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5692
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
5693
|
+
return;
|
|
5483
5694
|
}
|
|
5484
5695
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
5485
5696
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -5523,6 +5734,7 @@ var CacheService = class _CacheService {
|
|
|
5523
5734
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
5524
5735
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
5525
5736
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
5737
|
+
this._assertActive("set");
|
|
5526
5738
|
const span = this._startSpan("tricache.set");
|
|
5527
5739
|
if (this.opts.tracer) {
|
|
5528
5740
|
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
@@ -5533,17 +5745,21 @@ var CacheService = class _CacheService {
|
|
|
5533
5745
|
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5534
5746
|
const p = priority ?? inferPriority(cacheKey);
|
|
5535
5747
|
const k = this.nk(cacheKey);
|
|
5748
|
+
this._bumpKeyMutation(k);
|
|
5749
|
+
this.inflight.delete(k);
|
|
5750
|
+
this._pendingDiskDeletes.delete(k);
|
|
5536
5751
|
this.counters.sets++;
|
|
5537
5752
|
let activeTagVersions;
|
|
5538
|
-
|
|
5753
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5754
|
+
if (tagsToRegister?.length) {
|
|
5539
5755
|
if (this.opts.tagStrategy === "generational") {
|
|
5540
|
-
const vers = await Promise.all(
|
|
5756
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
5541
5757
|
activeTagVersions = {};
|
|
5542
|
-
for (let i = 0; i <
|
|
5543
|
-
activeTagVersions[
|
|
5758
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
5759
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5544
5760
|
}
|
|
5545
5761
|
} else {
|
|
5546
|
-
await this._registerTags(k,
|
|
5762
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
5547
5763
|
}
|
|
5548
5764
|
}
|
|
5549
5765
|
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
@@ -5587,7 +5803,11 @@ var CacheService = class _CacheService {
|
|
|
5587
5803
|
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
5588
5804
|
}
|
|
5589
5805
|
}
|
|
5590
|
-
|
|
5806
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5807
|
+
await this.publishInvalidation("del", k);
|
|
5808
|
+
} else {
|
|
5809
|
+
void this.publishInvalidation("del", k);
|
|
5810
|
+
}
|
|
5591
5811
|
} catch (err) {
|
|
5592
5812
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5593
5813
|
span.recordException?.(err);
|
|
@@ -5634,6 +5854,7 @@ var CacheService = class _CacheService {
|
|
|
5634
5854
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
5635
5855
|
*/
|
|
5636
5856
|
async delete(cacheKey) {
|
|
5857
|
+
this._assertActive("delete");
|
|
5637
5858
|
const span = this._startSpan("tricache.delete");
|
|
5638
5859
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5639
5860
|
try {
|
|
@@ -5641,11 +5862,31 @@ var CacheService = class _CacheService {
|
|
|
5641
5862
|
const k = this.nk(cacheKey);
|
|
5642
5863
|
this.counters.deletes++;
|
|
5643
5864
|
if (isPattern) {
|
|
5865
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
5866
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
5867
|
+
if (liveKey.startsWith(pfx)) {
|
|
5868
|
+
this._bumpKeyMutation(liveKey);
|
|
5869
|
+
}
|
|
5870
|
+
}
|
|
5871
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
5872
|
+
if (inflightKey.startsWith(pfx)) {
|
|
5873
|
+
this._bumpKeyMutation(inflightKey);
|
|
5874
|
+
this.inflight.delete(inflightKey);
|
|
5875
|
+
}
|
|
5876
|
+
}
|
|
5877
|
+
this._addPatternTombstone(pfx);
|
|
5644
5878
|
this.l1.deletePattern(k);
|
|
5645
5879
|
} else {
|
|
5880
|
+
this._bumpKeyMutation(k);
|
|
5881
|
+
this.inflight.delete(k);
|
|
5646
5882
|
this.l1.delete(k);
|
|
5883
|
+
this._pendingDiskDeletes.add(k);
|
|
5647
5884
|
setImmediate(() => {
|
|
5648
|
-
|
|
5885
|
+
try {
|
|
5886
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5887
|
+
} finally {
|
|
5888
|
+
this._pendingDiskDeletes.delete(k);
|
|
5889
|
+
}
|
|
5649
5890
|
});
|
|
5650
5891
|
this._cascadeDependencies(k);
|
|
5651
5892
|
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
@@ -5669,7 +5910,11 @@ var CacheService = class _CacheService {
|
|
|
5669
5910
|
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
5670
5911
|
}
|
|
5671
5912
|
}
|
|
5672
|
-
|
|
5913
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5914
|
+
await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
5915
|
+
} else {
|
|
5916
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
5917
|
+
}
|
|
5673
5918
|
} catch (err) {
|
|
5674
5919
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5675
5920
|
span.recordException?.(err);
|
|
@@ -5696,6 +5941,7 @@ var CacheService = class _CacheService {
|
|
|
5696
5941
|
* fleet-wide.
|
|
5697
5942
|
*/
|
|
5698
5943
|
async increment(cacheKey, ttlSeconds) {
|
|
5944
|
+
this._assertActive("increment");
|
|
5699
5945
|
const k = this.nk(cacheKey);
|
|
5700
5946
|
if (this._redisDisabled) {
|
|
5701
5947
|
if (!this._incrementFallbackWarned) {
|
|
@@ -5737,19 +5983,38 @@ var CacheService = class _CacheService {
|
|
|
5737
5983
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
5738
5984
|
*/
|
|
5739
5985
|
async clear(prefix) {
|
|
5986
|
+
this._assertActive("clear");
|
|
5740
5987
|
const span = this._startSpan("tricache.clear");
|
|
5741
5988
|
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
5742
5989
|
try {
|
|
5743
5990
|
this.counters.deletes++;
|
|
5744
5991
|
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
5745
5992
|
if (k) {
|
|
5993
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
5994
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
5995
|
+
if (liveKey.startsWith(pfx)) {
|
|
5996
|
+
this._bumpKeyMutation(liveKey);
|
|
5997
|
+
}
|
|
5998
|
+
}
|
|
5999
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6000
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6001
|
+
this._bumpKeyMutation(inflightKey);
|
|
6002
|
+
this.inflight.delete(inflightKey);
|
|
6003
|
+
}
|
|
6004
|
+
}
|
|
6005
|
+
this._addPatternTombstone(pfx);
|
|
5746
6006
|
this.l1.deletePattern(k);
|
|
5747
6007
|
} else {
|
|
6008
|
+
this._globalEpoch++;
|
|
6009
|
+
this.inflight.clear();
|
|
6010
|
+
this._patternTombstones.length = 0;
|
|
5748
6011
|
this.l1.clear();
|
|
5749
6012
|
if (!this._diskDisabled) this.disk.clear();
|
|
5750
6013
|
this._l1Counters.clear();
|
|
5751
6014
|
this.tagIndex.clear();
|
|
5752
6015
|
this.tagVersions.clear();
|
|
6016
|
+
this._pendingDiskDeletes.clear();
|
|
6017
|
+
this._keyMutationEpochs.clear();
|
|
5753
6018
|
}
|
|
5754
6019
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5755
6020
|
try {
|
|
@@ -5761,13 +6026,23 @@ var CacheService = class _CacheService {
|
|
|
5761
6026
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
5762
6027
|
}
|
|
5763
6028
|
}
|
|
5764
|
-
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
6029
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6030
|
+
await this.publishInvalidation(
|
|
6031
|
+
"del-glob",
|
|
6032
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6033
|
+
void 0,
|
|
6034
|
+
false,
|
|
6035
|
+
true
|
|
6036
|
+
);
|
|
6037
|
+
} else {
|
|
6038
|
+
void this.publishInvalidation(
|
|
6039
|
+
"del-glob",
|
|
6040
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6041
|
+
void 0,
|
|
6042
|
+
false,
|
|
6043
|
+
true
|
|
6044
|
+
);
|
|
6045
|
+
}
|
|
5771
6046
|
} catch (err) {
|
|
5772
6047
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5773
6048
|
span.recordException?.(err);
|
|
@@ -5782,6 +6057,7 @@ var CacheService = class _CacheService {
|
|
|
5782
6057
|
* Returns the number of entries evicted.
|
|
5783
6058
|
*/
|
|
5784
6059
|
rebalance() {
|
|
6060
|
+
this._assertActive("rebalance");
|
|
5785
6061
|
return this.l1.rebalance();
|
|
5786
6062
|
}
|
|
5787
6063
|
/**
|
|
@@ -5790,6 +6066,7 @@ var CacheService = class _CacheService {
|
|
|
5790
6066
|
* Only reflects L1 state — does not query Redis or disk.
|
|
5791
6067
|
*/
|
|
5792
6068
|
ttl(cacheKey) {
|
|
6069
|
+
this._assertActive("ttl");
|
|
5793
6070
|
return this.l1.ttl(this.nk(cacheKey));
|
|
5794
6071
|
}
|
|
5795
6072
|
/**
|
|
@@ -5797,6 +6074,7 @@ var CacheService = class _CacheService {
|
|
|
5797
6074
|
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
5798
6075
|
*/
|
|
5799
6076
|
has(cacheKey) {
|
|
6077
|
+
this._assertActive("has");
|
|
5800
6078
|
return this.l1.has(this.nk(cacheKey));
|
|
5801
6079
|
}
|
|
5802
6080
|
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
@@ -5807,6 +6085,7 @@ var CacheService = class _CacheService {
|
|
|
5807
6085
|
* for (const key of cache.keys()) console.log(key);
|
|
5808
6086
|
*/
|
|
5809
6087
|
*keys() {
|
|
6088
|
+
this._assertActive("keys");
|
|
5810
6089
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
5811
6090
|
for (const key of this.l1.liveKeys()) {
|
|
5812
6091
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -5821,6 +6100,7 @@ var CacheService = class _CacheService {
|
|
|
5821
6100
|
* for (const val of cache.values<User>()) console.log(val.id);
|
|
5822
6101
|
*/
|
|
5823
6102
|
*values() {
|
|
6103
|
+
this._assertActive("values");
|
|
5824
6104
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
5825
6105
|
if (!prefix) {
|
|
5826
6106
|
yield* this.l1.liveValues();
|
|
@@ -5839,6 +6119,7 @@ var CacheService = class _CacheService {
|
|
|
5839
6119
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
5840
6120
|
*/
|
|
5841
6121
|
*entries() {
|
|
6122
|
+
this._assertActive("entries");
|
|
5842
6123
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
5843
6124
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
5844
6125
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -5866,6 +6147,7 @@ var CacheService = class _CacheService {
|
|
|
5866
6147
|
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
5867
6148
|
*/
|
|
5868
6149
|
scan(fn) {
|
|
6150
|
+
this._assertActive("scan");
|
|
5869
6151
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
5870
6152
|
this.l1.scan((key, entry, pfx) => {
|
|
5871
6153
|
const value = entry.value !== void 0 ? entry.value : entry.data;
|
|
@@ -5879,6 +6161,7 @@ var CacheService = class _CacheService {
|
|
|
5879
6161
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
5880
6162
|
*/
|
|
5881
6163
|
async touch(cacheKey, newTtlSeconds) {
|
|
6164
|
+
this._assertActive("touch");
|
|
5882
6165
|
const k = this.nk(cacheKey);
|
|
5883
6166
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
5884
6167
|
if (hit && !this._redisDisabled) {
|
|
@@ -5899,6 +6182,7 @@ var CacheService = class _CacheService {
|
|
|
5899
6182
|
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
5900
6183
|
*/
|
|
5901
6184
|
getIfFresh(cacheKey) {
|
|
6185
|
+
this._assertActive("getIfFresh");
|
|
5902
6186
|
const k = this.nk(cacheKey);
|
|
5903
6187
|
const entry = this.l1.getEntry(k);
|
|
5904
6188
|
if (!entry) return null;
|
|
@@ -5916,6 +6200,7 @@ var CacheService = class _CacheService {
|
|
|
5916
6200
|
* const val = await cache.peek<User>('user:123');
|
|
5917
6201
|
*/
|
|
5918
6202
|
async peek(cacheKey) {
|
|
6203
|
+
this._assertActive("peek");
|
|
5919
6204
|
const k = this.nk(cacheKey);
|
|
5920
6205
|
const l1Hit = this.l1.get(k);
|
|
5921
6206
|
if (l1Hit !== null) {
|
|
@@ -5925,25 +6210,32 @@ var CacheService = class _CacheService {
|
|
|
5925
6210
|
if (this.opts.frozen) deepFreeze(val);
|
|
5926
6211
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
5927
6212
|
}
|
|
5928
|
-
if (!this._diskDisabled && this.
|
|
5929
|
-
|
|
5930
|
-
|
|
5931
|
-
|
|
5932
|
-
|
|
5933
|
-
|
|
5934
|
-
if (
|
|
5935
|
-
const
|
|
5936
|
-
|
|
5937
|
-
|
|
5938
|
-
);
|
|
5939
|
-
|
|
5940
|
-
|
|
5941
|
-
|
|
5942
|
-
|
|
5943
|
-
this.
|
|
5944
|
-
|
|
5945
|
-
|
|
5946
|
-
|
|
6213
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6214
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6215
|
+
try {
|
|
6216
|
+
this.disk.delete(k);
|
|
6217
|
+
} catch {
|
|
6218
|
+
}
|
|
6219
|
+
} else if (this.watchdog.isDiskAllowed()) {
|
|
6220
|
+
const diskStart = performance.now();
|
|
6221
|
+
const diskHit = this.disk.load(k);
|
|
6222
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6223
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6224
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6225
|
+
if (diskHit !== null) {
|
|
6226
|
+
const promoted = this.l1.importEntries(
|
|
6227
|
+
[{ key: k, entry: diskHit }],
|
|
6228
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6229
|
+
);
|
|
6230
|
+
if (promoted > 0) {
|
|
6231
|
+
const l1Check = this.l1.get(k);
|
|
6232
|
+
if (l1Check !== null) {
|
|
6233
|
+
this.counters.gets++;
|
|
6234
|
+
this.counters.diskHits++;
|
|
6235
|
+
const val = l1Check.value;
|
|
6236
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6237
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6238
|
+
}
|
|
5947
6239
|
}
|
|
5948
6240
|
}
|
|
5949
6241
|
}
|
|
@@ -5981,6 +6273,7 @@ var CacheService = class _CacheService {
|
|
|
5981
6273
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
5982
6274
|
*/
|
|
5983
6275
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
6276
|
+
this._assertActive("mget");
|
|
5984
6277
|
const span = this._startSpan("tricache.mget");
|
|
5985
6278
|
if (this.opts.tracer) {
|
|
5986
6279
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6049,8 +6342,16 @@ var CacheService = class _CacheService {
|
|
|
6049
6342
|
}
|
|
6050
6343
|
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6051
6344
|
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6052
|
-
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6053
6345
|
const k = this.nk(missKeys[j]);
|
|
6346
|
+
if (this._pendingDiskDeletes.has(k)) continue;
|
|
6347
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6348
|
+
try {
|
|
6349
|
+
this.disk.delete(k);
|
|
6350
|
+
} catch {
|
|
6351
|
+
}
|
|
6352
|
+
continue;
|
|
6353
|
+
}
|
|
6354
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6054
6355
|
const diskStart = performance.now();
|
|
6055
6356
|
const diskHit = this.disk.load(k);
|
|
6056
6357
|
const diskElapsed = performance.now() - diskStart;
|
|
@@ -6073,16 +6374,23 @@ var CacheService = class _CacheService {
|
|
|
6073
6374
|
}
|
|
6074
6375
|
}
|
|
6075
6376
|
}
|
|
6076
|
-
if (missKeys.length > 0) {
|
|
6377
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
6077
6378
|
this.counters.fetches++;
|
|
6078
6379
|
const fetched = await fetchFn(missKeys);
|
|
6380
|
+
const isMap = fetched instanceof Map;
|
|
6079
6381
|
const setPromises = [];
|
|
6080
6382
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6081
|
-
const
|
|
6383
|
+
const k = missKeys[j];
|
|
6384
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
6082
6385
|
result[missIndexes[j]] = v;
|
|
6083
|
-
if (v !== void 0) {
|
|
6084
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
6085
|
-
setPromises.push(this.set(
|
|
6386
|
+
if (v !== void 0 && v !== null) {
|
|
6387
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6388
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
6389
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
6390
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
6391
|
+
} else if (v === null) {
|
|
6392
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6393
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
6086
6394
|
}
|
|
6087
6395
|
}
|
|
6088
6396
|
if (setPromises.length > 0) {
|
|
@@ -6130,6 +6438,7 @@ var CacheService = class _CacheService {
|
|
|
6130
6438
|
* });
|
|
6131
6439
|
*/
|
|
6132
6440
|
async mset(entries) {
|
|
6441
|
+
this._assertActive("mset");
|
|
6133
6442
|
const span = this._startSpan("tricache.mset");
|
|
6134
6443
|
const keys = Object.keys(entries);
|
|
6135
6444
|
if (this.opts.tracer) {
|
|
@@ -6157,6 +6466,7 @@ var CacheService = class _CacheService {
|
|
|
6157
6466
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
6158
6467
|
*/
|
|
6159
6468
|
async mdel(keys) {
|
|
6469
|
+
this._assertActive("mdel");
|
|
6160
6470
|
const span = this._startSpan("tricache.mdel");
|
|
6161
6471
|
if (this.opts.tracer) {
|
|
6162
6472
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6184,6 +6494,7 @@ var CacheService = class _CacheService {
|
|
|
6184
6494
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
6185
6495
|
*/
|
|
6186
6496
|
async warmFromL2(pattern, opts) {
|
|
6497
|
+
this._assertActive("warmFromL2");
|
|
6187
6498
|
if (this._redisDisabled) return 0;
|
|
6188
6499
|
try {
|
|
6189
6500
|
const client = await this.getRedis();
|
|
@@ -6222,20 +6533,109 @@ var CacheService = class _CacheService {
|
|
|
6222
6533
|
}
|
|
6223
6534
|
}
|
|
6224
6535
|
/**
|
|
6225
|
-
*
|
|
6226
|
-
*
|
|
6536
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
6537
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
6538
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
6539
|
+
*/
|
|
6540
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
6541
|
+
const isPattern = isWildcardTag(tag);
|
|
6542
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6543
|
+
const matched = /* @__PURE__ */ new Set();
|
|
6544
|
+
const tagMatches = (t) => {
|
|
6545
|
+
if (t === tag) return true;
|
|
6546
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
6547
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
6548
|
+
return false;
|
|
6549
|
+
};
|
|
6550
|
+
if (shouldCascade && !isPattern) {
|
|
6551
|
+
matched.add(tag);
|
|
6552
|
+
}
|
|
6553
|
+
const tagPrefix = this.nk("_tag_:");
|
|
6554
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
6555
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
6556
|
+
if (tagMatches(t)) matched.add(t);
|
|
6557
|
+
}
|
|
6558
|
+
for (const t of this.tagVersions.keys()) {
|
|
6559
|
+
if (tagMatches(t)) matched.add(t);
|
|
6560
|
+
}
|
|
6561
|
+
this.l1.scan((_k, entry) => {
|
|
6562
|
+
if (entry.tagVersions) {
|
|
6563
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
6564
|
+
if (tagMatches(t)) matched.add(t);
|
|
6565
|
+
}
|
|
6566
|
+
}
|
|
6567
|
+
}, 0);
|
|
6568
|
+
if (!this._redisDisabled) {
|
|
6569
|
+
try {
|
|
6570
|
+
const client = await this.getRedis();
|
|
6571
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6572
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
6573
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6574
|
+
const pfx = this.nk("tag_ver:");
|
|
6575
|
+
for (const sk of scannedKeys) {
|
|
6576
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6577
|
+
if (tagMatches(t)) matched.add(t);
|
|
6578
|
+
}
|
|
6579
|
+
} else {
|
|
6580
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
6581
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6582
|
+
const pfx = this.nk("_tag_:");
|
|
6583
|
+
for (const sk of scannedKeys) {
|
|
6584
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6585
|
+
if (tagMatches(t)) matched.add(t);
|
|
6586
|
+
}
|
|
6587
|
+
}
|
|
6588
|
+
} catch (err) {
|
|
6589
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
6590
|
+
}
|
|
6591
|
+
}
|
|
6592
|
+
return matched;
|
|
6593
|
+
}
|
|
6594
|
+
/**
|
|
6595
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
6596
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
6597
|
+
*
|
|
6598
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
6599
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
6227
6600
|
*
|
|
6228
6601
|
* @example
|
|
6229
6602
|
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6230
6603
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
6604
|
+
*
|
|
6605
|
+
* @example
|
|
6606
|
+
* // Wildcard pattern invalidation
|
|
6607
|
+
* await cache.invalidateTag('org:123:*');
|
|
6608
|
+
*
|
|
6609
|
+
* @example
|
|
6610
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
6611
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
6231
6612
|
*/
|
|
6232
|
-
async invalidateTag(tag) {
|
|
6613
|
+
async invalidateTag(tag, opts) {
|
|
6614
|
+
this._assertActive("invalidateTag");
|
|
6233
6615
|
const span = this._startSpan("tricache.invalidate_tag");
|
|
6234
6616
|
if (this.opts.tracer) {
|
|
6235
6617
|
span.setAttribute("cache.tag", tag);
|
|
6236
6618
|
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6619
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
6237
6620
|
}
|
|
6238
6621
|
try {
|
|
6622
|
+
const isPattern = isWildcardTag(tag);
|
|
6623
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
6624
|
+
if (isPattern || shouldCascade) {
|
|
6625
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
6626
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6627
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
6628
|
+
if (matchedTags.size > 0) {
|
|
6629
|
+
await this.invalidateTags(Array.from(matchedTags));
|
|
6630
|
+
}
|
|
6631
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
6632
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6633
|
+
await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
6634
|
+
} else {
|
|
6635
|
+
void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
6636
|
+
}
|
|
6637
|
+
return;
|
|
6638
|
+
}
|
|
6239
6639
|
if (this.opts.tagStrategy === "generational") {
|
|
6240
6640
|
let newVer = 1;
|
|
6241
6641
|
if (!this._redisDisabled) {
|
|
@@ -6251,15 +6651,27 @@ var CacheService = class _CacheService {
|
|
|
6251
6651
|
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6252
6652
|
newVer = current + 1;
|
|
6253
6653
|
}
|
|
6254
|
-
this._setLocalTagVersion(tag, newVer,
|
|
6255
|
-
|
|
6654
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6655
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6656
|
+
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6657
|
+
} else {
|
|
6658
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6659
|
+
}
|
|
6256
6660
|
return;
|
|
6257
6661
|
}
|
|
6258
6662
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6259
6663
|
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6260
6664
|
for (const k of members) {
|
|
6261
6665
|
this.l1.delete(k);
|
|
6262
|
-
|
|
6666
|
+
this._bumpKeyMutation(k);
|
|
6667
|
+
this._pendingDiskDeletes.add(k);
|
|
6668
|
+
setImmediate(() => {
|
|
6669
|
+
try {
|
|
6670
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6671
|
+
} finally {
|
|
6672
|
+
this._pendingDiskDeletes.delete(k);
|
|
6673
|
+
}
|
|
6674
|
+
});
|
|
6263
6675
|
}
|
|
6264
6676
|
this.tagIndex.delete(tagKey);
|
|
6265
6677
|
if (!this._redisDisabled) {
|
|
@@ -6286,24 +6698,39 @@ var CacheService = class _CacheService {
|
|
|
6286
6698
|
}
|
|
6287
6699
|
/**
|
|
6288
6700
|
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
6289
|
-
*
|
|
6290
|
-
*
|
|
6701
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
6702
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
6291
6703
|
*
|
|
6292
|
-
*
|
|
6293
|
-
*
|
|
6704
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
6705
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
6294
6706
|
*
|
|
6295
6707
|
* @example
|
|
6296
|
-
*
|
|
6297
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
6708
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
6298
6709
|
*/
|
|
6299
|
-
async invalidateTags(tags) {
|
|
6710
|
+
async invalidateTags(tags, opts) {
|
|
6711
|
+
this._assertActive("invalidateTags");
|
|
6300
6712
|
if (tags.length === 0) return;
|
|
6713
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
6714
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
6715
|
+
if (hasWildcards || shouldCascade) {
|
|
6716
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
6717
|
+
for (const t of tags) {
|
|
6718
|
+
if (isWildcardTag(t) || shouldCascade) {
|
|
6719
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
6720
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
6721
|
+
} else {
|
|
6722
|
+
allResolvedTags.add(t);
|
|
6723
|
+
}
|
|
6724
|
+
}
|
|
6725
|
+
if (allResolvedTags.size === 0) return;
|
|
6726
|
+
tags = Array.from(allResolvedTags);
|
|
6727
|
+
}
|
|
6301
6728
|
if (tags.length === 1) {
|
|
6302
|
-
await this.invalidateTag(tags[0]);
|
|
6729
|
+
await this.invalidateTag(tags[0], opts);
|
|
6303
6730
|
return;
|
|
6304
6731
|
}
|
|
6305
6732
|
if (this.opts.tagStrategy === "generational") {
|
|
6306
|
-
const now =
|
|
6733
|
+
const now = performance.now();
|
|
6307
6734
|
if (!this._redisDisabled) {
|
|
6308
6735
|
try {
|
|
6309
6736
|
const client = await this.getRedis();
|
|
@@ -6314,7 +6741,11 @@ var CacheService = class _CacheService {
|
|
|
6314
6741
|
const [err, newVer] = results[i] ?? [null, null];
|
|
6315
6742
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
6316
6743
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
6317
|
-
|
|
6744
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6745
|
+
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6746
|
+
} else {
|
|
6747
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6748
|
+
}
|
|
6318
6749
|
}
|
|
6319
6750
|
return;
|
|
6320
6751
|
} catch (err) {
|
|
@@ -6324,7 +6755,11 @@ var CacheService = class _CacheService {
|
|
|
6324
6755
|
for (const tag of tags) {
|
|
6325
6756
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
6326
6757
|
this._setLocalTagVersion(tag, ver, now);
|
|
6327
|
-
|
|
6758
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6759
|
+
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6760
|
+
} else {
|
|
6761
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6762
|
+
}
|
|
6328
6763
|
}
|
|
6329
6764
|
return;
|
|
6330
6765
|
}
|
|
@@ -6339,7 +6774,15 @@ var CacheService = class _CacheService {
|
|
|
6339
6774
|
}
|
|
6340
6775
|
for (const k of allMembers) {
|
|
6341
6776
|
this.l1.delete(k);
|
|
6342
|
-
this.
|
|
6777
|
+
this._bumpKeyMutation(k);
|
|
6778
|
+
this._pendingDiskDeletes.add(k);
|
|
6779
|
+
setImmediate(() => {
|
|
6780
|
+
try {
|
|
6781
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6782
|
+
} finally {
|
|
6783
|
+
this._pendingDiskDeletes.delete(k);
|
|
6784
|
+
}
|
|
6785
|
+
});
|
|
6343
6786
|
}
|
|
6344
6787
|
if (!this._redisDisabled) {
|
|
6345
6788
|
try {
|
|
@@ -6376,6 +6819,7 @@ var CacheService = class _CacheService {
|
|
|
6376
6819
|
* `l2` is `null` when Redis is disabled.
|
|
6377
6820
|
*/
|
|
6378
6821
|
async ping() {
|
|
6822
|
+
this._assertActive("ping");
|
|
6379
6823
|
const t0 = Date.now();
|
|
6380
6824
|
this.l1.has("__ping__");
|
|
6381
6825
|
const l1 = Date.now() - t0;
|
|
@@ -6455,6 +6899,7 @@ var CacheService = class _CacheService {
|
|
|
6455
6899
|
* Returns the number of keys written.
|
|
6456
6900
|
*/
|
|
6457
6901
|
async drainToL2() {
|
|
6902
|
+
this._assertActive("drainToL2");
|
|
6458
6903
|
if (this._redisDisabled) return 0;
|
|
6459
6904
|
try {
|
|
6460
6905
|
const client = await this.getRedis();
|
|
@@ -6498,6 +6943,7 @@ var CacheService = class _CacheService {
|
|
|
6498
6943
|
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
6499
6944
|
*/
|
|
6500
6945
|
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
6946
|
+
this._assertActive("setIfAbsent");
|
|
6501
6947
|
const k = this.nk(cacheKey);
|
|
6502
6948
|
if (this.l1.has(k)) return false;
|
|
6503
6949
|
if (!this._redisDisabled) {
|
|
@@ -6516,6 +6962,8 @@ var CacheService = class _CacheService {
|
|
|
6516
6962
|
}
|
|
6517
6963
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
6518
6964
|
const p = priority ?? inferPriority(cacheKey);
|
|
6965
|
+
this._bumpKeyMutation(k);
|
|
6966
|
+
this._pendingDiskDeletes.delete(k);
|
|
6519
6967
|
this.l1.set(k, value, ttlMs, p);
|
|
6520
6968
|
this.counters.sets++;
|
|
6521
6969
|
return true;
|
|
@@ -6534,6 +6982,7 @@ var CacheService = class _CacheService {
|
|
|
6534
6982
|
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
6535
6983
|
*/
|
|
6536
6984
|
async lock(resourceKey, fn, options) {
|
|
6985
|
+
this._assertActive("lock");
|
|
6537
6986
|
const ttlSeconds = Math.max(1, options?.ttl ?? 30);
|
|
6538
6987
|
const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
|
|
6539
6988
|
const retryInterval = Math.max(10, options?.retryInterval ?? 100);
|
|
@@ -6560,6 +7009,10 @@ var CacheService = class _CacheService {
|
|
|
6560
7009
|
}
|
|
6561
7010
|
} catch (err) {
|
|
6562
7011
|
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
7012
|
+
const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
|
|
7013
|
+
if (failClosed) {
|
|
7014
|
+
throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
|
|
7015
|
+
}
|
|
6563
7016
|
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
6564
7017
|
resourceKey,
|
|
6565
7018
|
error: err.message
|
|
@@ -6905,6 +7358,7 @@ var CacheService = class _CacheService {
|
|
|
6905
7358
|
* the previous key for seamless fallback decryption of existing cache entries.
|
|
6906
7359
|
*/
|
|
6907
7360
|
async rotateEncryptionKey(newKeyBase64, newMode) {
|
|
7361
|
+
this._assertActive("rotateEncryptionKey");
|
|
6908
7362
|
this.enc.rotateKey(newKeyBase64, newMode);
|
|
6909
7363
|
if (this._workerPool) {
|
|
6910
7364
|
await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
|
|
@@ -6914,6 +7368,8 @@ var CacheService = class _CacheService {
|
|
|
6914
7368
|
/** Close Redis connections and stop all background timers. */
|
|
6915
7369
|
async destroy() {
|
|
6916
7370
|
this._destroyed = true;
|
|
7371
|
+
this._pendingDiskDeletes.clear();
|
|
7372
|
+
this._keyMutationEpochs.clear();
|
|
6917
7373
|
const g = globalThis;
|
|
6918
7374
|
const key = _CacheService.globalKey(this.opts);
|
|
6919
7375
|
if (g[key] === this) {
|