|
| 1 | +import { LRUCache } from "lru-cache"; |
| 2 | +import { CacheError } from "@unkey/cache"; |
| 3 | +import type { Store, Entry } from "@unkey/cache/stores"; |
| 4 | +import { Ok, Err, type Result } from "@unkey/error"; |
| 5 | + |
| 6 | +export type LRUMemoryStoreConfig = { |
| 7 | + /** |
| 8 | + * Maximum number of items to store in the cache. |
| 9 | + * This is a hard limit - the cache will never exceed this size. |
| 10 | + */ |
| 11 | + max: number; |
| 12 | + |
| 13 | + /** |
| 14 | + * Name for metrics/tracing. |
| 15 | + * @default "lru-memory" |
| 16 | + */ |
| 17 | + name?: string; |
| 18 | +}; |
| 19 | + |
| 20 | +/** |
| 21 | + * A memory store implementation using lru-cache. |
| 22 | + * |
| 23 | + * This provides O(1) get/set/delete operations and automatic LRU eviction |
| 24 | + * without blocking the event loop (unlike @unkey/cache's MemoryStore which |
| 25 | + * uses O(n) synchronous iteration for eviction). |
| 26 | + * |
| 27 | + * TTL is checked lazily on get() - expired items are not proactively removed |
| 28 | + * but will be evicted by LRU when the cache is full. |
| 29 | + */ |
| 30 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 31 | +export class LRUMemoryStore<TNamespace extends string, TValue = any> |
| 32 | + implements Store<TNamespace, TValue> |
| 33 | +{ |
| 34 | + readonly name: string; |
| 35 | + private readonly cache: LRUCache<string, Entry<TValue>>; |
| 36 | + |
| 37 | + constructor(config: LRUMemoryStoreConfig) { |
| 38 | + this.name = config.name ?? "lru-memory"; |
| 39 | + this.cache = new LRUCache<string, Entry<TValue>>({ |
| 40 | + max: config.max, |
| 41 | + // Don't use ttlAutopurge - it creates a setTimeout per item which |
| 42 | + // doesn't scale well at high throughput (thousands of items/second). |
| 43 | + // Instead, we check TTL lazily on get(). |
| 44 | + ttlAutopurge: false, |
| 45 | + // Allow returning stale values - the cache layer handles SWR semantics |
| 46 | + allowStale: true, |
| 47 | + // Use the staleUntil timestamp for TTL calculation |
| 48 | + ttl: 1, // Placeholder, we set per-item TTL in set() |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + private buildCacheKey(namespace: TNamespace, key: string): string { |
| 53 | + return `${namespace}::${key}`; |
| 54 | + } |
| 55 | + |
| 56 | + async get( |
| 57 | + namespace: TNamespace, |
| 58 | + key: string |
| 59 | + ): Promise<Result<Entry<TValue> | undefined, CacheError>> { |
| 60 | + try { |
| 61 | + const cacheKey = this.buildCacheKey(namespace, key); |
| 62 | + const entry = this.cache.get(cacheKey); |
| 63 | + |
| 64 | + if (!entry) { |
| 65 | + return Ok(undefined); |
| 66 | + } |
| 67 | + |
| 68 | + // Check if entry is expired (past staleUntil) |
| 69 | + // The cache layer will handle fresh vs stale semantics |
| 70 | + if (entry.staleUntil <= Date.now()) { |
| 71 | + // Remove expired entry |
| 72 | + this.cache.delete(cacheKey); |
| 73 | + return Ok(undefined); |
| 74 | + } |
| 75 | + |
| 76 | + return Ok(entry); |
| 77 | + } catch (err) { |
| 78 | + return Err( |
| 79 | + new CacheError({ |
| 80 | + tier: this.name, |
| 81 | + key, |
| 82 | + message: err instanceof Error ? err.message : String(err), |
| 83 | + }) |
| 84 | + ); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + async set( |
| 89 | + namespace: TNamespace, |
| 90 | + key: string, |
| 91 | + entry: Entry<TValue> |
| 92 | + ): Promise<Result<void, CacheError>> { |
| 93 | + try { |
| 94 | + const cacheKey = this.buildCacheKey(namespace, key); |
| 95 | + |
| 96 | + // Calculate TTL from staleUntil timestamp |
| 97 | + const ttl = Math.max(0, entry.staleUntil - Date.now()); |
| 98 | + |
| 99 | + this.cache.set(cacheKey, entry, { ttl }); |
| 100 | + |
| 101 | + return Ok(undefined as void); |
| 102 | + } catch (err) { |
| 103 | + return Err( |
| 104 | + new CacheError({ |
| 105 | + tier: this.name, |
| 106 | + key, |
| 107 | + message: err instanceof Error ? err.message : String(err), |
| 108 | + }) |
| 109 | + ); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + async remove( |
| 114 | + namespace: TNamespace, |
| 115 | + keys: string | string[] |
| 116 | + ): Promise<Result<void, CacheError>> { |
| 117 | + try { |
| 118 | + const keyArray = Array.isArray(keys) ? keys : [keys]; |
| 119 | + |
| 120 | + for (const key of keyArray) { |
| 121 | + const cacheKey = this.buildCacheKey(namespace, key); |
| 122 | + this.cache.delete(cacheKey); |
| 123 | + } |
| 124 | + |
| 125 | + return Ok(undefined as void); |
| 126 | + } catch (err) { |
| 127 | + return Err( |
| 128 | + new CacheError({ |
| 129 | + tier: this.name, |
| 130 | + key: Array.isArray(keys) ? keys.join(",") : keys, |
| 131 | + message: err instanceof Error ? err.message : String(err), |
| 132 | + }) |
| 133 | + ); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Returns the current number of items in the cache. |
| 139 | + */ |
| 140 | + get size(): number { |
| 141 | + return this.cache.size; |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * Clears all items from the cache. |
| 146 | + */ |
| 147 | + clear(): void { |
| 148 | + this.cache.clear(); |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +/** |
| 153 | + * Creates an LRU memory store with the specified maximum size. |
| 154 | + * |
| 155 | + * This is a drop-in replacement for createMemoryStore() that uses lru-cache |
| 156 | + * instead of @unkey/cache's MemoryStore, providing: |
| 157 | + * - O(1) operations (vs O(n) eviction in MemoryStore) |
| 158 | + * - No event loop blocking |
| 159 | + * - Strict memory bounds (hard max vs soft cap) |
| 160 | + * |
| 161 | + * @param maxItems Maximum number of items to store |
| 162 | + * @param name Optional name for metrics/tracing (default: "lru-memory") |
| 163 | + */ |
| 164 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 165 | +export function createLRUMemoryStore(maxItems: number, name?: string): LRUMemoryStore<string, any> { |
| 166 | + return new LRUMemoryStore({ max: maxItems, name }); |
| 167 | +} |
0 commit comments