@warlock.js/cache 5.52.0 → 5.53.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/CHANGELOG.md +36 -0
- package/cjs/index.cjs +528 -122
- package/cjs/index.cjs.map +1 -1
- package/esm/cache-manager.mjs.map +1 -1
- package/esm/cached/auto-key.d.mts +3 -1
- package/esm/cached/auto-key.d.mts.map +1 -1
- package/esm/cached/auto-key.mjs +9 -4
- package/esm/cached/auto-key.mjs.map +1 -1
- package/esm/cached/cached.mjs.map +1 -1
- package/esm/cached/normalize-args.mjs.map +1 -1
- package/esm/drivers/base-cache-driver.d.mts +40 -3
- package/esm/drivers/base-cache-driver.d.mts.map +1 -1
- package/esm/drivers/base-cache-driver.mjs +57 -7
- package/esm/drivers/base-cache-driver.mjs.map +1 -1
- package/esm/drivers/clone-value.mjs +17 -0
- package/esm/drivers/clone-value.mjs.map +1 -0
- package/esm/drivers/file-cache-driver.d.mts +40 -2
- package/esm/drivers/file-cache-driver.d.mts.map +1 -1
- package/esm/drivers/file-cache-driver.mjs +142 -18
- package/esm/drivers/file-cache-driver.mjs.map +1 -1
- package/esm/drivers/in-memory-tag-index.d.mts +5 -0
- package/esm/drivers/in-memory-tag-index.d.mts.map +1 -1
- package/esm/drivers/in-memory-tag-index.mjs +17 -0
- package/esm/drivers/in-memory-tag-index.mjs.map +1 -1
- package/esm/drivers/lru-memory-cache-driver.d.mts +18 -1
- package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
- package/esm/drivers/lru-memory-cache-driver.mjs +27 -2
- package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
- package/esm/drivers/memory-cache-driver.d.mts +16 -1
- package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
- package/esm/drivers/memory-cache-driver.mjs +34 -5
- package/esm/drivers/memory-cache-driver.mjs.map +1 -1
- package/esm/drivers/memory-extended-cache-driver.mjs.map +1 -1
- package/esm/drivers/mock-cache-driver.mjs.map +1 -1
- package/esm/drivers/null-cache-driver.d.mts.map +1 -1
- package/esm/drivers/null-cache-driver.mjs +22 -12
- package/esm/drivers/null-cache-driver.mjs.map +1 -1
- package/esm/drivers/pg-cache-driver.d.mts +19 -0
- package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
- package/esm/drivers/pg-cache-driver.mjs +52 -26
- package/esm/drivers/pg-cache-driver.mjs.map +1 -1
- package/esm/drivers/redis-cache-driver.d.mts +29 -0
- package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
- package/esm/drivers/redis-cache-driver.mjs +70 -36
- package/esm/drivers/redis-cache-driver.mjs.map +1 -1
- package/esm/idempotent.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/esm/list/memory-cache-list.mjs.map +1 -1
- package/esm/metrics.mjs.map +1 -1
- package/esm/scoped-cache.mjs.map +1 -1
- package/esm/structures/bloom-filter.mjs.map +1 -1
- package/esm/structures/cuckoo-filter.mjs.map +1 -1
- package/esm/structures/frequency-tracker.mjs.map +1 -1
- package/esm/structures/hash.mjs.map +1 -1
- package/esm/structures/hyperloglog.mjs.map +1 -1
- package/esm/structures/memory-structures-backend.mjs.map +1 -1
- package/esm/structures/redis-structures-backend.mjs.map +1 -1
- package/esm/structures/sizing.mjs.map +1 -1
- package/esm/structures/structures.mjs.map +1 -1
- package/esm/structures/types.mjs.map +1 -1
- package/esm/structures/unique-counter.mjs.map +1 -1
- package/esm/tag-sample.mjs +16 -0
- package/esm/tag-sample.mjs.map +1 -0
- package/esm/tagged-cache.d.mts +15 -0
- package/esm/tagged-cache.d.mts.map +1 -1
- package/esm/tagged-cache.mjs +31 -10
- package/esm/tagged-cache.mjs.map +1 -1
- package/esm/tagged-scoped-cache.mjs.map +1 -1
- package/esm/types.d.mts +24 -5
- package/esm/types.d.mts.map +1 -1
- package/esm/types.mjs.map +1 -1
- package/esm/utils.d.mts +20 -1
- package/esm/utils.d.mts.map +1 -1
- package/esm/utils.mjs +42 -3
- package/esm/utils.mjs.map +1 -1
- package/llms-full.txt +9 -6
- package/llms.txt +1 -1
- package/package.json +3 -3
- package/skills/cache-basics/SKILL.md +1 -1
- package/skills/pick-cache-driver/SKILL.md +1 -1
- package/skills/use-cache-namespace/SKILL.md +1 -0
- package/skills/use-cache-tags/SKILL.md +1 -1
- package/skills/use-cache-utils/SKILL.md +4 -2
- package/skills/use-cached-hof/SKILL.md +1 -1
package/cjs/index.cjs
CHANGED
|
@@ -99,10 +99,49 @@ var CacheConcurrencyError = class extends CacheError {
|
|
|
99
99
|
//#endregion
|
|
100
100
|
//#region ../../packages/cache/src/utils.ts
|
|
101
101
|
/**
|
|
102
|
-
*
|
|
102
|
+
* Characters that `parseCacheKey` strips or turns into the `.` separator.
|
|
103
|
+
* Inside a value they would make two different keys equal.
|
|
104
|
+
*/
|
|
105
|
+
const KEY_SEPARATOR_CHARACTERS = /[%.,:{}"[\]]/g;
|
|
106
|
+
/**
|
|
107
|
+
* Escape a value for use as ONE segment of a cache key or namespace: the
|
|
108
|
+
* characters the key format treats as separators or strips (`.` `,` `:`
|
|
109
|
+
* `{` `}` `"` `[` `]`, and `%` itself) are percent-encoded, so the value can
|
|
110
|
+
* never reach into another key or namespace. Values without those
|
|
111
|
+
* characters are returned unchanged.
|
|
112
|
+
*
|
|
113
|
+
* Use it for request-derived text (slugs, search terms, ids from a client).
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* cache.namespace(`tenant.${escapeCacheKeySegment(tenantSlug)}`);
|
|
117
|
+
* // slug "acme.billing" → namespace "tenant.acme%2Ebilling", never inside "tenant.acme"
|
|
118
|
+
*/
|
|
119
|
+
function escapeCacheKeySegment(value) {
|
|
120
|
+
return value.replace(KEY_SEPARATOR_CHARACTERS, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Escape every string (and object key) inside an object key, so a value that
|
|
124
|
+
* contains a separator cannot be read as two segments. Values without
|
|
125
|
+
* separator characters keep their exact previous encoding.
|
|
126
|
+
*/
|
|
127
|
+
function escapeKeyObject(value) {
|
|
128
|
+
if (typeof value === "string") return escapeCacheKeySegment(value);
|
|
129
|
+
if (Array.isArray(value)) return value.map(escapeKeyObject);
|
|
130
|
+
if (value === null || typeof value !== "object" || value instanceof Date) return value;
|
|
131
|
+
const escaped = Object.create(null);
|
|
132
|
+
for (const [name, child] of Object.entries(value)) escaped[escapeCacheKeySegment(name)] = escapeKeyObject(child);
|
|
133
|
+
return escaped;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Make a proper key for the cache.
|
|
137
|
+
*
|
|
138
|
+
* String keys are used as they are (`:` and `,` become `.`; `{}"[]` are
|
|
139
|
+
* removed). In an object key, separator characters inside the object's keys
|
|
140
|
+
* and string values are escaped first (see {@link escapeCacheKeySegment}),
|
|
141
|
+
* so `{ a: "b.c" }` and `{ a: "b", c: "" }` are different keys.
|
|
103
142
|
*/
|
|
104
143
|
function parseCacheKey(key, options = {}) {
|
|
105
|
-
if (typeof key === "object") key = JSON.stringify(key);
|
|
144
|
+
if (typeof key === "object") key = JSON.stringify(escapeKeyObject(key));
|
|
106
145
|
key = key.replace(/[{}"[\]]/g, "").replaceAll(/[:,]/g, ".");
|
|
107
146
|
const cachePrefix = typeof options.globalPrefix === "function" ? options.globalPrefix() : options.globalPrefix;
|
|
108
147
|
return (0, _mongez_reinforcements.rtrim)(String(cachePrefix ? (0, _mongez_reinforcements.rtrim)(cachePrefix, ".") + "." + key : key), ".");
|
|
@@ -2394,7 +2433,9 @@ function idempotent(key, fn, options) {
|
|
|
2394
2433
|
* `parseCacheKey` (e.g. `("1.private", "")` vs `("1", "private")`).
|
|
2395
2434
|
*
|
|
2396
2435
|
* Encoding rules: object keys are sorted, `Date` → ISO string, `undefined` →
|
|
2397
|
-
* `{"$u":1}`, `bigint` → decimal
|
|
2436
|
+
* `{"$u":1}`, `bigint` → `{"$b":"<decimal>"}`. Object keys that start with
|
|
2437
|
+
* `$` get one more `$`, so an argument can never spell one of those markers,
|
|
2438
|
+
* and an own `__proto__` key is kept as data.
|
|
2398
2439
|
*
|
|
2399
2440
|
* No args → the prefix alone.
|
|
2400
2441
|
*
|
|
@@ -2426,7 +2467,7 @@ function normalize(value, prefix, seen) {
|
|
|
2426
2467
|
case "string":
|
|
2427
2468
|
case "boolean": return value;
|
|
2428
2469
|
case "number": return Number.isFinite(value) ? value : { $n: String(value) };
|
|
2429
|
-
case "bigint": return
|
|
2470
|
+
case "bigint": return { $b: value.toString() };
|
|
2430
2471
|
case "function": return unsupported(prefix, "a function argument");
|
|
2431
2472
|
case "symbol": return unsupported(prefix, "a symbol argument");
|
|
2432
2473
|
}
|
|
@@ -2441,8 +2482,11 @@ function normalize(value, prefix, seen) {
|
|
|
2441
2482
|
else {
|
|
2442
2483
|
const proto = Object.getPrototypeOf(obj);
|
|
2443
2484
|
if (proto !== Object.prototype && proto !== null) unsupported(prefix, "a class instance argument");
|
|
2444
|
-
const out =
|
|
2445
|
-
for (const key of Object.keys(obj).sort())
|
|
2485
|
+
const out = Object.create(null);
|
|
2486
|
+
for (const key of Object.keys(obj).sort()) {
|
|
2487
|
+
const encodedKey = key.startsWith("$") ? `$${key}` : key;
|
|
2488
|
+
out[encodedKey] = normalize(obj[key], prefix, seen);
|
|
2489
|
+
}
|
|
2446
2490
|
result = out;
|
|
2447
2491
|
}
|
|
2448
2492
|
seen.delete(obj);
|
|
@@ -2614,6 +2658,20 @@ var MemoryCacheList = class {
|
|
|
2614
2658
|
}
|
|
2615
2659
|
};
|
|
2616
2660
|
|
|
2661
|
+
//#endregion
|
|
2662
|
+
//#region ../../packages/cache/src/tag-sample.ts
|
|
2663
|
+
/**
|
|
2664
|
+
* Up to `count` members starting at a random offset (all of them when there
|
|
2665
|
+
* are fewer), so repeated samples cover a large index over time.
|
|
2666
|
+
*
|
|
2667
|
+
* @internal
|
|
2668
|
+
*/
|
|
2669
|
+
function sampleMembers(members, count) {
|
|
2670
|
+
if (members.length <= count) return [...members];
|
|
2671
|
+
const start = Math.floor(Math.random() * members.length);
|
|
2672
|
+
return Array.from({ length: count }, (_, index) => members[(start + index) % members.length]);
|
|
2673
|
+
}
|
|
2674
|
+
|
|
2617
2675
|
//#endregion
|
|
2618
2676
|
//#region ../../packages/cache/src/tagged-cache.ts
|
|
2619
2677
|
/**
|
|
@@ -2667,15 +2725,37 @@ var TaggedCache = class TaggedCache {
|
|
|
2667
2725
|
* to its live members without any write paying for a full scan.
|
|
2668
2726
|
*/
|
|
2669
2727
|
async pruneTag(tagKey, justWritten) {
|
|
2670
|
-
const members = (await this.membersOf(tagKey)).filter((member) => member !== justWritten);
|
|
2671
|
-
if (members.length === 0) return;
|
|
2672
2728
|
const limit = TaggedCache.PRUNE_CHECKS_PER_WRITE;
|
|
2673
|
-
const
|
|
2674
|
-
|
|
2675
|
-
const
|
|
2676
|
-
|
|
2729
|
+
const window = (await this.sampleOf(tagKey, limit + 1)).filter((member) => member !== justWritten).slice(0, limit);
|
|
2730
|
+
if (window.length === 0) return;
|
|
2731
|
+
const present = await Promise.all(window.map((member) => this.memberExists(member)));
|
|
2732
|
+
const missing = window.filter((_, index) => !present[index]);
|
|
2677
2733
|
if (missing.length > 0) await this.removeFromTag(tagKey, missing);
|
|
2678
2734
|
}
|
|
2735
|
+
/**
|
|
2736
|
+
* Up to `count` random members of an index: the driver's `tagSample` when it
|
|
2737
|
+
* has one, else a window of the full member list.
|
|
2738
|
+
*/
|
|
2739
|
+
async sampleOf(tagKey, count) {
|
|
2740
|
+
if (typeof this.driver.tagSample === "function") return this.driver.tagSample(tagKey, count);
|
|
2741
|
+
return sampleMembers(await this.membersOf(tagKey), count);
|
|
2742
|
+
}
|
|
2743
|
+
/**
|
|
2744
|
+
* Whether an indexed key still has a live entry: the driver's `exists`
|
|
2745
|
+
* (no value read, no hit/miss events) when it has one, else `has()`.
|
|
2746
|
+
*/
|
|
2747
|
+
async memberExists(member) {
|
|
2748
|
+
if (typeof this.driver.exists === "function") return this.driver.exists(member);
|
|
2749
|
+
return this.driver.has(member);
|
|
2750
|
+
}
|
|
2751
|
+
/**
|
|
2752
|
+
* Remove entries by their indexed keys: the driver's batched `removeMany`
|
|
2753
|
+
* when it has one, else `remove()` per key.
|
|
2754
|
+
*/
|
|
2755
|
+
async removeEntries(keys) {
|
|
2756
|
+
if (typeof this.driver.removeMany === "function") return this.driver.removeMany(keys);
|
|
2757
|
+
for (const key of keys) await this.driver.remove(key);
|
|
2758
|
+
}
|
|
2679
2759
|
async addToTag(tagKey, members) {
|
|
2680
2760
|
if (typeof this.driver.tagAdd === "function") return this.driver.tagAdd(tagKey, members);
|
|
2681
2761
|
const current = await this.legacyMembers(tagKey);
|
|
@@ -2751,10 +2831,8 @@ var TaggedCache = class TaggedCache {
|
|
|
2751
2831
|
for (const tag of this.cacheTags) {
|
|
2752
2832
|
const tagKey = this.tagKey(tag);
|
|
2753
2833
|
const members = await this.membersOf(tagKey);
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
removed.add(member);
|
|
2757
|
-
}
|
|
2834
|
+
await this.removeEntries(members);
|
|
2835
|
+
for (const member of members) removed.add(member);
|
|
2758
2836
|
await this.removeFromTag(tagKey, members);
|
|
2759
2837
|
}
|
|
2760
2838
|
await this.driver.emitTagsInvalidated?.({
|
|
@@ -2852,7 +2930,7 @@ const messages = {
|
|
|
2852
2930
|
};
|
|
2853
2931
|
var BaseCacheDriver = class {
|
|
2854
2932
|
constructor() {
|
|
2855
|
-
this.shouldLog =
|
|
2933
|
+
this.shouldLog = false;
|
|
2856
2934
|
this.eventListeners = /* @__PURE__ */ new Map();
|
|
2857
2935
|
this.rememberInFlight = /* @__PURE__ */ new Map();
|
|
2858
2936
|
this.swrFetchInFlight = /* @__PURE__ */ new Map();
|
|
@@ -3018,6 +3096,35 @@ var BaseCacheDriver = class {
|
|
|
3018
3096
|
await this.runSerialized(this.parseKey(tagKey), () => this.remove(tagKey));
|
|
3019
3097
|
}
|
|
3020
3098
|
/**
|
|
3099
|
+
* {@inheritdoc}
|
|
3100
|
+
*
|
|
3101
|
+
* Default implementation: reads every member and picks a random window.
|
|
3102
|
+
* Drivers with a native random-member command override it (redis
|
|
3103
|
+
* `SRANDMEMBER`, the in-process drivers' index).
|
|
3104
|
+
*/
|
|
3105
|
+
async tagSample(tagKey, count) {
|
|
3106
|
+
return sampleMembers(await this.tagMembers(tagKey), count);
|
|
3107
|
+
}
|
|
3108
|
+
/**
|
|
3109
|
+
* {@inheritdoc}
|
|
3110
|
+
*
|
|
3111
|
+
* Default implementation: the raw entry read (no `hit`/`miss` on drivers
|
|
3112
|
+
* that override {@link getEntry}). Drivers with a cheaper existence check
|
|
3113
|
+
* override it.
|
|
3114
|
+
*/
|
|
3115
|
+
async exists(key) {
|
|
3116
|
+
return await this.getEntry(key) !== null;
|
|
3117
|
+
}
|
|
3118
|
+
/**
|
|
3119
|
+
* {@inheritdoc}
|
|
3120
|
+
*
|
|
3121
|
+
* Default implementation: `remove()` per key, one after another. Drivers
|
|
3122
|
+
* with a network round trip per command override it.
|
|
3123
|
+
*/
|
|
3124
|
+
async removeMany(keys) {
|
|
3125
|
+
for (const key of keys) await this.remove(key);
|
|
3126
|
+
}
|
|
3127
|
+
/**
|
|
3021
3128
|
* The index stored as a plain entry, or `[]`. Non-string members (a corrupted
|
|
3022
3129
|
* or foreign value) are ignored rather than trusted.
|
|
3023
3130
|
*/
|
|
@@ -3038,6 +3145,14 @@ var BaseCacheDriver = class {
|
|
|
3038
3145
|
await this.tags(tags).storeTagRelationship(key);
|
|
3039
3146
|
}
|
|
3040
3147
|
/**
|
|
3148
|
+
* Remove an entry by its already-parsed key (prefix applied). `remove()`
|
|
3149
|
+
* parses its key again, which would apply a `globalPrefix` twice; drivers
|
|
3150
|
+
* that store by parsed key override this. The default calls `remove()`.
|
|
3151
|
+
*/
|
|
3152
|
+
async removeParsed(parsedKey) {
|
|
3153
|
+
await this.remove(parsedKey);
|
|
3154
|
+
}
|
|
3155
|
+
/**
|
|
3041
3156
|
* {@inheritdoc}
|
|
3042
3157
|
*/
|
|
3043
3158
|
async has(key) {
|
|
@@ -3297,9 +3412,13 @@ var BaseCacheDriver = class {
|
|
|
3297
3412
|
* Log the operation
|
|
3298
3413
|
*/
|
|
3299
3414
|
log(operation, key) {
|
|
3300
|
-
|
|
3415
|
+
const alwaysLogged = operation === "connectionFailed" || operation === "error";
|
|
3416
|
+
if (!this.shouldLog && !alwaysLogged) return;
|
|
3301
3417
|
if (typeof key === "string") key = (0, _warlock_js_logger.maskEmailsInText)(key.replace(/\//g, "."));
|
|
3302
|
-
if (operation === "connectionFailed")
|
|
3418
|
+
if (operation === "connectionFailed") {
|
|
3419
|
+
_warlock_js_logger.log.fatal(`cache.${this.name}`, operation, key);
|
|
3420
|
+
if (!this.shouldLog) return;
|
|
3421
|
+
}
|
|
3303
3422
|
if (operation == "notFound" || operation == "expired") return _warlock_js_logger.log.info("cache." + this.name, operation, (key ? key + " " : "") + messages[operation]);
|
|
3304
3423
|
if (operation.endsWith("ed")) return _warlock_js_logger.log.success("cache." + this.name, operation, (key ? key + " " : "") + messages[operation]);
|
|
3305
3424
|
_warlock_js_logger.log.info("cache." + this.name, operation, (key ? key + " " : "") + messages[operation]);
|
|
@@ -3351,18 +3470,26 @@ var BaseCacheDriver = class {
|
|
|
3351
3470
|
return preparedData;
|
|
3352
3471
|
}
|
|
3353
3472
|
/**
|
|
3354
|
-
* Parse fetched data from cache
|
|
3473
|
+
* Parse fetched data from cache.
|
|
3474
|
+
*
|
|
3475
|
+
* Object values are deep-cloned so callers cannot mutate stored state; a
|
|
3476
|
+
* driver that just deserialized `data` (it is already a private copy)
|
|
3477
|
+
* passes `clone: false`.
|
|
3355
3478
|
*/
|
|
3356
|
-
async parseCachedData(key, data) {
|
|
3479
|
+
async parseCachedData(key, data, clone = true) {
|
|
3357
3480
|
this.log("fetched", key);
|
|
3358
3481
|
if (data.expiresAt && data.expiresAt < Date.now()) {
|
|
3359
|
-
|
|
3482
|
+
try {
|
|
3483
|
+
await this.removeParsed(key);
|
|
3484
|
+
} catch (error) {
|
|
3485
|
+
this.logError(`Failed to remove expired entry ${key}`, error);
|
|
3486
|
+
}
|
|
3360
3487
|
return null;
|
|
3361
3488
|
}
|
|
3362
3489
|
const value = data.data;
|
|
3363
3490
|
if (value === null || value === void 0) return value;
|
|
3364
3491
|
const type = typeof value;
|
|
3365
|
-
if (type === "string" || type === "number" || type === "boolean") return value;
|
|
3492
|
+
if (type === "string" || type === "number" || type === "boolean" || !clone) return value;
|
|
3366
3493
|
try {
|
|
3367
3494
|
return structuredClone(value);
|
|
3368
3495
|
} catch (error) {
|
|
@@ -3516,6 +3643,16 @@ var BaseCacheDriver = class {
|
|
|
3516
3643
|
|
|
3517
3644
|
//#endregion
|
|
3518
3645
|
//#region ../../packages/cache/src/drivers/file-cache-driver.ts
|
|
3646
|
+
/**
|
|
3647
|
+
* How many times an exclusive write (or a compare-and-delete) retries while
|
|
3648
|
+
* another caller is removing the same entry.
|
|
3649
|
+
*/
|
|
3650
|
+
const EXCLUSIVE_ATTEMPTS = 50;
|
|
3651
|
+
/**
|
|
3652
|
+
* A removal guard older than this belongs to a process that died while
|
|
3653
|
+
* holding it (the guarded step takes a few milliseconds).
|
|
3654
|
+
*/
|
|
3655
|
+
const STALE_GUARD_MS = 1e4;
|
|
3519
3656
|
var FileCacheDriver = class extends BaseCacheDriver {
|
|
3520
3657
|
constructor(..._args) {
|
|
3521
3658
|
super(..._args);
|
|
@@ -3662,8 +3799,9 @@ var FileCacheDriver = class extends BaseCacheDriver {
|
|
|
3662
3799
|
/**
|
|
3663
3800
|
* Create `filePath` only if it does not exist. Writes a temp file, then
|
|
3664
3801
|
* hard-links it to the target (EEXIST = already present). An existing but
|
|
3665
|
-
* expired entry is removed
|
|
3666
|
-
* link
|
|
3802
|
+
* expired entry is removed under the key's removal guard (see
|
|
3803
|
+
* {@link withRemovalGuard}), so of several contenders only one can ever
|
|
3804
|
+
* win the retried link.
|
|
3667
3805
|
*
|
|
3668
3806
|
* Returns `null` when written, or `{ existing }` on conflict.
|
|
3669
3807
|
*/
|
|
@@ -3671,26 +3809,21 @@ var FileCacheDriver = class extends BaseCacheDriver {
|
|
|
3671
3809
|
const tempPath = `${filePath}.${(0, node_crypto.randomBytes)(6).toString("hex")}.tmp`;
|
|
3672
3810
|
try {
|
|
3673
3811
|
await node_fs.default.promises.writeFile(tempPath, JSON.stringify(data, null, 2));
|
|
3674
|
-
for (let attempt = 0; attempt <
|
|
3812
|
+
for (let attempt = 0; attempt < EXCLUSIVE_ATTEMPTS; attempt++) {
|
|
3675
3813
|
try {
|
|
3676
3814
|
await node_fs.default.promises.link(tempPath, filePath);
|
|
3677
3815
|
return null;
|
|
3678
3816
|
} catch (error) {
|
|
3679
3817
|
if (error?.code !== "EEXIST") throw error;
|
|
3680
3818
|
}
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
if (attempt === 0 && expired) {
|
|
3690
|
-
await node_fs.default.promises.rm(filePath, { force: true });
|
|
3691
|
-
continue;
|
|
3692
|
-
}
|
|
3693
|
-
return { existing: null };
|
|
3819
|
+
const current = await this.readEntryFile(filePath);
|
|
3820
|
+
if (!current) continue;
|
|
3821
|
+
if (!current.entry) return { existing: null };
|
|
3822
|
+
if (!isExpiredEntry(current.entry)) return { existing: current.entry.data ?? null };
|
|
3823
|
+
if (!await this.withRemovalGuard(filePath, async () => {
|
|
3824
|
+
const latest = await this.readEntryFile(filePath);
|
|
3825
|
+
if (latest?.entry && latest.inode === current.inode && isExpiredEntry(latest.entry)) await node_fs.default.promises.unlink(filePath).catch(ignoreMissing);
|
|
3826
|
+
})) await delay(1);
|
|
3694
3827
|
}
|
|
3695
3828
|
return { existing: null };
|
|
3696
3829
|
} finally {
|
|
@@ -3698,6 +3831,106 @@ var FileCacheDriver = class extends BaseCacheDriver {
|
|
|
3698
3831
|
}
|
|
3699
3832
|
}
|
|
3700
3833
|
/**
|
|
3834
|
+
* Run `task` while holding the key's removal guard: a `<file>.guard` file
|
|
3835
|
+
* created exclusively. Entry files are only ever created by an exclusive
|
|
3836
|
+
* link onto a missing path, so while every removal of a live or expired
|
|
3837
|
+
* entry by `writeExclusive` / `deleteIfEquals` happens under this guard, no
|
|
3838
|
+
* removal can delete an entry another writer has just created.
|
|
3839
|
+
*
|
|
3840
|
+
* Returns `false` (without running `task`) when another caller holds the
|
|
3841
|
+
* guard. A guard left behind by a crashed process is cleared once it is
|
|
3842
|
+
* older than {@link STALE_GUARD_MS}.
|
|
3843
|
+
*/
|
|
3844
|
+
async withRemovalGuard(filePath, task) {
|
|
3845
|
+
const guardPath = `${filePath}.guard`;
|
|
3846
|
+
let handle;
|
|
3847
|
+
try {
|
|
3848
|
+
handle = await node_fs.default.promises.open(guardPath, "wx");
|
|
3849
|
+
} catch (error) {
|
|
3850
|
+
if (error?.code === "ENOENT") return true;
|
|
3851
|
+
if (error?.code !== "EEXIST") throw error;
|
|
3852
|
+
await this.clearStaleGuard(guardPath);
|
|
3853
|
+
return false;
|
|
3854
|
+
}
|
|
3855
|
+
try {
|
|
3856
|
+
await handle.close();
|
|
3857
|
+
await task();
|
|
3858
|
+
return true;
|
|
3859
|
+
} finally {
|
|
3860
|
+
await node_fs.default.promises.unlink(guardPath).catch(() => void 0);
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
/**
|
|
3864
|
+
* Remove a removal guard whose holder died (older than {@link STALE_GUARD_MS}).
|
|
3865
|
+
*/
|
|
3866
|
+
async clearStaleGuard(guardPath) {
|
|
3867
|
+
try {
|
|
3868
|
+
const { mtimeMs } = await node_fs.default.promises.stat(guardPath);
|
|
3869
|
+
if (Date.now() - mtimeMs > STALE_GUARD_MS) await node_fs.default.promises.unlink(guardPath).catch(ignoreMissing);
|
|
3870
|
+
} catch (error) {
|
|
3871
|
+
if (error?.code !== "ENOENT") throw error;
|
|
3872
|
+
}
|
|
3873
|
+
}
|
|
3874
|
+
/**
|
|
3875
|
+
* Read an entry file together with its inode, so a later step can tell
|
|
3876
|
+
* whether the file at the same path is still the one that was read.
|
|
3877
|
+
* `undefined` when the file does not exist; `entry: undefined` when it
|
|
3878
|
+
* cannot be parsed.
|
|
3879
|
+
*/
|
|
3880
|
+
async readEntryFile(filePath) {
|
|
3881
|
+
let handle;
|
|
3882
|
+
try {
|
|
3883
|
+
handle = await node_fs.default.promises.open(filePath, "r");
|
|
3884
|
+
} catch (error) {
|
|
3885
|
+
if (error?.code === "ENOENT") return void 0;
|
|
3886
|
+
throw error;
|
|
3887
|
+
}
|
|
3888
|
+
try {
|
|
3889
|
+
const { ino } = await handle.stat();
|
|
3890
|
+
const text = await handle.readFile("utf-8");
|
|
3891
|
+
try {
|
|
3892
|
+
const entry = JSON.parse(text);
|
|
3893
|
+
return {
|
|
3894
|
+
entry: entry && typeof entry === "object" ? entry : void 0,
|
|
3895
|
+
inode: ino
|
|
3896
|
+
};
|
|
3897
|
+
} catch {
|
|
3898
|
+
return {
|
|
3899
|
+
entry: void 0,
|
|
3900
|
+
inode: ino
|
|
3901
|
+
};
|
|
3902
|
+
}
|
|
3903
|
+
} finally {
|
|
3904
|
+
await handle.close();
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
/**
|
|
3908
|
+
* {@inheritdoc}
|
|
3909
|
+
*
|
|
3910
|
+
* Compare-and-delete under the key's removal guard, so a lock released just
|
|
3911
|
+
* as it expired never deletes a successor's lock.
|
|
3912
|
+
*/
|
|
3913
|
+
async deleteIfEquals(key, expected) {
|
|
3914
|
+
const parsedKey = this.parseKey(key);
|
|
3915
|
+
const fileDirectory = this.keyDirectory(parsedKey);
|
|
3916
|
+
const filePath = path.default.resolve(fileDirectory, this.fileName);
|
|
3917
|
+
let deleted = false;
|
|
3918
|
+
for (let attempt = 0; attempt < EXCLUSIVE_ATTEMPTS; attempt++) {
|
|
3919
|
+
if (await this.withRemovalGuard(filePath, async () => {
|
|
3920
|
+
const current = await this.readEntryFile(filePath);
|
|
3921
|
+
if (!current?.entry || isExpiredEntry(current.entry) || current.entry.data !== expected) return;
|
|
3922
|
+
await node_fs.default.promises.unlink(filePath).catch(ignoreMissing);
|
|
3923
|
+
deleted = true;
|
|
3924
|
+
})) break;
|
|
3925
|
+
await delay(1);
|
|
3926
|
+
}
|
|
3927
|
+
if (!deleted) return false;
|
|
3928
|
+
await node_fs.default.promises.rmdir(fileDirectory).catch(() => void 0);
|
|
3929
|
+
this.log("removed", parsedKey);
|
|
3930
|
+
await this.emit("removed", { key: parsedKey });
|
|
3931
|
+
return true;
|
|
3932
|
+
}
|
|
3933
|
+
/**
|
|
3701
3934
|
* {@inheritdoc}
|
|
3702
3935
|
*
|
|
3703
3936
|
* File driver does not yet ship with a file-lock primitive, so concurrent
|
|
@@ -3749,7 +3982,7 @@ var FileCacheDriver = class extends BaseCacheDriver {
|
|
|
3749
3982
|
await this.emit("miss", { key: parsedKey });
|
|
3750
3983
|
return null;
|
|
3751
3984
|
}
|
|
3752
|
-
const result = await this.parseCachedData(parsedKey, value);
|
|
3985
|
+
const result = await this.parseCachedData(parsedKey, value, false);
|
|
3753
3986
|
if (result === null) await this.emit("miss", { key: parsedKey });
|
|
3754
3987
|
else await this.emit("hit", {
|
|
3755
3988
|
key: parsedKey,
|
|
@@ -3761,7 +3994,12 @@ var FileCacheDriver = class extends BaseCacheDriver {
|
|
|
3761
3994
|
* {@inheritdoc}
|
|
3762
3995
|
*/
|
|
3763
3996
|
async remove(key) {
|
|
3764
|
-
|
|
3997
|
+
await this.removeParsed(this.parseKey(key));
|
|
3998
|
+
}
|
|
3999
|
+
/**
|
|
4000
|
+
* {@inheritdoc}
|
|
4001
|
+
*/
|
|
4002
|
+
async removeParsed(parsedKey) {
|
|
3765
4003
|
this.log("removing", parsedKey);
|
|
3766
4004
|
const fileDirectory = this.keyDirectory(parsedKey);
|
|
3767
4005
|
try {
|
|
@@ -3790,6 +4028,34 @@ var FileCacheDriver = class extends BaseCacheDriver {
|
|
|
3790
4028
|
await this.emit("connected");
|
|
3791
4029
|
}
|
|
3792
4030
|
};
|
|
4031
|
+
/**
|
|
4032
|
+
* Whether a stored entry is past its deadline. `Infinity` (no expiry) is
|
|
4033
|
+
* written to JSON as `null`, so only a real number can be expired.
|
|
4034
|
+
*/
|
|
4035
|
+
function isExpiredEntry(entry) {
|
|
4036
|
+
return typeof entry.expiresAt === "number" && entry.expiresAt <= Date.now();
|
|
4037
|
+
}
|
|
4038
|
+
function ignoreMissing(error) {
|
|
4039
|
+
if (error?.code !== "ENOENT") throw error;
|
|
4040
|
+
}
|
|
4041
|
+
function delay(ms) {
|
|
4042
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
4043
|
+
}
|
|
4044
|
+
|
|
4045
|
+
//#endregion
|
|
4046
|
+
//#region ../../packages/cache/src/drivers/clone-value.ts
|
|
4047
|
+
/**
|
|
4048
|
+
* Clone non-primitive values so cached state can't be mutated through
|
|
4049
|
+
* references held by callers. Primitives are immutable and returned as-is.
|
|
4050
|
+
*
|
|
4051
|
+
* @internal Shared by the in-process drivers; not part of the public API.
|
|
4052
|
+
*/
|
|
4053
|
+
function cloneValue$1(value) {
|
|
4054
|
+
if (value === null || value === void 0) return value;
|
|
4055
|
+
const type = typeof value;
|
|
4056
|
+
if (type === "string" || type === "number" || type === "boolean") return value;
|
|
4057
|
+
return structuredClone(value);
|
|
4058
|
+
}
|
|
3793
4059
|
|
|
3794
4060
|
//#endregion
|
|
3795
4061
|
//#region ../../packages/cache/src/drivers/in-memory-tag-index.ts
|
|
@@ -3827,6 +4093,23 @@ var InMemoryTagIndex = class {
|
|
|
3827
4093
|
return [...this.sets.get(tagKey) ?? []];
|
|
3828
4094
|
}
|
|
3829
4095
|
/**
|
|
4096
|
+
* Up to `count` members of a tag set from a random starting point, without
|
|
4097
|
+
* copying the whole set.
|
|
4098
|
+
*/
|
|
4099
|
+
sample(tagKey, count) {
|
|
4100
|
+
const set = this.sets.get(tagKey);
|
|
4101
|
+
if (!set || count <= 0) return [];
|
|
4102
|
+
const skip = set.size > count ? Math.floor(Math.random() * (set.size - count + 1)) : 0;
|
|
4103
|
+
const picked = [];
|
|
4104
|
+
let index = 0;
|
|
4105
|
+
for (const member of set) {
|
|
4106
|
+
if (index++ < skip) continue;
|
|
4107
|
+
picked.push(member);
|
|
4108
|
+
if (picked.length >= count) break;
|
|
4109
|
+
}
|
|
4110
|
+
return picked;
|
|
4111
|
+
}
|
|
4112
|
+
/**
|
|
3830
4113
|
* Remove members from a tag set; an emptied set is dropped.
|
|
3831
4114
|
*/
|
|
3832
4115
|
remove(tagKey, members) {
|
|
@@ -3979,7 +4262,7 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
|
|
|
3979
4262
|
const exists = Boolean(existingNode);
|
|
3980
4263
|
if (onConflict === "create" && exists) return {
|
|
3981
4264
|
wasSet: false,
|
|
3982
|
-
existing: existingNode.value
|
|
4265
|
+
existing: cloneValue$1(existingNode.value)
|
|
3983
4266
|
};
|
|
3984
4267
|
if (onConflict === "update" && !exists) return {
|
|
3985
4268
|
wasSet: false,
|
|
@@ -4055,12 +4338,22 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
|
|
|
4055
4338
|
const node = this.cache.get(parsedKey);
|
|
4056
4339
|
if (!node || node.isExpired) return null;
|
|
4057
4340
|
return {
|
|
4058
|
-
data: node.value,
|
|
4341
|
+
data: cloneValue$1(node.value),
|
|
4059
4342
|
expiresAt: node.expiresAt,
|
|
4060
4343
|
staleAt: node.staleAt
|
|
4061
4344
|
};
|
|
4062
4345
|
}
|
|
4063
4346
|
/**
|
|
4347
|
+
* {@inheritdoc}
|
|
4348
|
+
*
|
|
4349
|
+
* This driver stores the written value by reference, so the callers of a
|
|
4350
|
+
* cold-miss fetch get a copy rather than the stored object itself.
|
|
4351
|
+
*/
|
|
4352
|
+
async swrFetchAndStore(key, options, callback, freshSeconds, staleSeconds) {
|
|
4353
|
+
const result = await super.swrFetchAndStore(key, options, callback, freshSeconds, staleSeconds);
|
|
4354
|
+
return cloneValue$1(result);
|
|
4355
|
+
}
|
|
4356
|
+
/**
|
|
4064
4357
|
* Live node for `parsedKey`, or `undefined` when missing / expired (an
|
|
4065
4358
|
* expired node is unlinked). Synchronous.
|
|
4066
4359
|
*/
|
|
@@ -4227,6 +4520,20 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
|
|
|
4227
4520
|
}
|
|
4228
4521
|
/**
|
|
4229
4522
|
* {@inheritdoc}
|
|
4523
|
+
*/
|
|
4524
|
+
async tagSample(tagKey, count) {
|
|
4525
|
+
return this.tagIndex.sample(this.parseKey(tagKey), count);
|
|
4526
|
+
}
|
|
4527
|
+
/**
|
|
4528
|
+
* {@inheritdoc}
|
|
4529
|
+
*
|
|
4530
|
+
* A synchronous lookup: no copy, no events, no recency or TTL change.
|
|
4531
|
+
*/
|
|
4532
|
+
async exists(key) {
|
|
4533
|
+
return this.liveNode(this.parseKey(key)) !== void 0;
|
|
4534
|
+
}
|
|
4535
|
+
/**
|
|
4536
|
+
* {@inheritdoc}
|
|
4230
4537
|
*
|
|
4231
4538
|
* When a `globalPrefix` is configured, `flush` scopes itself to that prefix
|
|
4232
4539
|
* so multi-tenant caches don't accidentally wipe sibling tenants. Without
|
|
@@ -4307,6 +4614,12 @@ function cloneValue(value) {
|
|
|
4307
4614
|
if (type === "string" || type === "number" || type === "boolean") return value;
|
|
4308
4615
|
return structuredClone(value);
|
|
4309
4616
|
}
|
|
4617
|
+
/**
|
|
4618
|
+
* Entries a memory driver keeps when `maxSize` is not configured. Past it the
|
|
4619
|
+
* least recently used entries are evicted, so request-derived keys cannot
|
|
4620
|
+
* grow the heap without bound.
|
|
4621
|
+
*/
|
|
4622
|
+
const DEFAULT_MAX_SIZE = 1e4;
|
|
4310
4623
|
var MemoryCacheDriver = class extends BaseCacheDriver {
|
|
4311
4624
|
/**
|
|
4312
4625
|
* Read-only object view of the stored entries, keyed by parsed key.
|
|
@@ -4376,10 +4689,19 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
|
|
|
4376
4689
|
return entry;
|
|
4377
4690
|
}
|
|
4378
4691
|
/**
|
|
4379
|
-
*
|
|
4692
|
+
* The entry limit: `maxSize`, or 10,000 when it is not set. `Infinity`
|
|
4693
|
+
* (or `0`) means no limit.
|
|
4694
|
+
*/
|
|
4695
|
+
get maxSize() {
|
|
4696
|
+
const configured = this.options?.maxSize;
|
|
4697
|
+
if (configured === void 0) return DEFAULT_MAX_SIZE;
|
|
4698
|
+
return configured > 0 ? configured : Infinity;
|
|
4699
|
+
}
|
|
4700
|
+
/**
|
|
4701
|
+
* Mark an entry as most recently used (not tracked without a limit).
|
|
4380
4702
|
*/
|
|
4381
4703
|
touch(parsedKey, entry) {
|
|
4382
|
-
if (
|
|
4704
|
+
if (this.maxSize === Infinity) return;
|
|
4383
4705
|
this.entries.delete(parsedKey);
|
|
4384
4706
|
this.entries.set(parsedKey, entry);
|
|
4385
4707
|
}
|
|
@@ -4623,6 +4945,20 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
|
|
|
4623
4945
|
/**
|
|
4624
4946
|
* {@inheritdoc}
|
|
4625
4947
|
*/
|
|
4948
|
+
async tagSample(tagKey, count) {
|
|
4949
|
+
return this.tagIndex.sample(this.parseKey(tagKey), count);
|
|
4950
|
+
}
|
|
4951
|
+
/**
|
|
4952
|
+
* {@inheritdoc}
|
|
4953
|
+
*
|
|
4954
|
+
* A synchronous lookup: no copy, no events, no recency or TTL change.
|
|
4955
|
+
*/
|
|
4956
|
+
async exists(key) {
|
|
4957
|
+
return this.readLive(this.parseKey(key)) !== void 0;
|
|
4958
|
+
}
|
|
4959
|
+
/**
|
|
4960
|
+
* {@inheritdoc}
|
|
4961
|
+
*/
|
|
4626
4962
|
async flush() {
|
|
4627
4963
|
this.log("flushing");
|
|
4628
4964
|
if (this.options.globalPrefix) await this.removeNamespace("");
|
|
@@ -4641,9 +4977,9 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
|
|
|
4641
4977
|
* within `maxSize`. Never evicts `protectedKey` (the key just written).
|
|
4642
4978
|
*/
|
|
4643
4979
|
enforceMaxSize(protectedKey) {
|
|
4644
|
-
const maxSize = this.
|
|
4645
|
-
if (
|
|
4646
|
-
for (const lruKey of
|
|
4980
|
+
const maxSize = this.maxSize;
|
|
4981
|
+
if (this.entries.size <= maxSize) return;
|
|
4982
|
+
for (const lruKey of this.entries.keys()) {
|
|
4647
4983
|
if (this.entries.size <= maxSize) break;
|
|
4648
4984
|
if (lruKey === protectedKey) continue;
|
|
4649
4985
|
this.log("removing", lruKey);
|
|
@@ -5096,9 +5432,11 @@ var NullCacheDriver = class extends BaseCacheDriver {
|
|
|
5096
5432
|
* {@inheritdoc}
|
|
5097
5433
|
*/
|
|
5098
5434
|
async removeNamespace(namespace) {
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
|
|
5435
|
+
if (this.shouldLog) {
|
|
5436
|
+
const loggableNamespace = (0, _warlock_js_logger.maskEmailsInText)(namespace);
|
|
5437
|
+
_warlock_js_logger.log.info("cache", "clearing namespace", loggableNamespace);
|
|
5438
|
+
_warlock_js_logger.log.success("cache", "namespace cleared", loggableNamespace);
|
|
5439
|
+
}
|
|
5102
5440
|
return this;
|
|
5103
5441
|
}
|
|
5104
5442
|
/**
|
|
@@ -5111,16 +5449,20 @@ var NullCacheDriver = class extends BaseCacheDriver {
|
|
|
5111
5449
|
* {@inheritdoc}
|
|
5112
5450
|
*/
|
|
5113
5451
|
async set(key, _value, _ttlOrOptions) {
|
|
5114
|
-
|
|
5115
|
-
|
|
5452
|
+
if (this.shouldLog) {
|
|
5453
|
+
_warlock_js_logger.log.info("cache", "setting key", this.loggableKey(key));
|
|
5454
|
+
_warlock_js_logger.log.success("cache", "key set", this.loggableKey(key));
|
|
5455
|
+
}
|
|
5116
5456
|
return this;
|
|
5117
5457
|
}
|
|
5118
5458
|
/**
|
|
5119
5459
|
* {@inheritdoc}
|
|
5120
5460
|
*/
|
|
5121
5461
|
async get(key) {
|
|
5122
|
-
|
|
5123
|
-
|
|
5462
|
+
if (this.shouldLog) {
|
|
5463
|
+
_warlock_js_logger.log.info("cache", "fetching", this.loggableKey(key));
|
|
5464
|
+
_warlock_js_logger.log.success("cache", "fetched", this.loggableKey(key));
|
|
5465
|
+
}
|
|
5124
5466
|
return null;
|
|
5125
5467
|
}
|
|
5126
5468
|
/**
|
|
@@ -5135,15 +5477,19 @@ var NullCacheDriver = class extends BaseCacheDriver {
|
|
|
5135
5477
|
* {@inheritdoc}
|
|
5136
5478
|
*/
|
|
5137
5479
|
async remove(key) {
|
|
5138
|
-
|
|
5139
|
-
|
|
5480
|
+
if (this.shouldLog) {
|
|
5481
|
+
_warlock_js_logger.log.info("cache", "removing", this.loggableKey(key));
|
|
5482
|
+
_warlock_js_logger.log.success("cache", "removed", this.loggableKey(key));
|
|
5483
|
+
}
|
|
5140
5484
|
}
|
|
5141
5485
|
/**
|
|
5142
5486
|
* {@inheritdoc}
|
|
5143
5487
|
*/
|
|
5144
5488
|
async flush() {
|
|
5145
|
-
|
|
5146
|
-
|
|
5489
|
+
if (this.shouldLog) {
|
|
5490
|
+
_warlock_js_logger.log.info("cache", "flushing", "all");
|
|
5491
|
+
_warlock_js_logger.log.success("cache", "flushed", "all");
|
|
5492
|
+
}
|
|
5147
5493
|
}
|
|
5148
5494
|
/**
|
|
5149
5495
|
* {@inheritdoc}
|
|
@@ -5158,7 +5504,7 @@ var NullCacheDriver = class extends BaseCacheDriver {
|
|
|
5158
5504
|
* {@inheritdoc}
|
|
5159
5505
|
*/
|
|
5160
5506
|
async connect() {
|
|
5161
|
-
_warlock_js_logger.log.success("cache", "connected", "Connected to null cache driver");
|
|
5507
|
+
if (this.shouldLog) _warlock_js_logger.log.success("cache", "connected", "Connected to null cache driver");
|
|
5162
5508
|
}
|
|
5163
5509
|
};
|
|
5164
5510
|
|
|
@@ -5166,6 +5512,8 @@ var NullCacheDriver = class extends BaseCacheDriver {
|
|
|
5166
5512
|
//#region ../../packages/cache/src/drivers/pg-cache-driver.ts
|
|
5167
5513
|
/** Compare-and-set attempts before `update()` gives up under contention. */
|
|
5168
5514
|
const PG_UPDATE_MAX_ATTEMPTS = 10;
|
|
5515
|
+
/** Keys deleted per statement by `removeMany()`. */
|
|
5516
|
+
const PG_REMOVE_BATCH_SIZE = 500;
|
|
5169
5517
|
/**
|
|
5170
5518
|
* Allowed characters in a Postgres identifier (table name). We accept the
|
|
5171
5519
|
* conservative ASCII subset and reject anything else — interpolating an
|
|
@@ -5529,32 +5877,11 @@ var PgCacheDriver = class extends BaseCacheDriver {
|
|
|
5529
5877
|
if (typeof value === "string") try {
|
|
5530
5878
|
value = JSON.parse(value);
|
|
5531
5879
|
} catch {}
|
|
5532
|
-
|
|
5533
|
-
|
|
5534
|
-
|
|
5535
|
-
|
|
5536
|
-
|
|
5537
|
-
return value;
|
|
5538
|
-
}
|
|
5539
|
-
const type = typeof value;
|
|
5540
|
-
if (type === "string" || type === "number" || type === "boolean") {
|
|
5541
|
-
await this.emit("hit", {
|
|
5542
|
-
key: parsedKey,
|
|
5543
|
-
value
|
|
5544
|
-
});
|
|
5545
|
-
return value;
|
|
5546
|
-
}
|
|
5547
|
-
try {
|
|
5548
|
-
const cloned = structuredClone(value);
|
|
5549
|
-
await this.emit("hit", {
|
|
5550
|
-
key: parsedKey,
|
|
5551
|
-
value: cloned
|
|
5552
|
-
});
|
|
5553
|
-
return cloned;
|
|
5554
|
-
} catch (error) {
|
|
5555
|
-
this.logError(`Failed to clone cached value for ${parsedKey}`, error);
|
|
5556
|
-
throw error;
|
|
5557
|
-
}
|
|
5880
|
+
await this.emit("hit", {
|
|
5881
|
+
key: parsedKey,
|
|
5882
|
+
value
|
|
5883
|
+
});
|
|
5884
|
+
return value;
|
|
5558
5885
|
}
|
|
5559
5886
|
/**
|
|
5560
5887
|
* Read the raw {@link CacheData} wrapper, including `staleAt` metadata.
|
|
@@ -5734,6 +6061,51 @@ var PgCacheDriver = class extends BaseCacheDriver {
|
|
|
5734
6061
|
}
|
|
5735
6062
|
/**
|
|
5736
6063
|
* {@inheritdoc}
|
|
6064
|
+
*
|
|
6065
|
+
* `SELECT 1`: no value transfer, no `hit`/`miss` events.
|
|
6066
|
+
*/
|
|
6067
|
+
async exists(key) {
|
|
6068
|
+
const { rows } = await this.pgClient.query(`/* cache:exists */ SELECT 1 FROM ${this.table}
|
|
6069
|
+
WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`, [this.parseKey(key)]);
|
|
6070
|
+
return rows.length > 0;
|
|
6071
|
+
}
|
|
6072
|
+
/**
|
|
6073
|
+
* {@inheritdoc}
|
|
6074
|
+
*
|
|
6075
|
+
* Picks the members in the database and returns only those, however large
|
|
6076
|
+
* the index is.
|
|
6077
|
+
*/
|
|
6078
|
+
async tagSample(tagKey, count) {
|
|
6079
|
+
if (count <= 0) return [];
|
|
6080
|
+
const t = this.table;
|
|
6081
|
+
const { rows } = await this.pgClient.query(`/* cache:tag-sample */ SELECT x.member FROM ${t},
|
|
6082
|
+
jsonb_array_elements_text(
|
|
6083
|
+
CASE WHEN jsonb_typeof(${t}.value) = 'array' THEN ${t}.value ELSE '[]'::jsonb END
|
|
6084
|
+
) AS x(member)
|
|
6085
|
+
WHERE ${t}.key = $1 AND (${t}.expires_at IS NULL OR ${t}.expires_at > now())
|
|
6086
|
+
ORDER BY random()
|
|
6087
|
+
LIMIT $2`, [this.parseKey(tagKey), count]);
|
|
6088
|
+
return rows.map((row) => row.member);
|
|
6089
|
+
}
|
|
6090
|
+
/**
|
|
6091
|
+
* {@inheritdoc}
|
|
6092
|
+
*
|
|
6093
|
+
* One `DELETE … WHERE key = ANY($1)` per chunk instead of one per key.
|
|
6094
|
+
*/
|
|
6095
|
+
async removeMany(keys) {
|
|
6096
|
+
const parsedKeys = keys.map((key) => this.parseKey(key));
|
|
6097
|
+
for (let start = 0; start < parsedKeys.length; start += PG_REMOVE_BATCH_SIZE) {
|
|
6098
|
+
const chunk = parsedKeys.slice(start, start + PG_REMOVE_BATCH_SIZE);
|
|
6099
|
+
for (const parsedKey of chunk) this.log("removing", parsedKey);
|
|
6100
|
+
await this.pgClient.query(`/* cache:remove-many */ DELETE FROM ${this.table} WHERE key = ANY($1::text[])`, [chunk]);
|
|
6101
|
+
for (const parsedKey of chunk) {
|
|
6102
|
+
this.log("removed", parsedKey);
|
|
6103
|
+
await this.emit("removed", { key: parsedKey });
|
|
6104
|
+
}
|
|
6105
|
+
}
|
|
6106
|
+
}
|
|
6107
|
+
/**
|
|
6108
|
+
* {@inheritdoc}
|
|
5737
6109
|
*/
|
|
5738
6110
|
async remove(key) {
|
|
5739
6111
|
const parsedKey = this.parseKey(key);
|
|
@@ -6018,6 +6390,50 @@ var RedisCacheDriver = class extends BaseCacheDriver {
|
|
|
6018
6390
|
await this.client?.del(this.parseKey(tagKey));
|
|
6019
6391
|
}
|
|
6020
6392
|
/**
|
|
6393
|
+
* {@inheritdoc}
|
|
6394
|
+
*
|
|
6395
|
+
* `SRANDMEMBER key count`: transfers only the sampled members, however
|
|
6396
|
+
* large the index is.
|
|
6397
|
+
*/
|
|
6398
|
+
async tagSample(tagKey, count) {
|
|
6399
|
+
if (count <= 0) return [];
|
|
6400
|
+
const parsedKey = this.parseKey(tagKey);
|
|
6401
|
+
return this.withTagSet(parsedKey, async (client) => {
|
|
6402
|
+
if (typeof client.sRandMemberCount !== "function") return sampleMembers(await client.sMembers(parsedKey) ?? [], count);
|
|
6403
|
+
return await client.sRandMemberCount(parsedKey, count) ?? [];
|
|
6404
|
+
});
|
|
6405
|
+
}
|
|
6406
|
+
/**
|
|
6407
|
+
* {@inheritdoc}
|
|
6408
|
+
*
|
|
6409
|
+
* `EXISTS`: no value transfer, no `hit`/`miss` events.
|
|
6410
|
+
*/
|
|
6411
|
+
async exists(key) {
|
|
6412
|
+
const parsedKey = this.parseKey(key);
|
|
6413
|
+
const client = this.client;
|
|
6414
|
+
if (typeof client?.exists !== "function") return await this.client?.get(parsedKey) != null;
|
|
6415
|
+
return Number(await client.exists(parsedKey)) > 0;
|
|
6416
|
+
}
|
|
6417
|
+
/**
|
|
6418
|
+
* {@inheritdoc}
|
|
6419
|
+
*
|
|
6420
|
+
* Issues every key's `DEL` (and its SWR sidecar's) at once, in chunks, so
|
|
6421
|
+
* the client sends them pipelined instead of one round trip per key. Single
|
|
6422
|
+
* key commands keep it cluster-slot safe.
|
|
6423
|
+
*/
|
|
6424
|
+
async removeMany(keys) {
|
|
6425
|
+
const parsedKeys = keys.map((key) => this.parseKey(key));
|
|
6426
|
+
for (let start = 0; start < parsedKeys.length; start += REMOVE_BATCH_SIZE) {
|
|
6427
|
+
const chunk = parsedKeys.slice(start, start + REMOVE_BATCH_SIZE);
|
|
6428
|
+
for (const parsedKey of chunk) this.log("removing", parsedKey);
|
|
6429
|
+
await Promise.all(chunk.flatMap((parsedKey) => [this.client?.del(parsedKey), this.client?.del(this.swrMetaKey(parsedKey))]));
|
|
6430
|
+
for (const parsedKey of chunk) {
|
|
6431
|
+
this.log("removed", parsedKey);
|
|
6432
|
+
await this.emit("removed", { key: parsedKey });
|
|
6433
|
+
}
|
|
6434
|
+
}
|
|
6435
|
+
}
|
|
6436
|
+
/**
|
|
6021
6437
|
* Run a SET command against a tag key, upgrading a pre-5.20 index first.
|
|
6022
6438
|
*
|
|
6023
6439
|
* Earlier versions stored the index as a JSON-array STRING under the same
|
|
@@ -6055,6 +6471,7 @@ var RedisCacheDriver = class extends BaseCacheDriver {
|
|
|
6055
6471
|
const serialized = JSON.stringify(value);
|
|
6056
6472
|
const hasExpiry = Boolean(ttl) && ttl !== Infinity;
|
|
6057
6473
|
let reply;
|
|
6474
|
+
let sidecarWrite;
|
|
6058
6475
|
if (onConflict === "create") {
|
|
6059
6476
|
const options = { NX: true };
|
|
6060
6477
|
if (hasExpiry) options.EX = ttl;
|
|
@@ -6063,19 +6480,18 @@ var RedisCacheDriver = class extends BaseCacheDriver {
|
|
|
6063
6480
|
const options = { XX: true };
|
|
6064
6481
|
if (hasExpiry) options.EX = ttl;
|
|
6065
6482
|
reply = await this.client?.set(parsedKey, serialized, options);
|
|
6066
|
-
} else
|
|
6067
|
-
|
|
6483
|
+
} else {
|
|
6484
|
+
const write = hasExpiry ? this.client?.set(parsedKey, serialized, { EX: ttl }) : this.client?.set(parsedKey, serialized);
|
|
6485
|
+
sidecarWrite = this.writeSwrSidecar(parsedKey, staleAt, hasExpiry ? ttl : void 0);
|
|
6486
|
+
const [written] = await Promise.all([write, sidecarWrite]);
|
|
6487
|
+
reply = written;
|
|
6488
|
+
}
|
|
6068
6489
|
if ((onConflict === "create" || onConflict === "update") && !(reply === "OK")) return {
|
|
6069
6490
|
wasSet: false,
|
|
6070
6491
|
existing: onConflict === "create" ? await this.get(key) : null
|
|
6071
6492
|
};
|
|
6072
6493
|
if (tags && tags.length > 0) await this.applyTags(key, tags);
|
|
6073
|
-
if (
|
|
6074
|
-
else {
|
|
6075
|
-
const sidecarOptions = {};
|
|
6076
|
-
if (hasExpiry) sidecarOptions.EX = ttl;
|
|
6077
|
-
await this.client?.set(this.swrMetaKey(parsedKey), String(staleAt), sidecarOptions);
|
|
6078
|
-
}
|
|
6494
|
+
if (!sidecarWrite) await this.writeSwrSidecar(parsedKey, staleAt, hasExpiry ? ttl : void 0);
|
|
6079
6495
|
this.log("cached", parsedKey);
|
|
6080
6496
|
await this.emit("set", {
|
|
6081
6497
|
key: parsedKey,
|
|
@@ -6106,6 +6522,17 @@ var RedisCacheDriver = class extends BaseCacheDriver {
|
|
|
6106
6522
|
return true;
|
|
6107
6523
|
}
|
|
6108
6524
|
/**
|
|
6525
|
+
* Write (or clear) the SWR freshness sidecar of a key. A plain write
|
|
6526
|
+
* (`staleAt` undefined) drops any marker left by an earlier SWR write,
|
|
6527
|
+
* otherwise the old `staleAt` would apply to the new value; an SWR write
|
|
6528
|
+
* stores it next to the value — keeping the main value JSON compatible with
|
|
6529
|
+
* entries written before SWR landed.
|
|
6530
|
+
*/
|
|
6531
|
+
async writeSwrSidecar(parsedKey, staleAt, ttl) {
|
|
6532
|
+
if (staleAt === void 0) return this.client?.del(this.swrMetaKey(parsedKey));
|
|
6533
|
+
return this.client?.set(this.swrMetaKey(parsedKey), String(staleAt), ttl === void 0 ? {} : { EX: ttl });
|
|
6534
|
+
}
|
|
6535
|
+
/**
|
|
6109
6536
|
* Build the sidecar key Redis uses to track SWR freshness without
|
|
6110
6537
|
* wrapping the main value JSON.
|
|
6111
6538
|
*/
|
|
@@ -6157,32 +6584,11 @@ var RedisCacheDriver = class extends BaseCacheDriver {
|
|
|
6157
6584
|
}
|
|
6158
6585
|
this.log("fetched", key);
|
|
6159
6586
|
const parsedValue = JSON.parse(value);
|
|
6160
|
-
|
|
6161
|
-
|
|
6162
|
-
|
|
6163
|
-
|
|
6164
|
-
|
|
6165
|
-
return parsedValue;
|
|
6166
|
-
}
|
|
6167
|
-
const type = typeof parsedValue;
|
|
6168
|
-
if (type === "string" || type === "number" || type === "boolean") {
|
|
6169
|
-
await this.emit("hit", {
|
|
6170
|
-
key,
|
|
6171
|
-
value: parsedValue
|
|
6172
|
-
});
|
|
6173
|
-
return parsedValue;
|
|
6174
|
-
}
|
|
6175
|
-
try {
|
|
6176
|
-
const clonedValue = structuredClone(parsedValue);
|
|
6177
|
-
await this.emit("hit", {
|
|
6178
|
-
key,
|
|
6179
|
-
value: clonedValue
|
|
6180
|
-
});
|
|
6181
|
-
return clonedValue;
|
|
6182
|
-
} catch (error) {
|
|
6183
|
-
this.logError(`Failed to clone cached value for ${key}`, error);
|
|
6184
|
-
throw error;
|
|
6185
|
-
}
|
|
6587
|
+
await this.emit("hit", {
|
|
6588
|
+
key,
|
|
6589
|
+
value: parsedValue
|
|
6590
|
+
});
|
|
6591
|
+
return parsedValue;
|
|
6186
6592
|
}
|
|
6187
6593
|
/**
|
|
6188
6594
|
* {@inheritDoc}
|
|
@@ -6190,8 +6596,7 @@ var RedisCacheDriver = class extends BaseCacheDriver {
|
|
|
6190
6596
|
async remove(key) {
|
|
6191
6597
|
key = this.parseKey(key);
|
|
6192
6598
|
this.log("removing", key);
|
|
6193
|
-
await this.client?.del(key);
|
|
6194
|
-
await this.client?.del(this.swrMetaKey(key));
|
|
6599
|
+
await Promise.all([this.client?.del(key), this.client?.del(this.swrMetaKey(key))]);
|
|
6195
6600
|
this.log("removed", key);
|
|
6196
6601
|
await this.emit("removed", { key });
|
|
6197
6602
|
}
|
|
@@ -6466,6 +6871,7 @@ exports.cache = cache;
|
|
|
6466
6871
|
exports.cached = cached;
|
|
6467
6872
|
exports.cosineSimilarity = cosineSimilarity;
|
|
6468
6873
|
exports.deriveAutoKey = deriveAutoKey;
|
|
6874
|
+
exports.escapeCacheKeySegment = escapeCacheKeySegment;
|
|
6469
6875
|
exports.expiresAtToTtl = expiresAtToTtl;
|
|
6470
6876
|
exports.idempotent = idempotent;
|
|
6471
6877
|
exports.injectTags = injectTags;
|