GithubHelp home page GithubHelp logo

isaacs / node-lru-cache Goto Github PK

View Code? Open in Web Editor NEW
5.1K 53.0 339.0 1.53 MB

A fast cache that automatically deletes the least recently used items

Home Page: http://isaacs.github.io/node-lru-cache/

License: ISC License

JavaScript 27.43% TypeScript 71.24% Makefile 0.12% Shell 1.20%
cache caching lru lru-cache lrucache

node-lru-cache's Introduction

lru-cache

A cache object that deletes the least-recently-used items.

Specify a max number of the most recently used items that you want to keep, and this cache will keep that many of the most recently accessed items.

This is not primarily a TTL cache, and does not make strong TTL guarantees. There is no preemptive pruning of expired items by default, but you may set a TTL on the cache or on a single set. If you do so, it will treat expired items as missing, and delete them when fetched. If you are more interested in TTL caching than LRU caching, check out @isaacs/ttlcache.

As of version 7, this is one of the most performant LRU implementations available in JavaScript, and supports a wide diversity of use cases. However, note that using some of the features will necessarily impact performance, by causing the cache to have to do more work. See the "Performance" section below.

Installation

npm install lru-cache --save

Usage

// hybrid module, either works
import { LRUCache } from 'lru-cache'
// or:
const { LRUCache } = require('lru-cache')
// or in minified form for web browsers:
import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs'

// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does.  Most of them can be
// overridden for specific items in get()/set()
const options = {
  max: 500,

  // for use with tracking overall storage size
  maxSize: 5000,
  sizeCalculation: (value, key) => {
    return 1
  },

  // for use when you need to clean up something when objects
  // are evicted from the cache
  dispose: (value, key) => {
    freeFromMemoryOrWhatever(value)
  },

  // how long to live in ms
  ttl: 1000 * 60 * 5,

  // return stale items before removing from cache?
  allowStale: false,

  updateAgeOnGet: false,
  updateAgeOnHas: false,

  // async method to use for cache.fetch(), for
  // stale-while-revalidate type of behavior
  fetchMethod: async (
    key,
    staleValue,
    { options, signal, context }
  ) => {},
}

const cache = new LRUCache(options)

cache.set('key', 'value')
cache.get('key') // "value"

// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)

cache.clear() // empty the cache

If you put more stuff in the cache, then less recently used items will fall out. That's what an LRU cache is.

class LRUCache<K, V, FC = unknown>(options)

Create a new LRUCache object.

When using TypeScript, set the K and V types to the key and value types, respectively.

The FC ("fetch context") generic type defaults to unknown. If set to a value other than void or undefined, then any calls to cache.fetch() must provide a context option matching the FC type. If FC is set to void or undefined, then cache.fetch() must not provide a context option. See the documentation on async fetch() below.

Options

All options are available on the LRUCache instance, making it safe to pass an LRUCache instance as the options argument to make another empty cache of the same type.

Some options are marked read-only because changing them after instantiation is not safe. Changing any of the other options will of course only have an effect on subsequent method calls.

max (read only)

The maximum number of items that remain in the cache (assuming no TTL pruning or explicit deletions). Note that fewer items may be stored if size calculation is used, and maxSize is exceeded. This must be a positive finite intger.

At least one of max, maxSize, or TTL is required. This must be a positive integer if set.

It is strongly recommended to set a max to prevent unbounded growth of the cache. See "Storage Bounds Safety" below.

maxSize (read only)

Set to a positive integer to track the sizes of items added to the cache, and automatically evict items in order to stay below this size. Note that this may result in fewer than max items being stored.

Attempting to add an item to the cache whose calculated size is greater that this amount will be a no-op. The item will not be cached, and no other items will be evicted.

Optional, must be a positive integer if provided.

Sets maxEntrySize to the same value, unless a different value is provided for maxEntrySize.

At least one of max, maxSize, or TTL is required. This must be a positive integer if set.

Even if size tracking is enabled, it is strongly recommended to set a max to prevent unbounded growth of the cache. See "Storage Bounds Safety" below.

maxEntrySize

Set to a positive integer to track the sizes of items added to the cache, and prevent caching any item over a given size. Attempting to add an item whose calculated size is greater than this amount will be a no-op. The item will not be cached, and no other items will be evicted.

Optional, must be a positive integer if provided. Defaults to the value of maxSize if provided.

sizeCalculation

Function used to calculate the size of stored items. If you're storing strings or buffers, then you probably want to do something like n => n.length. The item is passed as the first argument, and the key is passed as the second argument.

This may be overridden by passing an options object to cache.set().

Requires maxSize to be set.

If the size (or return value of sizeCalculation) for a given entry is greater than maxEntrySize, then the item will not be added to the cache.

fetchMethod (read only)

Function that is used to make background asynchronous fetches. Called with fetchMethod(key, staleValue, { signal, options, context }). May return a Promise.

If fetchMethod is not provided, then cache.fetch(key) is equivalent to Promise.resolve(cache.get(key)).

If at any time, signal.aborted is set to true, or if the signal.onabort method is called, or if it emits an 'abort' event which you can listen to with addEventListener, then that means that the fetch should be abandoned. This may be passed along to async functions aware of AbortController/AbortSignal behavior.

The fetchMethod should only return undefined or a Promise resolving to undefined if the AbortController signaled an abort event. In all other cases, it should return or resolve to a value suitable for adding to the cache.

The options object is a union of the options that may be provided to set() and get(). If they are modified, then that will result in modifying the settings to cache.set() when the value is resolved, and in the case of noDeleteOnFetchRejection and allowStaleOnFetchRejection, the handling of fetchMethod failures.

For example, a DNS cache may update the TTL based on the value returned from a remote DNS server by changing options.ttl in the fetchMethod.

noDeleteOnFetchRejection

If a fetchMethod throws an error or returns a rejected promise, then by default, any existing stale value will be removed from the cache.

If noDeleteOnFetchRejection is set to true, then this behavior is suppressed, and the stale value remains in the cache in the case of a rejected fetchMethod.

This is important in cases where a fetchMethod is only called as a background update while the stale value is returned, when allowStale is used.

This is implicitly in effect when allowStaleOnFetchRejection is set.

This may be set in calls to fetch(), or defaulted on the constructor, or overridden by modifying the options object in the fetchMethod.

allowStaleOnFetchRejection

Set to true to return a stale value from the cache when a fetchMethod throws an error or returns a rejected Promise.

If a fetchMethod fails, and there is no stale value available, the fetch() will resolve to undefined. Ie, all fetchMethod errors are suppressed.

Implies noDeleteOnFetchRejection.

This may be set in calls to fetch(), or defaulted on the constructor, or overridden by modifying the options object in the fetchMethod.

allowStaleOnFetchAbort

