@cacheable/memory 2.0.9 → 2.2.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 +177 -0
- package/dist/index.cjs +867 -820
- package/dist/index.d.cts +382 -280
- package/dist/index.d.mts +412 -0
- package/dist/index.mjs +841 -0
- package/package.json +9 -9
- package/dist/index.d.ts +0 -310
- package/dist/index.js +0 -807
package/README.md
CHANGED
|
@@ -29,6 +29,8 @@ Here are some of the main features of `CacheableMemory`:
|
|
|
29
29
|
* [CacheableMemory Store Hashing](#cacheablememory-store-hashing)
|
|
30
30
|
* [CacheableMemory LRU Feature](#cacheablememory-lru-feature)
|
|
31
31
|
* [CacheableMemory Performance](#cacheablememory-performance)
|
|
32
|
+
* [CacheableMemory Statistics](#cacheablememory-statistics)
|
|
33
|
+
* [CacheableMemory Hooks and Events](#cacheablememory-hooks-and-events)
|
|
32
34
|
* [CacheableMemory Options](#cacheablememory-options)
|
|
33
35
|
* [CacheableMemory - API](#cacheablememory---api)
|
|
34
36
|
* [Keyv Storage Adapter - KeyvCacheableMemory](#keyv-storage-adapter---keyvcacheablememory)
|
|
@@ -226,14 +228,138 @@ Our goal with `cacheable` and `CacheableMemory` is to provide a high performance
|
|
|
226
228
|
|
|
227
229
|
As you can see from the benchmarks `CacheableMemory` is on par with other caching engines such as `Map`, `Node Cache`, and `bentocache`. We have also tested it against other LRU caching engines such as `quick-lru` and `lru.min` and it performs well against them too.
|
|
228
230
|
|
|
231
|
+
## Maximum Time to Live (maxTtl)
|
|
232
|
+
|
|
233
|
+
You can set a `maxTtl` option to enforce an upper bound on any TTL in the cache. When `maxTtl` is set:
|
|
234
|
+
- Any per-entry TTL that exceeds `maxTtl` will be capped to `maxTtl`.
|
|
235
|
+
- Entries with no TTL (that would otherwise live indefinitely) will be capped to `maxTtl`.
|
|
236
|
+
- The default TTL is still respected if it is within the `maxTtl` limit.
|
|
237
|
+
|
|
238
|
+
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.
|
|
239
|
+
|
|
240
|
+
```javascript
|
|
241
|
+
import { CacheableMemory } from '@cacheable/memory';
|
|
242
|
+
|
|
243
|
+
// No entry can live longer than 1 hour
|
|
244
|
+
const cache = new CacheableMemory({ maxTtl: '1h' });
|
|
245
|
+
|
|
246
|
+
cache.set('key1', 'value1', '2h'); // capped to 1 hour
|
|
247
|
+
cache.set('key2', 'value2'); // also capped to 1 hour (would otherwise be indefinite)
|
|
248
|
+
cache.set('key3', 'value3', '30m'); // 30 minutes is within maxTtl, so it stays as-is
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
You can also set `maxTtl` after construction:
|
|
252
|
+
|
|
253
|
+
```javascript
|
|
254
|
+
const cache = new CacheableMemory();
|
|
255
|
+
cache.maxTtl = 5000; // 5 seconds max
|
|
256
|
+
cache.maxTtl = '10m'; // 10 minutes max
|
|
257
|
+
cache.maxTtl = undefined; // disable maxTtl (no upper bound)
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
## CacheableMemory Statistics
|
|
261
|
+
|
|
262
|
+
`CacheableMemory` can track runtime statistics using the shared [`Stats`](https://cacheable.org/docs/utils/) implementation from `@cacheable/utils` (the same engine used by `cacheable` and `@cacheable/node-cache`). Statistics are disabled by default. Enable them with the `stats` option or by setting `cache.stats.enabled = true` at any time:
|
|
263
|
+
|
|
264
|
+
```javascript
|
|
265
|
+
import { CacheableMemory } from '@cacheable/memory';
|
|
266
|
+
|
|
267
|
+
const cache = new CacheableMemory({ stats: true });
|
|
268
|
+
|
|
269
|
+
cache.set('key', 'value');
|
|
270
|
+
cache.get('key'); // hit
|
|
271
|
+
cache.get('missing'); // miss
|
|
272
|
+
|
|
273
|
+
console.log(cache.stats.hits); // 1
|
|
274
|
+
console.log(cache.stats.misses); // 1
|
|
275
|
+
console.log(cache.stats.gets); // 2
|
|
276
|
+
console.log(cache.stats.sets); // 1
|
|
277
|
+
console.log(cache.stats.count); // 1
|
|
278
|
+
console.log(cache.stats.hitRate); // 0.5
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
The `stats` property exposes the following counters:
|
|
282
|
+
|
|
283
|
+
* `hits`: The number of reads that found a (non-expired) value.
|
|
284
|
+
* `misses`: The number of reads that did not find a value.
|
|
285
|
+
* `gets`: The number of read operations. Every key read counts as one get, so `getMany(['a', 'b'])` records two gets.
|
|
286
|
+
* `sets`: The number of writes. Every key written counts as one set, including overwrites.
|
|
287
|
+
* `deletes`: The number of keys removed via `delete`/`deleteMany`/`take`, as well as keys evicted by the LRU.
|
|
288
|
+
* `clears`: The number of times `clear()` was called.
|
|
289
|
+
* `count`: The number of keys currently tracked in the cache.
|
|
290
|
+
* `ksize`: The estimated byte size of the keys in the cache.
|
|
291
|
+
* `vsize`: The estimated byte size of the values in the cache.
|
|
292
|
+
* `hitRate` / `missRate`: The ratio of hits / misses to total lookups.
|
|
293
|
+
|
|
294
|
+
You can get a plain-object snapshot via `cache.stats.toJSON()` and reset all counters with `cache.stats.reset()`.
|
|
295
|
+
|
|
296
|
+
The `count`, `ksize`, and `vsize` values are kept in sync as entries are added, removed, overwritten, and lazily expired, so they reflect the current contents of the cache. (Expired entries are not counted as `deletes`, since their removal is not user-initiated.) Methods that perform a read internally — such as `has()`, `take()`, and the `wrap()` / `getOrSet()` memoization helpers — flow through `get`/`set`, so they update the statistics as well.
|
|
297
|
+
|
|
298
|
+
For accurate size counters, enable statistics before populating the cache: `count`/`ksize`/`vsize` only account for entries written while statistics were enabled, and are clamped at `0` so they never go negative if you enable stats after the cache already has data. Changing `storeHashSize` recreates the underlying stores and clears all entries, so the size counters are reset to `0` accordingly.
|
|
299
|
+
|
|
300
|
+
## CacheableMemory Hooks and Events
|
|
301
|
+
|
|
302
|
+
`CacheableMemory` extends [`Hookified`](https://github.com/jaredwray/hookified), so you can register handlers that run around cache operations via the `CacheableMemoryHooks` enum and the `onHook()` method:
|
|
303
|
+
|
|
304
|
+
* `BEFORE_SET`: Called before `set()`. The handler receives `{ key, value, ttl }` and can reassign any of them to change what gets stored.
|
|
305
|
+
* `AFTER_SET`: Called after `set()` with the (possibly modified) `{ key, value, ttl }`.
|
|
306
|
+
* `BEFORE_SET_MANY`: Called before `setMany()` with the array of `CacheableItem`s. Items can be mutated.
|
|
307
|
+
* `AFTER_SET_MANY`: Called after `setMany()` with the array of items.
|
|
308
|
+
* `BEFORE_GET`: Called before `get()` with the `key`.
|
|
309
|
+
* `AFTER_GET`: Called after `get()` with `{ key, result }` (`result` is `undefined` on a cache miss).
|
|
310
|
+
* `BEFORE_GET_MANY`: Called before `getMany()` with the array of `keys`.
|
|
311
|
+
* `AFTER_GET_MANY`: Called after `getMany()` with `{ keys, result }`.
|
|
312
|
+
* `BEFORE_DELETE`: Called before `delete()` with the `key`.
|
|
313
|
+
* `AFTER_DELETE`: Called after `delete()` with the `key`.
|
|
314
|
+
* `BEFORE_DELETE_MANY`: Called before `deleteMany()` with the array of `keys`.
|
|
315
|
+
* `AFTER_DELETE_MANY`: Called after `deleteMany()` with the array of `keys`.
|
|
316
|
+
* `BEFORE_CLEAR`: Called before `clear()`.
|
|
317
|
+
* `AFTER_CLEAR`: Called after `clear()`.
|
|
318
|
+
|
|
319
|
+
An example of how to use these hooks:
|
|
320
|
+
|
|
321
|
+
```javascript
|
|
322
|
+
import { CacheableMemory, CacheableMemoryHooks } from '@cacheable/memory';
|
|
323
|
+
|
|
324
|
+
const cache = new CacheableMemory();
|
|
325
|
+
|
|
326
|
+
cache.onHook(CacheableMemoryHooks.BEFORE_SET, (item) => {
|
|
327
|
+
console.log(`before set: ${item.key} ${item.value}`);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
cache.onHook(CacheableMemoryHooks.AFTER_GET, (item) => {
|
|
331
|
+
console.log(`after get: ${item.key} = ${item.result}`);
|
|
332
|
+
});
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
A `BEFORE_SET` handler can change the `key`, `value`, or `ttl` before the entry is stored. The `ttl` accepts a number (milliseconds), a [shorthand string](#shorthand-for-time-to-live-ttl), or a `SetOptions` object (`{ ttl, expire }`):
|
|
336
|
+
|
|
337
|
+
```javascript
|
|
338
|
+
cache.onHook(CacheableMemoryHooks.BEFORE_SET, (item) => {
|
|
339
|
+
item.key = `user:${item.key}`;
|
|
340
|
+
item.ttl = '1h';
|
|
341
|
+
});
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Hooks are dispatched synchronously via `hookSync`, which **skips `async` handler functions entirely** — an `async` handler will not run at all (not merely run un-awaited), so register only synchronous handlers.
|
|
345
|
+
|
|
346
|
+
> **TypeScript:** the hook payload types are exported so you can annotate your handlers — `CacheableMemoryHookItem`, `CacheableMemoryAfterGetItem`, and `CacheableMemoryAfterGetManyItem`. For example:
|
|
347
|
+
> ```ts
|
|
348
|
+
> cache.onHook(CacheableMemoryHooks.BEFORE_SET, (item: CacheableMemoryHookItem) => {
|
|
349
|
+
> item.ttl = '1h';
|
|
350
|
+
> });
|
|
351
|
+
> ```
|
|
352
|
+
|
|
229
353
|
## CacheableMemory Options
|
|
230
354
|
|
|
231
355
|
* `ttl`: The time to live for the cache in milliseconds. Default is `undefined` which is means indefinitely.
|
|
356
|
+
* `maxTtl`: The maximum time to live for any cache entry. When set, TTLs exceeding this value are capped. Default is `undefined` (no maximum).
|
|
232
357
|
* `useClones`: If the cache should use clones for the values. Default is `true`.
|
|
233
358
|
* `lruSize`: The size of the LRU cache. Default is `0`, which disables the LRU cache (no LRU eviction is performed). Maximum is `16,777,216 (2^24)`.
|
|
234
359
|
* `checkInterval`: The interval to check for expired keys in milliseconds. Default is `0` which is disabled.
|
|
235
360
|
* `storeHashSize`: The number of `Map` objects to use for the cache. Default is `16`.
|
|
236
361
|
* `storeHashAlgorithm`: The hashing algorithm to use for the cache. Default is `djb2`. Supported: DJB2, FNV1, MURMER, CRC32.
|
|
362
|
+
* `stats`: Whether to track runtime statistics (`hits`, `misses`, `gets`, `sets`, `deletes`, `clears`, `count`, `ksize`, `vsize`). Default is `false`.
|
|
237
363
|
|
|
238
364
|
## CacheableMemory - API
|
|
239
365
|
|
|
@@ -251,13 +377,16 @@ As you can see from the benchmarks `CacheableMemory` is on par with other cachin
|
|
|
251
377
|
* `takeMany([keys])`: Takes multiple values from the cache and deletes them.
|
|
252
378
|
* `wrap(function, WrapSyncOptions)`: Wraps a `sync` function in a cache.
|
|
253
379
|
* `clear()`: Clears the cache.
|
|
380
|
+
* `onHook(hook, handler)`: Registers a handler for a `CacheableMemoryHooks` event. See [CacheableMemory Hooks and Events](#cacheablememory-hooks-and-events).
|
|
254
381
|
* `ttl`: The default time to live for the cache in milliseconds. Default is `undefined` which is disabled.
|
|
382
|
+
* `maxTtl`: The maximum time to live for any cache entry. When set, TTLs exceeding this value are capped. Default is `undefined` (no maximum).
|
|
255
383
|
* `useClones`: If the cache should use clones for the values. Default is `true`.
|
|
256
384
|
* `lruSize`: The size of the LRU cache. Default is `0`, which disables the LRU cache (no LRU eviction is performed). Maximum is `16,777,216 (2^24)`.
|
|
257
385
|
* `size`: The number of keys in the cache.
|
|
258
386
|
* `checkInterval`: The interval to check for expired keys in milliseconds. Default is `0` which is disabled.
|
|
259
387
|
* `storeHashSize`: The number of `Map` objects to use for the cache. Default is `16`.
|
|
260
388
|
* `storeHashAlgorithm`: The hashing algorithm to use for the cache. Default is `djb2`. Supported: DJB2, FNV1, MURMER, CRC32.
|
|
389
|
+
* `stats`: The statistics for this instance which includes `hits`, `misses`, `gets`, `sets`, `deletes`, `clears`, `count`, `vsize`, and `ksize`. Disabled by default; enable via the `stats` option or `cache.stats.enabled = true`.
|
|
261
390
|
* `keys`: Get the keys in the cache. Not able to be set.
|
|
262
391
|
* `items`: Get the items in the cache as `CacheableStoreItem` example `{ key, value, expires? }`.
|
|
263
392
|
* `store`: The hash store for the cache which is an array of `Map` objects.
|
|
@@ -332,6 +461,54 @@ If you would like to generate your own key for the wrapped function you can set
|
|
|
332
461
|
|
|
333
462
|
We will pass in the `function` that is being wrapped, the `arguments` passed to the function, and the `options` used to wrap the function. You can then use these to generate a custom key for the cache.
|
|
334
463
|
|
|
464
|
+
# Get Or Set Memoization Function
|
|
465
|
+
|
|
466
|
+
`CacheableMemory` also has a `getOrSet` method that implements the cache-aside pattern in a single synchronous call. It attempts to retrieve a value from the cache, and if it is not found it calls the provided function to compute the value, stores it, and returns it. This is the synchronous counterpart to the `getOrSet` method on `cacheable` and is backed by `getOrSetSync` from [@cacheable/utils](https://cacheable.org/docs/utils/).
|
|
467
|
+
|
|
468
|
+
```javascript
|
|
469
|
+
import { CacheableMemory } from '@cacheable/memory';
|
|
470
|
+
|
|
471
|
+
const cache = new CacheableMemory();
|
|
472
|
+
|
|
473
|
+
const getUser = () => ({ id: 1, name: 'Alice' });
|
|
474
|
+
|
|
475
|
+
// First call computes the value and stores it
|
|
476
|
+
const user1 = cache.getOrSet('user:1', getUser, { ttl: '1h' });
|
|
477
|
+
// Second call returns the cached value without calling getUser again
|
|
478
|
+
const user2 = cache.getOrSet('user:1', getUser, { ttl: '1h' });
|
|
479
|
+
|
|
480
|
+
console.log(user1); // { id: 1, name: 'Alice' }
|
|
481
|
+
console.log(user1 === user2); // true (served from cache)
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
The third argument accepts the following options:
|
|
485
|
+
|
|
486
|
+
```typescript
|
|
487
|
+
export type GetOrSetFunctionOptions = {
|
|
488
|
+
ttl?: number | string;
|
|
489
|
+
cacheErrors?: boolean;
|
|
490
|
+
throwErrors?: boolean | 'function' | 'store';
|
|
491
|
+
};
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
* `ttl`: The time to live for the stored value. If omitted it falls back to the instance default `ttl`. Accepts milliseconds or the [shorthand](#shorthand-for-time-to-live-ttl) format such as `1h`.
|
|
495
|
+
* `cacheErrors`: When `true`, errors thrown by the function are cached so the function is not retried until the entry expires. Default is `false`.
|
|
496
|
+
* `throwErrors`: Controls whether errors are rethrown. `false` (default) emits errors on the `error` event and returns `undefined`; `true` rethrows any error; `'function'` only rethrows errors from the provided function; `'store'` only rethrows errors from reading/writing the cache.
|
|
497
|
+
|
|
498
|
+
Because `CacheableMemory` is synchronous there is no request coalescing — synchronous code runs to completion without interleaving, so concurrent callers cannot stampede the setter the way they can with the async `getOrSet` on `cacheable`.
|
|
499
|
+
|
|
500
|
+
You can also pass a function to compute the key:
|
|
501
|
+
|
|
502
|
+
```javascript
|
|
503
|
+
import { CacheableMemory, GetOrSetSyncKey } from '@cacheable/memory';
|
|
504
|
+
|
|
505
|
+
const cache = new CacheableMemory();
|
|
506
|
+
|
|
507
|
+
const generateKey: GetOrSetSyncKey = (options) => `user:${options?.ttl}`;
|
|
508
|
+
|
|
509
|
+
const value = cache.getOrSet(generateKey, () => Math.random() * 100, { ttl: '1h' });
|
|
510
|
+
```
|
|
511
|
+
|
|
335
512
|
# How to Contribute
|
|
336
513
|
|
|
337
514
|
You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README [https://github.com/jaredwray/cacheable](https://github.com/jaredwray/cacheable). This will talk about how to `Open a Pull Request`, `Ask a Question`, or `Post an Issue`.
|