@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/llms.txt CHANGED
@@ -17,10 +17,13 @@
17
17
  - [test-cache-code](@warlock.js/cache/skills/test-cache-code/SKILL.md): Test code that touches cache — MockCacheDriver (behavioral assertions with wasCalled / callLog), MemoryCacheDriver (full-stack), NullCacheDriver (graceful-degradation). Triggers: `MockCacheDriver`, `MemoryCacheDriver`, `NullCacheDriver`, `wasCalled`, `callLog`, `getStored`, `reset`, `cache.on`; "assert cache was invalidated", "test code that uses cache.set", "mock cache in vitest", "test similarity without a real embedder", "stub the pg cache driver"; typical import `import { cache, MockCacheDriver, MemoryCacheDriver } from "@warlock.js/cache"`. Skip: real driver picks — the `pick-cache-driver` topic; competing libs `jest-mock`, `sinon`, `redis-mock`; native `vi.fn`.
18
18
  - [use-cache-atomic](@warlock.js/cache/skills/use-cache-atomic/SKILL.md): Atomic counters via cache.increment(key, by=1, { ttl }?) / cache.decrement(key, by=1) — returns the new number, throws on non-numeric values. Triggers: `cache.increment`, `cache.decrement`, "view counter", "page views", "atomic counter", "decrement stock", "rate-limit counter", "INCRBY"; typical import `import { cache } from "@warlock.js/cache"`. Skip: read-modify-write of objects — the `use-cache-update-merge` topic; named-lock coordination — the `use-cache-lock` topic; competing libs `ioredis` `INCR`, native counters in a `Map`.
19
19
  - [use-cache-bulk](@warlock.js/cache/skills/use-cache-bulk/SKILL.md): Bulk reads/writes via cache.many(keys[]) → values[] (nulls for misses, order preserved) and cache.setMany(record, ttl?) → void. Triggers: `cache.many`, `cache.setMany`, "get multiple keys at once", "batch read cache", "warm the cache", "preload many keys", "mget", "mset"; typical import `import { cache } from "@warlock.js/cache"`. Skip: tag-based bulk invalidation — the `use-cache-tags` topic; single-key ops — the `cache-basics` topic; competing libs `ioredis` `MGET`/`MSET`.
20
+ - [use-cache-extend](@warlock.js/cache/skills/use-cache-extend/SKILL.md): Sliding expiry via cache.extend(key, ttl) — keeps the value and resets expiry to ttl from now (not added to time left); false when the key is missing. Triggers: `cache.extend`, "keep the session alive", "sliding expiration", "touch a cache key", Laravel `Cache::touch`. Skip: refresh the value — `cache.set`; slide on every read — `memoryExtended` driver in `pick-cache-driver`.
21
+ - [use-cache-idempotent](@warlock.js/cache/skills/use-cache-idempotent/SKILL.md): Run-once-per-key via idempotent(key, fn, {ttl}) or cache.idempotent — concurrent calls share one run, repeats within ttl replay the stored result, ttl 0 is in-flight dedupe only, failures are never stored. Triggers: `idempotent`, "Idempotency-Key", "dedupe payment", "webhook delivered twice", "retried job". Skip: skip-if-busy lock — `use-cache-lock`; HTTP header middleware — core `idempotency` middleware.
20
22
  - [use-cache-list](@warlock.js/cache/skills/use-cache-list/SKILL.md): Ordered collections via cache.list<T>(key) — push / unshift / pop / shift / slice / all / length / trim / clear. Triggers: `cache.list`, `push`, `unshift`, `pop`, `shift`, `slice`, `trim`, `clear`; "job queue in cache", "keep most recent N events", "audit log buffer", "FIFO queue"; typical import `import { cache } from "@warlock.js/cache"`. Skip: locking around list writes — the `use-cache-lock` topic; competing libs `bullmq`, `bee-queue`, `bull`, `ioredis` `LPUSH`; native `Array.push`.
21
23
  - [use-cache-lock](@warlock.js/cache/skills/use-cache-lock/SKILL.md): Distributed lock via cache.lock(key, ttl, fn) — acquire, run fn, auto-release. Returns {acquired: true, value} or {acquired: false}. Triggers: `cache.lock`, `LockOutcome`, `acquired`, `owner`; "run cron on only one server", "idempotent webhook handler", "dedup payment processing", "lock a task across nodes"; typical import `import { cache } from "@warlock.js/cache"`. Skip: raw `onConflict: "create"` recipe — the `apply-cache-patterns` topic; memoization — the `use-cached-hof` topic; competing libs `redlock`, `async-mutex`, `proper-lockfile`.
