Spaces:
Running

File size: 12,127 Bytes
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10963b9
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
7226608
 
50a005c
 
 
 
 
 
 
da57150
 
 
50a005c
da57150
50a005c
 
da57150
50a005c
 
 
 
da57150
50a005c
 
da57150
50a005c
 
 
 
 
 
 
 
 
da57150
50a005c
 
da57150
50a005c
da57150
50a005c
 
da57150
50a005c
 
 
 
 
92398e6
 
 
da57150
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
2eb93af
50a005c
 
2eb93af
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10963b9
50a005c
 
 
 
 
10963b9
50a005c
 
 
 
 
 
 
 
 
10963b9
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
700d33c
 
 
 
 
 
 
 
50a005c
 
 
da57150
700d33c
da57150
50a005c
 
 
 
 
 
 
 
 
 
 
2eb93af
7e932a9
50a005c
 
 
 
 
10963b9
50a005c
 
10963b9
50a005c
 
 
 
 
 
7e932a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10963b9
7e932a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50a005c
7e932a9
 
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
 * Redis Cache Layer — In-Memory LRU Fallback
 *
 * Architecture:
 * - If REDIS_URL is set → uses Redis for distributed caching
 * - If REDIS_URL is empty → falls back to in-memory LRU cache
 * - Both share the same API, so callers don't care which is active
 *
 * This is critical for:
 * 1. Course list queries (hit by every visitor)
 * 2. Category lists (hit on every page load)
 * 3. Testimonials (hit on homepage)
 * 4. Stats (hit on homepage)
 * 5. Session/rate-limit data (distributed across replicas)
 */

import { env } from "./env";
import { logger } from "./logger.js";

// ─── Types ───────────────────────────────────────────────────────────────────

interface CacheEntry<T> {
  value: T;
  expiresAt: number; // Unix timestamp ms
}

type CacheResult<T> = T | null;

// ─── In-Memory LRU Cache (fallback when no Redis) ────────────────────────────

class MemoryLRUCache {
  private readonly store = new Map<string, CacheEntry<unknown>>();
  private readonly maxSize: number;

  constructor(maxSize = 500) {
    this.maxSize = maxSize;
    // Cleanup expired entries every 5 minutes
    setInterval(() => this.cleanup(), 5 * 60 * 1000).unref();
  }

  // Purely synchronous in-memory ops — the Promise shape is kept so the
  // Memory/Redis implementations stay interchangeable behind the unified API.
  get<T>(key: string): Promise<CacheResult<T>> {
    const entry = this.store.get(key);
    if (!entry) return Promise.resolve(null);
    if (Date.now() > entry.expiresAt) {
      this.store.delete(key);
      return Promise.resolve(null);
    }
    // Move to end (most recently used)
    this.store.delete(key);
    this.store.set(key, entry);
    return Promise.resolve(entry.value as T);
  }

  set<T>(key: string, value: T, ttlSeconds: number): Promise<void> {
    // Evict oldest if at capacity
    if (this.store.size >= this.maxSize) {
      const firstKey = this.store.keys().next().value;
      if (firstKey) this.store.delete(firstKey);
    }
    this.store.set(key, {
      value,
      expiresAt: Date.now() + ttlSeconds * 1000,
    });
    return Promise.resolve();
  }

  del(key: string): Promise<void> {
    this.store.delete(key);
    return Promise.resolve();
  }

  delPattern(pattern: string): Promise<void> {
    // Simple prefix matching for in-memory
    const keysToDelete: string[] = [];
    for (const key of this.store.keys()) {
      if (key.startsWith(pattern)) keysToDelete.push(key);
    }
    for (const k of keysToDelete) {
      this.store.delete(k);
    }
    return Promise.resolve();
  }

  private cleanup(): void {
    const now = Date.now();
    for (const [key, entry] of this.store) {
      if (now > entry.expiresAt) this.store.delete(key);
    }
  }
}

// ─── Redis Cache ─────────────────────────────────────────────────────────────

