@warlock.js/cache 5.42.0 → 5.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/cjs/index.cjs +1341 -271
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/cache-manager.d.mts +41 -0
  5. package/esm/cache-manager.d.mts.map +1 -1
  6. package/esm/cache-manager.mjs +47 -2
  7. package/esm/cache-manager.mjs.map +1 -1
  8. package/esm/drivers/base-cache-driver.d.mts +14 -0
  9. package/esm/drivers/base-cache-driver.d.mts.map +1 -1
  10. package/esm/drivers/base-cache-driver.mjs +26 -1
  11. package/esm/drivers/base-cache-driver.mjs.map +1 -1
  12. package/esm/drivers/lru-memory-cache-driver.d.mts +17 -1
  13. package/esm/drivers/lru-memory-cache-driver.d.mts.map +1 -1
  14. package/esm/drivers/lru-memory-cache-driver.mjs +27 -2
  15. package/esm/drivers/lru-memory-cache-driver.mjs.map +1 -1
  16. package/esm/drivers/memory-cache-driver.d.mts +19 -1
  17. package/esm/drivers/memory-cache-driver.d.mts.map +1 -1
  18. package/esm/drivers/memory-cache-driver.mjs +34 -0
  19. package/esm/drivers/memory-cache-driver.mjs.map +1 -1
  20. package/esm/drivers/mock-cache-driver.d.mts +4 -0
  21. package/esm/drivers/mock-cache-driver.d.mts.map +1 -1
  22. package/esm/drivers/mock-cache-driver.mjs +18 -0
  23. package/esm/drivers/mock-cache-driver.mjs.map +1 -1
  24. package/esm/drivers/null-cache-driver.d.mts +6 -0
  25. package/esm/drivers/null-cache-driver.d.mts.map +1 -1
  26. package/esm/drivers/null-cache-driver.mjs +8 -0
  27. package/esm/drivers/null-cache-driver.mjs.map +1 -1
  28. package/esm/drivers/pg-cache-driver.d.mts +7 -0
  29. package/esm/drivers/pg-cache-driver.d.mts.map +1 -1
  30. package/esm/drivers/pg-cache-driver.mjs +17 -0
  31. package/esm/drivers/pg-cache-driver.mjs.map +1 -1
  32. package/esm/drivers/redis-cache-driver.d.mts +17 -1
  33. package/esm/drivers/redis-cache-driver.d.mts.map +1 -1
  34. package/esm/drivers/redis-cache-driver.mjs +29 -0
  35. package/esm/drivers/redis-cache-driver.mjs.map +1 -1
  36. package/esm/idempotent.d.mts +35 -0
  37. package/esm/idempotent.d.mts.map +1 -0
  38. package/esm/idempotent.mjs +74 -0
  39. package/esm/idempotent.mjs.map +1 -0
  40. package/esm/index.d.mts +12 -2
  41. package/esm/index.mjs +7 -3
  42. package/esm/scoped-cache.d.mts +5 -0
  43. package/esm/scoped-cache.d.mts.map +1 -1
  44. package/esm/scoped-cache.mjs +7 -0
  45. package/esm/scoped-cache.mjs.map +1 -1
  46. package/esm/structures/bloom-filter.d.mts +33 -0
  47. package/esm/structures/bloom-filter.d.mts.map +1 -0
  48. package/esm/structures/bloom-filter.mjs +56 -0
  49. package/esm/structures/bloom-filter.mjs.map +1 -0
  50. package/esm/structures/cuckoo-filter.d.mts +36 -0
  51. package/esm/structures/cuckoo-filter.d.mts.map +1 -0
  52. package/esm/structures/cuckoo-filter.mjs +70 -0
  53. package/esm/structures/cuckoo-filter.mjs.map +1 -0
  54. package/esm/structures/frequency-tracker.d.mts +33 -0
  55. package/esm/structures/frequency-tracker.d.mts.map +1 -0
  56. package/esm/structures/frequency-tracker.mjs +75 -0
  57. package/esm/structures/frequency-tracker.mjs.map +1 -0
  58. package/esm/structures/hash.mjs +69 -0
  59. package/esm/structures/hash.mjs.map +1 -0
  60. package/esm/structures/hyperloglog.d.mts +27 -0
  61. package/esm/structures/hyperloglog.d.mts.map +1 -0
  62. package/esm/structures/hyperloglog.mjs +67 -0
  63. package/esm/structures/hyperloglog.mjs.map +1 -0
  64. package/esm/structures/index.d.mts +10 -0
  65. package/esm/structures/index.mjs +11 -0
  66. package/esm/structures/memory-structures-backend.d.mts +56 -0
  67. package/esm/structures/memory-structures-backend.d.mts.map +1 -0
  68. package/esm/structures/memory-structures-backend.mjs +114 -0
  69. package/esm/structures/memory-structures-backend.mjs.map +1 -0
  70. package/esm/structures/redis-structures-backend.d.mts +42 -0
  71. package/esm/structures/redis-structures-backend.d.mts.map +1 -0
  72. package/esm/structures/redis-structures-backend.mjs +259 -0
  73. package/esm/structures/redis-structures-backend.mjs.map +1 -0
  74. package/esm/structures/sizing.mjs +26 -0
  75. package/esm/structures/sizing.mjs.map +1 -0
  76. package/esm/structures/structures.d.mts +22 -0
  77. package/esm/structures/structures.d.mts.map +1 -0
  78. package/esm/structures/structures.mjs +44 -0
  79. package/esm/structures/structures.mjs.map +1 -0
  80. package/esm/structures/types.d.mts +108 -0
  81. package/esm/structures/types.d.mts.map +1 -0
  82. package/esm/structures/types.mjs +8 -0
  83. package/esm/structures/types.mjs.map +1 -0
  84. package/esm/structures/unique-counter.d.mts +33 -0
  85. package/esm/structures/unique-counter.d.mts.map +1 -0
  86. package/esm/structures/unique-counter.mjs +43 -0
  87. package/esm/structures/unique-counter.mjs.map +1 -0
  88. package/esm/tagged-cache.d.mts +4 -0
  89. package/esm/tagged-cache.d.mts.map +1 -1
  90. package/esm/tagged-cache.mjs +6 -0
  91. package/esm/tagged-cache.mjs.map +1 -1
  92. package/esm/tagged-scoped-cache.d.mts +4 -0
  93. package/esm/tagged-scoped-cache.d.mts.map +1 -1
  94. package/esm/tagged-scoped-cache.mjs +6 -0
  95. package/esm/tagged-scoped-cache.mjs.map +1 -1
  96. package/esm/types.d.mts +24 -0
  97. package/esm/types.d.mts.map +1 -1
  98. package/esm/types.mjs.map +1 -1
  99. package/llms-full.txt +112 -1
  100. package/llms.txt +3 -0
  101. package/package.json +3 -3
  102. package/skills/index.md +3 -1
  103. package/skills/use-cache-extend/SKILL.md +22 -0
  104. package/skills/use-cache-idempotent/SKILL.md +27 -0
  105. package/skills/use-cache-structures/SKILL.md +48 -0
package/cjs/index.cjs CHANGED
@@ -26,212 +26,17 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  }) : target, mod));
27
27
 
28
28
  //#endregion
29
+ let _warlock_js_logger = require("@warlock.js/logger");
29
30
  let _mongez_reinforcements = require("@mongez/reinforcements");
30
31
  let ms = require("ms");
31
32
  ms = __toESM(ms, 1);
32
33
  let node_crypto = require("node:crypto");
33
- let _warlock_js_logger = require("@warlock.js/logger");
34
34
  let node_fs = require("node:fs");
35
35
  node_fs = __toESM(node_fs, 1);
36
36
  let _warlock_js_fs = require("@warlock.js/fs");
37
37
  let path = require("path");
38
38
  path = __toESM(path, 1);
39
39
 