22
24
  - [use-cache-namespace](@warlock.js/cache/skills/use-cache-namespace/SKILL.md): Scope cache keys via cache.namespace(prefix, options?) — every key auto-prefixed, scope-level ttl / tags defaults, nested scopes, .clear() sugar. Triggers: `cache.namespace`, `cache.removeNamespace`, `clear`, `globalPrefix`; "scope cache keys under a prefix", "share TTL across a whole prefix", "drop every key under user.1", "nested cache scopes"; typical import `import { cache } from "@warlock.js/cache"`. Skip: tag-based bulk drop — the `use-cache-tags` topic; multi-tenant driver-level prefix — the `pick-cache-driver` topic; SWR — the `use-swr` topic; competing libs `keyv` namespaces.
23
25
  - [use-cache-similarity](@warlock.js/cache/skills/use-cache-similarity/SKILL.md): Vector retrieval via cache.similar(vector, {topK, threshold?, tags?}) — index with set(k, v, {vector}), query nearest by cosine similarity. Triggers: `cache.similar`, `cache.set` with `vector`, `topK`, `threshold`, `tags`, `cosineSimilarity`; "build a semantic cache for an LLM", "RAG retrieval from cache", "nearest-neighbor over cached entries", "skip the LLM when a similar answer exists"; typical import `import { cache } from "@warlock.js/cache"`. Skip: pgvector setup specifics — the `configure-pg-cache` topic; competing libs `pinecone`, `weaviate`, `chromadb`, `lancedb`, `faiss-node`.
26
+ - [use-cache-structures](@warlock.js/cache/skills/use-cache-structures/SKILL.md): Probabilistic structures on the cache manager — cache.structures.bloom, cuckoo, uniqueCounter (HyperLogLog, .merge), frequency (Count-Min + Top-K) on redis and memory drivers. Triggers: `cache.structures`, "username taken check", "daily active users", "top search terms", "bloom filter"; other drivers throw `CacheUnsupportedError`. Skip: exact sets — `cache.list`; exact counters — `use-cache-atomic`.
24
27
  - [use-cache-tags](@warlock.js/cache/skills/use-cache-tags/SKILL.md): Tag-based invalidation — attach tags on write, then cache.tags([...]).invalidate() drops every key bound to any of those tags. Triggers: `cache.tags`, `invalidate`, `cache.set` with `tags`; "invalidate every key tagged users", "drop everything for tenant 42", "bulk cache invalidation without knowing keys", "tag a cached value"; typical import `import { cache } from "@warlock.js/cache"`. Skip: prefix-based drop — the `use-cache-namespace` topic; HOF memoization with tags — the `use-cached-hof` topic; SWR — the `use-swr` topic; competing libs `cache-manager` tags, Next.js `revalidateTag`.
25
28
  - [use-cache-update-merge](@warlock.js/cache/skills/use-cache-update-merge/SKILL.md): Atomic read-modify-write via cache.update(key, fn) (callback receives current) or cache.merge(key, partial) (shallow merge). Per-key chain lock serializes concurrent in-process callers. Triggers: `cache.update`, `cache.merge`, `cache.increment`, `cache.pull`; "atomically update a cached counter", "change one field on a cached object", "avoid get-spread-set race", "serialize concurrent cache writers"; typical import `import { cache } from "@warlock.js/cache"`. Skip: cross-process locking — the `use-cache-lock` topic; conditional create/update — the `configure-set-options` topic; competing libs `lodash.merge`, raw redis `WATCH`/`MULTI`.
26
29
  - [use-cache-utils](@warlock.js/cache/skills/use-cache-utils/SKILL.md): Low-level cache utilities re-exported from @warlock.js/cache — parseTtl, expiresAtToTtl, resolveTtl, normalizeToOptions, normalizeToRememberOptions, parseCacheKey, mergeTagSets, injectTags, cosineSimilarity, and the CACHE_FOR TTL enum. Triggers: `parseTtl`, `parseCacheKey`, `resolveTtl`, `expiresAtToTtl`, `cosineSimilarity`, `mergeTagSets`, `injectTags`, `CACHE_FOR`; "parse a duration to seconds", "build a cache key from an object", "score two vectors", "common TTL constant"; typical import `import { parseTtl, CACHE_FOR } from "@warlock.js/cache"`. Skip: building a whole custom driver — the `pick-cache-driver` topic; the high-level set API — the `configure-set-options` topic.
