File size: 9,830 Bytes
f0fe495
 
 
 
 
 
 
 
 
 
 
31d49af
f0fe495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31d49af
 
 
 
 
 
 
 
 
 
 
 
f0fe495
 
 
 
 
 
 
 
 
 
 
 
 
31d49af
 
 
f0fe495
31d49af
f0fe495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31d49af
 
f0fe495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31d49af
 
 
f0fe495
31d49af
f0fe495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31d49af
 
f0fe495
31d49af
 
f0fe495
31d49af
f0fe495
 
31d49af
f0fe495
 
31d49af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0fe495
 
 
31d49af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0fe495
 
31d49af
 
f0fe495
c22c35b
 
 
 
 
 
 
 
 
 
 
 
 
f0fe495
31d49af
 
 
 
 
 
f0fe495
 
 
 
 
 
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
/**
 * production-ready In-Memory Caching and Rate-Limiting Subsystem
 * Designed to protect the Supabase DB and Express server from spikes in traffic
 */

import dotenv from 'dotenv';
dotenv.config();

// Configuration flags
const IS_CACHE_ENABLED = process.env.CACHE_ENABLED !== 'false';
const DEFAULT_TTL_MS = (parseInt(process.env.CACHE_DEFAULT_TTL, 10) || 15) * 1000;
const CACHE_MAX_KEYS = parseInt(process.env.CACHE_MAX_KEYS, 10) || 1000;

const RATE_LIMIT_MAX = parseInt(process.env.RATE_LIMIT_MAX_REQUESTS, 10) || 60;
const RATE_LIMIT_WINDOW_MS = parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10) || 60000;

// Metrics tracker
const metrics = {
  hits: 0,
  misses: 0,
  setCount: 0,
  blockedRequests: 0,
};

// =========================================================================
// CACHE MANAGER CLASS
// =========================================================================
class CacheManager {
  constructor() {
    this.store = new Map();
    
    // Background garbage collection sweep every 30 seconds
    this.gcTimer = setInterval(() => {
      this.evictExpired();
    }, 30000).unref(); // .unref() allows Node process to exit cleanly if running tests
  }

  set(key, value, ttlMs = DEFAULT_TTL_MS) {
    if (!IS_CACHE_ENABLED) return;
    
    const now = Date.now();
    const expiresAt = now + ttlMs;
    
    if (this.store.has(key)) {
      // Delete existing to update its insertion order position (LRU)
      this.store.delete(key);
    } else if (this.store.size >= CACHE_MAX_KEYS) {
      // Evict the least recently used (oldest) key
      const oldestKey = this.store.keys().next().value;
      if (oldestKey !== undefined) {
        this.store.delete(oldestKey);
        console.log(`[CacheManager LRU] Evicted oldest key: ${oldestKey}`);
      }
    }
    
    this.store.set(key, {
      value,
      expiresAt,
    });
    metrics.setCount++;
  }

  get(key) {
    if (!IS_CACHE_ENABLED) return null;
    
    const entry = this.store.get(key);
    if (!entry) return null;
    
    // Refresh insertion order position for LRU
    this.store.delete(key);
    this.store.set(key, entry);
    
    // Return the entry even if expired. Freshness logic is handled by middleware
    return entry;
  }

  del(key) {
    return this.store.delete(key);
  }

  flush() {
    this.store.clear();
    console.log('[CacheManager] Cache flushed successfully.');
  }

  evictExpired() {
    const now = Date.now();
    let evictedCount = 0;
    
    for (const [key, entry] of this.store.entries()) {
      // Keep stale data in memory for up to 24 hours so it can be served during heavy compute spikes
      if (now > entry.expiresAt + 24 * 60 * 60 * 1000) {
        this.store.delete(key);
        evictedCount++;
      }
    }
    
    if (evictedCount > 0) {
      console.log(`[CacheManager GC] Swept and evicted ${evictedCount} expired cache keys.`);
    }
  }

  getStats() {
    const totalKeys = this.store.size;
    const totalRequests = metrics.hits + metrics.misses;
    const hitRatio = totalRequests > 0 ? ((metrics.hits / totalRequests) * 100).toFixed(1) + '%' : '0%';
    
    return {
      enabled: IS_CACHE_ENABLED,
      totalKeys,
      hits: metrics.hits,
      misses: metrics.misses,
      hitRatio,
      setCount: metrics.setCount,
      blockedRequests: metrics.blockedRequests,
    };
  }
}

export const cache = new CacheManager();

// =========================================================================
// RATE LIMITER CLASS
// =========================================================================
class RateLimiter {
  constructor() {
    this.clients = new Map();
    
    // Background sweeper to clear expired rate-limit buckets every 30 seconds
    this.gcTimer = setInterval(() => {
      this.evictExpired();
    }, 30000).unref();
  }

  /**
   * Check if client IP is within limits
   * @returns {object} { allowed: boolean, remaining: number, limit: number, resetTime: number }
   */
  check(ip) {
    const now = Date.now();
    let client = this.clients.get(ip);
    
    if (!client || now > client.resetTime) {
      // Create new window
      const resetTime = now + RATE_LIMIT_WINDOW_MS;
      client = {
        hits: 1,
        resetTime,
      };
      this.clients.set(ip, client);
      return {
        allowed: true,
        remaining: RATE_LIMIT_MAX - 1,
        limit: RATE_LIMIT_MAX,
        resetTime,
      };
    }
    
    client.hits++;
    const remaining = Math.max(0, RATE_LIMIT_MAX - client.hits);
    const allowed = client.hits <= RATE_LIMIT_MAX;
    
    return {
      allowed,
      remaining,
      limit: RATE_LIMIT_MAX,
      resetTime: client.resetTime,
    };
  }

