All files server/cache-providers/memory.ts

64.44% Statements 58/90
52.72% Branches 29/55
73.33% Functions 11/15
63.63% Lines 56/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301                                                                                                                  80x       80x     80x 80x     80x 80x 76x         76x 76x                     48x 48x   24x 24x 4x 4x 4x       20x   20x                             56x 56x     56x       56x             56x                                         4x     4x 4x 4x 12x 8x 8x 8x                                                           4x               12x 12x   4x           4x               80x 76x 76x   80x 80x                     4x 4x   4x 8x 8x 8x 8x       4x               16x                                     4x                   76x 76x       96x 96x 40x                            
/**
 * In-memory cache provider for Drizzle Cube
 * Suitable for development, testing, or single-instance deployments
 */
 
import type { CacheProvider, CacheGetResult } from '../types'
 
/**
 * Internal cache entry structure with TTL tracking
 */
interface CacheEntry<T> {
  value: T
  cachedAt: number
  ttlMs: number
  expiresAt: number
}
 
/**
 * Options for MemoryCacheProvider
 */
export interface MemoryCacheProviderOptions {
  /**
   * Default TTL in milliseconds
   * @default 300000 (5 minutes)
   */
  defaultTtlMs?: number
 
  /**
   * Maximum number of entries in the cache
   * When exceeded, oldest entries are evicted (LRU)
   * @default undefined (unlimited)
   */
  maxEntries?: number
 
  /**
   * Interval in milliseconds to run automatic cleanup
   * Set to 0 to disable automatic cleanup
   * @default 60000 (1 minute)
   */
  cleanupIntervalMs?: number
}
 
/**
 * Simple in-memory cache provider implementing the CacheProvider interface
 *
 * Features:
 * - TTL support with automatic expiration on read
 * - Optional automatic cleanup of expired entries
 * - Optional max entries limit with LRU eviction
 * - Full metadata support for TTL tracking
 *
 * Limitations:
 * - Not shared across processes/instances
 * - Data lost on process restart
 * - Not suitable for distributed deployments
 */
export class MemoryCacheProvider implements CacheProvider {
  private cache = new Map<string, CacheEntry<unknown>>()
  private defaultTtlMs: number
  private maxEntries?: number
  private cleanupIntervalId?: ReturnType<typeof setInterval>
  private accessOrder: string[] = [] // For LRU tracking
 
  constructor(options: MemoryCacheProviderOptions = {}) {
    this.defaultTtlMs = options.defaultTtlMs ?? 300000 // 5 minutes
    this.maxEntries = options.maxEntries
 
    // Start automatic cleanup if enabled
    const cleanupInterval = options.cleanupIntervalMs ?? 60000
    if (cleanupInterval > 0) {
      this.cleanupIntervalId = setInterval(() => {
        this.cleanup()
      }, cleanupInterval)
 
      // Unref the interval so it doesn't prevent process exit
      Eif (typeof this.cleanupIntervalId === 'object' && 'unref' in this.cleanupIntervalId) {
        this.cleanupIntervalId.unref()
      }
    }
  }
 
  /**
   * Get a cached value by key
   * Returns null if not found or expired
   * Automatically removes expired entries on access
   */
  async get<T>(key: string): Promise<CacheGetResult<T> | null> {
    const entry = this.cache.get(key)
    if (!entry) return null
 
    const now = Date.now()
    if (now > entry.expiresAt) {
      this.cache.delete(key)
      this.removeFromAccessOrder(key)
      return null
    }
 
    // Update LRU order
    this.touchAccessOrder(key)
 
    return {
      value: entry.value as T,
      metadata: {
        cachedAt: entry.cachedAt,
        ttlMs: entry.ttlMs,
        ttlRemainingMs: entry.expiresAt - now
      }
    }
  }
 
  /**
   * Set a value in the cache
   * Respects maxEntries limit with LRU eviction
   */
  async set<T>(key: string, value: T, ttlMs?: number): Promise<void> {
    const ttl = ttlMs ?? this.defaultTtlMs
    const now = Date.now()
 
    // Check if we need to evict entries for maxEntries
    Iif (this.maxEntries && this.cache.size >= this.maxEntries && !this.cache.has(key)) {
      this.evictOldest()
    }
 
    this.cache.set(key, {
      value,
      cachedAt: now,
      ttlMs: ttl,
      expiresAt: now + ttl
    })
 
    this.touchAccessOrder(key)
  }
 