package/package.json CHANGED
@@ -5,9 +5,9 @@
5
5
  "environment": "server"
6
6
  },
7
7
  "dependencies": {
8
- "@warlock.js/fs": "5.42.0",
8
+ "@warlock.js/fs": "5.43.0",
9
9
  "@mongez/reinforcements": "^4.0.2",
10
- "@warlock.js/logger": "5.42.0",
10
+ "@warlock.js/logger": "5.43.0",
11
11
  "ms": "^2.1.3"
12
12
  },
13
13
  "peerDependencies": {
@@ -47,7 +47,7 @@
47
47
  ],
48
48
  "author": "hassanzohdy",
49
49
  "license": "MIT",
50
- "version": "5.42.0",
50
+ "version": "5.43.0",
51
51
  "main": "./cjs/index.cjs",
52
52
  "module": "./esm/index.mjs",
53
53
  "types": "./esm/index.d.mts",
package/skills/index.md CHANGED
@@ -14,7 +14,9 @@ The `cache` singleton (a `CacheManager`) fronts one active driver. Everything, f
14
14
  4. Invalidate in groups: `use-cache-tags.md` or `use-cache-namespace.md`.
15
15
  5. Stampede protection and freshness: `use-swr.md`, `use-cache-lock.md`.
16
16
  6. TTL constants, key parsing and vector helpers: `use-cache-utils.md`.
17
- 7. Test with the mock driver: `test-cache-code.md`; errors and metrics: `handle-cache-errors.md`, `observe-cache.md`.
17
+ 7. Keep sessions alive and run work once: `use-cache-extend.md` (sliding expiry), `use-cache-idempotent.md` (payments, webhooks, retried jobs).
18
+ 8. Probabilistic structures (Bloom, cuckoo, unique counter, frequency): `use-cache-structures.md`.
19
+ 9. Test with the mock driver: `test-cache-code.md`; errors and metrics: `handle-cache-errors.md`, `observe-cache.md`.
18
20
 
19
21
  ## Conventions and pitfalls