Set to true to return a stale value from the cache when the AbortSignal passed to the fetchMethod dispatches an 'abort' event, whether user-triggered, or due to internal cache behavior.

Unless ignoreFetchAbort is also set, the underlying fetchMethod will still be considered canceled, and any value it returns will be ignored and not cached.

Caveat: since fetches are aborted when a new value is explicitly set in the cache, this can lead to fetch returning a stale value, since that was the fallback value at the moment the fetch() was initiated, even though the new updated value is now present in the cache.

For example:

const cache = new LRUCache<string, any>({
  ttl: 100,
  fetchMethod: async (url, oldValue, { signal }) => {
    const res = await fetch(url, { signal })
    return await res.json()
  },
})
cache.set('https://example.com/', { some: 'data' })
// 100ms go by...
const result = cache.fetch('https://example.com/')
cache.set('https://example.com/', { other: 'thing' })
console.log(await result) // { some: 'data' }
console.log(cache.get('https://example.com/')) // { other: 'thing' }

ignoreFetchAbort

Set to true to ignore the abort event emitted by the AbortSignal object passed to fetchMethod, and still cache the resulting resolution value, as long as it is not undefined.

When used on its own, this means aborted fetch() calls are not immediately resolved or rejected when they are aborted, and instead take the full time to await.

When used with allowStaleOnFetchAbort, aborted fetch() calls will resolve immediately to their stale cached value or undefined, and will continue to process and eventually update the cache when they resolve, as long as the resulting value is not undefined, thus supporting a "return stale on timeout while refreshing" mechanism by passing AbortSignal.timeout(n) as the signal.

For example:

const c = new LRUCache({
  ttl: 100,
  ignoreFetchAbort: true,
  allowStaleOnFetchAbort: true,
  fetchMethod: async (key, oldValue, { signal }) => {
    // note: do NOT pass the signal to fetch()!
    // let's say this fetch can take a long time.
    const res = await fetch(`https://slow-backend-server/${key}`)
    return await res.json()
  },
})

// this will return the stale value after 100ms, while still
// updating in the background for next time.
const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })

Note: regardless of this setting, an abort event is still emitted on the AbortSignal object, so may result in invalid results when passed to other underlying APIs that use AbortSignals.

This may be overridden on the fetch() call or in the fetchMethod itself.

dispose (read only)

Function that is called on items when they are dropped from the cache, as this.dispose(value, key, reason).

This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer stored in the cache.

NOTE: It is called before the item has been fully removed from the cache, so if you want to put it right back in, you need to wait until the next tick. If you try to add it back in during the dispose() function call, it will break things in subtle and weird ways.

Unlike several other options, this may not be overridden by passing an option to set(), for performance reasons.

The reason will be one of the following strings, corresponding to the reason for the item's deletion:

  • evict Item was evicted to make space for a new addition
  • set Item was overwritten by a new value
  • delete Item was removed by explicit cache.delete(key) or by calling cache.clear(), which deletes everything.

The dispose() method is not called for canceled calls to fetchMethod(). If you wish to handle evictions, overwrites, and deletes of in-flight asynchronous fetches, you must use the AbortSignal provided.

Optional, must be a function.

disposeAfter (read only)

The same as dispose, but called after the entry is completely removed and the cache is once again in a clean state.

It is safe to add an item right back into the cache at this point. However, note that it is very easy to inadvertently create infinite recursion in this way.

The disposeAfter() method is not called for canceled calls to fetchMethod(). If you wish to handle evictions, overwrites, and deletes of in-flight asynchronous fetches, you must use the AbortSignal provided.

noDisposeOnSet

Set to true to suppress calling the dispose() function if the entry key is still accessible within the cache.

This may be overridden by passing an options object to cache.set().

Boolean, default false. Only relevant if dispose or disposeAfter options are set.

ttl

Max time to live for items before they are considered stale. Note that stale items are NOT preemptively removed by default, and MAY live in the cache, contributing to its LRU max, long after they have expired.

Also, as this cache is optimized for LRU/MRU operations, some of the staleness/TTL checks will reduce performance.

This is not primarily a TTL cache, and does not make strong TTL guarantees. There is no pre-emptive pruning of expired items, but you may set a TTL on the cache, and it will treat expired items as missing when they are fetched, and delete them.

Optional, but must be a positive integer in ms if specified.

This may be overridden by passing an options object to cache.set().

At least one of max, maxSize, or TTL is required. This must be a positive integer if set.

Even if ttl tracking is enabled, it is strongly recommended to set a max to prevent unbounded growth of the cache. See "Storage Bounds Safety" below.

If ttl tracking is enabled, and max and maxSize are not set, and ttlAutopurge is not set, then a warning will be emitted cautioning about the potential for unbounded memory consumption. (The TypeScript definitions will also discourage this.)

noUpdateTTL

Boolean flag to tell the cache to not update the TTL when setting a new value for an existing key (ie, when updating a value rather than inserting a new value). Note that the TTL value is always set (if provided) when adding a new entry into the cache.

This may be passed as an option to cache.set().

Boolean, default false.

ttlResolution

Minimum amount of time in ms in which to check for staleness. Defaults to 1, which means that the current time is checked at most once per millisecond.

Set to 0 to check the current time every time staleness is tested.

Note that setting this to a higher value will improve performance somewhat while using ttl tracking, albeit at the expense of keeping stale items around a bit longer than intended.

ttlAutopurge

Preemptively remove stale items from the cache.

Note that this may significantly degrade performance, especially if the cache is storing a large number of items. It is almost always best to just leave the stale items in the cache, and let them fall out as new items are added.

Note that this means that allowStale is a bit pointless, as stale items will be deleted almost as soon as they expire.

Use with caution!

Boolean, default false

allowStale

By default, if you set ttl, it'll only delete stale items from the cache when you get(key). That is, it's not preemptively pruning items.

If you set allowStale:true, it'll return the stale value as well as deleting it. If you don't set this, then it'll return undefined when you try to get a stale entry.

Note that when a stale entry is fetched, even if it is returned due to allowStale being set, it is removed from the cache immediately. You can immediately put it back in the cache if you wish, thus resetting the TTL.

This may be overridden by passing an options object to cache.get(). The cache.has() method will always return false for stale items.

Boolean, default false, only relevant if ttl is set.

noDeleteOnStaleGet

When using time-expiring entries with ttl, by default stale items will be removed from the cache when the key is accessed with cache.get().

Setting noDeleteOnStaleGet to true will cause stale items to remain in the cache, until they are explicitly deleted with cache.delete(key), or retrieved with noDeleteOnStaleGet set to false.

This may be overridden by passing an options object to cache.get().

Boolean, default false, only relevant if ttl is set.

updateAgeOnGet

When using time-expiring entries with ttl, setting this to true will make each item's age reset to 0 whenever it is retrieved from cache with get(), causing it to not expire. (It can still fall out of cache based on recency of use, of course.)