  evictExpired() {
    const now = Date.now();
    let count = 0;
    
    for (const [ip, data] of this.clients.entries()) {
      if (now > data.resetTime) {
        this.clients.delete(ip);
        count++;
      }
    }
    
    if (count > 0) {
      console.log(`[RateLimiter GC] Evicted ${count} expired rate-limit records.`);
    }
  }
}

const rateLimiter = new RateLimiter();

// =========================================================================
// EXPRESS MIDDLEWARE
// =========================================================================

const pendingRequests = new Map();

/**
 * Express Middleware protecting route with Rate-Limiting, Coalescing, and Stale-While-Revalidate Cache
 * @param {number} ttlSeconds Custom TTL override in seconds
 */
export function cacheMiddleware(ttlSeconds) {
  const ttlMs = ttlSeconds ? ttlSeconds * 1000 : DEFAULT_TTL_MS;

  return async (req, res, next) => {
    // 1. Bypass check if cache is disabled globally
    if (!IS_CACHE_ENABLED) {
      return next();
    }

    // Extract real client IP (supports Express trust proxy)
    const ip = req.ip || req.headers['x-forwarded-for'] || req.socket.remoteAddress;

    // 2. Perform Rate Limiting
    const limitStatus = rateLimiter.check(ip);
    
    // Set standard rate limit headers
    res.setHeader('X-RateLimit-Limit', limitStatus.limit);
    res.setHeader('X-RateLimit-Remaining', limitStatus.remaining);
    res.setHeader('X-RateLimit-Reset', Math.ceil(limitStatus.resetTime / 1000));

    if (!limitStatus.allowed) {
      metrics.blockedRequests++;
      const retryAfter = Math.ceil((limitStatus.resetTime - Date.now()) / 1000);
      res.setHeader('Retry-After', retryAfter);
      
      console.warn(`[RateLimiter] Blocked IP: ${ip} for too many requests on path: ${req.path}`);
      return res.status(429).json({
        error: 'Too Many Requests',
        message: 'Превышен лимит запросов к серверу. Пожалуйста, подождите.',
        retryAfter,
      });
    }

    // 3. Perform Cache Lookup
    const sortedQueries = Object.keys(req.query)
      .sort()
      .map(k => `${k}=${req.query[k]}`)
      .join('&');
    
    const cacheKey = sortedQueries ? `${req.path}?${sortedQueries}` : req.path;
    const entry = cache.get(cacheKey);
    const now = Date.now();

    // CASE A: Cache is FRESH
    if (entry && now <= entry.expiresAt) {
      metrics.hits++;
      const remainingTtlSecs = Math.max(0, Math.ceil((entry.expiresAt - now) / 1000));
      res.setHeader('X-Cache', 'HIT');
      res.setHeader('X-Cache-TTL-Remaining', remainingTtlSecs);
      return res.json(entry.value);
    }

    // CASE B: Cache is STALE or MISS, and another request is already computing it
    if (pendingRequests.has(cacheKey)) {
      if (entry) {
        // Stale-While-Revalidate: Return old data immediately to avoid waiting
        metrics.hits++;
        res.setHeader('X-Cache', 'STALE');
        return res.json(entry.value);
      } else {
        // Request Coalescing: No old data exists, so wait for the pending request to finish
        metrics.misses++;
        res.setHeader('X-Cache', 'COALESCED');
        try {
          const value = await pendingRequests.get(cacheKey);
          return res.json(value);
        } catch (e) {
          return res.status(500).json({ error: 'Internal Server Error computing cache' });
        }
      }
    }

    // CASE C: Cache is STALE or MISS, and WE are the first request to trigger compute
    metrics.misses++;
    res.setHeader('X-Cache', 'MISS');

    // Create a pending Promise that others can wait on
    let resolvePending;
    let rejectPending;
    const pendingPromise = new Promise((resolve, reject) => {
      resolvePending = resolve;
      rejectPending = reject;
    });
    pendingRequests.set(cacheKey, pendingPromise);

    // Timeout safety net to prevent frozen promises if next() hangs forever
    const safetyTimeout = setTimeout(() => {
      if (pendingRequests.get(cacheKey) === pendingPromise) {
        pendingRequests.delete(cacheKey);
        rejectPending(new Error('Cache compute timeout'));
      }
    }, 5 * 60 * 1000);

    // Intercept res.json to store the result
    const originalJson = res.json;
    res.json = function (body) {
      clearTimeout(safetyTimeout);
      res.json = originalJson; // Restore
      
      // Save fresh data only on successful 2xx responses and check array structure for streams
      if (res.statusCode >= 200 && res.statusCode < 300) {
        let shouldCache = true;
        
        // If this is the streams list endpoint, ensure the body is a valid array
        if (req.path === '/api/streams' && !Array.isArray(body)) {
          shouldCache = false;
        }
        
        if (shouldCache) {
          cache.set(cacheKey, body, ttlMs);
        }
      }
      
      // Resolve the promise to unblock anyone who was coalesced (waiting)
      resolvePending(body);
      if (pendingRequests.get(cacheKey) === pendingPromise) {
        pendingRequests.delete(cacheKey);
      }
      
      return res.json(body);
    };

    next();
  };
}