class RedisCache {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private client: any = null;
  private connected = false;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private async getClient(): Promise<any> {
    if (this.client && this.connected) return this.client;

    try {
      const Redis = (await import("ioredis")).default;
      const redisUrl = env.REDIS_URL;
      if (!redisUrl) throw new Error("REDIS_URL not configured");
      this.client = new Redis(redisUrl, {
        maxRetriesPerRequest: 3,
        retryStrategy(times) {
          if (times > 5) return null; // Stop retrying
          return Math.min(times * 200, 2000);
        },
        lazyConnect: true,
      });

      this.client.on("error", (err: Error) => {
        logger.warn("[Cache] Redis error", { error: err.message });
        this.connected = false;
      });

      this.client.on("connect", () => {
        this.connected = true;
        logger.info("[Cache] Redis connected");
      });

      this.client.on("close", () => {
        this.connected = false;
      });

      await this.client.connect();
      return this.client;
    } catch (e) {
      logger.warn("[Cache] Redis connection failed, using memory fallback", { error: String(e) });
      this.connected = false;
      return null;
    }
  }

  async get<T>(key: string): Promise<CacheResult<T>> {
    try {
      const client = await this.getClient();
      if (!client) return null;
      const data = await client.get(key);
      if (!data) return null;
      return JSON.parse(data) as T;
    } catch {
      return null;
    }
  }

  async set<T>(key: string, value: T, ttlSeconds: number): Promise<void> {
    try {
      const client = await this.getClient();
      if (!client) return;
      await client.set(key, JSON.stringify(value), "EX", ttlSeconds);
    } catch {
      // Silent fail — cache miss is acceptable
    }
  }

  async del(key: string): Promise<void> {
    try {
      const client = await this.getClient();
      if (!client) return;
      await client.del(key);
    } catch {
      // Silent fail
    }
  }

  async delPattern(pattern: string): Promise<void> {
    try {
      const client = await this.getClient();
      if (!client) return;
      // ✅ SECURITY FIX (cfskill audit run-3, ADMIN-AUTH-01): every caller of
      // delPattern passes a PREFIX ("settings:", "courses:list:") while Redis
      // SCAN MATCH expects a GLOB — a prefix without '*' matches only the
      // literal key, so invalidation was a silent no-op under Redis and stale
      // settings (contact info, approval-gate state) kept serving for the
      // full section TTL. Normalize prefix → glob here so both cache backends
      // (in-memory startsWith and Redis SCAN) share one call contract.
      const glob = pattern.includes("*") || pattern.includes("?") || pattern.includes("[") ? pattern : `${pattern}*`;
      // ✅ Use SCAN instead of KEYS — KEYS is O(N) and blocks the Redis server in production
      let cursor = '0';
      do {
        // Cursor-based SCAN pagination: each round's cursor comes from the previous reply, so rounds cannot be parallelized.
        const [nextCursor, keys] = await client.scan(cursor, 'MATCH', glob, 'COUNT', 100); // NOSONAR: intentional sequential/throttled processing
        if (keys.length > 0) await client.del(...keys); // NOSONAR: intentional sequential/throttled processing
        cursor = nextCursor;
      } while (cursor !== '0');
    } catch {
      // Silent fail
    }
  }
}

// ─── Unified Cache API ───────────────────────────────────────────────────────

let cacheInstance: MemoryLRUCache | RedisCache | null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const inflightRequests = new Map<string, Promise<any>>();

export function getCache(): MemoryLRUCache | RedisCache {
  if (cacheInstance) return cacheInstance;

  if (env.REDIS_URL && env.REDIS_URL !== "redis://localhost:6379" && env.REDIS_URL.length > 20) {
    logger.info("[Cache] Using Redis");
    cacheInstance = new RedisCache();
  } else {
    logger.info("[Cache] Using in-memory LRU cache (no Redis configured)");
    cacheInstance = new MemoryLRUCache(500);
  }

  return cacheInstance;
}

/**
 * 🚀 Elite: fetchWithSWR (Stale-While-Revalidate)
 * Handles "Thundering Herd" protection and ensures 0-latency for users.
 * 
 * 1. Checks cache: if hit → returns immediately.
 * 2. If miss:
 *    - Check if another request for the same key is already in-flight.
 *    - If yes → wait for it and return.
 *    - If no → fetch from DB, update cache, and return.
 * 3. Support for "Stale" data (not implemented in this simplified version, but logic is ready).
 */
