cacheable 2.3.4 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +313 -33
- package/dist/index.cjs +1307 -1142
- package/dist/index.d.cts +741 -469
- package/dist/index.d.mts +766 -0
- package/dist/index.mjs +1210 -0
- package/package.json +13 -13
- package/dist/index.d.ts +0 -494
- package/dist/index.js +0 -1130
package/README.md
CHANGED
|
@@ -29,9 +29,13 @@
|
|
|
29
29
|
* [v1 to v2 Changes](#v1-to-v2-changes)
|
|
30
30
|
* [Basic Usage](#basic-usage)
|
|
31
31
|
* [Hooks and Events](#hooks-and-events)
|
|
32
|
+
* [Overriding the TTL in a BEFORE_SET Hook](#overriding-the-ttl-in-a-before_set-hook)
|
|
32
33
|
* [Storage Tiering and Caching](#storage-tiering-and-caching)
|
|
33
34
|
* [TTL Propagation and Storage Tiering](#ttl-propagation-and-storage-tiering)
|
|
35
|
+
* [Per-Store TTL per Operation](#per-store-ttl-per-operation)
|
|
34
36
|
* [Shorthand for Time to Live (ttl)](#shorthand-for-time-to-live-ttl)
|
|
37
|
+
* [Maximum Time to Live (maxTtl)](#maximum-time-to-live-maxttl)
|
|
38
|
+
* [Tag Based Invalidation](#tag-based-invalidation)
|
|
35
39
|
* [Iteration on Primary and Secondary Stores](#iteration-on-primary-and-secondary-stores)
|
|
36
40
|
* [Non-Blocking Operations](#non-blocking-operations)
|
|
37
41
|
* [Non-Blocking with @keyv/redis](#non-blocking-with-keyvredis)
|
|
@@ -39,6 +43,7 @@
|
|
|
39
43
|
* [Cacheable Options](#cacheable-options)
|
|
40
44
|
* [Cacheable Statistics (Instance Only)](#cacheable-statistics-instance-only)
|
|
41
45
|
* [Cacheable - API](#cacheable---api)
|
|
46
|
+
* [Static Instance (Singleton)](#static-instance-singleton)
|
|
42
47
|
* [CacheableMemory - In-Memory Cache](#cacheablememory---in-memory-cache)
|
|
43
48
|
* [Keyv Storage Adapter - KeyvCacheableMemory](#keyv-storage-adapter---keyvcacheablememory)
|
|
44
49
|
* [Wrap / Memoization for Sync and Async Functions](#wrap--memoization-for-sync-and-async-functions)
|
|
@@ -114,6 +119,61 @@ cacheable.onHook(CacheableHooks.BEFORE_SET, (data) => {
|
|
|
114
119
|
});
|
|
115
120
|
```
|
|
116
121
|
|
|
122
|
+
## Overriding the TTL in a BEFORE_SET Hook
|
|
123
|
+
|
|
124
|
+
A `BEFORE_SET` hook can change an entry's time-to-live by reassigning `data.ttl`. This works for `set()`, `getOrSet()`, and `wrap()` because they all run through `BEFORE_SET`. You can assign a single value (applied to every store) or a per-store object so the primary and secondary stores expire at different rates:
|
|
125
|
+
|
|
126
|
+
```javascript
|
|
127
|
+
import { Cacheable, CacheableHooks } from 'cacheable';
|
|
128
|
+
import KeyvRedis from '@keyv/redis';
|
|
129
|
+
const secondary = new KeyvRedis('redis://user:pass@localhost:6379');
|
|
130
|
+
const cache = new Cacheable({ secondary });
|
|
131
|
+
|
|
132
|
+
cache.onHook(CacheableHooks.BEFORE_SET, (data) => {
|
|
133
|
+
// Keep this entry short-lived in memory (primary) but longer in Redis (secondary)
|
|
134
|
+
data.ttl = { primary: '10s', secondary: '5m' };
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Each store resolves its TTL independently, taking the first defined value down this list and then capping it with [`maxTtl`](#maximum-time-to-live-maxttl). This is the single source of truth for how *every* TTL (operation, hook, or default) is resolved:
|
|
139
|
+
|
|
140
|
+
| Precedence (highest first) | Primary store | Secondary store |
|
|
141
|
+
| --- | --- | --- |
|
|
142
|
+
| 1. `BEFORE_SET` hook | `data.ttl` (scalar, or `.primary`) | `data.ttl` (scalar, or `.secondary`) |
|
|
143
|
+
| 2. Operation `ttl` | `ttl` (scalar, or `.primary`) | `ttl` (scalar, or `.secondary`) |
|
|
144
|
+
| 3. Store default | `new Keyv({ ttl })` on the primary | `new Keyv({ ttl })` on the secondary |
|
|
145
|
+
| 4. Instance `ttl` | `new Cacheable({ ttl })` | `new Cacheable({ ttl })` |
|
|
146
|
+
| Cap (applied last) | `maxTtl` | `maxTtl` |
|
|
147
|
+
|
|
148
|
+
What happens when you override:
|
|
149
|
+
|
|
150
|
+
* **Per-store object** (`{ primary, secondary }`): each field applies to that store independently. A field you leave out falls back to that store's normal resolution — including any per-store `ttl` you passed to the operation.
|
|
151
|
+
* **Scalar** (a number or [shorthand string](#shorthand-for-time-to-live-ttl)): applied to **every** store, discarding any per-store `secondary` you passed to the operation. Use the object form if you want the stores to differ.
|
|
152
|
+
* **Any assignment counts as an override**, even assigning the value `data.ttl` already holds. Leaving `data.ttl` untouched keeps each store on its normal resolution (the default behavior).
|
|
153
|
+
* **`0`, `null`, or `undefined` clears the TTL** → the entry never expires, *ignoring* the cascade (store default and instance `ttl`). This matches the "disable the ttl" behavior in [Shorthand for Time to Live](#shorthand-for-time-to-live-ttl); take care when assigning a possibly-nullable value to `data.ttl`.
|
|
154
|
+
* **An invalid shorthand string aborts the whole write.** Assigning an unparseable string (e.g. `'10 seconds'`) throws; `set` catches it, emits the [`error` event](#hooks-and-events), and returns `false` **without caching** — so a hook typo silently disables caching for that write. Listen on `error` to catch it.
|
|
155
|
+
* **`maxTtl` is re-applied to each store after the hook**, so a hook can never push an entry past the cap.
|
|
156
|
+
* **Tag snapshots** use the longer of the two store TTLs (and never expire while either copy is immortal, including `ttl: 0`) so [tag invalidation](#tag-based-invalidation) can always reach the longest-lived copy.
|
|
157
|
+
* By the time **`AFTER_SET`** runs (and for [sync replication](#cacheablesync---distributed-updates)), `data.ttl` has been normalized to the effective **primary** TTL as a number; the secondary store's effective TTL is not exposed on the item. **`AFTER_SET_MANY` differs:** `setMany` does not mutate the items you passed, so a handler there still sees each `item.ttl` exactly as set (a per-store object stays an object).
|
|
158
|
+
|
|
159
|
+
> **TypeScript:** `onHook(CacheableHooks.BEFORE_SET, (data) => …)` types `data` automatically — no annotation needed, and an invalid `data.ttl` shape is a compile error. Payload types are exported too (`CacheableHookItem`, `CacheableSetItem`).
|
|
160
|
+
|
|
161
|
+
> **Note on backfills:** like a per-store `ttl` passed to an operation, a primary TTL set by a hook governs only that write — it is not persisted per key. Once the primary copy expires, the next read repopulates the primary from the secondary using the usual [TTL propagation](#ttl-propagation-and-storage-tiering) rules. Set a primary store default TTL (`new Keyv({ ttl })`) or an instance `maxTtl` if you need the primary to stay short across backfills.
|
|
162
|
+
|
|
163
|
+
> **Note on sync:** a per-store TTL writes the secondary's TTL to the (typically shared) secondary store directly; [CacheableSync](#cacheablesync---distributed-updates) replicates only the **primary** TTL to other instances' in-memory primaries. For the usual shared-secondary topology this is correct — the secondary is written once and read by every instance.
|
|
164
|
+
|
|
165
|
+
The same per-store object is accepted by `setMany` items and the `BEFORE_SET_MANY` hook:
|
|
166
|
+
|
|
167
|
+
```javascript
|
|
168
|
+
cache.onHook(CacheableHooks.BEFORE_SET_MANY, (items) => {
|
|
169
|
+
for (const item of items) {
|
|
170
|
+
item.ttl = { primary: '10s', secondary: '5m' };
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
await cache.setMany([{ key: 'a', value: 1, ttl: { primary: '10s', secondary: '5m' } }]);
|
|
175
|
+
```
|
|
176
|
+
|
|
117
177
|
Here is an example of how to use `BEFORE_SECONDARY_SETS_PRIMARY` hook:
|
|
118
178
|
|
|
119
179
|
```javascript
|
|
@@ -125,7 +185,7 @@ cache.onHook(CacheableHooks.BEFORE_SECONDARY_SETS_PRIMARY, (data) => {
|
|
|
125
185
|
console.log(`before secondary sets primary: ${data.key} ${data.value} ${data.ttl}`);
|
|
126
186
|
});
|
|
127
187
|
```
|
|
128
|
-
This is called when the secondary store sets the value in the primary store. This is useful if you want to do something before the value is set in the primary store such as manipulating the ttl or the value.
|
|
188
|
+
This is called when the secondary store sets the value in the primary store. This is useful if you want to do something before the value is set in the primary store such as manipulating the ttl or the value. Because this hook only writes the primary store, its `ttl` is a single value (a number or shorthand string), not a per-store object.
|
|
129
189
|
|
|
130
190
|
The following events are provided:
|
|
131
191
|
|
|
@@ -171,8 +231,9 @@ When `Getting Data` if the value does not exist in the primary store it will try
|
|
|
171
231
|
|
|
172
232
|
```javascript
|
|
173
233
|
import { Cacheable } from 'cacheable';
|
|
234
|
+
import {Keyv} from 'keyv';
|
|
174
235
|
import KeyvRedis from '@keyv/redis';
|
|
175
|
-
const secondary = new KeyvRedis('redis://user:pass@localhost:6379',
|
|
236
|
+
const secondary = new Keyv({ store: new KeyvRedis('redis://user:pass@localhost:6379'), ttl: 1000 });
|
|
176
237
|
const cache = new Cacheable({secondary, ttl: 100});
|
|
177
238
|
|
|
178
239
|
await cache.set('key', 'value'); // sets the value in the primary store with a ttl of 100 ms and secondary store with a ttl of 1000 ms
|
|
@@ -189,10 +250,10 @@ import { Cacheable } from 'cacheable';
|
|
|
189
250
|
import {Keyv} from 'keyv';
|
|
190
251
|
import KeyvRedis from '@keyv/redis';
|
|
191
252
|
const primary = new Keyv({ ttl: 200 });
|
|
192
|
-
const secondary = new KeyvRedis('redis://user:pass@localhost:6379',
|
|
253
|
+
const secondary = new Keyv({ store: new KeyvRedis('redis://user:pass@localhost:6379'), ttl: 1000 });
|
|
193
254
|
const cache = new Cacheable({primary, secondary});
|
|
194
255
|
|
|
195
|
-
await cache.set('key', 'value'); // sets the value in the primary store with a ttl of
|
|
256
|
+
await cache.set('key', 'value'); // sets the value in the primary store with a ttl of 200 ms and secondary store with a ttl of 1000 ms
|
|
196
257
|
|
|
197
258
|
await sleep(200); // wait for .2 seconds
|
|
198
259
|
|
|
@@ -209,6 +270,43 @@ ttl = set at the function ?? storage adapter ttl ?? cacheable ttl
|
|
|
209
270
|
|
|
210
271
|
This means that if you set a TTL at the function level it will override the storage adapter TTL and the cacheable TTL. If you do not set a TTL at the function level it will use the storage adapter TTL and then the cacheable TTL. If you do not set a TTL at all it will use the default TTL of `undefined` which is disabled.
|
|
211
272
|
|
|
273
|
+
# Per-Store TTL per Operation
|
|
274
|
+
|
|
275
|
+
When you override the `ttl` on an operation it normally applies to both the primary and secondary stores. If you want each store to expire at a different rate for that specific key, pass a per-store object as the `ttl` with `primary` and/or `secondary` fields. Each field accepts a number in milliseconds or a [shorthand string](#shorthand-for-time-to-live-ttl).
|
|
276
|
+
|
|
277
|
+
```javascript
|
|
278
|
+
import { Cacheable } from 'cacheable';
|
|
279
|
+
import { Keyv } from 'keyv';
|
|
280
|
+
import KeyvRedis from '@keyv/redis';
|
|
281
|
+
const secondary = new KeyvRedis('redis://user:pass@localhost:6379');
|
|
282
|
+
const cache = new Cacheable({ secondary });
|
|
283
|
+
|
|
284
|
+
// Keep this key 10 seconds in memory (primary) but 5 minutes in Redis (secondary)
|
|
285
|
+
await cache.set('key', 'value', { ttl: { primary: '10s', secondary: '5m' } });
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Any field you leave out falls back to that store's own default TTL resolution (storage adapter TTL, then the cacheable instance TTL). For example, only overriding the primary store leaves the secondary on its default:
|
|
289
|
+
|
|
290
|
+
```javascript
|
|
291
|
+
const secondary = new Keyv({ store: new KeyvRedis('redis://user:pass@localhost:6379'), ttl: '1h' });
|
|
292
|
+
const cache = new Cacheable({ secondary });
|
|
293
|
+
|
|
294
|
+
// Primary expires in 10s; secondary keeps its own 1 hour default
|
|
295
|
+
await cache.set('key', 'value', { ttl: { primary: '10s' } });
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
The per-store object works anywhere a `ttl` is accepted, including [`getOrSet`](#get-or-set-memoization-function) and [`wrap`](#wrap--memoization-for-sync-and-async-functions):
|
|
299
|
+
|
|
300
|
+
```javascript
|
|
301
|
+
await cache.getOrSet('key', async () => 'value', { ttl: { primary: '10s', secondary: '5m' } });
|
|
302
|
+
|
|
303
|
+
const getUser = cache.wrap(fetchUser, { ttl: { primary: '1m', secondary: '1d' } });
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Passing a plain number or shorthand string (such as `'1h'`) still applies the same TTL to every store, and the [`maxTtl`](#maximum-time-to-live-maxttl) cap is applied to each store independently. The same per-store object is accepted by `setMany` items, and a [`BEFORE_SET` hook](#overriding-the-ttl-in-a-before_set-hook) can override these per-store TTLs and takes precedence over the value passed to the operation.
|
|
307
|
+
|
|
308
|
+
> **Note on backfills:** A per-store TTL (whether passed to the operation or set by a `BEFORE_SET` hook) governs the *write* of that operation. The primary TTL is not persisted per key, so once a primary (layer 1) entry expires, the next read is served from the secondary and repopulates the primary using the secondary's remaining lifetime — following the usual [TTL propagation](#ttl-propagation-and-storage-tiering) rules — rather than re-applying the original primary TTL. If you need the primary to keep a consistently shorter lifetime across backfills, set a primary store default TTL (`new Keyv({ ttl })`) or an instance `maxTtl`, which both bound the repopulated TTL.
|
|
309
|
+
|
|
212
310
|
# Shorthand for Time to Live (ttl)
|
|
213
311
|
|
|
214
312
|
By default `Cacheable` and `CacheableMemory` the `ttl` is in milliseconds but you can use shorthand for the time to live. Here are the following shorthand values:
|
|
@@ -302,42 +400,88 @@ The `hasMany` method returns an array of booleans in the same order as the input
|
|
|
302
400
|
|
|
303
401
|
# Iteration on Primary and Secondary Stores
|
|
304
402
|
|
|
305
|
-
The `Cacheable` class exposes both `primary` and `secondary` Keyv instances,
|
|
403
|
+
The `Cacheable` class exposes both `primary` and `secondary` as [Keyv](https://keyv.org) instances. Keyv provides an `iterator()` async generator for walking every entry in a store, but **it is only available on stores that support iteration**. When a store does not support it, `keyv.iterator` is `undefined`, so you must feature-check it before calling.
|
|
404
|
+
|
|
405
|
+
Keyv enables `iterator()` for:
|
|
406
|
+
|
|
407
|
+
- A plain `new Keyv()` whose store is a `Map` (the Keyv default), and
|
|
408
|
+
- The server-backed adapters Keyv recognizes as iterable: `@keyv/redis`, `@keyv/valkey`, `@keyv/mongo`, `@keyv/sqlite`, `@keyv/postgres`, `@keyv/mysql`, and `@keyv/etcd`.
|
|
409
|
+
|
|
410
|
+
> **Heads up:** Cacheable's *default* primary store is the high-performance in-memory store from [`@cacheable/memory`](https://cacheable.org/docs/memory/) (created with `createKeyv()`). It is neither a raw `Map` nor one of the recognized adapters, so `cache.primary.iterator` is `undefined`. See [Iterating the default in-memory primary](#iterating-the-default-in-memory-primary) for how to walk it.
|
|
306
411
|
|
|
307
412
|
**Important Notes:**
|
|
308
|
-
- Not all storage adapters support iteration. Always check if `iterator` exists before using it.
|
|
309
|
-
- The iterator automatically filters by namespace, skips expired entries (and deletes them), and deserializes values.
|
|
310
|
-
- **Performance Warning:** Be careful when using `iterator()` as it can cause performance issues with large datasets.
|
|
311
413
|
|
|
312
|
-
|
|
414
|
+
- Always check that `iterator` exists before using it — it is `undefined` on stores that don't support iteration.
|
|
415
|
+
- The iterator filters by namespace, skips expired entries (deleting them), and deserializes values for you.
|
|
416
|
+
- **Performance Warning:** Iterating can be expensive on large datasets (for example, `@keyv/redis` uses `SCAN` under the hood). Avoid it on hot paths.
|
|
417
|
+
|
|
418
|
+
## Iterating a Secondary Store
|
|
419
|
+
|
|
420
|
+
A secondary store backed by a recognized adapter (Redis, Valkey, Mongo, SQLite, Postgres, MySQL, etcd) supports `iterator()` directly. Each iteration yields a `[key, value]` tuple:
|
|
313
421
|
|
|
314
422
|
```typescript
|
|
315
423
|
import { Cacheable } from 'cacheable';
|
|
316
424
|
import KeyvRedis from '@keyv/redis';
|
|
317
425
|
|
|
318
|
-
// Create cache with primary (in-memory) and secondary (Redis) stores
|
|
319
426
|
const secondary = new KeyvRedis('redis://user:pass@localhost:6379');
|
|
320
427
|
const cache = new Cacheable({ secondary });
|
|
321
428
|
|
|
322
|
-
// Add some data
|
|
323
429
|
await cache.set('user:1', { name: 'Alice', role: 'admin' });
|
|
324
430
|
await cache.set('user:2', { name: 'Bob', role: 'user' });
|
|
325
|
-
await cache.set('session:abc', { userId: '1', active: true });
|
|
326
431
|
|
|
327
|
-
|
|
328
|
-
|
|
432
|
+
if (cache.secondary?.iterator) {
|
|
433
|
+
for await (const [key, value] of cache.secondary.iterator()) {
|
|
434
|
+
console.log(`${key}:`, value);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
## Iterating the Primary Store
|
|
440
|
+
|
|
441
|
+
If you need a primary store you can walk with `iterator()`, use a `Map`-backed `new Keyv()` (or any recognized adapter) as the primary. A plain `Keyv` is iterable because its default store is a `Map`:
|
|
442
|
+
|
|
443
|
+
```typescript
|
|
444
|
+
import { Cacheable } from 'cacheable';
|
|
445
|
+
import { Keyv } from 'keyv';
|
|
446
|
+
|
|
447
|
+
const cache = new Cacheable({ primary: new Keyv() });
|
|
448
|
+
|
|
449
|
+
await cache.set('user:1', { name: 'Alice' });
|
|
450
|
+
await cache.set('user:2', { name: 'Bob' });
|
|
451
|
+
|
|
329
452
|
if (cache.primary.iterator) {
|
|
330
453
|
for await (const [key, value] of cache.primary.iterator()) {
|
|
331
|
-
console.log(
|
|
454
|
+
console.log(`${key}:`, value);
|
|
332
455
|
}
|
|
333
456
|
}
|
|
457
|
+
```
|
|
334
458
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
459
|
+
### Iterating the default in-memory primary
|
|
460
|
+
|
|
461
|
+
The default primary from `@cacheable/memory` does not provide a Keyv `iterator()`. To walk it, reach the underlying `CacheableMemory` store through `cache.primary.store` and use its `items` iterator. Each item is a `{ key, value, expires }` record (expired entries are skipped automatically), where `value` holds Keyv's stored envelope — the decoded value is at `item.value.value`:
|
|
462
|
+
|
|
463
|
+
```typescript
|
|
464
|
+
import { Cacheable, KeyvCacheableMemory } from 'cacheable';
|
|
465
|
+
|
|
466
|
+
const cache = new Cacheable();
|
|
467
|
+
await cache.set('user:1', { name: 'Alice' });
|
|
468
|
+
await cache.set('user:2', { name: 'Bob' });
|
|
469
|
+
|
|
470
|
+
// cache.primary.store is the KeyvCacheableMemory adapter; its .store is the CacheableMemory
|
|
471
|
+
const memory = (cache.primary.store as KeyvCacheableMemory).store;
|
|
472
|
+
|
|
473
|
+
for (const item of memory.items) {
|
|
474
|
+
// item.value is Keyv's { value, expires } envelope
|
|
475
|
+
console.log(`${item.key}:`, item.value.value);
|
|
476
|
+
}
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
If you'd rather not depend on the envelope shape, iterate the keys and read each entry back through the cache:
|
|
480
|
+
|
|
481
|
+
```typescript
|
|
482
|
+
const memory = (cache.primary.store as KeyvCacheableMemory).store;
|
|
483
|
+
for (const { key } of memory.items) {
|
|
484
|
+
console.log(`${key}:`, await cache.get(key));
|
|
341
485
|
}
|
|
342
486
|
```
|
|
343
487
|
|
|
@@ -372,18 +516,22 @@ await iterateStore(cache.primary, 'Primary');
|
|
|
372
516
|
await iterateStore(cache.secondary, 'Secondary');
|
|
373
517
|
```
|
|
374
518
|
|
|
519
|
+
Note that with the default configuration the `Primary` branch above will report that it "does not support iteration" — that is expected, because the default `@cacheable/memory` primary has no `iterator()`. Use the [`CacheableMemory.items`](#iterating-the-default-in-memory-primary) approach for it.
|
|
520
|
+
|
|
375
521
|
## Storage Adapter Support
|
|
376
522
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
523
|
+
Keyv assigns an `iterator()` method only when the store is a raw `Map` or one of the adapters it recognizes as iterable. For every other store, `keyv.iterator` is `undefined`.
|
|
524
|
+
|
|
525
|
+
Stores that support `iterator()`:
|
|
526
|
+
|
|
527
|
+
- A plain `new Keyv()` (its store is a `Map`)
|
|
528
|
+
- `@keyv/redis` and `@keyv/valkey`
|
|
529
|
+
- `@keyv/mongo`, `@keyv/sqlite`, `@keyv/postgres`, `@keyv/mysql`, and `@keyv/etcd`
|
|
530
|
+
|
|
531
|
+
Stores that do **not** support `iterator()`:
|
|
381
532
|
|
|
382
|
-
|
|
383
|
-
-
|
|
384
|
-
- @keyv/redis
|
|
385
|
-
- @keyv/valkey
|
|
386
|
-
- Other Keyv adapters that implement the iterator interface
|
|
533
|
+
- The default `@cacheable/memory` primary (`createKeyv()`) — walk it through its [`CacheableMemory.items`](#iterating-the-default-in-memory-primary) accessor instead
|
|
534
|
+
- Any adapter that doesn't implement Keyv's iterable interface
|
|
387
535
|
|
|
388
536
|
# Non-Blocking Operations
|
|
389
537
|
|
|
@@ -606,6 +754,94 @@ const value = await serviceB.get('config'); // undefined
|
|
|
606
754
|
* The sync feature requires a message provider to be running and accessible by all cache instances.
|
|
607
755
|
* Each cache instance has a unique `cacheId`. Events are only applied if they come from a different instance, preventing infinite loops.
|
|
608
756
|
|
|
757
|
+
# Maximum Time to Live (maxTtl)
|
|
758
|
+
|
|
759
|
+
You can set a `maxTtl` option to enforce an upper bound on any TTL in the cache. When `maxTtl` is set:
|
|
760
|
+
- Any per-entry TTL that exceeds `maxTtl` will be capped to `maxTtl`.
|
|
761
|
+
- Entries with no TTL (that would otherwise live indefinitely) will be capped to `maxTtl`.
|
|
762
|
+
- The default TTL is still respected if it is within the `maxTtl` limit.
|
|
763
|
+
- The `maxTtl` is enforced on both primary and secondary stores.
|
|
764
|
+
- A TTL set by a [`BEFORE_SET` hook](#overriding-the-ttl-in-a-before_set-hook) is also capped, per store.
|
|
765
|
+
|
|
766
|
+
This is useful when you want to guarantee that no cache entry lives longer than a certain duration, regardless of what TTL is passed to individual `set()` calls or set by a hook.
|
|
767
|
+
|
|
768
|
+
```javascript
|
|
769
|
+
import { Cacheable } from 'cacheable';
|
|
770
|
+
|
|
771
|
+
// No entry can live longer than 1 hour
|
|
772
|
+
const cache = new Cacheable({ maxTtl: '1h' });
|
|
773
|
+
|
|
774
|
+
await cache.set('key1', 'value1', '2h'); // capped to 1 hour
|
|
775
|
+
await cache.set('key2', 'value2'); // also capped to 1 hour (would otherwise be indefinite)
|
|
776
|
+
await cache.set('key3', 'value3', '30m'); // 30 minutes is within maxTtl, so it stays as-is
|
|
777
|
+
```
|
|
778
|
+
|
|
779
|
+
You can also set `maxTtl` after construction:
|
|
780
|
+
|
|
781
|
+
```javascript
|
|
782
|
+
const cache = new Cacheable();
|
|
783
|
+
cache.maxTtl = 5000; // 5 seconds max
|
|
784
|
+
cache.maxTtl = '10m'; // 10 minutes max
|
|
785
|
+
cache.maxTtl = undefined; // disable maxTtl (no upper bound)
|
|
786
|
+
```
|
|
787
|
+
|
|
788
|
+
# Tag Based Invalidation
|
|
789
|
+
|
|
790
|
+
You can associate cache entries with tags and later invalidate every entry that shares a tag in a single call. This is useful for content caching where one upstream entity (a product, a user, a CMS document) is referenced by many cache entries:
|
|
791
|
+
|
|
792
|
+
```javascript
|
|
793
|
+
import { Cacheable } from 'cacheable';
|
|
794
|
+
|
|
795
|
+
const cache = new Cacheable({ tags: true });
|
|
796
|
+
|
|
797
|
+
await cache.set('page:/products', html, { ttl: '10m', tags: ['entity:42', 'collection:products'] });
|
|
798
|
+
await cache.set('page:/products/42', detailHtml, { ttl: '10m', tags: ['entity:42'] });
|
|
799
|
+
|
|
800
|
+
// entity 42 changed - purge everything that referenced it
|
|
801
|
+
await cache.tags.invalidateTag('entity:42');
|
|
802
|
+
|
|
803
|
+
await cache.get('page:/products'); // undefined
|
|
804
|
+
await cache.get('page:/products/42'); // undefined
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
You can also pass tags per item with `setMany`, and invalidate several tags at once:
|
|
808
|
+
|
|
809
|
+
```javascript
|
|
810
|
+
await cache.setMany([
|
|
811
|
+
{ key: 'user:1', value: userOne, tags: ['users'] },
|
|
812
|
+
{ key: 'user:2', value: userTwo, tags: ['users', 'org:7'] },
|
|
813
|
+
]);
|
|
814
|
+
|
|
815
|
+
await cache.tags.invalidateTags(['users', 'org:7']);
|
|
816
|
+
```
|
|
817
|
+
|
|
818
|
+
Tag functionality lives on the `tags` service — an instance of the `CacheTags` class from [`@cacheable/utils`](https://npmjs.com/package/@cacheable/utils) that is created by default in the constructor. Invalidation uses a lazy, constant-time model: `invalidateTag` simply bumps a version counter for the tag, no matter how many entries reference it. Each tagged entry stores a snapshot of its tags' versions, and on the next `get` / `getMany` the snapshot is compared to the live versions. If any tag has been bumped since, the entry is treated as a miss and removed from both the primary and secondary stores (and a `delete` is published via [sync](#cacheablesync---distributed-updates) when enabled). The trade-off is one additional tag-store read per cache lookup while the tag service is enabled.
|
|
819
|
+
|
|
820
|
+
Tag metadata is stored in the secondary store when one is configured, otherwise in the primary store. With a shared secondary store (such as Redis), an invalidation performed by one instance is seen by every instance:
|
|
821
|
+
|
|
822
|
+
```javascript
|
|
823
|
+
import { Cacheable } from 'cacheable';
|
|
824
|
+
import KeyvRedis from '@keyv/redis';
|
|
825
|
+
|
|
826
|
+
// enable tags on every instance that shares the store - writers and readers
|
|
827
|
+
const writer = new Cacheable({ secondary: new KeyvRedis('redis://localhost:6379'), tags: true });
|
|
828
|
+
const reader = new Cacheable({ secondary: new KeyvRedis('redis://localhost:6379'), tags: true });
|
|
829
|
+
|
|
830
|
+
await writer.set('page:/products', html, { tags: ['entity:42'] });
|
|
831
|
+
await writer.tags.invalidateTag('entity:42');
|
|
832
|
+
await reader.get('page:/products'); // undefined - stale copy is also purged from reader's primary
|
|
833
|
+
```
|
|
834
|
+
|
|
835
|
+
The tag service is disabled by default so untagged workloads pay no extra cost, and you have to turn it on to use it — either with the `tags: true` option or by setting `cache.tags.enabled = true`. While disabled, all tag operations are no-ops: values set with `tags` are stored without tag tracking and invalidations have no effect. The service never enables itself, which keeps behavior predictable across distributed instances — enable it on every instance that shares the store (writers and readers) so invalidations are honored and tag snapshots are cleaned up consistently.
|
|
836
|
+
|
|
837
|
+
The full `CacheTags` API is available on the service:
|
|
838
|
+
|
|
839
|
+
```javascript
|
|
840
|
+
await cache.tags.getTags('page:/products'); // ['entity:42', 'collection:products']
|
|
841
|
+
await cache.tags.getKeysByTag('entity:42'); // keys referencing a tag (debugging / tests)
|
|
842
|
+
cache.tags.enabled; // whether freshness checks run on get / getMany
|
|
843
|
+
```
|
|
844
|
+
|
|
609
845
|
# Cacheable Options
|
|
610
846
|
|
|
611
847
|
The following options are available for you to configure `cacheable`:
|
|
@@ -615,8 +851,10 @@ The following options are available for you to configure `cacheable`:
|
|
|
615
851
|
* `nonBlocking`: If the secondary store is non-blocking. Default is `false`.
|
|
616
852
|
* `stats`: To enable statistics for this instance. Default is `false`.
|
|
617
853
|
* `ttl`: The default time to live for the cache in milliseconds. Default is `undefined` which is disabled.
|
|
854
|
+
* `maxTtl`: The maximum time to live for any cache entry. When set, TTLs exceeding this value are capped. Enforced on both primary and secondary stores. Default is `undefined` (no maximum).
|
|
618
855
|
* `namespace`: The namespace for the cache. Default is `undefined`.
|
|
619
856
|
* `cacheId`: A unique identifier for this cache instance. Used for sync filtering. Default is a random string.
|
|
857
|
+
* `tags`: Enables the tag service so tag-based invalidation can be used and freshness checks run on `get` / `getMany`. Tags must be explicitly enabled — while disabled, all tag operations are no-ops. Default is `false`.
|
|
620
858
|
* `sync`: Enable distributed cache synchronization. Can be:
|
|
621
859
|
- `CacheableSync` instance
|
|
622
860
|
- `CacheableSyncOptions` object with `{ qified: MessageProvider | MessageProvider[] | Qified }`
|
|
@@ -641,8 +879,8 @@ _This does not enable statistics for your layer 2 cache as that is a distributed
|
|
|
641
879
|
|
|
642
880
|
# Cacheable - API
|
|
643
881
|
|
|
644
|
-
* `set(key, value,
|
|
645
|
-
* `setMany([{key, value, ttl?}])`: Sets multiple values in the cache.
|
|
882
|
+
* `set(key, value, ttlOrOptions?)`: Sets a value in the cache. The third argument can be a `ttl` or an options object such as `{ ttl: '1h', tags: ['entity:42'] }`.
|
|
883
|
+
* `setMany([{key, value, ttl?, tags?}])`: Sets multiple values in the cache.
|
|
646
884
|
* `get(key)`: Gets a value from the cache.
|
|
647
885
|
* `get(key, { raw: true })`: Gets a raw value from the cache.
|
|
648
886
|
* `getMany([keys])`: Gets multiple values from the cache.
|
|
@@ -654,6 +892,7 @@ _This does not enable statistics for your layer 2 cache as that is a distributed
|
|
|
654
892
|
* `delete(key)`: Deletes a value from the cache.
|
|
655
893
|
* `deleteMany([keys])`: Deletes multiple values from the cache.
|
|
656
894
|
* `clear()`: Clears the cache stores. Be careful with this as it will clear both layer 1 and layer 2.
|
|
895
|
+
* `tags`: The `CacheTags` service from `@cacheable/utils` used for tag-based invalidation, such as `tags.invalidateTag(tag)`, `tags.invalidateTags([tags])`, `tags.getTags(key)`, `tags.getKeysByTag(tag)`, and `tags.enabled`.
|
|
657
896
|
* `wrap(function, WrapOptions)`: Wraps an `async` function in a cache.
|
|
658
897
|
* `getOrSet(GetOrSetKey, valueFunction, GetOrSetFunctionOptions)`: Gets a value from cache or sets it if not found using the provided function.
|
|
659
898
|
* `disconnect()`: Disconnects from the cache stores.
|
|
@@ -663,12 +902,51 @@ _This does not enable statistics for your layer 2 cache as that is a distributed
|
|
|
663
902
|
* `removeListener(event, callback)`: Removes a listener.
|
|
664
903
|
* `hash(object: any, algorithm = 'SHA-256'): Promise<string>`: Asynchronously hashes an object with a cryptographic algorithm (SHA-256, SHA-384, SHA-512). Default is `SHA-256`.
|
|
665
904
|
* `hashSync(object: any, algorithm = 'djb2'): string`: Synchronously hashes an object with a non-cryptographic algorithm (djb2, fnv1, murmer, crc32). Default is `djb2`.
|
|
905
|
+
* `getStaticInstance(options?)`: Static. Gets a shared singleton instance, creating it on the first call. Options apply only on first creation; passing options after init emits an `error` event and is otherwise ignored.
|
|
906
|
+
* `setStaticInstance(instance?)`: Static. Sets or clears the shared singleton instance. Pass `undefined` to reset it.
|
|
666
907
|
* `primary`: The primary store for the cache (layer 1) defaults to in-memory by Keyv.
|
|
667
908
|
* `secondary`: The secondary store for the cache (layer 2) usually a persistent cache by Keyv.
|
|
668
909
|
* `namespace`: The namespace for the cache. Default is `undefined`. This will set the namespace for the primary and secondary stores.
|
|
910
|
+
* `maxTtl`: The maximum time to live for any cache entry. When set, TTLs exceeding this value are capped. Default is `undefined` (no maximum).
|
|
669
911
|
* `nonBlocking`: If the secondary store is non-blocking. Default is `false`.
|
|
670
912
|
* `stats`: The statistics for this instance which includes `hits`, `misses`, `sets`, `deletes`, `clears`, `errors`, `count`, `vsize`, `ksize`.
|
|
671
913
|
|
|
914
|
+
# Static Instance (Singleton)
|
|
915
|
+
|
|
916
|
+
If you want a single cache shared across your application without constructing a `Cacheable` instance and passing it around, use the static `getStaticInstance()` accessor. The first call creates the shared instance; every later call returns that same instance:
|
|
917
|
+
|
|
918
|
+
```javascript
|
|
919
|
+
import { Cacheable } from 'cacheable';
|
|
920
|
+
|
|
921
|
+
const cache = Cacheable.getStaticInstance({ ttl: '1h' });
|
|
922
|
+
await cache.set('key', 'value');
|
|
923
|
+
|
|
924
|
+
// Anywhere else in your app, the same instance is returned:
|
|
925
|
+
const same = Cacheable.getStaticInstance();
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
Options are only applied when the instance is first created. If you pass options again after the instance already exists, they are ignored and an `error` event is emitted on the instance to surface the conflict — listen with `cache.on('error', ...)`. To reconfigure, replace the instance with `setStaticInstance()` (shown below).
|
|
929
|
+
|
|
930
|
+
You can replace or reset the shared instance with `setStaticInstance()`. Pass a `Cacheable` instance to swap it, or `undefined` to clear it so the next `getStaticInstance()` call creates a fresh one:
|
|
931
|
+
|
|
932
|
+
```javascript
|
|
933
|
+
import { Cacheable } from 'cacheable';
|
|
934
|
+
import KeyvRedis from '@keyv/redis';
|
|
935
|
+
|
|
936
|
+
// Provide a fully configured instance as the shared one
|
|
937
|
+
Cacheable.setStaticInstance(new Cacheable({ secondary: new KeyvRedis('redis://localhost:6379') }));
|
|
938
|
+
|
|
939
|
+
// Reset back to no shared instance
|
|
940
|
+
Cacheable.setStaticInstance(undefined);
|
|
941
|
+
```
|
|
942
|
+
|
|
943
|
+
Things to know:
|
|
944
|
+
|
|
945
|
+
* The shared instance is process-global and long-lived. Calling `clear()` or `disconnect()` on it affects every part of your app that uses it.
|
|
946
|
+
* After `disconnect()`, `getStaticInstance()` keeps returning the same (now disconnected) instance — it is not recreated automatically. Call `setStaticInstance(undefined)` first, then `getStaticInstance()` to get a fresh one.
|
|
947
|
+
* `setStaticInstance(undefined)` only drops the reference; it does not `disconnect()` or `clear()` the previous instance, so disconnect it first if it holds open connections.
|
|
948
|
+
* This package ships separate CommonJS and ESM builds. An app (or dependency graph) that loads both formats gets one shared instance *per build*, not one process-wide. For a single shared cache, use one module format, or create the instance once and share it via `setStaticInstance()`.
|
|
949
|
+
|
|
672
950
|
# CacheableMemory - In-Memory Cache
|
|
673
951
|
|
|
674
952
|
`cacheable` comes with a built-in in-memory cache called `CacheableMemory` from `@cacheable/memory`. This is a simple in-memory cache that is used as the primary store for `cacheable`. You can use this as a standalone cache or as a primary store for `cacheable`. Here is an example of how to use `CacheableMemory`:
|
|
@@ -790,13 +1068,15 @@ The `getOrSet` method that comes from [@cacheable/utils](https://cacheable.org/
|
|
|
790
1068
|
|
|
791
1069
|
```typescript
|
|
792
1070
|
export type GetOrSetFunctionOptions = {
|
|
793
|
-
ttl?: number | string;
|
|
1071
|
+
ttl?: number | string | { primary?: number | string; secondary?: number | string };
|
|
794
1072
|
cacheErrors?: boolean;
|
|
795
1073
|
throwErrors?: boolean;
|
|
796
1074
|
nonBlocking?: boolean;
|
|
797
1075
|
};
|
|
798
1076
|
```
|
|
799
1077
|
|
|
1078
|
+
The `ttl` also accepts a [per-store object](#per-store-ttl-per-operation) such as `{ primary: '10s', secondary: '5m' }` to give the primary and secondary stores different expirations for this operation.
|
|
1079
|
+
|
|
800
1080
|
The `nonBlocking` option allows you to override the instance-level `nonBlocking` setting for the `get` call within `getOrSet`. When set to `false`, the `get` will block and wait for a response from the secondary store before deciding whether to call the provided function. When set to `true`, the primary store returns immediately and syncs from secondary in the background.
|
|
801
1081
|
|
|
802
1082
|
Here is an example of how to use the `getOrSet` method:
|