This may be overridden by passing an options object to cache.get().

Boolean, default false, only relevant if ttl is set.

updateAgeOnHas

When using time-expiring entries with ttl, setting this to true will make each item's age reset to 0 whenever its presence in the cache is checked with has(), causing it to not expire. (It can still fall out of cache based on recency of use, of course.)

This may be overridden by passing an options object to cache.has().

Boolean, default false, only relevant if ttl is set.

API

new LRUCache<K, V, FC = unknown>(options)

Create a new LRUCache. All options are documented above, and are on the cache as public members.

The K and V types define the key and value types, respectively. The optional FC type defines the type of the context object passed to cache.fetch().

Keys and values must not be null or undefined.

cache.max, cache.maxSize, cache.allowStale,

cache.noDisposeOnSet, cache.sizeCalculation, cache.dispose, cache.maxSize, cache.ttl, cache.updateAgeOnGet, cache.updateAgeOnHas

All option names are exposed as public members on the cache object.

These are intended for read access only. Changing them during program operation can cause undefined behavior.

cache.size

The total number of items held in the cache at the current moment.

cache.calculatedSize

The total size of items in cache when using size tracking.

set(key, value, [{ size, sizeCalculation, ttl, noDisposeOnSet, start, status }])

Add a value to the cache.

Optional options object may contain ttl and sizeCalculation as described above, which default to the settings on the cache object.

If start is provided, then that will set the effective start time for the TTL calculation. Note that this must be a previous value of performance.now() if supported, or a previous value of Date.now() if not.

Options object may also include size, which will prevent calling the sizeCalculation function and just use the specified number if it is a positive integer, and noDisposeOnSet which will prevent calling a dispose function in the case of overwrites.

If the size (or return value of sizeCalculation) for a given entry is greater than maxEntrySize, then the item will not be added to the cache.

Will update the recency of the entry.

Returns the cache object.

For the usage of the status option, see Status Tracking below.

If the value is undefined, then this is an alias for cache.delete(key). undefined is never stored in the cache. See Storing Undefined Values below.

get(key, { updateAgeOnGet, allowStale, status } = {}) => value

Return a value from the cache.

Will update the recency of the cache entry found.

If the key is not found, get() will return undefined.

For the usage of the status option, see Status Tracking below.

info(key) => Entry | undefined

Return an Entry object containing the currently cached value, as well as ttl and size information if available. Returns undefined if the key is not found in the cache.

Unlike dump() (which is designed to be portable and survive serialization), the start value is always the current timestamp, and the ttl is a calculated remaining time to live (negative if expired).

Note that stale values are always returned, rather than being pruned and treated as if they were not in the cache. If you wish to exclude stale entries, guard against a negative ttl value.

async fetch(key, options = {}) => Promise

The following options are supported:

  • updateAgeOnGet
  • allowStale
  • size
  • sizeCalculation
  • ttl
  • noDisposeOnSet
  • forceRefresh
  • status - See Status Tracking below.
  • signal - AbortSignal can be used to cancel the fetch(). Note that the signal option provided to the fetchMethod is a different object, because it must also respond to internal cache state changes, but aborting this signal will abort the one passed to fetchMethod as well.
  • context - sets the context option passed to the underlying fetchMethod.

If the value is in the cache and not stale, then the returned Promise resolves to the value.

If not in the cache, or beyond its TTL staleness, then fetchMethod(key, staleValue, { options, signal, context }) is called, and the value returned will be added to the cache once resolved.

If called with allowStale, and an asynchronous fetch is currently in progress to reload a stale value, then the former stale value will be returned.

If called with forceRefresh, then the cached item will be re-fetched, even if it is not stale. However, if allowStale is set, then the old value will still be returned. This is useful in cases where you want to force a reload of a cached value. If a background fetch is already in progress, then forceRefresh has no effect.

Multiple fetches for the same key will only call fetchMethod a single time, and all will be resolved when the value is resolved, even if different options are used.

If fetchMethod is not specified, then this is effectively an alias for Promise.resolve(cache.get(key)).

When the fetch method resolves to a value, if the fetch has not been aborted due to deletion, eviction, or being overwritten, then it is added to the cache using the options provided.

If the key is evicted or deleted before the fetchMethod resolves, then the AbortSignal passed to the fetchMethod will receive an abort event, and the promise returned by fetch() will reject with the reason for the abort.

If a signal is passed to the fetch() call, then aborting the signal will abort the fetch and cause the fetch() promise to reject with the reason provided.

Setting context

If an FC type is set to a type other than unknown, void, or undefined in the LRUCache constructor, then all calls to cache.fetch() must provide a context option. If set to undefined or void, then calls to fetch must not provide a context option.

The context param allows you to provide arbitrary data that might be relevant in the course of fetching the data. It is only relevant for the course of a single fetch() operation, and discarded afterwards.

Note: fetch() calls are inflight-unique

If you call fetch() multiple times with the same key value, then every call after the first will resolve on the same promise1, even if they have different settings that would otherwise change the behvavior of the fetch, such as noDeleteOnFetchRejection or ignoreFetchAbort.