40
- //#region ../../packages/cache/src/metrics.ts
41
- /**
42
- * Default size of the circular latency-sample buffer. 1000 samples covers
43
- * "tell me the current p95" for every realistic workload while keeping the
44
- * memory cost negligible (8KB at 8 bytes per number).
45
- */
46
- const DEFAULT_LATENCY_BUFFER_SIZE = 1e3;
47
- /**
48
- * Listens to `CacheManager` events and accumulates running counters + a
49
- * circular latency buffer per driver. Returned to consumers via
50
- * `cache.metrics()` as a {@link CacheMetricsSnapshot}.
51
- *
52
- * **Role.** Single-instance observability layer attached to the manager.
53
- * Subscribes once at construction; survives `cache.use()` driver switches
54
- * because the global event registry on the manager re-attaches handlers to
55
- * every loaded driver.
56
- *
57
- * **Responsibility.**
58
- * - Owns: per-driver and aggregate counters (`hits`, `misses`, `sets`,
59
- * `removed`, `errors`), the latency circular buffer, and snapshot
60
- * computation including hit-rate + percentile calculation.
61
- * - Does NOT own: event emission (driven by drivers via `BaseCacheDriver.emit`),
62
- * timing instrumentation (done at the manager level via `recordLatency`),
63
- * or persistence — every metric resets on `resetMetrics()` and on process
64
- * restart.
65
- *
66
- * @example
67
- * cache.metrics();
68
- * // {
69
- * // hits: 9821, misses: 173, hitRate: 0.983,
70
- * // latencyMs: { p50: 0.4, p95: 2.1, p99: 8.2, samples: 1000 },
71
- * // byDriver: { memory: { ... }, redis: { ... } },
72
- * // startedAt: 1714185600000,
73
- * // }
74
- */
75
- var CacheMetricsCollector = class {
76
- constructor(bufferSize = DEFAULT_LATENCY_BUFFER_SIZE) {
77
- this.byDriver = /* @__PURE__ */ new Map();
78
- this.startedAt = Date.now();
79
- this.bufferSize = bufferSize;
80
- this.aggregate = this.createCounters();
81
- }
82
- /**
83
- * Increment the appropriate counters for a cache event. Called from the
84
- * manager's global listeners (one per event type).
85
- */
86
- recordEvent(event, data) {
87
- const driverBucket = this.bucketFor(data.driver);
88
- const aggregate = this.aggregate;
89
- switch (event) {
90
- case "hit":
91
- aggregate.hits += 1;
92
- driverBucket.hits += 1;
93
- break;
94
- case "miss":
95
- aggregate.misses += 1;
96
- driverBucket.misses += 1;
97
- break;
98
- case "set":
99
- aggregate.sets += 1;
100
- driverBucket.sets += 1;
101
- break;
102
- case "removed":
103
- aggregate.removed += 1;
104
- driverBucket.removed += 1;
105
- break;
106
- case "error":
107
- aggregate.errors += 1;
108
- driverBucket.errors += 1;
109
- }
110
- }
111
- /**
112
- * Append a latency sample for `driver`. Called by the manager from its
113
- * timed wrappers around `get` / `set` / `remove`. Uses circular-buffer
114
- * semantics: oldest samples are overwritten once the buffer is full.
115
- */
116
- recordLatency(driver, durationMs) {
117
- this.appendLatency(this.aggregate, durationMs);
118
- this.appendLatency(this.bucketFor(driver), durationMs);
119
- }
120
- /**
121
- * Compute and return the current snapshot. Latency percentiles are
122
- * derived from a sorted copy of the buffer at call time — O(N log N)
123
- * on N=1000 is cheap enough that we don't bother caching.
124
- */
125
- snapshot() {
126
- const byDriver = {};
127
- for (const [driverName, bucket] of this.byDriver) byDriver[driverName] = this.toRow(bucket);
128
- return {
129
- ...this.toRow(this.aggregate),
130
- byDriver,
131
- startedAt: this.startedAt
132
- };
133
- }
134
- /**
135
- * Wipe every counter, drop every latency sample, and reset `startedAt`.
136
- * The collector itself stays subscribed to events.
137
- */
138
- reset() {
139
- this.resetCounters(this.aggregate);
140
- this.byDriver.clear();
141
- this.startedAt = Date.now();
142
- }
143
- /**
144
- * Locate the per-driver bucket, creating it on first reference. Driver
145
- * names are taken verbatim from `CacheEventData.driver`.
146
- */
147
- bucketFor(driverName) {
148
- let bucket = this.byDriver.get(driverName);
149
- if (!bucket) {
150
- bucket = this.createCounters();
151
- this.byDriver.set(driverName, bucket);
152
- }
153
- return bucket;
154
- }
155
- /**
156
- * Convert raw counters into the public snapshot row shape. Computes
157
- * `hitRate` and the latency percentiles on the fly.
158
- */
159
- toRow(bucket) {
160
- const totalReads = bucket.hits + bucket.misses;
161
- const hitRate = totalReads === 0 ? 0 : bucket.hits / totalReads;
162
- const latency = this.computeLatency(bucket.latencySamples);
163
- return {
164
- hits: bucket.hits,
165
- misses: bucket.misses,
166
- sets: bucket.sets,
167
- removed: bucket.removed,
168
- errors: bucket.errors,
169
- hitRate,
170
- latencyMs: latency,
171
- startedAt: this.startedAt
172
- };
173
- }
174
- /**
175
- * Sort a copy of the buffer and pick the percentile entries directly.
176
- * Empty buffers return zeroed percentiles so consumers can render
177
- * dashboards without null-checking.
178
- */
179
- computeLatency(samples) {
180
- if (samples.length === 0) return {
181
- p50: 0,
182
- p95: 0,
183
- p99: 0,
184
- samples: 0
185
- };
186
- const sorted = [...samples].sort((a, b) => a - b);
187
- const pick = (quantile) => {
188
- const index = Math.min(sorted.length - 1, Math.floor(quantile * sorted.length));
189
- return sorted[index] ?? 0;
190
- };
191
- return {
192
- p50: pick(.5),
193
- p95: pick(.95),
194
- p99: pick(.99),
195
- samples: sorted.length
196
- };
197
- }
198
- /**
199
- * Append a latency sample using circular-buffer semantics — overwrite the
200
- * oldest entry once the buffer is full instead of growing unbounded.
201
- */
202
- appendLatency(bucket, durationMs) {
203
- if (bucket.latencySamples.length < this.bufferSize) {
204
- bucket.latencySamples.push(durationMs);
205
- return;
206
- }
207
- bucket.latencySamples[bucket.latencyCursor] = durationMs;
208
- bucket.latencyCursor = (bucket.latencyCursor + 1) % this.bufferSize;
209
- }
210
- /** Build a fresh counter row with zeroed totals and an empty buffer. */
211
- createCounters() {
212
- return {
213
- hits: 0,
214
- misses: 0,
215
- sets: 0,
216
- removed: 0,
217
- errors: 0,
218
- latencySamples: [],
219
- latencyCursor: 0
220
- };
221
- }
222
- /** Reset an existing counter row in place. Used by `reset()` for the aggregate. */
223
- resetCounters(bucket) {
224
- bucket.hits = 0;
225
- bucket.misses = 0;
226
- bucket.sets = 0;
227
- bucket.removed = 0;
228
- bucket.errors = 0;
229
- bucket.latencySamples.length = 0;
230
- bucket.latencyCursor = 0;
231
- }
232
- };
233
-
234
- //#endregion
235
40
  //#region ../../packages/cache/src/types.ts
236
41
  /**
237
42
  * Base error class for cache-related errors
@@ -530,23 +335,286 @@ let CACHE_FOR = /* @__PURE__ */ function(CACHE_FOR) {
530
335
  */
531
336
  CACHE_FOR[CACHE_FOR["HALF_MONTH"] = 1296e3] = "HALF_MONTH";
532
337
  /**
533
- * Cache for 30 Days (in seconds)
338
+ * Cache for 30 Days (in seconds)
339
+ */
340
+ CACHE_FOR[CACHE_FOR["ONE_MONTH"] = 2592e3] = "ONE_MONTH";
341
+ /**
342
+ * Cache for 60 Days (in seconds)
343
+ */
344
+ CACHE_FOR[CACHE_FOR["TWO_MONTHS"] = 5184e3] = "TWO_MONTHS";
345
+ /**
346
+ * Cache for 180 Days (in seconds)
347
+ */
348
+ CACHE_FOR[CACHE_FOR["SIX_MONTHS"] = 15768e3] = "SIX_MONTHS";
349
+ /**
350
+ * Cache for 365 Days (in seconds)
351
+ */
352
+ CACHE_FOR[CACHE_FOR["ONE_YEAR"] = 31536e3] = "ONE_YEAR";
353
+ return CACHE_FOR;
354
+ }({});
355
+
356
+ //#endregion
357
+ //#region ../../packages/cache/src/idempotent.ts
358
+ const MIN_POLL_MS = 25;
359
+ const MAX_POLL_MS = 250;
360
+ const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
361
+ async function readStored(driver, storeKey) {
362
+ const value = await driver.get(storeKey);
363
+ if (value && typeof value === "object" && value.idempotent === true) return value;
364
+ return null;
365
+ }
366
+ async function store(driver, storeKey, result, seconds) {
367
+ try {
368
+ await driver.set(storeKey, {
369
+ idempotent: true,
370
+ result
371
+ }, seconds);
372
+ } catch (error) {
373
+ _warlock_js_logger.log.error("cache", "idempotent", (0, _warlock_js_logger.maskEmailsInText)(`Could not store the result of ${storeKey}: ${String(error)}`));
374
+ }
375
+ }
376
+ /**
377
+ * Implementation behind `cache.idempotent()`.
378
+ */
379
+ function runIdempotent(driver, flights, key, fn, options) {
380
+ const seconds = parseTtl(options.ttl);
381
+ const keyString = typeof key === "string" ? key : parseCacheKey(key);
382
+ const storeKey = `idempotent.${keyString}`;
383
+ const driverFlights = flights.get(driver) ?? /* @__PURE__ */ new Map();
384
+ flights.set(driver, driverFlights);
385
+ const existing = driverFlights.get(storeKey);
386
+ if (existing) return existing;
387
+ const run = async () => {
388
+ if (seconds === 0) return fn();
389
+ const stored = await readStored(driver, storeKey);
390
+ if (stored) return stored.result;
391
+ if (options.distributed) return runDistributed(driver, keyString, storeKey, fn, seconds, options);
392
+ const result = await fn();
393
+ await store(driver, storeKey, result, seconds);
394
+ return result;
395
+ };
396
+ const promise = run().finally(() => {
397
+ if (driverFlights.get(storeKey) === promise) driverFlights.delete(storeKey);
398
+ });
399
+ driverFlights.set(storeKey, promise);
400
+ return promise;
401
+ }
402
+ async function runDistributed(driver, keyString, storeKey, fn, seconds, options) {
403
+ const lockKey = `idempotent.lock.${keyString}`;
404
+ const lockSeconds = parseTtl(options.lockTtl ?? "30s");
405
+ const deadline = Date.now() + lockSeconds * 1e3;
406
+ let pause = MIN_POLL_MS;
407
+ while (true) {
408
+ const outcome = await driver.lock(lockKey, lockSeconds, async () => {
409
+ const stored = await readStored(driver, storeKey);
410
+ if (stored) return stored.result;
411
+ const result = await fn();
412
+ await store(driver, storeKey, result, seconds);
413
+ return result;
414
+ });
415
+ if (outcome.acquired) return outcome.value;
416
+ await sleep(pause);
417
+ pause = Math.min(pause * 2, MAX_POLL_MS);
418
+ const stored = await readStored(driver, storeKey);
419
+ if (stored) return stored.result;
420
+ if (Date.now() >= deadline) throw new CacheConcurrencyError(`idempotent("${keyString}") timed out after ${lockSeconds}s waiting for another run to finish.`);
421
+ }
422
+ }
423
+
424
+ //#endregion
425
+ //#region ../../packages/cache/src/metrics.ts
426
+ /**
427
+ * Default size of the circular latency-sample buffer. 1000 samples covers
428
+ * "tell me the current p95" for every realistic workload while keeping the
429
+ * memory cost negligible (8KB at 8 bytes per number).
430
+ */
431
+ const DEFAULT_LATENCY_BUFFER_SIZE = 1e3;
432
+ /**
433
+ * Listens to `CacheManager` events and accumulates running counters + a
434
+ * circular latency buffer per driver. Returned to consumers via
435
+ * `cache.metrics()` as a {@link CacheMetricsSnapshot}.
436
+ *
437
+ * **Role.** Single-instance observability layer attached to the manager.
438
+ * Subscribes once at construction; survives `cache.use()` driver switches
439
+ * because the global event registry on the manager re-attaches handlers to
440
+ * every loaded driver.
441
+ *
442
+ * **Responsibility.**
443
+ * - Owns: per-driver and aggregate counters (`hits`, `misses`, `sets`,
444
+ * `removed`, `errors`), the latency circular buffer, and snapshot
445
+ * computation including hit-rate + percentile calculation.
446
+ * - Does NOT own: event emission (driven by drivers via `BaseCacheDriver.emit`),
447
+ * timing instrumentation (done at the manager level via `recordLatency`),
448
+ * or persistence — every metric resets on `resetMetrics()` and on process
449
+ * restart.
450
+ *
451
+ * @example
452
+ * cache.metrics();
453
+ * // {
454
+ * // hits: 9821, misses: 173, hitRate: 0.983,
455
+ * // latencyMs: { p50: 0.4, p95: 2.1, p99: 8.2, samples: 1000 },
456
+ * // byDriver: { memory: { ... }, redis: { ... } },
457
+ * // startedAt: 1714185600000,
458
+ * // }
459
+ */
460
+ var CacheMetricsCollector = class {
461
+ constructor(bufferSize = DEFAULT_LATENCY_BUFFER_SIZE) {
462
+ this.byDriver = /* @__PURE__ */ new Map();
463
+ this.startedAt = Date.now();
464
+ this.bufferSize = bufferSize;
465
+ this.aggregate = this.createCounters();
466
+ }
467
+ /**
468
+ * Increment the appropriate counters for a cache event. Called from the
469
+ * manager's global listeners (one per event type).
470
+ */
471
+ recordEvent(event, data) {
472
+ const driverBucket = this.bucketFor(data.driver);
473
+ const aggregate = this.aggregate;
474
+ switch (event) {
475
+ case "hit":
476
+ aggregate.hits += 1;
477
+ driverBucket.hits += 1;
478
+ break;
479
+ case "miss":
480
+ aggregate.misses += 1;
481
+ driverBucket.misses += 1;
482
+ break;
483
+ case "set":
484
+ aggregate.sets += 1;
485
+ driverBucket.sets += 1;
486
+ break;
487
+ case "removed":
488
+ aggregate.removed += 1;
489
+ driverBucket.removed += 1;
490
+ break;
491
+ case "error":
492
+ aggregate.errors += 1;
493
+ driverBucket.errors += 1;
494
+ }
495
+ }
496
+ /**
497
+ * Append a latency sample for `driver`. Called by the manager from its
498
+ * timed wrappers around `get` / `set` / `remove`. Uses circular-buffer
499
+ * semantics: oldest samples are overwritten once the buffer is full.
500
+ */
501
+ recordLatency(driver, durationMs) {
502
+ this.appendLatency(this.aggregate, durationMs);
503
+ this.appendLatency(this.bucketFor(driver), durationMs);
504
+ }
505
+ /**
506
+ * Compute and return the current snapshot. Latency percentiles are
507
+ * derived from a sorted copy of the buffer at call time — O(N log N)
508
+ * on N=1000 is cheap enough that we don't bother caching.
509
+ */
510
+ snapshot() {
511
+ const byDriver = {};
512
+ for (const [driverName, bucket] of this.byDriver) byDriver[driverName] = this.toRow(bucket);
513
+ return {
514
+ ...this.toRow(this.aggregate),
515
+ byDriver,
516
+ startedAt: this.startedAt
517
+ };
518
+ }
519
+ /**
520
+ * Wipe every counter, drop every latency sample, and reset `startedAt`.
521
+ * The collector itself stays subscribed to events.
522
+ */
523
+ reset() {
524
+ this.resetCounters(this.aggregate);
525
+ this.byDriver.clear();
526
+ this.startedAt = Date.now();
527
+ }
528
+ /**
529
+ * Locate the per-driver bucket, creating it on first reference. Driver
530
+ * names are taken verbatim from `CacheEventData.driver`.
534
531
  */
535
- CACHE_FOR[CACHE_FOR["ONE_MONTH"] = 2592e3] = "ONE_MONTH";
532
+ bucketFor(driverName) {
533
+ let bucket = this.byDriver.get(driverName);
534
+ if (!bucket) {
535
+ bucket = this.createCounters();
536
+ this.byDriver.set(driverName, bucket);
537
+ }
538
+ return bucket;
539
+ }
536
540
  /**
537
- * Cache for 60 Days (in seconds)
541
+ * Convert raw counters into the public snapshot row shape. Computes
542
+ * `hitRate` and the latency percentiles on the fly.
538
543
  */
539
- CACHE_FOR[CACHE_FOR["TWO_MONTHS"] = 5184e3] = "TWO_MONTHS";
544
+ toRow(bucket) {
545
+ const totalReads = bucket.hits + bucket.misses;
546
+ const hitRate = totalReads === 0 ? 0 : bucket.hits / totalReads;
547
+ const latency = this.computeLatency(bucket.latencySamples);
548
+ return {
549
+ hits: bucket.hits,
550
+ misses: bucket.misses,
551
+ sets: bucket.sets,
552
+ removed: bucket.removed,
553
+ errors: bucket.errors,
554
+ hitRate,
555
+ latencyMs: latency,
556
+ startedAt: this.startedAt
557
+ };
558
+ }
540
559
  /**
541
- * Cache for 180 Days (in seconds)
560
+ * Sort a copy of the buffer and pick the percentile entries directly.
561
+ * Empty buffers return zeroed percentiles so consumers can render
562
+ * dashboards without null-checking.
542
563
  */
543
- CACHE_FOR[CACHE_FOR["SIX_MONTHS"] = 15768e3] = "SIX_MONTHS";
564
+ computeLatency(samples) {
565
+ if (samples.length === 0) return {
566
+ p50: 0,
567
+ p95: 0,
568
+ p99: 0,
569
+ samples: 0
570
+ };
571
+ const sorted = [...samples].sort((a, b) => a - b);
572
+ const pick = (quantile) => {
573
+ const index = Math.min(sorted.length - 1, Math.floor(quantile * sorted.length));
574
+ return sorted[index] ?? 0;
575
+ };
576
+ return {
577
+ p50: pick(.5),
578
+ p95: pick(.95),
579
+ p99: pick(.99),
580
+ samples: sorted.length
581
+ };
582
+ }
544
583
  /**
545
- * Cache for 365 Days (in seconds)
584
+ * Append a latency sample using circular-buffer semantics — overwrite the
585
+ * oldest entry once the buffer is full instead of growing unbounded.
546
586
  */
547
- CACHE_FOR[CACHE_FOR["ONE_YEAR"] = 31536e3] = "ONE_YEAR";
548
- return CACHE_FOR;
549
- }({});
587
+ appendLatency(bucket, durationMs) {
588
+ if (bucket.latencySamples.length < this.bufferSize) {
589
+ bucket.latencySamples.push(durationMs);
590
+ return;
591
+ }
592
+ bucket.latencySamples[bucket.latencyCursor] = durationMs;
593
+ bucket.latencyCursor = (bucket.latencyCursor + 1) % this.bufferSize;
594
+ }
595
+ /** Build a fresh counter row with zeroed totals and an empty buffer. */
596
+ createCounters() {
597
+ return {
598
+ hits: 0,
599
+ misses: 0,
600
+ sets: 0,
601
+ removed: 0,
602
+ errors: 0,
603
+ latencySamples: [],
604
+ latencyCursor: 0
605
+ };
606
+ }
607
+ /** Reset an existing counter row in place. Used by `reset()` for the aggregate. */
608
+ resetCounters(bucket) {
609
+ bucket.hits = 0;
610
+ bucket.misses = 0;
611
+ bucket.sets = 0;
612
+ bucket.removed = 0;
613
+ bucket.errors = 0;
614
+ bucket.latencySamples.length = 0;
615
+ bucket.latencyCursor = 0;
616
+ }
617
+ };
550
618
 