  /**
   * Delete a specific key from the cache
   * Returns true if key existed and was deleted
   */
  async delete(key: string): Promise<boolean> {
    const existed = this.cache.delete(key)
    if (existed) {
      this.removeFromAccessOrder(key)
    }
    return existed
  }
 
  /**
   * Delete all keys matching a pattern
   * Supports glob-style patterns with trailing '*'
   * Returns number of keys deleted
   */
  async deletePattern(pattern: string): Promise<number> {
    let deleted = 0
 
    // Simple glob matching - only supports trailing *
    if (pattern.endsWith('*')) {
      const prefix = pattern.slice(0, -1)
      for (const key of this.cache.keys()) {
        if (key.startsWith(prefix)) {
          this.cache.delete(key)
          this.removeFromAccessOrder(key)
          deleted++
        }
      }
    E} else if (pattern.startsWith('*')) {
      const suffix = pattern.slice(1)
      for (const key of this.cache.keys()) {
        if (key.endsWith(suffix)) {
          this.cache.delete(key)
          this.removeFromAccessOrder(key)
          deleted++
        }
      }
    } else if (pattern.includes('*')) {
      // Handle middle wildcard: prefix*suffix
      const [prefix, suffix] = pattern.split('*')
      for (const key of this.cache.keys()) {
        if (key.startsWith(prefix) && key.endsWith(suffix)) {
          this.cache.delete(key)
          this.removeFromAccessOrder(key)
          deleted++
        }
      }
    } else {
      // No wildcard - exact match
      if (this.cache.delete(pattern)) {
        this.removeFromAccessOrder(pattern)
        deleted++
      }
    }
 
    return deleted
  }
 
  /**
   * Check if a key exists in the cache
   * Returns false for expired entries
   */
  async has(key: string): Promise<boolean> {
    const entry = this.cache.get(key)
    if (!entry) return false
 
    Iif (Date.now() > entry.expiresAt) {
      this.cache.delete(key)
      this.removeFromAccessOrder(key)
      return false
    }
 
    return true
  }
 
  /**
   * Stop automatic cleanup and clear the cache
   * Call this when the cache provider is no longer needed
   */
  async close(): Promise<void> {
    if (this.cleanupIntervalId) {
      clearInterval(this.cleanupIntervalId)
      this.cleanupIntervalId = undefined
    }
    this.cache.clear()
    this.accessOrder = []
  }
 
  /**
   * Remove all expired entries from the cache
   * Called automatically by cleanup interval
   * Can also be called manually
   *
   * @returns Number of entries removed
   */
  cleanup(): number {
    const now = Date.now()
    let cleaned = 0
 
    for (const [key, entry] of this.cache.entries()) {
      Eif (now > entry.expiresAt) {
        this.cache.delete(key)
        this.removeFromAccessOrder(key)
        cleaned++
      }
    }
 
    return cleaned
  }
 
  /**
   * Get current cache size (number of entries)
   * Note: May include expired entries that haven't been cleaned up yet
   */
  size(): number {
    return this.cache.size
  }
 
  /**
   * Clear all entries from the cache
   */
  clear(): void {
    this.cache.clear()
    this.accessOrder = []
  }
 
  /**
   * Get cache statistics
   */
  stats(): {
    size: number
    maxEntries?: number
    defaultTtlMs: number
  } {
    return {
      size: this.cache.size,
      maxEntries: this.maxEntries,
      defaultTtlMs: this.defaultTtlMs
    }
  }
 
  // LRU tracking helpers
 
  private touchAccessOrder(key: string): void {
    this.removeFromAccessOrder(key)
    this.accessOrder.push(key)
  }
 
  private removeFromAccessOrder(key: string): void {
    const index = this.accessOrder.indexOf(key)
    if (index > -1) {
      this.accessOrder.splice(index, 1)
    }
  }
 
  private evictOldest(): void {
    // Evict the least recently used entry
    while (this.accessOrder.length > 0 && this.maxEntries && this.cache.size >= this.maxEntries) {
      const oldestKey = this.accessOrder.shift()
      if (oldestKey) {
        this.cache.delete(oldestKey)
      }
    }
  }
}