In most cases, this is not a problem (in fact, only fetching something once is what you probably want, if you're caching in the first place). If you are changing the fetch() options dramatically between runs, there's a good chance that you might be trying to fit divergent semantics into a single object, and would be better off with multiple cache instances.

1: Ie, they're not the "same Promise", but they resolve at the same time, because they're both waiting on the same underlying fetchMethod response.

peek(key, { allowStale } = {}) => value

Like get() but doesn't update recency or delete stale items.

Returns undefined if the item is stale, unless allowStale is set either on the cache or in the options object.

has(key, { updateAgeOnHas, status } = {}) => Boolean

Check if a key is in the cache, without updating the recency of use. Age is updated if updateAgeOnHas is set to true in either the options or the constructor.

Will return false if the item is stale, even though it is technically in the cache. The difference can be determined (if it matters) by using a status argument, and inspecting the has field.

For the usage of the status option, see Status Tracking below.

delete(key)

Deletes a key out of the cache.

Returns true if the key was deleted, false otherwise.

clear()

Clear the cache entirely, throwing away all values.

keys()

Return a generator yielding the keys in the cache, in order from most recently used to least recently used.

rkeys()

Return a generator yielding the keys in the cache, in order from least recently used to most recently used.

values()

Return a generator yielding the values in the cache, in order from most recently used to least recently used.

rvalues()

Return a generator yielding the values in the cache, in order from least recently used to most recently used.

entries()

Return a generator yielding [key, value] pairs, in order from most recently used to least recently used.

rentries()

Return a generator yielding [key, value] pairs, in order from least recently used to most recently used.

find(fn, [getOptions])

Find a value for which the supplied fn method returns a truthy value, similar to Array.find().

fn is called as fn(value, key, cache).

The optional getOptions are applied to the resulting get() of the item found.

dump()

Return an array of [key, entry] objects which can be passed to cache.load()

The start fields are calculated relative to a portable Date.now() timestamp, even if performance.now() is available.

Stale entries are always included in the dump, even if allowStale is false.

Note: this returns an actual array, not a generator, so it can be more easily passed around.

load(entries)

Reset the cache and load in the items in entries in the order listed. Note that the shape of the resulting cache may be different if the same options are not used in both caches.

The start fields are assumed to be calculated relative to a portable Date.now() timestamp, even if performance.now() is available.

purgeStale()

Delete any stale entries. Returns true if anything was removed, false otherwise.

getRemainingTTL(key)

Return the number of ms left in the item's TTL. If item is not in cache, returns 0. Returns Infinity if item is in cache without a defined TTL.

forEach(fn, [thisp])

Call the fn function with each set of fn(value, key, cache) in the LRU cache, from most recent to least recently used.

Does not affect recency of use.

If thisp is provided, function will be called in the this-context of the provided object.

rforEach(fn, [thisp])

Same as cache.forEach(fn, thisp), but in order from least recently used to most recently used.

pop()

Evict the least recently used item, returning its value.

Returns undefined if cache is empty.

Status Tracking

Occasionally, it may be useful to track the internal behavior of the cache, particularly for logging, debugging, or for behavior within the fetchMethod. To do this, you can pass a status object to the get(), set(), has(), and fetch() methods.

The status option should be a plain JavaScript object.

The following fields will be set appropriately:

interface Status<V> {
  /**
   * The status of a set() operation.
   *
   * - add: the item was not found in the cache, and was added
   * - update: the item was in the cache, with the same value provided
   * - replace: the item was in the cache, and replaced
   * - miss: the item was not added to the cache for some reason
   */
  set?: 'add' | 'update' | 'replace' | 'miss'

  /**
   * the ttl stored for the item, or undefined if ttls are not used.
   */
  ttl?: LRUMilliseconds

  /**
   * the start time for the item, or undefined if ttls are not used.
   */
  start?: LRUMilliseconds

  /**
   * The timestamp used for TTL calculation
   */
  now?: LRUMilliseconds

  /**
   * the remaining ttl for the item, or undefined if ttls are not used.
   */
  remainingTTL?: LRUMilliseconds

  /**
   * The calculated size for the item, if sizes are used.
   */
  size?: LRUSize

  /**
   * A flag indicating that the item was not stored, due to exceeding the
   * {@link maxEntrySize}
   */
  maxEntrySizeExceeded?: true

  /**
   * The old value, specified in the case of `set:'update'` or
   * `set:'replace'`
   */
  oldValue?: V

  /**
   * The results of a {@link has} operation
   *
   * - hit: the item was found in the cache
   * - stale: the item was found in the cache, but is stale
   * - miss: the item was not found in the cache
   */
  has?: 'hit' | 'stale' | 'miss'

  /**
   * The status of a {@link fetch} operation.
   * Note that this can change as the underlying fetch() moves through
   * various states.
   *
   * - inflight: there is another fetch() for this key which is in process
   * - get: there is no fetchMethod, so {@link get} was called.
   * - miss: the item is not in cache, and will be fetched.
   * - hit: the item is in the cache, and was resolved immediately.
   * - stale: the item is in the cache, but stale.
   * - refresh: the item is in the cache, and not stale, but
   *   {@link forceRefresh} was specified.
   */
  fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'

  /**
   * The {@link fetchMethod} was called
   */
  fetchDispatched?: true

  /**
   * The cached value was updated after a successful call to fetchMethod
   */
  fetchUpdated?: true

  /**
   * The reason for a fetch() rejection.  Either the error raised by the
   * {@link fetchMethod}, or the reason for an AbortSignal.
   */
  fetchError?: Error

  /**
   * The fetch received an abort signal
   */
  fetchAborted?: true

  /**
   * The abort signal received was ignored, and the fetch was allowed to
   * continue.
   */
  fetchAbortIgnored?: true

  /**
   * The fetchMethod promise resolved successfully
   */
  fetchResolved?: true

  /**
   * The results of the fetchMethod promise were stored in the cache
   */
  fetchUpdated?: true

  /**
   * The fetchMethod promise was rejected
   */
  fetchRejected?: true

  /**
   * The status of a {@link get} operation.
   *
   * - fetching: The item is currently being fetched.  If a previous value is
   *   present and allowed, that will be returned.
   * - stale: The item is in the cache, and is stale.
   * - hit: the item is in the cache
   * - miss: the item is not in the cache
   */
  get?: 'stale' | 'hit' | 'miss'

  /**
   * A fetch or get operation returned a stale value.
   */
  returnedStale?: true
}

Storage Bounds Safety

This implementation aims to be as flexible as possible, within the limits of safe memory consumption and optimal performance.

At initial object creation, storage is allocated for max items. If max is set to zero, then some performance is lost, and item count is unbounded. Either maxSize or ttl must be set if max is not specified.

If maxSize is set, then this creates a safe limit on the maximum storage consumed, but without the performance benefits of pre-allocation. When maxSize is set, every item must provide a size, either via the sizeCalculation method provided to the constructor, or via a size or sizeCalculation option provided to cache.set(). The size of every item must be a positive integer.

If neither max nor maxSize are set, then ttl tracking must be enabled. Note that, even when tracking item ttl, items are not preemptively deleted when they become stale, unless ttlAutopurge is enabled. Instead, they are only purged the next time the key is requested. Thus, if ttlAutopurge, max, and maxSize are all not set, then the cache will potentially grow unbounded.

In this case, a warning is printed to standard error. Future versions may require the use of ttlAutopurge if max and maxSize are not specified.

If you truly wish to use a cache that is bound only by TTL expiration, consider using a Map object, and calling setTimeout to delete entries when they expire. It will perform much better than an LRU cache.

Here is an implementation you may use, under the same license as this package:

// a storage-unbounded ttl cache that is not an lru-cache
const cache = {
  data: new Map(),
  timers: new Map(),
  set: (k, v, ttl) => {
    if (cache.timers.has(k)) {
      clearTimeout(cache.timers.get(k))
    }
    cache.timers.set(
      k,
      setTimeout(() => cache.delete(k), ttl)
    )
    cache.data.set(k, v)
  },
  get: k => cache.data.get(k),
  has: k => cache.data.has(k),
  delete: k => {
    if (cache.timers.has(k)) {
      clearTimeout(cache.timers.get(k))
    }
    cache.timers.delete(k)
    return cache.data.delete(k)
  },
  clear: () => {
    cache.data.clear()
    for (const v of cache.timers.values()) {
      clearTimeout(v)
    }
    cache.timers.clear()
  },
}

If that isn't to your liking, check out @isaacs/ttlcache.

Storing Undefined Values

This cache never stores undefined values, as undefined is used internally in a few places to indicate that a key is not in the cache.

You may call cache.set(key, undefined), but this is just an an alias for cache.delete(key). Note that this has the effect that cache.has(key) will return false after setting it to undefined.

cache.set(myKey, undefined)
cache.has(myKey) // false!

If you need to track undefined values, and still note that the key is in the cache, an easy workaround is to use a sigil object of your own.

import { LRUCache } from 'lru-cache'
const undefinedValue = Symbol('undefined')
const cache = new LRUCache(...)
const mySet = (key, value) =>
  cache.set(key, value === undefined ? undefinedValue : value)
const myGet = (key, value) => {
  const v = cache.get(key)
  return v === undefinedValue ? undefined : v
}

Performance

As of January 2022, version 7 of this library is one of the most performant LRU cache implementations in JavaScript.

Benchmarks can be extremely difficult to get right. In particular, the performance of set/get/delete operations on objects will vary wildly depending on the type of key used. V8 is highly optimized for objects with keys that are short strings, especially integer numeric strings. Thus any benchmark which tests solely using numbers as keys will tend to find that an object-based approach performs the best.

Note that coercing anything to strings to use as object keys is unsafe, unless you can be 100% certain that no other type of value will be used. For example:

const myCache = {}
const set = (k, v) => (myCache[k] = v)
const get = k => myCache[k]

set({}, 'please hang onto this for me')
set('[object Object]', 'oopsie')

Also beware of "Just So" stories regarding performance. Garbage collection of large (especially: deep) object graphs can be incredibly costly, with several "tipping points" where it increases exponentially. As a result, putting that off until later can make it much worse, and less predictable. If a library performs well, but only in a scenario where the object graph is kept shallow, then that won't help you if you are using large objects as keys.

In general, when attempting to use a library to improve performance (such as a cache like this one), it's best to choose an option that will perform well in the sorts of scenarios where you'll actually use it.

This library is optimized for repeated gets and minimizing eviction time, since that is the expected need of a LRU. Set operations are somewhat slower on average than a few other options, in part because of that optimization. It is assumed that you'll be caching some costly operation, ideally as rarely as possible, so optimizing set over get would be unwise.

If performance matters to you:

  1. If it's at all possible to use small integer values as keys, and you can guarantee that no other types of values will be used as keys, then do that, and use a cache such as lru-fast, or mnemonist's LRUCache which uses an Object as its data store.

  2. Failing that, if at all possible, use short non-numeric strings (ie, less than 256 characters) as your keys, and use mnemonist's LRUCache.

  3. If the types of your keys will be anything else, especially long strings, strings that look like floats, objects, or some mix of types, or if you aren't sure, then this library will work well for you.

    If you do not need the features that this library provides (like asynchronous fetching, a variety of TTL staleness options, and so on), then mnemonist's LRUMap is a very good option, and just slightly faster than this module (since it does considerably less).

  4. Do not use a dispose function, size tracking, or especially ttl behavior, unless absolutely needed. These features are convenient, and necessary in some use cases, and every attempt has been made to make the performance impact minimal, but it isn't nothing.

Breaking Changes in Version 7

This library changed to a different algorithm and internal data structure in version 7, yielding significantly better performance, albeit with some subtle changes as a result.

If you were relying on the internals of LRUCache in version 6 or before, it probably will not work in version 7 and above.

Breaking Changes in Version 8

  • The fetchContext option was renamed to context, and may no longer be set on the cache instance itself.
  • Rewritten in TypeScript, so pretty much all the types moved around a lot.
  • The AbortController/AbortSignal polyfill was removed. For this reason, Node version 16.14.0 or higher is now required.
  • Internal properties were moved to actual private class properties.
  • Keys and values must not be null or undefined.
  • Minified export available at 'lru-cache/min', for both CJS and MJS builds.

Changes in Version 9

  • Named export only, no default export.
  • AbortController polyfill returned, albeit with a warning when used.

For more info, see the change log.

node-lru-cache's People

Contributors

aheckmann avatar alexgleason avatar amilajack avatar cblage avatar chriscinelli avatar eugene1g avatar gkoberger avatar indutny avatar isaacs avatar jimbly avatar jldailey avatar jounqin avatar julianlam avatar kapouer avatar kentcdodds avatar kevinohara80 avatar kikobeats avatar mbroadst avatar mcavage avatar mikeybyker avatar nil1511 avatar nornagon avatar polotek avatar sebastinez avatar tedpennings avatar th507 avatar theganyo avatar thenkei avatar tootallnate avatar trentm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-lru-cache's Issues

Performance and Memory Issues (Worse now with 3.2.0)

Hi guys,

We've been using lru-cache in our product for a couple weeks now in tonicdev and have noticed some performance and memory issues. We use it all the time and love the work you guys are doing. For some context, we set the size of the cache to be 64 * 1000 * 1000 (~64MB). Our cache is storing string for keys and values (path1 -> path2). So the length calculation is just key.length + value.length (this isn't super accurate since its not 1 byte per char, but its kind of on inconsequential for what we're experiencing). So basically the cache can have as many as like 800,000 items.

Basically, we are seeing an explosion of memory use, and separately severe performance degradation once we hit the size limitation of the cache (the work of a cache miss far outweighs the benefits for cache hits). We are currently running 2.7.0, but this has gotten (significantly) worse in 3.2.0. @pouwerkerk has collected the results of a reduction we wrote (which measures worst case performance: constantly missing the cache and thus always resulting in one removal):

screen shot 2015-12-14 at 3 25 56 pm

Here you can see that once we hit the magic cutoff where we have reached the limitation of the cache size, performance degrades to up to 10s of milliseconds per retrieval (whereas before that point it had sub-millisecond performance).

Now this is the performance of 3.2.0:

screen shot 2015-12-14 at 3 31 26 pm

We believe the culprit is the new reverseKeys function which seems to create an array of the entire size of the cache on every call.

Either way, we have taken the time to write an alternate implementation that uses a doubly linked list (we based it on ideas here: http://www.geeksforgeeks.org/implement-lru-cache/ ) and thus actually slightly improves performance once the max cache size is hit (since no more new objects ever need to be created - graph below, 3.2.0 left out):

screen shot 2015-12-14 at 3 33 31 pm

We've put up the code here: https://github.com/playgroundtheory/fast-lru . It contains also the test cases in the test/ directory. You can npm install each one and just node main.js. We've also put our data here: https://docs.google.com/spreadsheets/d/1fzdFYhtd2_-BLimCPGAW_qJhKsDwigKBvWxx_n_gkDs/edit#gid=0

We wanted to run this by you guys because we know lots of packages depend on this, but we only wrote our lru to serve our needs for now (didn't both with most the methods, or maxAge, etc). All those are certainly doable and should not affect anything, but just will take a while to complete. We were hoping to get your feedback whether you thought a merge would be worthwhile, and if it is we could start moving in that direction but if not we can just keep ours up on the separate repo. Also, we only just wrote this and will be spending the rest of the day integrating it into our system, so of course would also appreciate making sure we didn't write anything incorrectly that could explain the discrepancy.

Thanks!

Francisco

Memory leaks

I don't have anything other than anecdotal evidence to support this right now, but at high volume lru-cache leaks memory. It's not noticeable on most projects, but on my high volume sites I find that the servers are bleeding memory and require restarts every few hours. This is consistent with any caching modules that uses lru-cache as the underlying mechanism (mongoose-cache, async-cache, etc).

I'm still looking into this and trying to do memory profiling to determine what the bug is. I assume it has something to do with storing complex objects. But I just wanted to give a heads up in case anyone else plans on using this at large scale.

Patch welcome: Use -1 as maxAge to always automatically expire

In isaacs/async-cache#6, @kadishmal uses 0 as the maxAge to automatically expire entries.

However, a maxAge of 0 is used as just "no maximum age" (so items never expire).

Changing maxAge of 0 to mean "automatically expire" is a huge breaking change, in a really subtle way that's bound to bite a lot of people unnecessarily. So, I'd rather not do that.

However, this module could accept -1 as a maxAge value and use that to mean "automatically expire", which at least provides a workaround.

Patch welcome for this. Please include docs and test.

reverse forEach

would be great if it would be possible to iterate over lru entries in ascending order of recent-ness

covert `.get()`

This is a strange use case but I need a .get() that doesn't effect the LRU state.

Basically, I need to check a property in the object against the request to know if it's a valid hit to the LRU.

maxAge not working in Node 6 Express app

Hi,

today i noticed in my Node (v6.0.0) Express app that maxAge is not working properly, it expires much earlier than it should:

const router = require('express').Router();
const LRU = require('lru-cache');
const activeTokensCache = new LRU({
  max: 1000,
  maxAge: 1000 * 60 * 60 * 24 * 7  // 7 days
});

router.get('/test-cache/:addToCache?', (req, res) => {
  if (req.params.addToCache) {
    const maxAge = 120 * 60 * 1000 // 120 min
    activeTokensCache.set('test', 'value', maxAge);
    return res.send('Added to cache');
  } else {
    const token = activeTokensCache.get('test');
    const response = token === undefined ? 'UNDEFINED' : token
    res.send(response);
  }
});

According to code, token should expire after 120 min. In my case, it expires after 2 min.
Here's how i tested it:

I call url to add it to cache

example.com/test-cache/1
Added to cache

After one min, item is still there:

example.com/test-cache
value

2 min after a previous call it disappears:

example.com/test-cache
UNDEFINED

When i omit maxAge on set() call, and set 120 min on global config, it expires after 5 min, which is really strange. Here's the code to test that:

const router = require('express').Router();
const LRU = require('lru-cache');
const activeTokensCache = new LRU({
  max: 1000,
  maxAge: 120 * 60 * 1000 // 120 min
});

router.get('/test-cache/:addToCache?', (req, res) => {
  if (req.params.addToCache) {
    activeTokensCache.set('test', 'value');
    return res.send('Added to cache');
  } else {
    const token = activeTokensCache.get('test');
    const response = token === undefined ? 'UNDEFINED' : token
    res.send(response);
  }
});

I don't have idea what could be a problem.

Also, some additional info: I'm running Node in Docker container (https://hub.docker.com/r/risingstack/alpine, tag 3.3-v6.0.0-3.5.0) with Docker compose. Server timezone is UTC, but that shouldn't be an issue since everything is done on the server.

Do you know what could be an issue?

Thanks.

Performance tests

I'm hesitant to use this module when there are no performance tests. How well does this module compare to other lru implementations? Another one I am looking at is js-lru.

Setting to a negative value disables the cache

It would be nice if I could pass a negative value to the cache to disable it.

This would come handy in integration-tests of my app.

I would implement it and make a pull request, just asking before if that is something that you would merge.

npm test failing locally

> tap test --branches=100 --functions=100 --lines=100 --statements=100

test/basic.js ..................................... 521/521
test/foreach.js ..................................... 72/72
test/inspect.js ..................................... 28/28
test/no-symbol.js ................................. 521/521
test/serialize.js ................................... 56/56
total ........................................... 1198/1198

  1198 passing (5s)

  ok
ERROR: No coverage files found.
---------------|----------|----------|----------|----------|----------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
---------------|----------|----------|----------|----------|----------------|
 lib/          |      100 |      100 |      100 |      100 |                |
  lru-cache.js |      100 |      100 |      100 |      100 |                |
---------------|----------|----------|----------|----------|----------------|
All files      |      100 |      100 |      100 |      100 |                |
---------------|----------|----------|----------|----------|----------------|

npm ERR! Test failed.  See above for more details.

Coverage files are being generated in .nyc_output, but maybe istanbul just doesn't know where to look for them?

calling set() inside of dispose() creates an infinite loop?

Hey there,

this may just be a case of me implementing this module incorrectly, but I'm running into an issue where I need to call cache.set() inside of the dispose handler, which seems to result in an endless set -> dispose -> set -> dispose... loop.

use case: I am caching a single API response from a server ( cache length === 1 ). When a user hits the route, they are served the cache.

If the cache is older than 1 hour, a new request should be made and stored into the cache, prior to serving the new value to the user. If this API request fails, the prior "stale" cache should be re-set for another hour, so that there is no data downtime.

Here is my code...

const cache = lru({
  max: 1,
  maxAge: ONE_HOUR,
  stale: true,
  dispose: recache,
});

function recache(key = null, value = null) {
  let prevData;
  if (key && value) {
    prevData = value;
  } else if (cache.peek('data').length) {
    prevData = cache.peek('data');
  }
  return apiRequest(endpoint, { timeout: 5000 })
    .then(({ data }) => {
      // if we got back data, set them.
      if (data && data.length) {
        return Promise.resolve(cache.set('data', data));
      }
      // otherwise, return error
      return Promise.reject(reqError(500, 'No data returned from the API.'));
    })
    .catch((err) => {
      // something went wrong, re-set the old cache values.
      return Promise.resolve(cache.set('data', prevData));
    });
}

function checkCache() {
  if (cache.has('data')) {
    return Promise.resolve();
  }
  return recache();
}

router.get('/', (req, res) => {
  checkCache()
    .then(() => res.json(cache.peek('data')))
    .catch((err) => {
      res.status(500).json({
        error: err.message,
      });
    });
});

again, I may just be implementing incorrectly, but I would appreciate any advice or input. :) It's not entirely clear to me how to use this module for one data set, that I don't want to "refresh" when it's accessed -- rather I want it to be reliably re-cached each hour.

package.json must be actual JSON, not just JavaScript

npm ERR! Darwin 13.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install"
npm ERR! node v0.10.32
npm ERR! npm v2.1.4
npm ERR! file /Users/democle/.npm/lru-cache/2.5.0/package/package.json
npm ERR! code EJSONPARSE

npm ERR! Failed to parse json
npm ERR! Unexpected end of input
npm ERR! File: /Users/democle/.npm/lru-cache/2.5.0/package/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

option to set maxAge on a cache key

Right now the maxAge is setup on the options of the lru-cache instance.
Would it be useful to specify the maxAge when doing a set? ie. LRU.set('key', 'value', 3000)

iterable prune

Currently if one have a very large cache, prune can take a very long time blocking other tasks. It would be nice to have a way to prune parts of the cache, do other work and continue pruning. If lru-cache had some form of iterator in its public API this could be easily achieve.

Breaking change in 2.7.1

I am getting the following error on 2.7.1 when calling has(undefined);

.../node_modules/lru-cache/lib/lru-cache.js:18
    throw new TypeError("key must be a string or number. " + typeof key)

While it makes sense to throw now, it did not throw in 2.7.0.
Should this be a major release instead?

More detailed log

jacobp:/tmp
$ npm i [email protected]
[email protected] node_modules/lru-cache
jacobp:/tmp
$ node
> var cache = require('lru-cache')(10)
undefined
> cache.has(undefined)
false
> 
(^C again to quit)
> 
jacobp:/tmp
$ npm i [email protected]
[email protected] node_modules/lru-cache
jacobp:/tmp
$ node
> var cache = require('lru-cache')(10)
undefined
> cache.has(undefined)
TypeError: key must be a string or number. undefined
    at typeCheckKey (/private/tmp/node_modules/lru-cache/lib/lru-cache.js:18:11)
    at LRUCache.has (/private/tmp/node_modules/lru-cache/lib/lru-cache.js:217:3)
    at repl:1:7
    at REPLServer.defaultEval (repl.js:164:27)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:393:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:210:10)
> 

Using maxAge does not check for item's age. It checks for last access time.

I'm not sure if this is intended behaviour. Up to version 2.5.0 setting maxAge caused removal of item from cache after maxAge milliseconds. At the moment the check is not made against total age of item but against its last access date.

This means that cached item can be stored indefinately if they are accessed often. Item will be removed only if it's accessed after time greater than maxAge.

Is this intended behaviour? If it is it should be made clear in the documentation.

No changelog

Please add changelog at least for major releases.

getOrCreate() method

This seems like a very common use case, and in fact it's the preferred way you use a cache in Rails. Is there any reason it's not implemented?

cache.getOrCreate(key, () => { expensive computation })

Where:

LRU.prototype.fetch = function (key, fn) {
  if (this.has(key)) return this.get(key)
  var result = fn()
  this.set(key, result)
  return result
}

proactive pruning

The documentation indicates that given a maxAge "Items are not pro-actively pruned out as they age". Are there any plans to provide such behavior? Has anyone been able to implement this easily with the existing implementation?

Add an environment configuration to disable cache

The logic is similar to the reason https://github.com/gajus/bluefeather#map adds BLUEFEATHER_MAX_CONCURRENCY configuration:

This method is identical to Bluebird#map except that the concurrency setting can be overridden using BLUEFEATHER_MAX_CONCURRENCY environment variable. Controlling max concurrency using environment variables enables debugging of the codebase without refactoring the code.

Sometimes you want to quickly check if cache is the causing the underlying issue. Having a way to disable LRU cache with environment variable would be useful.

Clarification of length usage

Could someone clarify

  • how is the length in options being used by this library and
  • a few examples on how to set it correctly

For example, in the docs (under usage) I see
length: function (n, key) { return n * 2 + key.length }

Does this mean the key length should be added every time?
What if I am storing array of complex JS objects using a string key?
Should I calculate length as array length plus key length? Or do I need to consider the object size as well?

A few examples would be really helpful.

Thanks
Z

The method get doesn't update the "recently used"-ness of the key as the doc says

The documentation says (under the get and set methods):

Both of these will update the "recently used"-ness of the key. They do what you think.

But the get method doesn't update the element age. I checked the source code, and the now attribute of the hit isn't updated. I made this simple test code to check and confirm this:

var LRU = require("lru-cache");

var cache = LRU( {
    max: 100,
    maxAge: 10000
} );

cache.set( "1234", 1 );

setTimeout( function() {
    cache.set( "1234", 2 );
    console.log( "testing after 5s: " + cache.get( "1234" ) );
}, 5000 );

setTimeout( function() {
    console.log( "testing after 9s: " + cache.get( "1234" ) );
}, 9000 );

setTimeout( function() {
    console.log( "testing after 11s: " + cache.get( "1234" ) );
}, 11000 );

setTimeout( function() {
    console.log( "testing after 16s: " + cache.get( "1234" ) );
}, 16000 );

If the get method updates the age of the key, shouldn't the last timeout (16s) print the value 2 again instead of undefined?

itemCount is not reduced when trim() is executed

When trim() is executed to remove the items when length > max then itemCount is not reduced. Because of that cache.keys().length becomes more than max.

For example
var LRU = require("lru-cache");
var options = { max: 5 };
var cache = LRU(options);
cache.set("key1", "value1");
cache.set("key2", "value2");
cache.set("key3", "value3");
cache.set("key4", "value4");
cache.set("key5", "value5");
cache.set("key6", "value6");

cache.keys() now returns [ 'key6',
'key5',
'key4',
'key3',
'key2',
] and cache.keys().length returns 6

when you do add one more value to the cache like cache.set("key7", "value7"); then
cache.keys() returns
[ 'key7',
'key6',
'key5',
'key4',
'key3',
,
] and cache.keys().length returns 7.

I wonder whether this will lead to a memory leak when we add more items to the cache even if there is "max" property is set.

Performance issue on Node 4x

On NodeJS 4x, when configuring lru-cache with a max setting above 8192, behavior gradually becomes very slow. The longer it runs, the slower it gets.

Starting with a max of 8193, the program abruptly slows down soon after the maximum number of elements have been reached. Soon it will take upwards of 30 seconds to process 5000 set/removes. As the max setting is raised higher and higher, performance still slows down but the program needs to run longer and longer to reach the same level of performance degradation.

I haven't been able to reproduce this behavior on any of these earlier releases of Node/iojs:

  • iojs-3.3.1
  • iojs-2.5.0
  • iojs-1.8.4
  • node-0.12.7
  • node-0.11.16
  • node-0.10.40

This is probably a V8 bug but worth making this known here.

Note: I forked this module and changed it to use Map instead of Object.create(null) and the issue is resolved. Not sure if switching to a Map is the right choice for this module due to backward compatibility (and browser support) but it looks like it could be a good solution going forward. I haven't pushed my code public yet but let me know if you'd be interested in going that direction.

`load()` methods

We have .dump() and .dumpLRU, would be nice if you could do something like.

var lru = require('lru-cache').load(JSON.parse(fs.readFileSync('./dump.json').toString()))

Maybe a matching one for loadLRU.

length (value, key)

My cache stores path->path. As such, the keys kind of take up as much space as the values. I could do length(v) => v.length * 2, but length(v,k) => v.length + k.length would be ideal.

IE compatibility

I ran into an IE bug when using LRUCache with numeric keys.

The bug is documented here. Here's the important part:

All IEs that support Object.create seem to be affected. If there are only numeric properties in the created object and no new keyword has been used to initialize the same, hasOwnProperty check as well as isPropertyEnumerable will miserably fail.

The bug affects LRUCache's hOP check during LRUCache.prototype.set. In IE, if I only have numeric keys and try to set with an existing key, set will think that the key doesn't yet exist and create a new entry instead of overwriting the existing entry.

There are a couple ways we can get around this

1 Modify hOP to use the in operator. This is safe because hOP is only used on this._cache and this._cache has no prototype.

function hOP (obj, key) {
  return key in obj;
}

2 Modify the creation of this._cache. If we set a configurable numeric property and then delete it, the object will then behave correctly.

function makeObject() {
  var obj = Object.create(null);
  delete Object.defineProperty(obj, 0, {configurable: true})[0];
  return obj;
}

@isaacs do you have any preference on which fix to apply? 2 seems like the safer route, since hOP's behavior will be unchanged. There won't be much of a performance hit since objects are only created in LRUCache.prototype.reset. I'm happy to open a PR.

What is the mean about option: max? what is the unit? byte? or kb?

I try below code:

var options = { max: 100,
    length: function (n, key) {console.log(`-${n} ${key}-`); return n + key.length;},
    dispose: function (key, n) { console.log(`delete ${key}`);},
    maxAge: 1000 * 60 * 60
    
}
var cache = LRU(options);
const repl = require('repl');

const replServer = repl.start({prompt: '> '});
for(var i = 0 ; i < 100000; i++){
    cache.set('k' + i, 'v' + i);
}

I had set max = 100, and length function And put 100000 item into cache. But it i can get every item, Why? the max does not work?

Iteration API

It would be nice to be able to iterate over at least all the keys in the cache

test failure no-symbol.js

On node 6.9.1, running tap 8

TypeError: Symbol is not a function
    at net.js:122:20
    at NativeModule.compile (bootstrap_node.js:497:7)
    at NativeModule.require (bootstrap_node.js:438:18)
    at internal/child_process.js:6:13
    at NativeModule.compile (bootstrap_node.js:497:7)
    at NativeModule.require (bootstrap_node.js:438:18)
    at child_process.js:12:23
    at NativeModule.compile (bootstrap_node.js:497:7)
    at Function.NativeModule.require (bootstrap_node.js:438:18)
    at Function.Module._load (module.js:426:25)

MRU & Max Safe Integer

I can see a potential flaw in your _mru counter. We're using lru-cache as our services receive several thousand requests a second. If there is never any reduction in the MRU counter, eventually it'll overflow the Number.MAX_SAFE_INTEGER and things will begin to go pair shaped.

To create ourselves a safety net, we have implemented an interval that resets the cache every hour. Would you consider a configurable option to do something like this in your module? Or maybe just something that resets when it sees the MRU is at the MAX_SAFE_INTEGER?

For each doesn't remove all stale entries

As for each has two boundaries namely: k which decrements and i which increments, it will not delete all stale children inside the cache.

Example:

Cache has 3 entries, all stale, the least recently used one won't be removed from the cache.

Simple usage leaks memory

The below code leaks memory for me at a steady rate of approximately 100KB per second.

var lru = require('lru-cache');

var leaks = lru(1);
var index = 0;

setInterval(function() {
    index += 1;
    if (index === 10) {
        index = 0;
    }
    leaks.set(('key' + index), 'item');
}, 1);

There must be something I am doing wrong here, though I can't seem to figure out what that is. Any input would be appreciated!

2.7.2 breaks backwards compatibility

With [email protected] this code works. It stores an object in the cache using a mongo ObjectID as key:

var LRU = require('lru-cache');
var ObjectID = require('mongodb').ObjectID;

var cache = LRU();
var key = new ObjectID();
cache.set(key, {}) // works fine

Something changed in [email protected] that broke backwards compatibility, as now the call to cache.set complains about the key not being a string:

TypeError: key must be a string or number. object
    at typeCheckKey (..node_modules/lru-cache/lib/lru-cache.js:18:11)
    at LRUCache.set (...node_modules/lru-cache/lib/lru-cache.js:171:3)
    at repl:1:7
    ...

This new behaviour sounds reasonable to me, but I think it should be fixed in a major release (not in 2.7.x), as it breaks backwards compatibility. What do you think?

I'm using node 4.2.1 if that helps.

Using objects as cache keys

As I'm sure you know, using objects as cache keys causes a 100% collision rate for all object keys. All object keys are stored with a key [object Object] and therefore resolve to the same value.

Would you be open to a PR to allow users to specify objects as cache keys?

We could use an array as the underlying store, for the object section or for the whole cache (slower). Here's the basic implementation I'd add:

const cacheArray = []

function get(key) {
  const hit = cacheArray.find(elem => elem.key === key)
  if (hit) {
    // LRU staleness and touch logic here
    return hit.value
  }
  return false
}

function set(key, value) {
  cacheArray.push({key, value})
  // LRU eviction logic here
}

If you don't want to do this, no worries, but I'd love to send README PR to mention that cache keys should not be an object (or array).

Object and arrays as keys not working

Hi, you've made a great, very useful library!
But it seems that .get() doesn't work with keys that are objects or arrays. I have v4.0.0 of the library and v4.3.1 of node:

$ node
> var lru = require('lru-cache');
undefined
> var cache = lru();
undefined
> cache
LRUCache {}
> cache.set('1', 1);
true
> cache.get('1'); // this is OK
1
> cache.set(2, 3);
true
> cache.get(2) // again OK
3
> cache.set({ a: 1, b : 1 }, 4);
true
> cache.get({ a: 1, b : 1 }) // oops
undefined
> cache.set([1,2,3,4], 5);
true
> cache.get([1,2,3,4]) // no no
undefined
> cache.keys() // however it seems that all keys were saved
[ [ 1, 2, 3, 4 ], { a: 1, b: 1 }, 2, '1' ]
> cache.values() // and all values too
[ 5, 4, 3, 1 ]

Please advise if I'm doing something wrong. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.