551
619
  //#endregion
552
620
  //#region ../../packages/cache/src/tagged-scoped-cache.ts
@@ -670,6 +738,12 @@ var TaggedScopedCache = class {
670
738
  return this.scope.increment(key, value, options);
671
739
  }
672
740
  /**
741
+ * Reset the expiry of the scoped key to `ttl` from now. Tags are untouched.
742
+ */
743
+ extend(key, ttl) {
744
+ return this.scope.extend(key, ttl);
745
+ }
746
+ /**
673
747
  * Atomic counter decrement on the scoped key. See {@link increment}.
674
748
  */
675
749
  decrement(key, value) {
@@ -864,6 +938,13 @@ var ScopedCache = class ScopedCache {
864
938
  return this.source.increment(this.scopedKey(key), value, { ttl: options?.ttl ?? this.defaults.ttl });
865
939
  }
866
940
  /**
941
+ * Reset the expiry of the scoped key to `ttl` from now. Resolves to `false`
942
+ * when the key is missing. See `CacheDriver.extend`.
943
+ */
944
+ extend(key, ttl) {
945
+ return this.source.extend(this.scopedKey(key), ttl);
946
+ }
947
+ /**
867
948
  * Atomic counter decrement on the scoped key. See {@link increment} for
868
949
  * TTL semantics.
869
950
  */
@@ -889,95 +970,879 @@ var ScopedCache = class ScopedCache {
889
970
  return this.source.merge(scopedKey, partial, await this.writeOptions(scopedKey, options));
890
971
  }
891
972
  /**
892
- * Resolve the ttl options for update/merge: explicit ttl, else the scope
893
- * default only for keys that don't exist yet, else nothing (keep remaining).
973
+ * Resolve the ttl options for update/merge: explicit ttl, else the scope
974
+ * default only for keys that don't exist yet, else nothing (keep remaining).
975
+ */
976
+ async writeOptions(scopedKey, options) {
977
+ if (options?.ttl !== void 0) return { ttl: options.ttl };
978
+ if (this.defaults.ttl === void 0) return {};
979
+ return await this.source.has(scopedKey) ? {} : { ttl: this.defaults.ttl };
980
+ }
981
+ /**
982
+ * Return a list accessor bound to the scoped key. The accessor itself
983
+ * does its own read-mutate-write under the prefixed entry.
984
+ */
985
+ list(key) {
986
+ return this.source.list(this.scopedKey(key));
987
+ }
988
+ /**
989
+ * Acquire a distributed lock on the scoped key. Caller's TTL wins; when
990
+ * the options form omits `ttl`, the scope default fills in.
991
+ */
992
+ lock(key, ttlOrOptions, fn) {
993
+ if (typeof ttlOrOptions === "object" && ttlOrOptions !== null) {
994
+ const merged = {
995
+ ...ttlOrOptions,
996
+ ttl: ttlOrOptions.ttl ?? this.defaults.ttl ?? ttlOrOptions.ttl
997
+ };
998
+ return this.source.lock(this.scopedKey(key), merged, fn);
999
+ }
1000
+ return this.source.lock(this.scopedKey(key), ttlOrOptions, fn);
1001
+ }
1002
+ /**
1003
+ * Similarity retrieval, scope-isolated. Hits whose keys fall outside this
1004
+ * scope are filtered out before the result is returned. `topK` applies to
1005
+ * the underlying retrieval — when the scope contains fewer than `topK`
1006
+ * matches but other scopes do, the caller will see fewer hits than `topK`.
1007
+ */
1008
+ async similar(vector, options) {
1009
+ const hits = await this.source.similar(vector, options);
1010
+ const parsedPrefix = this.source.parseKey(this.prefix);
1011
+ return hits.filter((hit) => hit.key === parsedPrefix || hit.key.startsWith(parsedPrefix + "."));
1012
+ }
1013
+ /**
1014
+ * Build the source-side key by prepending the scope prefix. Object keys
1015
+ * are normalized via {@link parseCacheKey} first so they compose with the
1016
+ * prefix as plain dot-strings.
1017
+ */
1018
+ scopedKey(key) {
1019
+ const keyString = typeof key === "string" ? key : parseCacheKey(key);
1020
+ if (!keyString) return this.prefix;
1021
+ return `${this.prefix}.${keyString}`;
1022
+ }
1023
+ /**
1024
+ * Coerce the polymorphic 3rd `set` argument into a {@link CacheSetOptions}
1025
+ * with scope defaults filled in. Per-call values always win; tags merge
1026
+ * additively. `expiresAt` is preserved without injecting the scope's `ttl`
1027
+ * default (absolute deadlines override relative ones).
1028
+ */
1029
+ mergeSetOptions(input) {
1030
+ const options = normalizeToOptions(input);
1031
+ const ttl = options.ttl ?? (options.expiresAt === void 0 ? this.defaults.ttl : void 0);
1032
+ const tags = mergeTagSets(this.defaults.tags, options.tags);
1033
+ const merged = { ...options };
1034
+ if (ttl !== void 0) merged.ttl = ttl;
1035
+ if (tags !== void 0) merged.tags = tags;
1036
+ return merged;
1037
+ }
1038
+ /**
1039
+ * Same merge as {@link mergeSetOptions} but for the `remember()` shape
1040
+ * ({@link RememberOptions} — no `expiresAt`).
1041
+ */
1042
+ mergeRememberOptions(input) {
1043
+ const options = normalizeToRememberOptions(input);
1044
+ const ttl = options.ttl ?? this.defaults.ttl;
1045
+ const tags = mergeTagSets(this.defaults.tags, options.tags);
1046
+ const merged = { ...options };
1047
+ if (ttl !== void 0) merged.ttl = ttl;
1048
+ if (tags !== void 0) merged.tags = tags;
1049
+ return merged;
1050
+ }
1051
+ /**
1052
+ * Convert the scope's default `ttl` (which may be a duration string) into
1053
+ * seconds, for the few methods (`setMany`, `setNX`) that accept only a
1054
+ * numeric ttl.
1055
+ */
1056
+ scopeTtlSeconds() {
1057
+ if (this.defaults.ttl === void 0) return;
1058
+ return parseTtl(this.defaults.ttl);
1059
+ }
1060
+ };
1061
+
1062
+ //#endregion
1063
+ //#region ../../packages/cache/src/structures/hash.ts
1064
+ const encoder = new TextEncoder();
1065
+ /**
1066
+ * MurmurHash3 (x86, 32-bit) over the UTF-8 bytes of `input`.
1067
+ *
1068
+ * Pure and deterministic: the same input and seed give the same hash on every
1069
+ * process, platform and release, which matters because the hashes decide where
1070
+ * an item lives in a structure stored in a shared cache.
1071
+ */
1072
+ function murmur3(input, seed) {
1073
+ const bytes = encoder.encode(input);
1074
+ const length = bytes.length;
1075
+ const blocks = length >> 2;
1076
+ let hash = seed >>> 0;
1077
+ for (let index = 0; index < blocks; index++) {
1078
+ const offset = index << 2;
1079
+ let block = bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24;
1080
+ block = Math.imul(block, 3432918353);
1081
+ block = block << 15 | block >>> 17;
1082
+ block = Math.imul(block, 461845907);
1083
+ hash ^= block;
1084
+ hash = hash << 13 | hash >>> 19;
1085
+ hash = Math.imul(hash, 5) + 3864292196 | 0;
1086
+ }
1087
+ let tail = 0;
1088
+ const tailOffset = blocks << 2;
1089
+ const remainder = length & 3;
1090
+ if (remainder === 3) tail ^= bytes[tailOffset + 2] << 16;
1091
+ if (remainder >= 2) tail ^= bytes[tailOffset + 1] << 8;
1092
+ if (remainder >= 1) {
1093
+ tail ^= bytes[tailOffset];
1094
+ tail = Math.imul(tail, 3432918353);
1095
+ tail = tail << 15 | tail >>> 17;
1096
+ tail = Math.imul(tail, 461845907);
1097
+ hash ^= tail;
1098
+ }
1099
+ hash ^= length;
1100
+ hash ^= hash >>> 16;
1101
+ hash = Math.imul(hash, 2246822507);
1102
+ hash ^= hash >>> 13;
1103
+ hash = Math.imul(hash, 3266489909);
1104
+ hash ^= hash >>> 16;
1105
+ return hash >>> 0;
1106
+ }
1107
+ /**
1108
+ * Two independent 32-bit hashes of `item`, for double hashing. The second one
1109
+ * is forced odd so the probe sequence never collapses onto a few slots.
1110
+ */
1111
+ function hashPair(item) {
1112
+ return [murmur3(item, 2538058380), (murmur3(item, 1540483477) | 1) >>> 0];
1113
+ }
1114
+ /**
1115
+ * The `index`-th probe position of `item` inside `size` slots (enhanced double
1116
+ * hashing, so successive positions are well spread even for small `size`).
1117
+ */
1118
+ function probe(hashes, index, size) {
1119
+ const [first, second] = hashes;
1120
+ return (first + index * second + index * index) % size >>> 0;
1121
+ }
1122
+ /**
1123
+ * A 64-bit hash of `item` as two unsigned 32-bit halves.
1124
+ */
1125
+ function hash64(item) {
1126
+ return [murmur3(item, 461845907), murmur3(item, 2246822507)];
1127
+ }
1128
+
1129
+ //#endregion
1130
+ //#region ../../packages/cache/src/structures/sizing.ts
1131
+ /**
1132
+ * Bloom filter geometry for `expectedItems` at `errorRate`: the number of bits
1133
+ * and the number of hash functions that minimise memory for that error rate.
1134
+ *
1135
+ * One million items at 1% need about 9.6 million bits (1.2 MB) and 7 hashes;
1136
+ * at 0.1% about 14.4 million bits (1.8 MB) and 10 hashes.
1137
+ */
1138
+ function bloomGeometry(expectedItems, errorRate) {
1139
+ assertPositiveInteger("expectedItems", expectedItems);
1140
+ if (!(errorRate > 0 && errorRate < 1)) throw new CacheConfigurationError(`Invalid errorRate: ${errorRate}. Expected a number between 0 and 1 (exclusive), e.g. 0.01.`);
1141
+ const bits = Math.ceil(-expectedItems * Math.log(errorRate) / Math.LN2 ** 2);
1142
+ return {
1143
+ bits,
1144
+ hashes: Math.max(1, Math.round(bits / expectedItems * Math.LN2))
1145
+ };
1146
+ }
1147
+ function assertPositiveInteger(name, value) {
1148
+ if (!Number.isInteger(value) || value <= 0) throw new CacheConfigurationError(`Invalid ${name}: ${value}. Expected a positive integer.`);
1149
+ }
1150
+
1151
+ //#endregion
1152
+ //#region ../../packages/cache/src/structures/bloom-filter.ts
1153
+ async function nativeOf(backend) {
1154
+ return backend.native ? backend.native() : null;
1155
+ }
1156
+ /**
1157
+ * Bloom filter: answers "definitely not added" or "probably added".
1158
+ * Items can be added but not removed or listed.
1159
+ */
1160
+ var BloomFilter = class {
1161
+ constructor(key, options, context) {
1162
+ this.key = key;
1163
+ this.context = context;
1164
+ this.errorRate = options.errorRate ?? .01;
1165
+ this.capacity = options.expectedItems;
1166
+ const geometry = bloomGeometry(options.expectedItems, this.errorRate);
1167
+ this.bits = geometry.bits;
1168
+ this.hashes = geometry.hashes;
1169
+ }
1170
+ positions(item) {
1171
+ const hashes = hashPair(item);
1172
+ return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.bits));
1173
+ }
1174
+ /**
1175
+ * Add an item. Resolves to `true` when the item was not (probably) present
1176
+ * before and `false` when it probably was.
1177
+ */
1178
+ async add(item) {
1179
+ const value = String(item);
1180
+ const backend = this.context.backend();
1181
+ const native = await nativeOf(backend);
1182
+ if (native) return native.bloomAdd(this.key, value, {
1183
+ capacity: this.capacity,
1184
+ errorRate: this.errorRate,
1185
+ ttl: this.context.ttl
1186
+ });
1187
+ return (await backend.bitSet(this.key, this.positions(value), { ttl: this.context.ttl })).some((bit) => !bit);
1188
+ }
1189
+ /**
1190
+ * `false` means the item was definitely never added; `true` means it
1191
+ * probably was (a small, configured share of `true` answers are wrong).
1192
+ */
1193
+ async mightContain(item) {
1194
+ const value = String(item);
1195
+ const backend = this.context.backend();
1196
+ const native = await nativeOf(backend);
1197
+ if (native) return native.bloomExists(this.key, value);
1198
+ return (await backend.bitGet(this.key, this.positions(value))).every(Boolean);
1199
+ }
1200
+ };
1201
+
1202
+ //#endregion
1203
+ //#region ../../packages/cache/src/structures/cuckoo-filter.ts
1204
+ /**
1205
+ * Membership filter that supports removal.
1206
+ *
1207
+ * With RedisBloom this is a real cuckoo filter (`CF.*`). Everywhere else it is
1208
+ * a counting Bloom filter: the same API and error rate, with one counter per
1209
+ * cell instead of one bit, so `remove()` can undo an `add()`.
1210
+ *
1211
+ * Never remove an item that was not added: on either implementation it
1212
+ * corrupts the filter and can hide other items.
1213
+ */
1214
+ var CuckooFilter = class {
1215
+ constructor(key, options, context) {
1216
+ this.key = key;
1217
+ this.context = context;
1218
+ const geometry = bloomGeometry(options.expectedItems, options.errorRate ?? .01);
1219
+ this.cells = geometry.bits;
1220
+ this.hashes = geometry.hashes;
1221
+ this.capacity = options.expectedItems;
1222
+ }
1223
+ positions(item) {
1224
+ const hashes = hashPair(item);
1225
+ return Array.from({ length: this.hashes }, (_, index) => probe(hashes, index, this.cells));
1226
+ }
1227
+ /**
1228
+ * Add an item. Resolves to `true` when stored.
1229
+ */
1230
+ async add(item) {
1231
+ const value = String(item);
1232
+ const backend = this.context.backend();
1233
+ const native = await nativeOf(backend);
1234
+ if (native) return native.cuckooAdd(this.key, value, {
1235
+ capacity: this.capacity,
1236
+ ttl: this.context.ttl
1237
+ });
1238
+ await backend.gridAdd(this.key, this.positions(value), 1, { ttl: this.context.ttl });
1239
+ return true;
1240
+ }
1241
+ /**
1242
+ * Remove an item that was added. Resolves to `true` when something was removed.
1243
+ */
1244
+ async remove(item) {
1245
+ const value = String(item);
1246
+ const backend = this.context.backend();
1247
+ const native = await nativeOf(backend);
1248
+ if (native) return native.cuckooRemove(this.key, value);
1249
+ const positions = this.positions(value);
1250
+ if ((await backend.gridGet(this.key, positions)).some((count) => count === 0)) return false;
1251
+ await backend.gridAdd(this.key, positions, -1);
1252
+ return true;
1253
+ }
1254
+ /**
1255
+ * `false` means definitely not present; `true` means probably present.
1256
+ */
1257
+ async mightContain(item) {
1258
+ const value = String(item);
1259
+ const backend = this.context.backend();
1260
+ const native = await nativeOf(backend);
1261
+ if (native) return native.cuckooExists(this.key, value);
1262
+ return (await backend.gridGet(this.key, this.positions(value))).every((count) => count > 0);
1263
+ }
1264
+ };
1265
+
1266
+ //#endregion
1267
+ //#region ../../packages/cache/src/structures/frequency-tracker.ts
1268
+ /**
1269
+ * Count-Min sketch with a Top-K list: how often a value was seen, and which
1270
+ * values are seen most. Estimates never fall below the true count; they can
1271
+ * only be too high.
1272
+ */
1273
+ var FrequencyTracker = class {
1274
+ constructor(key, options, context) {
1275
+ this.key = key;
1276
+ this.context = context;
1277
+ this.width = options.width ?? 2e3;
1278
+ this.depth = options.depth ?? 5;
1279
+ this.topK = options.topK ?? 10;
1280
+ assertPositiveInteger("width", this.width);
1281
+ assertPositiveInteger("depth", this.depth);
1282
+ assertPositiveInteger("topK", this.topK);
1283
+ }
1284
+ cellsOf(item) {
1285
+ const hashes = hashPair(item);
1286
+ return Array.from({ length: this.depth }, (_, row) => row * this.width + probe(hashes, row, this.width));
1287
+ }
1288
+ /**
1289
+ * Count `count` more occurrences of a value (default one).
1290
+ */
1291
+ async add(value, count = 1) {
1292
+ assertPositiveInteger("count", count);
1293
+ const item = String(value);
1294
+ const backend = this.context.backend();
1295
+ const native = await nativeOf(backend);
1296
+ if (native) {
1297
+ await native.frequencyAdd(this.key, item, count, {
1298
+ width: this.width,
1299
+ depth: this.depth,
1300
+ topK: this.topK,
1301
+ ttl: this.context.ttl
1302
+ });
1303
+ return;
1304
+ }
1305
+ const counters = await backend.gridAdd(this.key, this.cellsOf(item), count, { ttl: this.context.ttl });
1306
+ await backend.rankedSet(`${this.key}.top`, item, Math.min(...counters), this.topK, { ttl: this.context.ttl });
1307
+ }
1308
+ /**
1309
+ * Estimated number of times a value was counted. Never lower than the true
1310
+ * count; may be higher.
1311
+ */
1312
+ async estimate(value) {
1313
+ const item = String(value);
1314
+ const backend = this.context.backend();
1315
+ const native = await nativeOf(backend);
1316
+ if (native) return native.frequencyEstimate(this.key, item);
1317
+ const counters = await backend.gridGet(this.key, this.cellsOf(item));
1318
+ return Math.min(...counters);
1319
+ }
1320
+ /**
1321
+ * The most frequent values seen, highest count first. Holds at most `topK`
1322
+ * values; `count` defaults to all of them.
894
1323
  */
895
- async writeOptions(scopedKey, options) {
896
- if (options?.ttl !== void 0) return { ttl: options.ttl };
897
- if (this.defaults.ttl === void 0) return {};
898
- return await this.source.has(scopedKey) ? {} : { ttl: this.defaults.ttl };
1324
+ async top(count = this.topK) {
1325
+ const backend = this.context.backend();
1326
+ const native = await nativeOf(backend);
1327
+ const limit = Math.min(count, this.topK);
1328
+ return (native ? await native.frequencyTop(this.key, limit) : await backend.rankedTop(`${this.key}.top`, limit)).map((entry) => ({
1329
+ value: entry.member,
1330
+ count: entry.score
1331
+ }));
1332
+ }
1333
+ };
1334
+
1335
+ //#endregion
1336
+ //#region ../../packages/cache/src/structures/hyperloglog.ts
1337
+ const HLL_REGISTERS = 16384;
1338
+ const INDEX_SHIFT = 18;
1339
+ const HIGH_REMAINDER_BITS = INDEX_SHIFT;
1340
+ const HIGH_REMAINDER_MASK = (1 << HIGH_REMAINDER_BITS) - 1;
1341
+ const MAX_RANK = 51;
1342
+ /**
1343
+ * HyperLogLog cardinality estimator over a 64-bit hash.
1344
+ *
1345
+ * Used by the in-process structures backend; Redis uses its native
1346
+ * `PFADD` / `PFCOUNT` instead.
1347
+ */
1348
+ var HyperLogLog = class {
1349
+ constructor(registers) {
1350
+ this.registers = registers ?? new Uint8Array(16384);
1351
+ }
1352
+ /**
1353
+ * Record `item`. Returns true when the estimate may have changed (a register
1354
+ * grew), which is also how `PFADD` reports a probably-new item.
1355
+ */
1356
+ add(item) {
1357
+ const [high, low] = hash64(item);
1358
+ const index = high >>> INDEX_SHIFT;
1359
+ const remainder = high & HIGH_REMAINDER_MASK;
1360
+ let rank;
1361
+ if (remainder !== 0) rank = Math.clz32(remainder) - 14 + 1;
1362
+ else if (low !== 0) rank = HIGH_REMAINDER_BITS + Math.clz32(low) + 1;
1363
+ else rank = MAX_RANK;
1364
+ if (rank > this.registers[index]) {
1365
+ this.registers[index] = rank;
1366
+ return true;
1367
+ }
1368
+ return false;
899
1369
  }
900
1370
  /**
901
- * Return a list accessor bound to the scoped key. The accessor itself
902
- * does its own read-mutate-write under the prefixed entry.
1371
+ * Fold `other` into this counter (register-wise maximum), so the result
1372
+ * counts the union of both sets.
903
1373
  */
904
- list(key) {
905
- return this.source.list(this.scopedKey(key));
1374
+ merge(other) {
1375
+ for (let index = 0; index < HLL_REGISTERS; index++) {
1376
+ const value = other.registers[index];
1377
+ if (value > this.registers[index]) this.registers[index] = value;
1378
+ }
1379
+ return this;
906
1380
  }
907
1381
  /**
908
- * Acquire a distributed lock on the scoped key. Caller's TTL wins; when
909
- * the options form omits `ttl`, the scope default fills in.
1382
+ * Estimated number of distinct items.
910
1383
  */
911
- lock(key, ttlOrOptions, fn) {
912
- if (typeof ttlOrOptions === "object" && ttlOrOptions !== null) {
913
- const merged = {
914
- ...ttlOrOptions,
915
- ttl: ttlOrOptions.ttl ?? this.defaults.ttl ?? ttlOrOptions.ttl
916
- };
917
- return this.source.lock(this.scopedKey(key), merged, fn);
1384
+ count() {
1385
+ let sum = 0;
1386
+ let zeros = 0;
1387
+ for (let index = 0; index < HLL_REGISTERS; index++) {
1388
+ const value = this.registers[index];
1389
+ sum += 2 ** -value;
1390
+ if (value === 0) zeros++;
918
1391
  }
919
- return this.source.lock(this.scopedKey(key), ttlOrOptions, fn);
1392
+ const estimate = .7213 / 1.0000658569335938 * HLL_REGISTERS * HLL_REGISTERS / sum;
1393
+ if (estimate <= 2.5 * 16384 && zeros > 0) return Math.round(HLL_REGISTERS * Math.log(HLL_REGISTERS / zeros));
1394
+ return Math.round(estimate);
920
1395
  }
1396
+ };
1397
+
1398
+ //#endregion
1399
+ //#region ../../packages/cache/src/structures/memory-structures-backend.ts
1400
+ /**
1401
+ * In-process implementation of the structure primitives, shared by the memory
1402
+ * family of drivers. State lives next to the driver's entries and follows its
1403
+ * `flush()` and `removeNamespace()`.
1404
+ */
1405
+ var MemoryStructuresBackend = class {
921
1406
  /**
922
- * Similarity retrieval, scope-isolated. Hits whose keys fall outside this
923
- * scope are filtered out before the result is returned. `topK` applies to
924
- * the underlying retrieval — when the scope contains fewer than `topK`
925
- * matches but other scopes do, the caller will see fewer hits than `topK`.
1407
+ * @param parseKey the owning driver's key parser (applies the cache prefix)
926
1408
  */
927
- async similar(vector, options) {
928
- const hits = await this.source.similar(vector, options);
929
- const parsedPrefix = this.source.parseKey(this.prefix);
930
- return hits.filter((hit) => hit.key === parsedPrefix || hit.key.startsWith(parsedPrefix + "."));
1409
+ constructor(parseKey) {
1410
+ this.parseKey = parseKey;
1411
+ this.slots = /* @__PURE__ */ new Map();
1412
+ }
1413
+ /** Drop every structure. */
1414
+ clear() {
1415
+ this.slots.clear();
1416
+ }
1417
+ /** Drop every structure whose parsed key starts with `prefix`. */
1418
+ clearPrefix(prefix) {
1419
+ for (const key of [...this.slots.keys()]) if (key.startsWith(prefix)) this.slots.delete(key);
1420
+ }
1421
+ async bitSet(key, offsets, options) {
1422
+ const slot = this.slot(key, "bits", () => /* @__PURE__ */ new Uint8Array(0), options);
1423
+ const needed = (offsets.reduce((max, offset) => Math.max(max, offset), 0) >> 3) + 1;
1424
+ if (slot.value.length < needed) {
1425
+ const grown = new Uint8Array(Math.max(needed, slot.value.length * 2));
1426
+ grown.set(slot.value);
1427
+ slot.value = grown;
1428
+ }
1429
+ return offsets.map((offset) => {
1430
+ const mask = 1 << (offset & 7);
1431
+ const byte = slot.value[offset >> 3] ?? 0;
1432
+ const previous = (byte & mask) !== 0;
1433
+ slot.value[offset >> 3] = byte | mask;
1434
+ return previous;
1435
+ });
1436
+ }
1437
+ async bitGet(key, offsets) {
1438
+ const slot = this.find(key, "bits");
1439
+ return offsets.map((offset) => {
1440
+ const byte = slot?.value[offset >> 3];
1441
+ return byte !== void 0 && (byte & 1 << (offset & 7)) !== 0;
1442
+ });
1443
+ }
1444
+ async gridAdd(key, cells, delta, options) {
1445
+ const slot = this.slot(key, "grid", () => /* @__PURE__ */ new Map(), options);
1446
+ return cells.map((cell) => {
1447
+ const next = Math.max(0, (slot.value.get(cell) ?? 0) + delta);
1448
+ if (next === 0) slot.value.delete(cell);
1449
+ else slot.value.set(cell, next);
1450
+ return next;
1451
+ });
1452
+ }
1453
+ async gridGet(key, cells) {
1454
+ const slot = this.find(key, "grid");
1455
+ return cells.map((cell) => slot?.value.get(cell) ?? 0);
1456
+ }
1457
+ async uniqueAdd(key, member, options) {
1458
+ return this.slot(key, "unique", () => new HyperLogLog(), options).value.add(member);
1459
+ }
1460
+ async uniqueCount(keys) {
1461
+ const merged = new HyperLogLog();
1462
+ for (const key of keys) {
1463
+ const slot = this.find(key, "unique");
1464
+ if (slot) merged.merge(slot.value);
1465
+ }
1466
+ return merged.count();
1467
+ }
1468
+ async rankedSet(key, member, score, capacity, options) {
1469
+ const slot = this.slot(key, "ranked", () => /* @__PURE__ */ new Map(), options);
1470
+ slot.value.set(member, score);
1471
+ if (slot.value.size > capacity) {
1472
+ let lowest;
1473
+ for (const [candidate, candidateScore] of slot.value) if (lowest === void 0 || candidateScore < slot.value.get(lowest)) lowest = candidate;
1474
+ slot.value.delete(lowest);
1475
+ }
1476
+ }
1477
+ async rankedTop(key, count) {
1478
+ const slot = this.find(key, "ranked");
1479
+ if (!slot) return [];
1480
+ return [...slot.value].map(([member, score]) => ({
1481
+ member,
1482
+ score
1483
+ })).sort((a, b) => b.score - a.score || (a.member < b.member ? -1 : 1)).slice(0, count);
1484
+ }
1485
+ find(key, type) {
1486
+ const parsed = this.parseKey(key);
1487
+ const slot = this.slots.get(parsed);
1488
+ if (!slot) return;
1489
+ if (slot.expiresAt !== void 0 && slot.expiresAt <= Date.now()) {
1490
+ this.slots.delete(parsed);
1491
+ return;
1492
+ }
1493
+ return slot.type === type ? slot : void 0;
1494
+ }
1495
+ slot(key, type, create, options) {
1496
+ const existing = this.find(key, type);
1497
+ if (existing) return existing;
1498
+ const slot = {
1499
+ type,
1500
+ value: create()
1501
+ };
1502
+ if (options?.ttl && Number.isFinite(options.ttl)) slot.expiresAt = Date.now() + options.ttl * 1e3;
1503
+ this.slots.set(this.parseKey(key), slot);
1504
+ return slot;
1505
+ }
1506
+ };
1507
+
1508
+ //#endregion
1509
+ //#region ../../packages/cache/src/structures/redis-structures-backend.ts
1510
+ /**
1511
+ * Redis implementation of the structure primitives.
1512
+ *
1513
+ * Portable path (any Redis): bitmaps (`SETBIT` / `GETBIT`), hashes
1514
+ * (`HINCRBY`), native HyperLogLog (`PFADD` / `PFCOUNT`) and sorted sets.
1515
+ * When the server runs RedisBloom, {@link native} exposes `BF.*`, `CF.*`,
1516
+ * `CMS.*` and `TOPK.*` operations, detected once with `MODULE LIST`.
1517
+ */
1518
+ var RedisStructuresBackend = class {
1519
+ constructor(getClient, parseKey) {
1520
+ this.getClient = getClient;
1521
+ this.parseKey = parseKey;
1522
+ }
1523
+ send(args) {
1524
+ return this.getClient().sendCommand(args.map(String));
931
1525
  }
932
1526
  /**
933
- * Build the source-side key by prepending the scope prefix. Object keys
934
- * are normalized via {@link parseCacheKey} first so they compose with the
935
- * prefix as plain dot-strings.
1527
+ * Give a key without an expiry its ttl. A key that already expires keeps its
1528
+ * deadline, so later writes never push the window back.
936
1529
  */
937
- scopedKey(key) {
938
- const keyString = typeof key === "string" ? key : parseCacheKey(key);
939
- if (!keyString) return this.prefix;
940
- return `${this.prefix}.${keyString}`;
1530
+ async applyTtl(key, options) {
1531
+ if (!options?.ttl || !Number.isFinite(options.ttl)) return;
1532
+ if (Number(await this.send(["TTL", key])) === -1) await this.send([
1533
+ "EXPIRE",
1534
+ key,
1535
+ Math.ceil(options.ttl)
1536
+ ]);
1537
+ }
1538
+ async bitSet(key, offsets, options) {
1539
+ const parsed = this.parseKey(key);
1540
+ const previous = await Promise.all(offsets.map((offset) => this.send([
1541
+ "SETBIT",
1542
+ parsed,
1543
+ offset,
1544
+ 1
1545
+ ])));
1546
+ await this.applyTtl(parsed, options);
1547
+ return previous.map((value) => Number(value) === 1);
1548
+ }
1549
+ async bitGet(key, offsets) {
1550
+ const parsed = this.parseKey(key);
1551
+ return (await Promise.all(offsets.map((offset) => this.send([
1552
+ "GETBIT",
1553
+ parsed,
1554
+ offset
1555
+ ])))).map((value) => Number(value) === 1);
1556
+ }
1557
+ async gridAdd(key, cells, delta, options) {
1558
+ const parsed = this.parseKey(key);
1559
+ const values = await Promise.all(cells.map((cell) => this.send([
1560
+ "HINCRBY",
1561
+ parsed,
1562
+ cell,
1563
+ delta
1564
+ ])));
1565
+ await this.applyTtl(parsed, options);
1566
+ return values.map((value) => Math.max(0, Number(value)));
1567
+ }
1568
+ async gridGet(key, cells) {
1569
+ if (cells.length === 0) return [];
1570
+ return (await this.send([
1571
+ "HMGET",
1572
+ this.parseKey(key),
1573
+ ...cells
1574
+ ])).map((value) => Math.max(0, Number(value ?? 0)));
1575
+ }
1576
+ async uniqueAdd(key, member, options) {
1577
+ const parsed = this.parseKey(key);
1578
+ const changed = await this.send([
1579
+ "PFADD",
1580
+ parsed,
1581
+ member
1582
+ ]);
1583
+ await this.applyTtl(parsed, options);
1584
+ return Number(changed) === 1;
1585
+ }
1586
+ async uniqueCount(keys) {
1587
+ if (keys.length === 0) return 0;
1588
+ return Number(await this.send(["PFCOUNT", ...keys.map((key) => this.parseKey(key))]));
1589
+ }
1590
+ async rankedSet(key, member, score, capacity, options) {
1591
+ const parsed = this.parseKey(key);
1592
+ await this.send([
1593
+ "ZADD",
1594
+ parsed,
1595
+ score,
1596
+ member
1597
+ ]);
1598
+ await this.send([
1599
+ "ZREMRANGEBYRANK",
1600
+ parsed,
1601
+ 0,
1602
+ -(capacity + 1)
1603
+ ]);
1604
+ await this.applyTtl(parsed, options);
1605
+ }
1606
+ async rankedTop(key, count) {
1607
+ return pairs(await this.send([
1608
+ "ZREVRANGE",
1609
+ this.parseKey(key),
1610
+ 0,
1611
+ count - 1,
1612
+ "WITHSCORES"
1613
+ ])).map(([member, score]) => ({
1614
+ member: String(member),
1615
+ score: Number(score)
1616
+ }));
1617
+ }
1618
+ native() {
1619
+ this.nativeProbe ??= this.detectModule().then((present) => present ? this.createNative() : null);
1620
+ return this.nativeProbe;
1621
+ }
1622
+ async detectModule() {
1623
+ try {
1624
+ return containsModule(await this.send(["MODULE", "LIST"]));
1625
+ } catch {
1626
+ return false;
1627
+ }
1628
+ }
1629
+ /** Run `command`; when the key is missing, `init` creates it and `command` runs again. */
1630
+ async withInit(command, init) {
1631
+ try {
1632
+ return await command();
1633
+ } catch (error) {
1634
+ if (!/not exist|no such key|not found/i.test(String(error?.message))) throw error;
1635
+ try {
1636
+ await init();
1637
+ } catch (initError) {
1638
+ if (!/exist/i.test(String(initError?.message))) throw initError;
1639
+ }
1640
+ return command();
1641
+ }
1642
+ }
1643
+ createNative() {
1644
+ const first = (reply) => Array.isArray(reply) ? reply[0] : reply;
1645
+ return {
1646
+ bloomAdd: async (key, item, { capacity, errorRate, ttl }) => {
1647
+ const parsed = this.parseKey(key);
1648
+ const reply = await this.send([
1649
+ "BF.INSERT",
1650
+ parsed,
1651
+ "CAPACITY",
1652
+ capacity,
1653
+ "ERROR",
1654
+ errorRate,
1655
+ "ITEMS",
1656
+ item
1657
+ ]);
1658
+ await this.applyTtl(parsed, { ttl });
1659
+ return Number(first(reply)) === 1;
1660
+ },
1661
+ bloomExists: async (key, item) => Number(await this.send([
1662
+ "BF.EXISTS",
1663
+ this.parseKey(key),
1664
+ item
1665
+ ])) === 1,
1666
+ cuckooAdd: async (key, item, { capacity, ttl }) => {
1667
+ const parsed = this.parseKey(key);
1668
+ const reply = await this.send([
1669
+ "CF.INSERT",
1670
+ parsed,
1671
+ "CAPACITY",
1672
+ capacity,
1673
+ "ITEMS",
1674
+ item
1675
+ ]);
1676
+ await this.applyTtl(parsed, { ttl });
1677
+ return Number(first(reply)) === 1;
1678
+ },
1679
+ cuckooRemove: async (key, item) => Number(await this.send([
1680
+ "CF.DEL",
1681
+ this.parseKey(key),
1682
+ item
1683
+ ])) === 1,
1684
+ cuckooExists: async (key, item) => Number(await this.send([
1685
+ "CF.EXISTS",
1686
+ this.parseKey(key),
1687
+ item
1688
+ ])) === 1,
1689
+ frequencyAdd: async (key, item, count, { width, depth, topK, ttl }) => {
1690
+ const cms = `${this.parseKey(key)}.cms`;
1691
+ const top = `${this.parseKey(key)}.topk`;
1692
+ await this.withInit(() => this.send([
1693
+ "CMS.INCRBY",
1694
+ cms,
1695
+ item,
1696
+ count
1697
+ ]), () => this.send([
1698
+ "CMS.INITBYDIM",
1699
+ cms,
1700
+ width,
1701
+ depth
1702
+ ]));
1703
+ await this.withInit(() => this.send([
1704
+ "TOPK.INCRBY",
1705
+ top,
1706
+ item,
1707
+ count
1708
+ ]), () => this.send([
1709
+ "TOPK.RESERVE",
1710
+ top,
1711
+ topK,
1712
+ width,
1713
+ depth,
1714
+ "0.9"
1715
+ ]));
1716
+ await this.applyTtl(cms, { ttl });
1717
+ await this.applyTtl(top, { ttl });
1718
+ },
1719
+ frequencyEstimate: async (key, item) => {
1720
+ try {
1721
+ return Number(first(await this.send([
1722
+ "CMS.QUERY",
1723
+ `${this.parseKey(key)}.cms`,
1724
+ item
1725
+ ])));
1726
+ } catch (error) {
1727
+ if (/not exist|no such key|not found/i.test(String(error?.message))) return 0;
1728
+ throw error;
1729
+ }
1730
+ },
1731
+ frequencyTop: async (key, count) => {
1732
+ try {
1733
+ return pairs(await this.send([
1734
+ "TOPK.LIST",
1735
+ `${this.parseKey(key)}.topk`,
1736
+ "WITHCOUNT"
1737
+ ])).map(([member, score]) => ({
1738
+ member: String(member),
1739
+ score: Number(score)
1740
+ })).slice(0, count);
1741
+ } catch (error) {
1742
+ if (/not exist|no such key|not found/i.test(String(error?.message))) return [];
1743
+ throw error;
1744
+ }
1745
+ }
1746
+ };
1747
+ }
1748
+ };
1749
+ function pairs(flat) {
1750
+ const result = [];
1751
+ for (let index = 0; index + 1 < flat.length; index += 2) result.push([flat[index], flat[index + 1]]);
1752
+ return result;
1753
+ }
1754
+ /** True when a `MODULE LIST` reply (any client shape) names the RedisBloom module. */
1755
+ function containsModule(reply) {
1756
+ if (typeof reply === "string") {
1757
+ const name = reply.toLowerCase();
1758
+ return name === "bf" || name === "redisbloom";
1759
+ }
1760
+ if (Array.isArray(reply)) return reply.some(containsModule);
1761
+ if (reply && typeof reply === "object") return Object.values(reply).some(containsModule);
1762
+ return false;
1763
+ }
1764
+
1765
+ //#endregion
1766
+ //#region ../../packages/cache/src/structures/unique-counter.ts
1767
+ /**
1768
+ * Approximate count of distinct values (HyperLogLog): about 12 KB per counter,
1769
+ * standard error 0.81%. Cannot tell whether one specific value was counted.
1770
+ */
1771
+ var UniqueCounter = class {
1772
+ constructor(key, context) {
1773
+ this.key = key;
1774
+ this.context = context;
941
1775
  }
942
1776
  /**
943
- * Coerce the polymorphic 3rd `set` argument into a {@link CacheSetOptions}
944
- * with scope defaults filled in. Per-call values always win; tags merge
945
- * additively. `expiresAt` is preserved without injecting the scope's `ttl`
946
- * default (absolute deadlines override relative ones).
1777
+ * Count a value. Adding the same value again changes nothing.
947
1778
  */
948
- mergeSetOptions(input) {
949
- const options = normalizeToOptions(input);
950
- const ttl = options.ttl ?? (options.expiresAt === void 0 ? this.defaults.ttl : void 0);
951
- const tags = mergeTagSets(this.defaults.tags, options.tags);
952
- const merged = { ...options };
953
- if (ttl !== void 0) merged.ttl = ttl;
954
- if (tags !== void 0) merged.tags = tags;
955
- return merged;
1779
+ async add(...values) {
1780
+ const backend = this.context.backend();
1781
+ for (const value of values) await backend.uniqueAdd(this.key, String(value), { ttl: this.context.ttl });
956
1782
  }
957
1783
  /**
958
- * Same merge as {@link mergeSetOptions} but for the `remember()` shape
959
- * ({@link RememberOptions} — no `expiresAt`).
1784
+ * Approximate number of distinct values counted so far.
960
1785
  */
961
- mergeRememberOptions(input) {
962
- const options = normalizeToRememberOptions(input);
963
- const ttl = options.ttl ?? this.defaults.ttl;
964
- const tags = mergeTagSets(this.defaults.tags, options.tags);
965
- const merged = { ...options };
966
- if (ttl !== void 0) merged.ttl = ttl;
967
- if (tags !== void 0) merged.tags = tags;
968
- return merged;
1786
+ async count() {
1787
+ return this.context.backend().uniqueCount([this.key]);
1788
+ }
1789
+ };
1790
+ /**
1791
+ * The union of several unique counters, counted without changing any of them.
1792
+ */
1793
+ var UniqueCounterGroup = class {
1794
+ constructor(keys, context) {
1795
+ this.keys = keys;
1796
+ this.context = context;
969
1797
  }
970
1798
  /**
971
- * Convert the scope's default `ttl` (which may be a duration string) into
972
- * seconds, for the few methods (`setMany`, `setNX`) that accept only a
973
- * numeric ttl.
1799
+ * Approximate number of distinct values across every counter in the group.
974
1800
  */
975
- scopeTtlSeconds() {
976
- if (this.defaults.ttl === void 0) return;
977
- return parseTtl(this.defaults.ttl);
1801
+ async count() {
1802
+ return this.context.backend().uniqueCount(this.keys);
978
1803
  }
979
1804
  };
980
1805
 
1806
+ //#endregion
1807
+ //#region ../../packages/cache/src/structures/types.ts
1808
+ function isStructuresCapable(driver) {
1809
+ return typeof driver === "object" && driver !== null && typeof driver.structuresBackend === "function";
1810
+ }
1811
+
1812
+ //#endregion
1813
+ //#region ../../packages/cache/src/structures/structures.ts
1814
+ /**
1815
+ * Resolve the backend of a driver, or throw {@link CacheUnsupportedError} when
1816
+ * the driver does not opt in.
1817
+ */
1818
+ function structuresBackendOf(driver) {
1819
+ if (!isStructuresCapable(driver)) throw new CacheUnsupportedError(`'${driver.name}' driver does not support cache.structures. Use the 'redis' driver or a memory driver ('memory', 'memoryExtended', 'lru').`);
1820
+ return driver.structuresBackend();
1821
+ }
1822
+ function ttlSeconds(options) {
1823
+ if (options?.ttl === void 0) return;
1824
+ const seconds = parseTtl(options.ttl);
1825
+ return seconds > 0 && Number.isFinite(seconds) ? seconds : void 0;
1826
+ }
1827
+ /**
1828
+ * Build the `cache.structures` namespace. `getBackend` is called on every
1829
+ * operation, so structures always follow the manager's current driver.
1830
+ */
1831
+ function createStructures(getBackend) {
1832
+ const context = (options) => ({
1833
+ backend: getBackend,
1834
+ ttl: ttlSeconds(options)
1835
+ });
1836
+ const uniqueCounter = ((key, options) => new UniqueCounter(`structures.unique.${key}`, context(options)));
1837
+ uniqueCounter.merge = (keys) => new UniqueCounterGroup(keys.map((key) => `structures.unique.${key}`), context());
1838
+ return {
1839
+ bloom: (key, options) => new BloomFilter(`structures.bloom.${key}`, options, context(options)),
1840
+ cuckoo: (key, options) => new CuckooFilter(`structures.cuckoo.${key}`, options, context(options)),
1841
+ uniqueCounter,
1842
+ frequency: (key, options = {}) => new FrequencyTracker(`structures.frequency.${key}`, options, context(options))
1843
+ };
1844
+ }
1845
+
981
1846
  //#endregion
982
1847
  //#region ../../packages/cache/src/cache-manager.ts
983
1848
  var CacheManager = class {
@@ -990,6 +1855,11 @@ var CacheManager = class {
990
1855
  };
991
1856
  this.globalEventListeners = /* @__PURE__ */ new Map();
992
1857
  this.name = "cacheManager";
1858
+ this.idempotentFlights = /* @__PURE__ */ new WeakMap();
1859
+ this.structures = createStructures(() => {
1860
+ this.ensureDriverInitialized();
1861
+ return structuresBackendOf(this.currentDriver);
1862
+ });
993
1863
  }
994
1864
  /**
995
1865
  * {@inheritdoc}
@@ -1334,6 +2204,37 @@ var CacheManager = class {
1334
2204
  }
1335
2205
  /**
1336
2206
  * {@inheritdoc}
2207
+ *
2208
+ * @example
2209
+ * await cache.extend(`session.${id}`, "30m"); // active again: 30 minutes from now
2210
+ */
2211
+ async extend(key, ttl) {
2212
+ this.ensureDriverInitialized();
2213
+ return this.currentDriver.extend(key, ttl);
2214
+ }
2215
+ /**
2216
+ * Run `fn` once per `key`: concurrent calls share the single run, and repeat
2217
+ * calls within `ttl` get the stored result instead of running again. Use it
2218
+ * for work that must not repeat, such as charging a payment, handling a
2219
+ * webhook delivery or a retried job.
2220
+ *
2221
+ * A run that throws stores nothing: every caller sharing that run gets the
2222
+ * error, and the next call runs `fn` again. `ttl: 0` only shares in-flight
2223
+ * runs and never touches the store. See {@link IdempotentOptions} for
2224
+ * `distributed`.
2225
+ *
2226
+ * @example
2227
+ * const charge = await cache.idempotent(`charge.${orderId}`, () => gateway.charge(order), {
2228
+ * ttl: "24h",
2229
+ * });
2230
+ */
2231
+ async idempotent(key, fn, options) {
2232
+ this.ensureDriverInitialized();
2233
+ const driver = options.driver ? await this.load(options.driver) : this.currentDriver;
2234
+ return runIdempotent(driver, this.idempotentFlights, key, fn, options);
2235
+ }
2236
+ /**
2237
+ * {@inheritdoc}
1337
2238
  */
1338
2239
  async many(keys) {
1339
2240
  this.ensureDriverInitialized();
@@ -1475,6 +2376,12 @@ var CacheManager = class {
1475
2376
  }
1476
2377
  };
1477
2378
  const cache = new CacheManager();
2379
+ /**
2380
+ * Run `fn` once per `key` on the default `cache`. See {@link CacheManager.idempotent}.
2381
+ */
2382
+ function idempotent(key, fn, options) {
2383
+ return cache.idempotent(key, fn, options);
2384
+ }
1478
2385
 
1479
2386
  //#endregion
1480
2387
  //#region ../../packages/cache/src/cached/auto-key.ts
@@ -1910,6 +2817,12 @@ var TaggedCache = class TaggedCache {
1910
2817
  /**
1911
2818
  * {@inheritdoc}
1912
2819
  */
2820
+ async extend(key, ttl) {
2821
+ return this.driver.extend(key, ttl);
2822
+ }
2823
+ /**
2824
+ * {@inheritdoc}
2825
+ */
1913
2826
  async decrement(key, value = 1) {
1914
2827
  return this.increment(key, -value);
1915
2828
  }
@@ -2301,6 +3214,31 @@ var BaseCacheDriver = class {
2301
3214
  }
2302
3215
  /**
2303
3216
  * {@inheritdoc}
3217
+ *
3218
+ * Default implementation: read the value and write it back with the new ttl,
3219
+ * serialized per key in THIS process. Drivers with a native expiry command
3220
+ * or in-place metadata override it.
3221
+ */
3222
+ async extend(key, ttl) {
3223
+ const seconds = this.resolveExtendTtl(ttl);
3224
+ return this.runSerialized(this.parseKey(key), async () => {
3225
+ const value = await this.get(key);
3226
+ if (value === null) return false;
3227
+ await this.set(key, value, seconds);
3228
+ return true;
3229
+ });
3230
+ }
3231
+ /**
3232
+ * Resolve the `ttl` argument of `extend()` into seconds. `0` and `Infinity`
3233
+ * both mean "no expiry" and resolve to `Infinity`; negative numbers, NaN and
3234
+ * unparseable strings throw a `CacheConfigurationError`.
3235
+ */
3236
+ resolveExtendTtl(ttl) {
3237
+ const seconds = parseTtl(ttl);
3238
+ return seconds === 0 ? Infinity : seconds;
3239
+ }
3240
+ /**
3241
+ * {@inheritdoc}
2304
3242
  */
2305
3243
  async forever(key, value) {
2306
3244
  return this.set(key, value, Infinity);
@@ -2999,9 +3937,12 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
2999
3937
  this.log("clearing", parsedNamespace || "(all)");
3000
3938
  const removed = [];
3001
3939
  this.tagIndex.removeNamespace(parsedNamespace);
3002
- if (parsedNamespace === "") for (const key of this.cache.keys()) removed.push(key);
3003
- else {
3940
+ if (parsedNamespace === "") {
3941
+ this.structureStore?.clear();
3942
+ for (const key of this.cache.keys()) removed.push(key);
3943
+ } else {
3004
3944
  const prefix = parsedNamespace + ".";
3945
+ this.structureStore?.clearPrefix(prefix);
3005
3946
  for (const key of this.cache.keys()) if (key === parsedNamespace || key.startsWith(prefix)) removed.push(key);
3006
3947
  }
3007
3948
  for (const key of removed) {
@@ -3018,6 +3959,13 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
3018
3959
  /**
3019
3960
  * {@inheritdoc}
3020
3961
  */
3962
+ structuresBackend() {
3963
+ this.structureStore ??= new MemoryStructuresBackend((key) => this.parseKey(key));
3964
+ return this.structureStore;
3965
+ }
3966
+ /**
3967
+ * {@inheritdoc}
3968
+ */
3021
3969
  async set(key, value, ttlOrOptions) {
3022
3970
  const parsedKey = this.parseKey(key);
3023
3971
  const { ttl, tags, onConflict, vector, staleAt } = this.resolveSetOptions(ttlOrOptions);
@@ -3160,6 +4108,19 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
3160
4108
  /**
3161
4109
  * {@inheritdoc}
3162
4110
  *
4111
+ * The deadline moves in place, synchronously.
4112
+ */
4113
+ async extend(key, ttl) {
4114
+ const seconds = this.resolveExtendTtl(ttl);
4115
+ const node = this.liveNode(this.parseKey(key));
4116
+ if (!node) return false;
4117
+ node.expiresAt = Number.isFinite(seconds) ? Date.now() + seconds * 1e3 : void 0;
4118
+ this.moveHead(node);
4119
+ return true;
4120
+ }
4121
+ /**
4122
+ * {@inheritdoc}
4123
+ *
3163
4124
  * Read and unlink run synchronously, so a value is handed out exactly once
3164
4125
  * even when concurrent callers pull the same key.
3165
4126
  */
@@ -3277,6 +4238,7 @@ var LRUMemoryCacheDriver = class extends BaseCacheDriver {
3277
4238
  else {
3278
4239
  this.cache.clear();
3279
4240
  this.tagIndex.clear();
4241
+ this.structureStore?.clear();
3280
4242
  this.init();
3281
4243
  }
3282
4244
  this.log("flushed");
@@ -3386,6 +4348,13 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
3386
4348
  this.cleanupInterval.unref();
3387
4349
  }
3388
4350
  /**
4351
+ * {@inheritdoc}
4352
+ */
4353
+ structuresBackend() {
4354
+ this.structureStore ??= new MemoryStructuresBackend((key) => this.parseKey(key));
4355
+ return this.structureStore;
4356
+ }
4357
+ /**
3389
4358
  * Delete an entry and every side record (expiry, vector). Synchronous.
3390
4359
  */
3391
4360
  dropEntry(parsedKey) {
@@ -3436,11 +4405,13 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
3436
4405
  namespace = this.parseKey(namespace);
3437
4406
  this.tagIndex.removeNamespace(namespace);
3438
4407
  if (namespace === "") {
4408
+ this.structureStore?.clear();
3439
4409
  this.entries.clear();
3440
4410
  this.expiry.clear();
3441
4411
  this.vectorIndex.clear();
3442
4412
  } else {
3443
4413
  const prefix = namespace + ".";
4414
+ this.structureStore?.clearPrefix(prefix);
3444
4415
  for (const key of [...this.entries.keys()]) if (key === namespace || key.startsWith(prefix)) this.dropEntry(key);
3445
4416
  }
3446
4417
  this.log("cleared", namespace);
@@ -3537,6 +4508,29 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
3537
4508
  /**
3538
4509
  * {@inheritdoc}
3539
4510
  *
4511
+ * The deadline moves in place, synchronously, so concurrent callers never
4512
+ * interleave with the read.
4513
+ */
4514
+ async extend(key, ttl) {
4515
+ const seconds = this.resolveExtendTtl(ttl);
4516
+ const parsedKey = this.parseKey(key);
4517
+ const entry = this.readLive(parsedKey);
4518
+ if (!entry) return false;
4519
+ if (Number.isFinite(seconds)) {
4520
+ entry.ttl = seconds;
4521
+ entry.expiresAt = this.getExpiresAt(seconds);
4522
+ this.expiry.set(parsedKey, entry.expiresAt);
4523
+ } else {
4524
+ delete entry.ttl;
4525
+ delete entry.expiresAt;
4526
+ this.expiry.delete(parsedKey);
4527
+ }
4528
+ this.touch(parsedKey, entry);
4529
+ return true;
4530
+ }
4531
+ /**
4532
+ * {@inheritdoc}
4533
+ *
3540
4534
  * Read and delete run synchronously, so a value is handed out exactly once
3541
4535
  * even when concurrent callers pull the same key.
3542
4536
  */
@@ -3637,6 +4631,7 @@ var MemoryCacheDriver = class extends BaseCacheDriver {
3637
4631
  this.expiry.clear();
3638
4632
  this.vectorIndex.clear();
3639
4633
  this.tagIndex.clear();
4634
+ this.structureStore?.clear();
3640
4635
  }
3641
4636
  this.log("flushed");
3642
4637
  await this.emit("flushed");
@@ -3905,6 +4900,24 @@ var MockCacheDriver = class extends BaseCacheDriver {
3905
4900
  return newValue;
3906
4901
  }
3907
4902
  /**
4903
+ * Synchronous in-place deadline reset.
4904
+ */
4905
+ async extend(key, ttl) {
4906
+ const seconds = this.resolveExtendTtl(ttl);
4907
+ const parsedKey = this.parseKey(key);
4908
+ this.recordCall("extend", parsedKey, [ttl]);
4909
+ const entry = this.liveEntry(parsedKey);
4910
+ if (!entry) return false;
4911
+ if (Number.isFinite(seconds)) {
4912
+ entry.ttl = seconds;
4913
+ entry.expiresAt = Date.now() + seconds * 1e3;
4914
+ } else {
4915
+ delete entry.ttl;
4916
+ delete entry.expiresAt;
4917
+ }
4918
+ return true;
4919
+ }
4920
+ /**
3908
4921
  * Synchronous read-and-delete: a value is handed out exactly once.
3909
4922
  */
3910
4923
  async pull(key) {
@@ -4112,6 +5125,14 @@ var NullCacheDriver = class extends BaseCacheDriver {
4112
5125
  }
4113
5126
  /**
4114
5127
  * {@inheritdoc}
5128
+ *
5129
+ * The null driver stores nothing, so there is never an entry to extend.
5130
+ */
5131
+ async extend(_key, _ttl) {
5132
+ return false;
5133
+ }
5134
+ /**
5135
+ * {@inheritdoc}
4115
5136
  */
4116
5137
  async remove(key) {
4117
5138
  _warlock_js_logger.log.info("cache", "removing", this.loggableKey(key));
@@ -4609,6 +5630,23 @@ var PgCacheDriver = class extends BaseCacheDriver {
4609
5630
  /**
4610
5631
  * {@inheritdoc}
4611
5632
  *
5633
+ * One atomic `UPDATE … RETURNING` on a live row; an expired or missing row
5634
+ * updates nothing. `NULL` expiry means the row never expires.
5635
+ */
5636
+ async extend(key, ttl) {
5637
+ const seconds = this.resolveExtendTtl(ttl);
5638
+ const parsedKey = this.parseKey(key);
5639
+ const t = this.table;
5640
+ const { rows } = await this.pgClient.query(`/* cache:extend */ UPDATE ${t}
5641
+ SET expires_at = CASE WHEN $2::double precision IS NULL THEN NULL
5642
+ ELSE now() + make_interval(secs => $2::double precision) END
5643
+ WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())
5644
+ RETURNING key`, [parsedKey, this.ttlToSeconds(seconds)]);
5645
+ return rows.length > 0;
5646
+ }
5647
+ /**
5648
+ * {@inheritdoc}
5649
+ *
4612
5650
  * One atomic `DELETE … RETURNING`, so a value is handed out exactly once
4613
5651
  * across servers. Expired rows count as missing.
4614
5652
  */
@@ -5325,6 +6363,34 @@ var RedisCacheDriver = class extends BaseCacheDriver {
5325
6363
  return result || 0;
5326
6364
  }
5327
6365
  /**
6366
+ * {@inheritdoc}
6367
+ *
6368
+ * `PEXPIRE` (or `PERSIST` for no expiry) on the key and its freshness
6369
+ * sidecar: one atomic command, `0` when the key does not exist.
6370
+ */
6371
+ async extend(key, ttl) {
6372
+ const seconds = this.resolveExtendTtl(ttl);
6373
+ const parsedKey = this.parseKey(key);
6374
+ const client = this.client;
6375
+ const applied = Number.isFinite(seconds) ? await client.pExpire(parsedKey, Math.ceil(seconds * 1e3)) : await client.persist(parsedKey);
6376
+ if (!applied && Number.isFinite(seconds)) return false;
6377
+ if (!applied) return Number(await client.exists(parsedKey)) > 0;
6378
+ const sidecar = this.swrMetaKey(parsedKey);
6379
+ if (Number.isFinite(seconds)) await client.pExpire(sidecar, Math.ceil(seconds * 1e3));
6380
+ else await client.persist(sidecar);
6381
+ return true;
6382
+ }
6383
+ /**
6384
+ * {@inheritdoc}
6385
+ *
6386
+ * Uses RedisBloom (`BF.*`, `CF.*`, `CMS.*`, `TOPK.*`) when the server has
6387
+ * it, and plain Redis commands otherwise.
6388
+ */
6389
+ structuresBackend() {
6390
+ this.structureBackend ??= new RedisStructuresBackend(() => this.client, (key) => this.parseKey(key));
6391
+ return this.structureBackend;
6392
+ }
6393
+ /**
5328
6394
  * Atomic decrement using Redis native DECRBY command
5329
6395
  * {@inheritdoc}
5330
6396
  */
@@ -5383,6 +6449,7 @@ exports.LRUMemoryCacheDriver = LRUMemoryCacheDriver;
5383
6449
  exports.MemoryCacheDriver = MemoryCacheDriver;
5384
6450
  exports.MemoryCacheList = MemoryCacheList;
5385
6451
  exports.MemoryExtendedCacheDriver = MemoryExtendedCacheDriver;
6452
+ exports.MemoryStructuresBackend = MemoryStructuresBackend;
5386
6453
  exports.MockCacheDriver = MockCacheDriver;
5387
6454
  exports.NullCacheDriver = NullCacheDriver;
5388
6455
  exports.PgCacheDriver = PgCacheDriver;
@@ -5391,6 +6458,7 @@ exports.REDIS_COMPARE_DELETE_SCRIPT = REDIS_COMPARE_DELETE_SCRIPT;
5391
6458
  exports.REDIS_GET_DEL_SCRIPT = REDIS_GET_DEL_SCRIPT;
5392
6459
  exports.REDIS_INCREMENT_SCRIPT = REDIS_INCREMENT_SCRIPT;
5393
6460
  exports.RedisCacheDriver = RedisCacheDriver;
6461
+ exports.RedisStructuresBackend = RedisStructuresBackend;
5394
6462
  exports.ScopedCache = ScopedCache;
5395
6463
  exports.TaggedCache = TaggedCache;
5396
6464
  exports.TaggedScopedCache = TaggedScopedCache;
@@ -5399,7 +6467,9 @@ exports.cached = cached;
5399
6467
  exports.cosineSimilarity = cosineSimilarity;
5400
6468
  exports.deriveAutoKey = deriveAutoKey;
5401
6469
  exports.expiresAtToTtl = expiresAtToTtl;
6470
+ exports.idempotent = idempotent;
5402
6471
  exports.injectTags = injectTags;
6472
+ exports.isStructuresCapable = isStructuresCapable;
5403
6473
  exports.mergeTagSets = mergeTagSets;
5404
6474
  exports.normalizeCachedArgs = normalizeCachedArgs;
5405
6475
  exports.normalizeToOptions = normalizeToOptions;