UNPKG

@credo-ts/core

Version:

<p align="center"> <br /> <img alt="Credo Logo" src="https://github.com/openwallet-foundation/credo-ts/blob/c7886cb8377ceb8ee4efe8d264211e561a75072d/images/credo-logo.png" height="250px" /> </p> <h1 align="center"><b>Credo - Core</b></h1

59 lines (58 loc) • 1.94 kB
import LRUMap from "lru_map"; //#region src/modules/cache/InMemoryLruCache.ts /** * In memory LRU cache. * * This cache can be used with multiple agent context instances. Keys are namespaced by the * `contextCorrelationId` of the agent context by default, and by `global:` for entries using the * `'global'` scope. Note that separate root agent instances sharing this cache also share the * `default` context namespace. * * The `limit` applies to the cache as a whole, spanning all contexts and the global scope, so a * busy context can evict entries of other contexts. `clear()` also clears all scopes and contexts. */ var InMemoryLruCache = class { constructor({ limit }) { this.cache = new LRUMap.LRUMap(limit); } getNamespacedKey(agentContext, key, options) { if (options?.scope === "global") return `global:${key}`; return `${agentContext.contextCorrelationId}:${key}`; } async get(agentContext, key, options) { this.removeExpiredItems(); key = this.getNamespacedKey(agentContext, key, options); const item = this.cache.get(key); if (!item) return null; return item.value; } async set(agentContext, key, value, expiresInSeconds, options) { this.removeExpiredItems(); let expiresDate; if (expiresInSeconds) { expiresDate = /* @__PURE__ */ new Date(); expiresDate.setSeconds(expiresDate.getSeconds() + expiresInSeconds); } key = this.getNamespacedKey(agentContext, key, options); this.cache.set(key, { expiresAt: expiresDate?.getTime(), value }); } clear() { this.cache.clear(); } async remove(agentContext, key, options) { this.removeExpiredItems(); key = this.getNamespacedKey(agentContext, key, options); this.cache.delete(key); } removeExpiredItems() { this.cache.forEach((value, key) => { if (value.expiresAt && Date.now() > value.expiresAt) this.cache.delete(key); }); } }; //#endregion export { InMemoryLruCache }; //# sourceMappingURL=InMemoryLruCache.mjs.map