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/dist/edge/index.cjs
CHANGED
|
@@ -210,13 +210,17 @@ var WebCryptoEncryption = class {
|
|
|
210
210
|
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
211
211
|
var KEY_STAGING_OFFSET = 2e4;
|
|
212
212
|
var MAX_KEY_BYTES = 512;
|
|
213
|
-
var
|
|
214
|
-
|
|
215
|
-
|
|
213
|
+
var bloomWasmModule;
|
|
214
|
+
function getBloomWasmModule() {
|
|
215
|
+
return bloomWasmModule ??= new WebAssembly.Module(
|
|
216
|
+
base64ToUint8Array(BLOOM_WASM_BASE64)
|
|
217
|
+
);
|
|
218
|
+
}
|
|
216
219
|
var WasmBloomFilter = class {
|
|
217
220
|
exports;
|
|
218
221
|
mem;
|
|
219
222
|
stagingTarget;
|
|
223
|
+
stagingView;
|
|
220
224
|
encoder = new TextEncoder();
|
|
221
225
|
numBits = 1e5;
|
|
222
226
|
/** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
|
|
@@ -224,16 +228,28 @@ var WasmBloomFilter = class {
|
|
|
224
228
|
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
225
229
|
_insertionCount = 0;
|
|
226
230
|
constructor() {
|
|
227
|
-
const instance = new WebAssembly.Instance(
|
|
231
|
+
const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
|
|
228
232
|
this.exports = instance.exports;
|
|
229
233
|
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
230
234
|
this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
|
|
235
|
+
this.stagingView = new DataView(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
|
|
231
236
|
const k = 7, p = 0.01;
|
|
232
237
|
this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
|
|
233
238
|
}
|
|
234
239
|
writeKey(key) {
|
|
235
240
|
if (key.length === 0) return 0;
|
|
236
|
-
|
|
241
|
+
const encoded = this.encoder.encodeInto(key, this.stagingTarget);
|
|
242
|
+
if (encoded.read === key.length) return encoded.written;
|
|
243
|
+
let first = 2166136261, second = 5381;
|
|
244
|
+
for (let index = 0; index < key.length; index++) {
|
|
245
|
+
const unit = key.charCodeAt(index);
|
|
246
|
+
first = Math.imul(first ^ unit, 16777619) >>> 0;
|
|
247
|
+
second = (Math.imul(second, 33) ^ unit) >>> 0;
|
|
248
|
+
}
|
|
249
|
+
this.stagingTarget[0] = 255;
|
|
250
|
+
this.stagingView.setUint32(1, first, true);
|
|
251
|
+
this.stagingView.setUint32(5, second, true);
|
|
252
|
+
return 9;
|
|
237
253
|
}
|
|
238
254
|
add(key) {
|
|
239
255
|
const len = this.writeKey(key);
|
|
@@ -437,16 +453,40 @@ function isChildTag(parentTag, candidateTag, delimiter = ":") {
|
|
|
437
453
|
return candidateTag.startsWith(prefix);
|
|
438
454
|
}
|
|
439
455
|
|
|
456
|
+
// src/utils/namespace-key.ts
|
|
457
|
+
var NAMESPACE_KEY_VERSION = "tricache:v3:";
|
|
458
|
+
function encodeNamespaceSegment(namespace) {
|
|
459
|
+
let encoded = "";
|
|
460
|
+
for (let index = 0; index < namespace.length; index++) {
|
|
461
|
+
encoded += namespace.charCodeAt(index).toString(16).padStart(4, "0");
|
|
462
|
+
}
|
|
463
|
+
return encoded;
|
|
464
|
+
}
|
|
465
|
+
function namespaceKeyPrefix(namespace) {
|
|
466
|
+
return `${NAMESPACE_KEY_VERSION}${encodeNamespaceSegment(namespace)}:`;
|
|
467
|
+
}
|
|
468
|
+
function namespaceDomainPrefix(namespace, domain) {
|
|
469
|
+
return `${namespaceKeyPrefix(namespace)}${domain}:`;
|
|
470
|
+
}
|
|
471
|
+
|
|
440
472
|
// src/edge/cache.ts
|
|
473
|
+
var NAMESPACE_TAG = "_tricache_namespace_";
|
|
441
474
|
var EdgeCacheService = class _EdgeCacheService {
|
|
442
475
|
maxKeys;
|
|
443
476
|
maxBytes;
|
|
444
477
|
defaultTtl;
|
|
445
478
|
namespace;
|
|
479
|
+
namespacePrefix;
|
|
480
|
+
dataPrefix;
|
|
481
|
+
tagVersionPrefix;
|
|
446
482
|
remoteStorage;
|
|
447
483
|
enc;
|
|
448
484
|
tracer;
|
|
449
485
|
bloomFilter;
|
|
486
|
+
bloomAuthoritative;
|
|
487
|
+
globalEpoch = 0;
|
|
488
|
+
lastGlobalMutationAt = 0;
|
|
489
|
+
keyEpochs = /* @__PURE__ */ new Map();
|
|
450
490
|
// L1 Dual-bounded LRU
|
|
451
491
|
l1 = /* @__PURE__ */ new Map();
|
|
452
492
|
currentBytes = 0;
|
|
@@ -463,9 +503,14 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
463
503
|
this.maxBytes = options?.maxBytes ?? 32 * 1024 * 1024;
|
|
464
504
|
this.defaultTtl = options?.defaultTtlSeconds ?? 300;
|
|
465
505
|
this.namespace = options?.namespace?.trim() ?? "";
|
|
506
|
+
this.namespacePrefix = namespaceKeyPrefix(this.namespace);
|
|
507
|
+
this.dataPrefix = namespaceDomainPrefix(this.namespace, "data");
|
|
508
|
+
this.tagVersionPrefix = namespaceDomainPrefix(this.namespace, "tag-version");
|
|
466
509
|
this.remoteStorage = options?.remoteStorage ?? null;
|
|
467
510
|
this.tracer = options?.tracer ?? null;
|
|
468
511
|
this.enc = new WebCryptoEncryption(options?.encryption);
|
|
512
|
+
this.bloomAuthoritative = options?.bloomFilterAuthoritative ?? false;
|
|
513
|
+
if (!Number.isInteger(this.maxKeys) || this.maxKeys < 0 || !Number.isFinite(this.maxBytes) || this.maxBytes < 0 || !Number.isFinite(this.defaultTtl) || this.defaultTtl < 0) throw new Error("Edge cache limits and TTL must be finite non-negative values");
|
|
469
514
|
if (options?.bloomFilter === true) {
|
|
470
515
|
try {
|
|
471
516
|
this.bloomFilter = new WasmBloomFilter();
|
|
@@ -485,11 +530,76 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
485
530
|
return this.bloomFilter;
|
|
486
531
|
}
|
|
487
532
|
nk(key) {
|
|
488
|
-
return
|
|
533
|
+
return `${this.dataPrefix}${key}`;
|
|
534
|
+
}
|
|
535
|
+
tagVersionKey(tag) {
|
|
536
|
+
return `${this.tagVersionPrefix}${tag}`;
|
|
489
537
|
}
|
|
490
538
|
_estimateBytes(key, serialized) {
|
|
491
539
|
return (key.length + serialized.length) * 2 + 64;
|
|
492
540
|
}
|
|
541
|
+
fence(key) {
|
|
542
|
+
return `${this.globalEpoch}:${this.keyEpochs.get(key) ?? 0}`;
|
|
543
|
+
}
|
|
544
|
+
mutate(key) {
|
|
545
|
+
this.keyEpochs.set(key, (this.keyEpochs.get(key) ?? 0) + 1);
|
|
546
|
+
this.inflight.delete(key);
|
|
547
|
+
if (this.keyEpochs.size > 5e4) {
|
|
548
|
+
this.globalEpoch++;
|
|
549
|
+
this.keyEpochs.clear();
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
invalidateWork() {
|
|
553
|
+
this.globalEpoch++;
|
|
554
|
+
this.lastGlobalMutationAt = Date.now();
|
|
555
|
+
this.inflight.clear();
|
|
556
|
+
}
|
|
557
|
+
storeL1(key, entry) {
|
|
558
|
+
this._deleteL1(key);
|
|
559
|
+
if (entry.bytes > this.maxBytes || this.maxKeys === 0 || entry.staleUntil <= Date.now()) return false;
|
|
560
|
+
this._evictIfNeeded(entry.bytes);
|
|
561
|
+
this.l1.set(key, entry);
|
|
562
|
+
this.currentBytes += entry.bytes;
|
|
563
|
+
for (const tag of entry.tags ?? []) {
|
|
564
|
+
const members = this.tagIndex.get(tag) ?? /* @__PURE__ */ new Set();
|
|
565
|
+
members.add(key);
|
|
566
|
+
this.tagIndex.set(tag, members);
|
|
567
|
+
}
|
|
568
|
+
this.bloomFilter?.add(key);
|
|
569
|
+
return true;
|
|
570
|
+
}
|
|
571
|
+
async commit(key, value, ttl, options, versions, epoch) {
|
|
572
|
+
const namespaced = this.nk(key);
|
|
573
|
+
if (this.fence(namespaced) !== epoch) return;
|
|
574
|
+
const serialized = JSON.stringify(value);
|
|
575
|
+
if (serialized === void 0) return;
|
|
576
|
+
const now = Date.now();
|
|
577
|
+
const entry = {
|
|
578
|
+
value,
|
|
579
|
+
serialized,
|
|
580
|
+
bytes: this._estimateBytes(namespaced, serialized),
|
|
581
|
+
expiresAt: now + ttl * 1e3,
|
|
582
|
+
staleUntil: now + (ttl + (options?.swr ?? 0)) * 1e3,
|
|
583
|
+
tags: options?.tags ? [...new Set(options.tags)] : void 0,
|
|
584
|
+
tagVersions: versions
|
|
585
|
+
};
|
|
586
|
+
this.storeL1(namespaced, entry);
|
|
587
|
+
if (this.remoteStorage) {
|
|
588
|
+
const registry = namespaceDomainPrefix(this.namespace, "tag-registry");
|
|
589
|
+
for (const tag of entry.tags ?? []) await this.remoteStorage.set(`${registry}${tag}`, "1");
|
|
590
|
+
const envelope = JSON.stringify({
|
|
591
|
+
__t_edge: 2,
|
|
592
|
+
__t_val: value,
|
|
593
|
+
__t_tv: versions,
|
|
594
|
+
__t_exp: entry.expiresAt,
|
|
595
|
+
__t_stale: entry.staleUntil,
|
|
596
|
+
__t_tags: entry.tags
|
|
597
|
+
});
|
|
598
|
+
const payload = this.enc.isEnabled ? await this.enc.encrypt(envelope) : envelope;
|
|
599
|
+
if (this.fence(namespaced) !== epoch) return;
|
|
600
|
+
await this.remoteStorage.set(namespaced, payload, ttl + (options?.swr ?? 0));
|
|
601
|
+
}
|
|
602
|
+
}
|
|
493
603
|
_evictIfNeeded(newBytes) {
|
|
494
604
|
while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
|
|
495
605
|
const oldestKey = this.l1.keys().next().value;
|
|
@@ -551,7 +661,8 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
551
661
|
if (oldestKey !== void 0) this.tagVersionCache.delete(oldestKey);
|
|
552
662
|
}
|
|
553
663
|
}
|
|
554
|
-
this.tagVersionCache.
|
|
664
|
+
const known = this.tagVersionCache.get(tag)?.version ?? 0;
|
|
665
|
+
this.tagVersionCache.set(tag, { version: Math.max(known, version), expiresAt });
|
|
555
666
|
}
|
|
556
667
|
async _getTagVersion(tag) {
|
|
557
668
|
const cached = this.tagVersionCache.get(tag);
|
|
@@ -563,9 +674,9 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
563
674
|
if (this.remoteStorage) {
|
|
564
675
|
try {
|
|
565
676
|
if (typeof this.remoteStorage.getTagVersion === "function") {
|
|
566
|
-
version = await this.remoteStorage.getTagVersion(this.
|
|
677
|
+
version = await this.remoteStorage.getTagVersion(this.tagVersionKey(tag));
|
|
567
678
|
} else {
|
|
568
|
-
const raw = await this.remoteStorage.get(this.
|
|
679
|
+
const raw = await this.remoteStorage.get(this.tagVersionKey(tag));
|
|
569
680
|
version = raw ? parseInt(raw, 10) || 1 : 1;
|
|
570
681
|
}
|
|
571
682
|
} catch {
|
|
@@ -575,11 +686,11 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
575
686
|
version = cached?.version ?? 1;
|
|
576
687
|
}
|
|
577
688
|
this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
|
|
578
|
-
return version;
|
|
689
|
+
return this.tagVersionCache.get(tag)?.version ?? version;
|
|
579
690
|
}
|
|
580
691
|
async _batchGetTagVersions(tags) {
|
|
581
692
|
const now = Date.now();
|
|
582
|
-
const result =
|
|
693
|
+
const result = /* @__PURE__ */ Object.create(null);
|
|
583
694
|
const missingTags = [];
|
|
584
695
|
for (const t of tags) {
|
|
585
696
|
const c = this.tagVersionCache.get(t);
|
|
@@ -592,12 +703,12 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
592
703
|
if (missingTags.length > 0 && this.remoteStorage) {
|
|
593
704
|
try {
|
|
594
705
|
if (typeof this.remoteStorage.batchGetTagVersions === "function") {
|
|
595
|
-
const nsTags = missingTags.map((t) => this.
|
|
706
|
+
const nsTags = missingTags.map((t) => this.tagVersionKey(t));
|
|
596
707
|
const remoteVersions = await this.remoteStorage.batchGetTagVersions(nsTags);
|
|
597
708
|
for (let i = 0; i < missingTags.length; i++) {
|
|
598
709
|
const t = missingTags[i];
|
|
599
|
-
const v = remoteVersions[this.
|
|
600
|
-
result[t] = v;
|
|
710
|
+
const v = remoteVersions[this.tagVersionKey(t)] ?? 1;
|
|
711
|
+
result[t] = Math.max(this.tagVersionCache.get(t)?.version ?? 0, v);
|
|
601
712
|
this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
|
|
602
713
|
}
|
|
603
714
|
} else {
|
|
@@ -625,7 +736,7 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
625
736
|
const span = this._startSpan("tricache.get");
|
|
626
737
|
span.setAttribute("cache.key", key);
|
|
627
738
|
const nsKey = this.nk(key);
|
|
628
|
-
|
|
739
|
+
let now = Date.now();
|
|
629
740
|
const resolvedTtl = ttlSeconds ?? this.defaultTtl;
|
|
630
741
|
try {
|
|
631
742
|
const l1Entry = this.l1.get(nsKey);
|
|
@@ -641,6 +752,7 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
641
752
|
}
|
|
642
753
|
}
|
|
643
754
|
}
|
|
755
|
+
now = Date.now();
|
|
644
756
|
if (isTagStale) {
|
|
645
757
|
this._deleteL1(nsKey);
|
|
646
758
|
} else {
|
|
@@ -652,85 +764,115 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
652
764
|
span.setAttribute("cache.hit_tier", "l1");
|
|
653
765
|
return l1Entry.value;
|
|
654
766
|
}
|
|
655
|
-
if (l1Entry.staleUntil > now && fetchFn) {
|
|
767
|
+
if (l1Entry.staleUntil > now && fetchFn && (options?.swr ?? 0) > 0) {
|
|
656
768
|
span.setAttribute("cache.hit", true);
|
|
657
769
|
span.setAttribute("cache.item.tier", "memory");
|
|
658
770
|
span.setAttribute("cache.hit_tier", "l1");
|
|
659
771
|
span.setAttribute("cache.stale", true);
|
|
660
|
-
const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
|
|
772
|
+
const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: options?.tags ?? l1Entry.tags });
|
|
661
773
|
if (options?.ctx?.waitUntil) {
|
|
662
774
|
options.ctx.waitUntil(revalPromise);
|
|
663
775
|
}
|
|
664
776
|
return l1Entry.value;
|
|
665
777
|
}
|
|
666
|
-
this._deleteL1(nsKey);
|
|
778
|
+
if (l1Entry.staleUntil <= now) this._deleteL1(nsKey);
|
|
667
779
|
}
|
|
668
780
|
}
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
781
|
+
const existing = this.inflight.get(nsKey);
|
|
782
|
+
if (existing) {
|
|
783
|
+
span.setAttribute("cache.stampede_coalesced", true);
|
|
784
|
+
return await existing;
|
|
785
|
+
}
|
|
786
|
+
const epoch = this.fence(nsKey);
|
|
787
|
+
const execution = Promise.resolve().then(async () => {
|
|
788
|
+
try {
|
|
789
|
+
if (this.remoteStorage) {
|
|
790
|
+
if (this.bloomAuthoritative && this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
|
|
791
|
+
span.setAttribute("cache.bloom.filtered", true);
|
|
792
|
+
} else {
|
|
793
|
+
try {
|
|
794
|
+
const rawRemote = await this.remoteStorage.get(nsKey);
|
|
795
|
+
if (rawRemote !== null) {
|
|
796
|
+
const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
|
|
797
|
+
const parsedJson = JSON.parse(plain);
|
|
798
|
+
let parsed;
|
|
799
|
+
let activeTagVersions;
|
|
800
|
+
let isStaleRemote = false;
|
|
801
|
+
if (parsedJson && typeof parsedJson === "object" && "__t_val" in parsedJson && "__t_tv" in parsedJson) {
|
|
802
|
+
parsed = parsedJson.__t_val;
|
|
803
|
+
activeTagVersions = parsedJson.__t_tv;
|
|
804
|
+
if (!activeTagVersions || typeof activeTagVersions !== "object" || Array.isArray(activeTagVersions) || Object.values(activeTagVersions).some((version) => !Number.isSafeInteger(version) || version < 0)) throw new Error("Invalid remote tag versions");
|
|
805
|
+
const tagNames = Object.keys(activeTagVersions);
|
|
806
|
+
const currentVers = await this._batchGetTagVersions(tagNames);
|
|
807
|
+
for (const tag of tagNames) {
|
|
808
|
+
if (currentVers[tag] > activeTagVersions[tag]) {
|
|
809
|
+
isStaleRemote = true;
|
|
810
|
+
break;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
} else {
|
|
814
|
+
parsed = parsedJson;
|
|
815
|
+
}
|
|
816
|
+
if (!isStaleRemote) {
|
|
817
|
+
const freshUntil = Number(parsedJson?.__t_exp);
|
|
818
|
+
const staleUntil = Number(parsedJson?.__t_stale);
|
|
819
|
+
const versioned = parsedJson?.__t_edge === 2 && Number.isFinite(freshUntil) && Number.isFinite(staleUntil) && staleUntil >= freshUntil;
|
|
820
|
+
if (versioned && (staleUntil <= Date.now() || freshUntil <= Date.now() && (!(options?.swr ?? 0) || !fetchFn))) {
|
|
821
|
+
isStaleRemote = true;
|
|
822
|
+
} else {
|
|
823
|
+
if (versioned && this.fence(nsKey) === epoch) {
|
|
824
|
+
const serialized = JSON.stringify(parsed);
|
|
825
|
+
const tags2 = Array.isArray(parsedJson.__t_tags) ? parsedJson.__t_tags : Object.keys(activeTagVersions ?? {}).filter((tag) => tag !== NAMESPACE_TAG);
|
|
826
|
+
this.storeL1(nsKey, {
|
|
827
|
+
value: parsed,
|
|
828
|
+
serialized,
|
|
829
|
+
bytes: this._estimateBytes(nsKey, serialized),
|
|
830
|
+
expiresAt: freshUntil,
|
|
831
|
+
staleUntil,
|
|
832
|
+
tags: tags2,
|
|
833
|
+
tagVersions: activeTagVersions
|
|
834
|
+
});
|
|
835
|
+
if (freshUntil <= Date.now() && fetchFn) {
|
|
836
|
+
const refresh = execution.then(() => this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: tags2 }));
|
|
837
|
+
options?.ctx?.waitUntil(refresh);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
span.setAttribute("cache.hit", true);
|
|
841
|
+
span.setAttribute("cache.item.tier", "remote");
|
|
842
|
+
span.setAttribute("cache.hit_tier", "l2");
|
|
843
|
+
return parsed;
|
|
844
|
+
}
|
|
690
845
|
}
|
|
691
846
|
}
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
}
|
|
695
|
-
if (!isStaleRemote) {
|
|
696
|
-
await this.set(key, parsed, resolvedTtl, options);
|
|
697
|
-
span.setAttribute("cache.hit", true);
|
|
698
|
-
span.setAttribute("cache.item.tier", "remote");
|
|
699
|
-
span.setAttribute("cache.hit_tier", "l2");
|
|
700
|
-
return parsed;
|
|
847
|
+
} catch (remoteErr) {
|
|
848
|
+
span.recordException?.(remoteErr);
|
|
701
849
|
}
|
|
702
850
|
}
|
|
703
|
-
} catch (remoteErr) {
|
|
704
|
-
span.recordException?.(remoteErr);
|
|
705
851
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
span.setAttribute("cache.hit_tier", "miss");
|
|
711
|
-
return null;
|
|
712
|
-
}
|
|
713
|
-
let inflightPromise = this.inflight.get(nsKey);
|
|
714
|
-
let coalesced = false;
|
|
715
|
-
if (inflightPromise) {
|
|
716
|
-
coalesced = true;
|
|
717
|
-
} else {
|
|
718
|
-
inflightPromise = (async () => {
|
|
719
|
-
try {
|
|
720
|
-
const fresh = await fetchFn();
|
|
721
|
-
await this.set(key, fresh, resolvedTtl, options);
|
|
722
|
-
return fresh;
|
|
723
|
-
} finally {
|
|
724
|
-
this.inflight.delete(nsKey);
|
|
852
|
+
if (!fetchFn) {
|
|
853
|
+
span.setAttribute("cache.hit", false);
|
|
854
|
+
span.setAttribute("cache.hit_tier", "miss");
|
|
855
|
+
return null;
|
|
725
856
|
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
857
|
+
const tags = [.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
|
|
858
|
+
const versions = await this._batchGetTagVersions(tags);
|
|
859
|
+
const fresh = await fetchFn();
|
|
860
|
+
const current = await this._batchGetTagVersions(tags);
|
|
861
|
+
if (this.fence(nsKey) === epoch && tags.every((tag) => current[tag] === versions[tag])) {
|
|
862
|
+
try {
|
|
863
|
+
await this.commit(key, fresh, resolvedTtl, options, versions, epoch);
|
|
864
|
+
} catch (error) {
|
|
865
|
+
span.recordException?.(error);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
869
|
+
return fresh;
|
|
870
|
+
} finally {
|
|
871
|
+
if (this.inflight.get(nsKey) === execution) this.inflight.delete(nsKey);
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
this.inflight.set(nsKey, execution);
|
|
875
|
+
return await execution;
|
|
734
876
|
} catch (err) {
|
|
735
877
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
736
878
|
span.recordException?.(err);
|
|
@@ -742,15 +884,19 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
742
884
|
async _revalidate(key, fetchFn, ttl, options) {
|
|
743
885
|
const nsKey = this.nk(key);
|
|
744
886
|
if (this.inflight.has(nsKey)) return;
|
|
745
|
-
const
|
|
887
|
+
const epoch = this.fence(nsKey);
|
|
888
|
+
const task = Promise.resolve().then(async () => {
|
|
746
889
|
try {
|
|
890
|
+
const tags = [.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
|
|
891
|
+
const versions = await this._batchGetTagVersions(tags);
|
|
747
892
|
const fresh = await fetchFn();
|
|
748
|
-
await this.
|
|
893
|
+
const current = await this._batchGetTagVersions(tags);
|
|
894
|
+
if (this.fence(nsKey) === epoch && tags.every((tag) => current[tag] === versions[tag])) await this.commit(key, fresh, ttl, options, versions, epoch);
|
|
749
895
|
} catch {
|
|
750
896
|
} finally {
|
|
751
|
-
this.inflight.delete(nsKey);
|
|
897
|
+
if (this.inflight.get(nsKey) === task) this.inflight.delete(nsKey);
|
|
752
898
|
}
|
|
753
|
-
})
|
|
899
|
+
});
|
|
754
900
|
this.inflight.set(nsKey, task);
|
|
755
901
|
await task;
|
|
756
902
|
}
|
|
@@ -761,48 +907,15 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
761
907
|
const span = this._startSpan("tricache.set");
|
|
762
908
|
span.setAttribute("cache.key", key);
|
|
763
909
|
const nsKey = this.nk(key);
|
|
910
|
+
this.mutate(nsKey);
|
|
911
|
+
const epoch = this.fence(nsKey);
|
|
764
912
|
const resolvedTtl = ttlSeconds ?? this.defaultTtl;
|
|
765
|
-
const now = Date.now();
|
|
766
913
|
const optObj = Array.isArray(options) ? { tags: options } : options;
|
|
767
914
|
const swrSeconds = optObj?.swr ?? 0;
|
|
768
915
|
try {
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
}
|
|
773
|
-
const serialized = JSON.stringify(value);
|
|
774
|
-
const bytes = this._estimateBytes(nsKey, serialized);
|
|
775
|
-
this._deleteL1(nsKey);
|
|
776
|
-
this._evictIfNeeded(bytes);
|
|
777
|
-
const entry = {
|
|
778
|
-
value,
|
|
779
|
-
serialized,
|
|
780
|
-
bytes,
|
|
781
|
-
expiresAt: now + resolvedTtl * 1e3,
|
|
782
|
-
staleUntil: now + (resolvedTtl + swrSeconds) * 1e3,
|
|
783
|
-
tags: optObj?.tags,
|
|
784
|
-
tagVersions: activeTagVersions
|
|
785
|
-
};
|
|
786
|
-
this.l1.set(nsKey, entry);
|
|
787
|
-
this.currentBytes += bytes;
|
|
788
|
-
if (optObj?.tags) {
|
|
789
|
-
for (const tag of optObj.tags) {
|
|
790
|
-
let s = this.tagIndex.get(tag);
|
|
791
|
-
if (!s) {
|
|
792
|
-
s = /* @__PURE__ */ new Set();
|
|
793
|
-
this.tagIndex.set(tag, s);
|
|
794
|
-
}
|
|
795
|
-
s.add(nsKey);
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
if (this.remoteStorage) {
|
|
799
|
-
const toStoreRaw = activeTagVersions ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions }) : serialized;
|
|
800
|
-
const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
|
|
801
|
-
await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
|
|
802
|
-
}
|
|
803
|
-
if (this.bloomFilter) {
|
|
804
|
-
this.bloomFilter.add(nsKey);
|
|
805
|
-
}
|
|
916
|
+
if (!Number.isFinite(resolvedTtl) || resolvedTtl < 0 || !Number.isFinite(swrSeconds) || swrSeconds < 0) throw new Error("Edge TTL and SWR must be finite non-negative values");
|
|
917
|
+
const versions = await this._batchGetTagVersions([.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...optObj?.tags ?? []])]);
|
|
918
|
+
await this.commit(key, value, resolvedTtl, optObj, versions, epoch);
|
|
806
919
|
} catch (err) {
|
|
807
920
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
808
921
|
span.recordException?.(err);
|
|
@@ -819,6 +932,7 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
819
932
|
span.setAttribute("cache.key", key);
|
|
820
933
|
const nsKey = this.nk(key);
|
|
821
934
|
try {
|
|
935
|
+
this.mutate(nsKey);
|
|
822
936
|
this._deleteL1(nsKey);
|
|
823
937
|
if (this.remoteStorage) {
|
|
824
938
|
await this.remoteStorage.delete(nsKey);
|
|
@@ -836,13 +950,17 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
836
950
|
* re-entering wildcard/cascade resolution.
|
|
837
951
|
*/
|
|
838
952
|
async _invalidateConcreteTag(tag) {
|
|
953
|
+
this.invalidateWork();
|
|
954
|
+
const previous = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
839
955
|
let newVer = 1;
|
|
840
956
|
if (this.remoteStorage) {
|
|
841
957
|
try {
|
|
842
958
|
if (typeof this.remoteStorage.incrementTagVersion === "function") {
|
|
843
|
-
newVer = await this.remoteStorage.incrementTagVersion(this.
|
|
959
|
+
newVer = await this.remoteStorage.incrementTagVersion(this.tagVersionKey(tag));
|
|
960
|
+
if (newVer <= previous) newVer = await this.remoteStorage.incrementTagVersion(this.tagVersionKey(tag));
|
|
961
|
+
newVer = Math.max(previous + 1, newVer);
|
|
844
962
|
} else {
|
|
845
|
-
const key = this.
|
|
963
|
+
const key = this.tagVersionKey(tag);
|
|
846
964
|
const current = await this._getTagVersion(tag);
|
|
847
965
|
newVer = Math.max(current + 1, Date.now());
|
|
848
966
|
await this.remoteStorage.set(key, String(newVer));
|
|
@@ -855,7 +973,7 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
855
973
|
const current = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
856
974
|
newVer = current + 1;
|
|
857
975
|
}
|
|
858
|
-
this._setTagVersionCache(tag, newVer, Date.now() +
|
|
976
|
+
this._setTagVersionCache(tag, newVer, Date.now() + this.tagVersionTtlMs);
|
|
859
977
|
const keys = this.tagIndex.get(tag);
|
|
860
978
|
if (keys) {
|
|
861
979
|
const keysArr = Array.from(keys);
|
|
@@ -876,6 +994,9 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
876
994
|
const isPattern = isWildcardTag(tag);
|
|
877
995
|
const shouldCascade = Boolean(opts?.cascade);
|
|
878
996
|
if (isPattern || shouldCascade) {
|
|
997
|
+
if (this.remoteStorage && !this.remoteStorage.scanKeys) {
|
|
998
|
+
throw new Error("Remote wildcard/cascade tag invalidation requires an adapter with scanKeys");
|
|
999
|
+
}
|
|
879
1000
|
const matched = /* @__PURE__ */ new Set();
|
|
880
1001
|
const tagMatches = (t) => {
|
|
881
1002
|
if (t === tag) return true;
|
|
@@ -889,6 +1010,14 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
889
1010
|
for (const t of this.tagVersionCache.keys()) {
|
|
890
1011
|
if (tagMatches(t)) matched.add(t);
|
|
891
1012
|
}
|
|
1013
|
+
if (this.remoteStorage?.scanKeys) {
|
|
1014
|
+
const registry = namespaceDomainPrefix(this.namespace, "tag-registry");
|
|
1015
|
+
for await (const key of this.remoteStorage.scanKeys(registry)) {
|
|
1016
|
+
if (!key.startsWith(registry)) continue;
|
|
1017
|
+
const concrete = key.slice(registry.length);
|
|
1018
|
+
if (tagMatches(concrete)) matched.add(concrete);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
892
1021
|
if (shouldCascade && !isPattern) matched.add(tag);
|
|
893
1022
|
for (const t of matched) {
|
|
894
1023
|
await this._invalidateConcreteTag(t);
|
|
@@ -910,6 +1039,8 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
910
1039
|
async clear() {
|
|
911
1040
|
const span = this._startSpan("tricache.clear");
|
|
912
1041
|
try {
|
|
1042
|
+
const previousNamespace = await this._getTagVersion(NAMESPACE_TAG);
|
|
1043
|
+
this.invalidateWork();
|
|
913
1044
|
this.l1.clear();
|
|
914
1045
|
this.currentBytes = 0;
|
|
915
1046
|
this.tagIndex.clear();
|
|
@@ -918,8 +1049,10 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
918
1049
|
this.bloomFilter.reset();
|
|
919
1050
|
}
|
|
920
1051
|
if (this.remoteStorage) {
|
|
921
|
-
await this.remoteStorage.clear?.(this.
|
|
1052
|
+
await this.remoteStorage.clear?.(this.dataPrefix);
|
|
922
1053
|
}
|
|
1054
|
+
this._setTagVersionCache(NAMESPACE_TAG, previousNamespace, Date.now() + this.tagVersionTtlMs);
|
|
1055
|
+
await this._invalidateConcreteTag(NAMESPACE_TAG);
|
|
923
1056
|
} catch (err) {
|
|
924
1057
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
925
1058
|
span.recordException?.(err);
|
|
@@ -933,6 +1066,7 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
933
1066
|
*/
|
|
934
1067
|
async mget(keys, fetchFn, ttlSeconds) {
|
|
935
1068
|
const span = this._startSpan("tricache.mget");
|
|
1069
|
+
const epochs = new Map(keys.map((key) => [key, this.fence(this.nk(key))]));
|
|
936
1070
|
span.setAttribute("cache.batch.size", keys.length);
|
|
937
1071
|
try {
|
|
938
1072
|
const results = Array.from({ length: keys.length }, () => null);
|
|
@@ -954,10 +1088,10 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
954
1088
|
const isMap = fetchedMap instanceof Map;
|
|
955
1089
|
for (let j = 0; j < missKeys.length; j++) {
|
|
956
1090
|
const k = missKeys[j];
|
|
957
|
-
const fetchedVal = isMap ? fetchedMap.get(k) : fetchedMap[k];
|
|
1091
|
+
const fetchedVal = isMap ? fetchedMap.get(k) : Object.hasOwn(fetchedMap, k) ? fetchedMap[k] : void 0;
|
|
958
1092
|
if (fetchedVal !== void 0) {
|
|
959
1093
|
results[missIndices[j]] = fetchedVal;
|
|
960
|
-
await this.set(k, fetchedVal, ttlSeconds);
|
|
1094
|
+
if (this.fence(this.nk(k)) === epochs.get(k)) await this.set(k, fetchedVal, ttlSeconds);
|
|
961
1095
|
}
|
|
962
1096
|
}
|
|
963
1097
|
}
|
|
@@ -979,7 +1113,8 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
979
1113
|
const entries = [];
|
|
980
1114
|
for (const [nsKey, entry] of this.l1.entries()) {
|
|
981
1115
|
if (entry.expiresAt > now || entry.staleUntil > now) {
|
|
982
|
-
|
|
1116
|
+
if (!nsKey.startsWith(this.dataPrefix)) continue;
|
|
1117
|
+
const cleanKey = nsKey.slice(this.dataPrefix.length);
|
|
983
1118
|
entries.push({
|
|
984
1119
|
key: cleanKey,
|
|
985
1120
|
value: entry.value,
|
|
@@ -991,7 +1126,8 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
991
1126
|
}
|
|
992
1127
|
}
|
|
993
1128
|
const payload = {
|
|
994
|
-
version:
|
|
1129
|
+
version: 3,
|
|
1130
|
+
namespace: this.namespacePrefix,
|
|
995
1131
|
writtenAt: now,
|
|
996
1132
|
entries
|
|
997
1133
|
};
|
|
@@ -1019,6 +1155,7 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
1019
1155
|
* }
|
|
1020
1156
|
*/
|
|
1021
1157
|
async hydrate(source, options) {
|
|
1158
|
+
const epoch = this.globalEpoch;
|
|
1022
1159
|
let rawStr = null;
|
|
1023
1160
|
if (source && typeof source === "object") {
|
|
1024
1161
|
if ("get" in source && typeof source.get === "function") {
|
|
@@ -1057,13 +1194,14 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
1057
1194
|
} catch {
|
|
1058
1195
|
return 0;
|
|
1059
1196
|
}
|
|
1060
|
-
if (!payload || !Array.isArray(payload.entries)) {
|
|
1197
|
+
if (!payload || payload.version !== 3 || payload.namespace !== this.namespacePrefix || !Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
|
|
1061
1198
|
return 0;
|
|
1062
1199
|
}
|
|
1063
1200
|
const now = Date.now();
|
|
1064
1201
|
const maxAgeMs = options?.maxAgeMs ?? 72e5;
|
|
1065
1202
|
const tolerance = options?.clockSkewToleranceMs ?? 250;
|
|
1066
1203
|
const writtenAt = payload.writtenAt ?? 0;
|
|
1204
|
+
if (!Number.isFinite(writtenAt) || writtenAt < this.lastGlobalMutationAt) return 0;
|
|
1067
1205
|
if (writtenAt - now > tolerance) {
|
|
1068
1206
|
return 0;
|
|
1069
1207
|
}
|
|
@@ -1074,10 +1212,23 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
1074
1212
|
let imported = 0;
|
|
1075
1213
|
for (const item of payload.entries) {
|
|
1076
1214
|
if (!item || typeof item.key !== "string") continue;
|
|
1215
|
+
if (!Number.isFinite(item.expiresAt) || !Number.isFinite(item.staleUntil)) continue;
|
|
1077
1216
|
if (item.expiresAt <= now && item.staleUntil <= now) continue;
|
|
1217
|
+
if (item.value === void 0) continue;
|
|
1218
|
+
if (item.tags !== void 0 && (!Array.isArray(item.tags) || item.tags.some((tag) => typeof tag !== "string"))) continue;
|
|
1219
|
+
if (item.tagVersions !== void 0 && (typeof item.tagVersions !== "object" || item.tagVersions === null || Array.isArray(item.tagVersions) || Object.values(item.tagVersions).some((version) => !Number.isFinite(version)))) continue;
|
|
1220
|
+
let serialized;
|
|
1221
|
+
try {
|
|
1222
|
+
const encoded = JSON.stringify(item.value);
|
|
1223
|
+
if (typeof encoded !== "string") continue;
|
|
1224
|
+
serialized = encoded;
|
|
1225
|
+
} catch {
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1078
1228
|
const nsKey = this.nk(item.key);
|
|
1079
|
-
|
|
1229
|
+
if (this.l1.has(nsKey) || this.keyEpochs.has(nsKey)) continue;
|
|
1080
1230
|
const bytes = this._estimateBytes(nsKey, serialized);
|
|
1231
|
+
if (bytes > this.maxBytes || this.maxKeys === 0) continue;
|
|
1081
1232
|
this._deleteL1(nsKey);
|
|
1082
1233
|
this._evictIfNeeded(bytes);
|
|
1083
1234
|
const entry = {
|
|
@@ -1102,7 +1253,7 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
1102
1253
|
}
|
|
1103
1254
|
}
|
|
1104
1255
|
if (this.bloomFilter) {
|
|
1105
|
-
this.bloomFilter.add(
|
|
1256
|
+
this.bloomFilter.add(nsKey);
|
|
1106
1257
|
}
|
|
1107
1258
|
imported++;
|
|
1108
1259
|
}
|
|
@@ -1124,9 +1275,11 @@ var EdgeCacheService = class _EdgeCacheService {
|
|
|
1124
1275
|
|
|
1125
1276
|
// src/edge/adapters/upstash.ts
|
|
1126
1277
|
var UpstashRedisAdapter = class {
|
|
1278
|
+
tagConsistency = "atomic";
|
|
1127
1279
|
baseUrl;
|
|
1128
1280
|
token;
|
|
1129
1281
|
customFetch;
|
|
1282
|
+
dangerouslyFlushDatabase;
|
|
1130
1283
|
constructor(options) {
|
|
1131
1284
|
if (!options?.url || !options?.token) {
|
|
1132
1285
|
throw new Error("UpstashRedisAdapter: url and token are required.");
|
|
@@ -1134,6 +1287,7 @@ var UpstashRedisAdapter = class {
|
|
|
1134
1287
|
this.baseUrl = options.url.replace(/\/+$/, "");
|
|
1135
1288
|
this.token = options.token;
|
|
1136
1289
|
this.customFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1290
|
+
this.dangerouslyFlushDatabase = options.dangerouslyFlushDatabase ?? false;
|
|
1137
1291
|
}
|
|
1138
1292
|
async _executeCommand(command) {
|
|
1139
1293
|
const res = await this.customFetch(this.baseUrl, {
|
|
@@ -1209,29 +1363,43 @@ var UpstashRedisAdapter = class {
|
|
|
1209
1363
|
await this._executeCommand(["MSET", ...args]);
|
|
1210
1364
|
}
|
|
1211
1365
|
}
|
|
1366
|
+
async *scanKeys(prefix) {
|
|
1367
|
+
const pattern = prefix.replaceAll("\\", "\\\\").replaceAll("*", "\\*").replaceAll("?", "\\?").replaceAll("[", "\\[").replaceAll("]", "\\]") + "*";
|
|
1368
|
+
let cursor = "0";
|
|
1369
|
+
do {
|
|
1370
|
+
const result = await this._executeCommand(["SCAN", cursor, "MATCH", pattern, "COUNT", 256]);
|
|
1371
|
+
if (!Array.isArray(result) || !Array.isArray(result[1])) throw new Error("Invalid Upstash SCAN response");
|
|
1372
|
+
cursor = String(result[0]);
|
|
1373
|
+
for (const key of result[1]) if (key.startsWith(prefix)) yield key;
|
|
1374
|
+
} while (cursor !== "0");
|
|
1375
|
+
}
|
|
1212
1376
|
async clear(prefix) {
|
|
1213
|
-
if (prefix) {
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1377
|
+
if (!prefix) {
|
|
1378
|
+
if (!this.dangerouslyFlushDatabase) throw new Error("Unscoped Upstash clear requires dangerouslyFlushDatabase: true");
|
|
1379
|
+
await this._executeCommand(["FLUSHDB"]);
|
|
1380
|
+
return;
|
|
1381
|
+
}
|
|
1382
|
+
let keys = [];
|
|
1383
|
+
for await (const key of this.scanKeys(prefix)) {
|
|
1384
|
+
keys.push(key);
|
|
1385
|
+
if (keys.length === 256) {
|
|
1217
1386
|
await this._executeCommand(["DEL", ...keys]);
|
|
1387
|
+
keys = [];
|
|
1218
1388
|
}
|
|
1219
|
-
} else {
|
|
1220
|
-
await this._executeCommand(["FLUSHDB"]);
|
|
1221
1389
|
}
|
|
1390
|
+
if (keys.length) await this._executeCommand(["DEL", ...keys]);
|
|
1222
1391
|
}
|
|
1223
1392
|
async incrementTagVersion(tag) {
|
|
1224
|
-
const res = await this._executeCommand(["INCR",
|
|
1393
|
+
const res = await this._executeCommand(["INCR", tag]);
|
|
1225
1394
|
return typeof res === "number" ? res : 1;
|
|
1226
1395
|
}
|
|
1227
1396
|
async getTagVersion(tag) {
|
|
1228
|
-
const res = await this._executeCommand(["GET",
|
|
1397
|
+
const res = await this._executeCommand(["GET", tag]);
|
|
1229
1398
|
return res ? parseInt(res, 10) || 1 : 1;
|
|
1230
1399
|
}
|
|
1231
1400
|
async batchGetTagVersions(tags) {
|
|
1232
1401
|
if (tags.length === 0) return {};
|
|
1233
|
-
const
|
|
1234
|
-
const res = await this.mget(keys);
|
|
1402
|
+
const res = await this.mget(tags);
|
|
1235
1403
|
const result = {};
|
|
1236
1404
|
for (let i = 0; i < tags.length; i++) {
|
|
1237
1405
|
const raw = res[i];
|
|
@@ -1244,6 +1412,7 @@ var UpstashRedisAdapter = class {
|
|
|
1244
1412
|
// src/edge/adapters/cloudflare-kv.ts
|
|
1245
1413
|
var MIN_CF_KV_TTL = 60;
|
|
1246
1414
|
var CloudflareKVAdapter = class {
|
|
1415
|
+
tagConsistency = "eventual";
|
|
1247
1416
|
kv;
|
|
1248
1417
|
constructor(kv) {
|
|
1249
1418
|
if (!kv) {
|
|
@@ -1295,19 +1464,21 @@ var CloudflareKVAdapter = class {
|
|
|
1295
1464
|
const keys = Object.keys(entries);
|
|
1296
1465
|
await Promise.all(keys.map((k) => this.set(k, entries[k], ttlSeconds)));
|
|
1297
1466
|
}
|
|
1298
|
-
async
|
|
1299
|
-
if (!this.kv.list)
|
|
1467
|
+
async *scanKeys(prefix) {
|
|
1468
|
+
if (!this.kv.list) throw new Error("Workers KV binding does not support list");
|
|
1300
1469
|
let cursor;
|
|
1301
1470
|
do {
|
|
1302
|
-
const res = await this.kv.list({ prefix, cursor });
|
|
1303
|
-
|
|
1304
|
-
await Promise.all(res.keys.map((item) => this.kv.delete(item.name)));
|
|
1305
|
-
}
|
|
1471
|
+
const res = await this.kv.list({ prefix, cursor, limit: 256 });
|
|
1472
|
+
for (const item of res.keys) if (item.name.startsWith(prefix)) yield item.name;
|
|
1306
1473
|
cursor = res.list_complete ? void 0 : res.cursor;
|
|
1474
|
+
if (!res.list_complete && !cursor) throw new Error("Workers KV list omitted its continuation cursor");
|
|
1307
1475
|
} while (cursor);
|
|
1308
1476
|
}
|
|
1477
|
+
async clear(prefix = "") {
|
|
1478
|
+
for await (const key of this.scanKeys(prefix)) await this.kv.delete(key);
|
|
1479
|
+
}
|
|
1309
1480
|
async incrementTagVersion(tag) {
|
|
1310
|
-
const key =
|
|
1481
|
+
const key = tag;
|
|
1311
1482
|
const raw = await this.kv.get(key);
|
|
1312
1483
|
const prev = raw ? parseInt(raw, 10) || 0 : 0;
|
|
1313
1484
|
const nextVer = Math.max(prev + 1, Date.now());
|
|
@@ -1315,7 +1486,7 @@ var CloudflareKVAdapter = class {
|
|
|
1315
1486
|
return nextVer;
|
|
1316
1487
|
}
|
|
1317
1488
|
async getTagVersion(tag) {
|
|
1318
|
-
const raw = await this.kv.get(
|
|
1489
|
+
const raw = await this.kv.get(tag);
|
|
1319
1490
|
return raw ? parseInt(raw, 10) || 1 : 1;
|
|
1320
1491
|
}
|
|
1321
1492
|
async batchGetTagVersions(tags) {
|
|
@@ -1330,6 +1501,7 @@ var CloudflareKVAdapter = class {
|
|
|
1330
1501
|
|
|
1331
1502
|
// src/edge/adapters/cloudflare-do.ts
|
|
1332
1503
|
var CloudflareDOStorageAdapter = class {
|
|
1504
|
+
tagConsistency = "atomic";
|
|
1333
1505
|
storage;
|
|
1334
1506
|
constructor(storage) {
|
|
1335
1507
|
if (!storage) {
|
|
@@ -1389,16 +1561,33 @@ var CloudflareDOStorageAdapter = class {
|
|
|
1389
1561
|
}
|
|
1390
1562
|
await this.storage.put(record);
|
|
1391
1563
|
}
|
|
1392
|
-
async
|
|
1393
|
-
if (!this.storage.list)
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1564
|
+
async *scanKeys(prefix) {
|
|
1565
|
+
if (!this.storage.list) throw new Error("Durable Object storage does not support list");
|
|
1566
|
+
let startAfter;
|
|
1567
|
+
while (true) {
|
|
1568
|
+
const page = await this.storage.list({ prefix, startAfter, limit: 256 });
|
|
1569
|
+
if (page.size === 0) return;
|
|
1570
|
+
const keys = [...page.keys()];
|
|
1571
|
+
for (const key of keys) if (key.startsWith(prefix)) yield key;
|
|
1572
|
+
const next = keys[keys.length - 1];
|
|
1573
|
+
if (next === startAfter) throw new Error("Durable Object list did not advance");
|
|
1574
|
+
startAfter = next;
|
|
1575
|
+
if (page.size < 256) return;
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
async clear(prefix = "") {
|
|
1579
|
+
let keys = [];
|
|
1580
|
+
for await (const key of this.scanKeys(prefix)) {
|
|
1581
|
+
keys.push(key);
|
|
1582
|
+
if (keys.length === 256) {
|
|
1583
|
+
await this.storage.delete(keys);
|
|
1584
|
+
keys = [];
|
|
1585
|
+
}
|
|
1398
1586
|
}
|
|
1587
|
+
if (keys.length) await this.storage.delete(keys);
|
|
1399
1588
|
}
|
|
1400
1589
|
async incrementTagVersion(tag) {
|
|
1401
|
-
const key =
|
|
1590
|
+
const key = tag;
|
|
1402
1591
|
const raw = await this.storage.get(key);
|
|
1403
1592
|
const prev = raw && typeof raw === "object" && "val" in raw ? parseInt(raw.val, 10) || 0 : typeof raw === "string" ? parseInt(raw, 10) || 0 : 0;
|
|
1404
1593
|
const nextVer = prev + 1;
|
|
@@ -1406,18 +1595,18 @@ var CloudflareDOStorageAdapter = class {
|
|
|
1406
1595
|
return nextVer;
|
|
1407
1596
|
}
|
|
1408
1597
|
async getTagVersion(tag) {
|
|
1409
|
-
const raw = await this.storage.get(
|
|
1598
|
+
const raw = await this.storage.get(tag);
|
|
1410
1599
|
if (raw && typeof raw === "object" && "val" in raw) {
|
|
1411
1600
|
return parseInt(raw.val, 10) || 1;
|
|
1412
1601
|
}
|
|
1413
1602
|
return typeof raw === "string" ? parseInt(raw, 10) || 1 : 1;
|
|
1414
1603
|
}
|
|
1415
1604
|
async batchGetTagVersions(tags) {
|
|
1416
|
-
const keys = tags
|
|
1605
|
+
const keys = tags;
|
|
1417
1606
|
const map = await this.storage.get(keys);
|
|
1418
1607
|
const result = {};
|
|
1419
1608
|
for (const tag of tags) {
|
|
1420
|
-
const entry = map.get(
|
|
1609
|
+
const entry = map.get(tag);
|
|
1421
1610
|
if (entry && typeof entry === "object" && "val" in entry) {
|
|
1422
1611
|
result[tag] = parseInt(entry.val, 10) || 1;
|
|
1423
1612
|
} else {
|
|
@@ -1496,7 +1685,6 @@ function honoEdgeCache(options = {}) {
|
|
|
1496
1685
|
cache,
|
|
1497
1686
|
etag = true,
|
|
1498
1687
|
ttl = 300,
|
|
1499
|
-
swr,
|
|
1500
1688
|
tags,
|
|
1501
1689
|
skipCache,
|
|
1502
1690
|
keyGenerator,
|
|
@@ -1510,6 +1698,8 @@ function honoEdgeCache(options = {}) {
|
|
|
1510
1698
|
if (skipCache && skipCache(c)) {
|
|
1511
1699
|
return await next();
|
|
1512
1700
|
}
|
|
1701
|
+
const credentials = ["authorization", "cookie", "x-api-key", "x-auth-token"].filter((name) => c.req.header?.(name));
|
|
1702
|
+
if (c.req.header?.("range") || credentials.length > 0 && (!options.cacheAuthenticated || !keyGenerator && !credentials.every((name) => headerWhitelist?.some((header) => header.toLowerCase() === name)))) return await next();
|
|
1513
1703
|
const cc = c.req.header?.("cache-control") || c.req.header?.("Cache-Control");
|
|
1514
1704
|
if (typeof cc === "string") {
|
|
1515
1705
|
const lower = cc.toLowerCase();
|
|
@@ -1520,7 +1710,12 @@ function honoEdgeCache(options = {}) {
|
|
|
1520
1710
|
if (!cache) {
|
|
1521
1711
|
return await next();
|
|
1522
1712
|
}
|
|
1523
|
-
|
|
1713
|
+
let key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
|
|
1714
|
+
if (credentials.length) {
|
|
1715
|
+
if (!globalThis.crypto?.subtle) return await next();
|
|
1716
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
|
|
1717
|
+
key = `edge:http:identity:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
1718
|
+
}
|
|
1524
1719
|
const ifNoneMatch = c.req.header?.("if-none-match") || c.req.header?.("If-None-Match");
|
|
1525
1720
|
const resolvedTags = typeof tags === "function" ? tags(c) : tags;
|
|
1526
1721
|
let ranNext = false;
|
|
@@ -1543,6 +1738,10 @@ function honoEdgeCache(options = {}) {
|
|
|
1543
1738
|
});
|
|
1544
1739
|
}
|
|
1545
1740
|
const cc2 = res.headers?.get?.("cache-control");
|
|
1741
|
+
const vary = String(res.headers?.get?.("vary") ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
|
|
1742
|
+
if (res.headers?.get?.("set-cookie") || vary.includes("*") || !keyGenerator && vary.some((name) => !headerWhitelist?.some((header) => header.toLowerCase() === name))) {
|
|
1743
|
+
throw new NonCacheableEdgeResponseError({ body: "", contentType, status: 0 });
|
|
1744
|
+
}
|
|
1546
1745
|
if (cc2) {
|
|
1547
1746
|
const lowerCc = cc2.toLowerCase();
|
|
1548
1747
|
if (lowerCc.includes("no-store") || lowerCc.includes("no-cache") || lowerCc.includes("private")) {
|
|
@@ -1584,9 +1783,9 @@ function honoEdgeCache(options = {}) {
|
|
|
1584
1783
|
},
|
|
1585
1784
|
ttl,
|
|
1586
1785
|
{
|
|
1587
|
-
swr,
|
|
1786
|
+
swr: 0,
|
|
1588
1787
|
tags: resolvedTags,
|
|
1589
|
-
ctx: c
|
|
1788
|
+
ctx: readExecutionContext(c)
|
|
1590
1789
|
}
|
|
1591
1790
|
);
|
|
1592
1791
|
if (!cached) {
|
|
@@ -1613,6 +1812,13 @@ function honoEdgeCache(options = {}) {
|
|
|
1613
1812
|
}
|
|
1614
1813
|
};
|
|
1615
1814
|
}
|
|
1815
|
+
function readExecutionContext(c) {
|
|
1816
|
+
try {
|
|
1817
|
+
return c.executionCtx;
|
|
1818
|
+
} catch {
|
|
1819
|
+
return void 0;
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1616
1822
|
function applyEdgeResponse(c, body, status, headers) {
|
|
1617
1823
|
const response = c.body(body, status, headers);
|
|
1618
1824
|
c.res = response;
|