export async function fetchWithSWR<T>(
  key: string,
  fetchFn: () => Promise<T>,
  ttlSeconds: number
): Promise<T> {
  const cache = getCache();
  
  // 1. Try Cache
  const cached = await cache.get<T>(key);
  if (cached) return cached;

  // 2. Thundering Herd Protection (In-flight request deduplication)
  const existingPromise = inflightRequests.get(key);
  if (existingPromise) {
    logger.info(`[Cache][SWR] Deduplicating request`, { key });
    return existingPromise;
  }

  // 3. Fresh Fetch
  const fetchPromise = (async () => {
    try {
      const freshData = await fetchFn();
      if (freshData !== null && freshData !== undefined) {
        await cache.set(key, freshData, ttlSeconds);
      }
      return freshData;
    } finally {
      inflightRequests.delete(key);
    }
  })();

  inflightRequests.set(key, fetchPromise);
  return fetchPromise;
}

// ─── Predefined TTL Constants ────────────────────────────────────────────────
// ... [rest of file]


export const CACHE_TTL = {
  COURSES: 5 * 60,
  CATEGORIES: 30 * 60,
  TESTIMONIALS: 15 * 60,
  STATS: 10 * 60,
  COURSE_DETAIL: 5 * 60,
  LESSON_PROGRESS: 2 * 60,
  SAVED_POSITION: 3 * 60,
  RATE_LIMIT: 15 * 60,
  SETTINGS_SECTION: 15 * 60,
  ACTIVE_PROMOTIONS: 5 * 60,
  HEALTH_CHECK: 30,
} as const;

// ─── Cache Key Generators ────────────────────────────────────────────────────

export const cacheKeys = {
  courseList: (params: string) => `courses:list:${params}`,
  courseDetail: (slug: string) => `courses:detail:${slug}`,
  categories: () => "courses:categories",
  testimonials: () => "content:testimonials",
  stats: () => "site:stats",
  userProgress: (userId: number, courseId: number) => `progress:${userId}:${courseId}`,
  savedPosition: (userId: number, lessonId: number) => `position:${userId}:${lessonId}`,
  rateLimit: (ip: string, action: string) => `rl:${action}:${ip}`,
  settingsSection: (section: string) => `settings:section:${section}`,
  activePromotions: () => "settings:promotions:active",
  healthCheck: () => "health:check",
} as const;

// ─── Cache Invalidation Helpers ─────────────────────────────────────────────
// Call these whenever data is modified to keep cache fresh.

/**
 * Invalidate all course-related cache entries (course lists, details, stats).
 * Call this when a course is created, updated, or its status changes.
 */
export async function invalidateCourseCache(): Promise<void> {
  const cache = getCache();
  await cache.del(cacheKeys.stats());
  await cache.del(cacheKeys.categories());
  await cache.delPattern("courses:list:");
  await cache.delPattern("courses:detail:");
}

/**
 * Invalidate cache for a specific course by slug.
 * Call this when a single course is updated.
 */
export async function invalidateCourseDetailCache(slug: string): Promise<void> {
  const cache = getCache();
  await cache.del(cacheKeys.courseDetail(slug));
  await cache.del(cacheKeys.stats());
}

/**
 * Invalidate homepage stats cache.
 * Call this when enrollments, courses, or users change.
 */
export async function invalidateStatsCache(): Promise<void> {
  const cache = getCache();
  await cache.del(cacheKeys.stats());
}

/**
 * Invalidate all settings-related cache (themes, CMS settings, promotions).
 * Call this when admin updates site settings, themes, or promotions.
 */
export async function invalidateSettingsCache(): Promise<void> {
  const cache = getCache();
  await cache.delPattern("settings:");
  await cache.delPattern("theme:");
}

/**
 * Invalidate testimonial cache.
 * NOTE: Currently no API endpoint modifies testimonials (managed directly in DB).
 * Wire this up when a testimonial CRUD endpoint is added to the admin router.
 */
export async function invalidateTestimonialCache(): Promise<void> {
  const cache = getCache();
  await cache.del(cacheKeys.testimonials());
}