20
22
 
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: use-cache-extend
3
+ description: 'Sliding expiry via cache.extend(key, ttl) — keeps the value and resets expiry to ttl from now (not added to time left); false when the key is missing. Triggers: `cache.extend`, "keep the session alive", "sliding expiration", "touch a cache key", Laravel `Cache::touch`. Skip: refresh the value — `cache.set`; slide on every read — `memoryExtended` driver in `pick-cache-driver`.'
4
+ ---
5
+
6
+ # `cache.extend(key, ttl)` — sliding expiry
7
+
8
+ Keeps the cached value and makes it expire `ttl` from now. Resolves to `true` when extended, `false` when the key is missing or already expired (nothing is created).
9
+
10
+ ```ts
11
+ const alive = await cache.extend(`session.${id}`, "30m");
12
+ ```
13
+
14
+ ## Rules
15
+
16
+ - It RESETS the deadline to `ttl` from the call. It does not add `ttl` to the time left: a 10-minute entry with 4 minutes left, extended by `"10m"`, expires in 10 minutes, not 14. A shorter `ttl` shortens the entry.
17
+ - `ttl` takes the same forms as `set`: seconds or a duration string. `0` or `Infinity` removes the expiry. Negative, `NaN` or an unparseable string throws `CacheConfigurationError`.
18
+ - Works on `cache`, `cache.namespace(...)` (key is prefixed) and `cache.tags(...)` (tags untouched).
19
+ - Redis uses one atomic `PEXPIRE`; `pg` one `UPDATE`; memory drivers update in place; `file` and custom `BaseCacheDriver` subclasses read and rewrite the value. `null` always returns `false`.
20
+ - Laravel calls this `Cache::touch`.
21
+
22
+ Docs: `/v/latest/cache/extend/`.
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: use-cache-idempotent
3
+ description: 'Run-once-per-key via idempotent(key, fn, {ttl}) or cache.idempotent — concurrent calls share one run, repeats within ttl replay the stored result, ttl 0 is in-flight dedupe only, failures are never stored. Triggers: `idempotent`, "Idempotency-Key", "dedupe payment", "webhook delivered twice", "retried job". Skip: skip-if-busy lock — `use-cache-lock`; HTTP header middleware — core `idempotency` middleware.'
4
+ ---
5
+
6
+ # `idempotent(key, fn, { ttl })`
7
+
8
+ ```ts
9
+ import { idempotent } from "@warlock.js/cache";
10
+
11
+ const charge = await idempotent(`charge.${order.id}`, () => gateway.charge(order), { ttl: "24h" });
12
+ ```
13
+
14
+ `cache.idempotent(...)` is the same call on the manager.
15
+
16
+ ## Behaviour
17
+
18
+ - Concurrent calls with one key share a single run (per process).
19
+ - Repeat calls within `ttl` return the stored result without calling `fn`. Falsy, `null` and `undefined` results are stored too.
20
+ - `ttl: 0` is pure in-flight dedupe: nothing is read from or written to the cache.
21
+ - A run that throws stores nothing; all callers sharing it get the error; the next call runs `fn` again.
22
+ - Results live in the cache store under `idempotent.<key>`, so with Redis or Postgres a result is shared across servers.
23
+ - Two servers at the same instant each run `fn` unless `distributed: true`, which takes the cache lock (`lockTtl`, default `"30s"`, must exceed `fn`'s duration); waiters read the stored result, take over if the holder fails, and throw `CacheConcurrencyError` after `lockTtl`.
24
+ - If storing the result fails, the result is still returned and the failure is logged.
25
+ - Options: `ttl` (required), `distributed`, `lockTtl`, `driver`.
26
+
27
+ Docs: `/v/latest/cache/idempotent/`.
@@ -0,0 +1,48 @@
1
+ ---
2
+ name: use-cache-structures
3
+ description: 'Probabilistic structures on the cache manager — cache.structures.bloom, cuckoo, uniqueCounter (HyperLogLog, .merge), frequency (Count-Min + Top-K) on redis and memory drivers. Triggers: `cache.structures`, "username taken check", "daily active users", "top search terms", "bloom filter"; other drivers throw `CacheUnsupportedError`. Skip: exact sets — `cache.list`; exact counters — `use-cache-atomic`.'
4
+ ---
5
+
6
+ # `cache.structures`
7
+
8
+ Small structures that trade a known error for tiny memory. Supported on `redis` (RedisBloom when present, plain Redis otherwise) and `memory` / `memoryExtended` / `lru`. All other drivers throw `CacheUnsupportedError`. Every structure takes `ttl`, applied when it is first written and never pushed back.
9
+
10
+ ```ts
11
+ const names = cache.structures.bloom("users.usernames", {
12
+ expectedItems: 1_000_000,
13
+ errorRate: 0.01,
14
+ });
15
+ await names.add("hasan");
16
+ await names.mightContain(input); // false = definitely free
17
+
18
+ const banned = cache.structures.cuckoo("users.banned", { expectedItems: 100_000 });
19
+ await banned.add(id);
20
+ await banned.remove(id); // only remove what was added
21
+
22
+ const dau = cache.structures.uniqueCounter(`stats.dau.${today}`, { ttl: "40d" });
23
+ await dau.add(userId);
24
+ await dau.count();
25
+ await cache.structures.uniqueCounter.merge(lastSevenDaysKeys).count();
26
+
27
+ const terms = cache.structures.frequency("search.terms", {
28
+ width: 2000,
29
+ depth: 5,
30
+ topK: 100,
31
+ ttl: "1h",
32
+ });
33
+ await terms.add(term);
34
+ await terms.estimate("laptop");
35
+ await terms.top(10); // [{ value, count }]
36
+ ```
37
+
38
+ ## Facts
39
+
40
+ - Bloom: 1M items at 1% is about 1.2 MB, 7 hashes. No removal, no listing. Not for exact "yes" decisions.
41
+ - Cuckoo: real filter on RedisBloom; a counting Bloom filter elsewhere. Removing a never-added item corrupts it.
42
+ - Unique counter: 12 KB, standard error 0.81%. Cannot answer "was X counted". Not for billing.
43
+ - Frequency: 2000 x 5 is about 40 KB. Estimates are never below the true count. Not for rare values.
44
+ - Keys follow the driver prefix and are stored as `structures.<kind>.<key>`.
45
+ - A custom driver opts in with `structuresBackend(): CacheStructuresBackend` (the `StructuresCapable` shape; `isStructuresCapable(driver)` checks it). It can return a built-in backend instead of writing its own: `new MemoryStructuresBackend((key) => this.parseKey(key))`, created once and reused, or `new RedisStructuresBackend(() => client, (key) => this.parseKey(key))` for a driver that wraps a Redis client.
46
+ - Handle types for annotations: `BloomFilter`, `CuckooFilter`, `UniqueCounter`, `UniqueCounterGroup` (from `uniqueCounter.merge`), `FrequencyTracker`. Create them through `cache.structures`, never with `new`.
47
+
48
+ Docs: `/v/latest/cache/structures/`.