import { cacheConfig } from "../config/cache.js"; import { cacheHits, cacheMisses } from "../monitoring/metrics.js"; import { logCacheHit, logCacheMiss } from "../monitoring/logger.js"; import { RedisCache } from "./redisCache.js"; /** * Cache-Interface für Abstraktion */ export interface CacheInterface { set(key: string, data: T, ttl?: number): void | Promise; get(key: string): T | null | Promise; clear(): void | Promise; delete(key: string): void | Promise; } /** * In-Memory Cache (Fallback wenn Redis nicht verfügbar) */ class InMemoryCache implements CacheInterface { private cache = new Map(); private defaultTTL: number; private cacheType: string; constructor(defaultTTL: number, cacheType: string) { this.defaultTTL = defaultTTL; this.cacheType = cacheType; } async set(key: string, data: T, ttl?: number): Promise { const expiresAt = Date.now() + (ttl || this.defaultTTL); this.cache.set(key, { data, expiresAt }); } async get(key: string): Promise { const entry = this.cache.get(key); if (!entry) { cacheMisses.inc({ cache_type: this.cacheType }); logCacheMiss(key, this.cacheType); return null; } if (Date.now() > entry.expiresAt) { this.cache.delete(key); cacheMisses.inc({ cache_type: this.cacheType }); logCacheMiss(key, this.cacheType); return null; } cacheHits.inc({ cache_type: this.cacheType }); logCacheHit(key, this.cacheType); return entry.data; } async clear(): Promise { this.cache.clear(); } async delete(key: string): Promise { this.cache.delete(key); } } /** * Cache-Instanzen * Verwendet Redis wenn aktiviert, sonst In-Memory */ const useRedis = process.env["REDIS_ENABLED"] === "true"; export const cache = { pages: useRedis ? new RedisCache(cacheConfig.pages.ttl, "pages") : new InMemoryCache(cacheConfig.pages.ttl, "pages"), pageSeo: useRedis ? new RedisCache(cacheConfig.pageSeo.ttl, "pageSeo") : new InMemoryCache(cacheConfig.pageSeo.ttl, "pageSeo"), navigation: useRedis ? new RedisCache(cacheConfig.navigation.ttl, "navigation") : new InMemoryCache(cacheConfig.navigation.ttl, "navigation"), products: useRedis ? new RedisCache(cacheConfig.products.ttl, "products") : new InMemoryCache(cacheConfig.products.ttl, "products"), };