sanket3280/code-execution
0
1/**2 * Problems Cache Utility3 * Caches fullProblems.json in memory to avoid blocking file reads4 */5 6const fs = require('fs').promises;7const path = require('path');8const logger = require('./logger');9 10let problemsCache = null;11let cacheTimestamp = null;12const CACHE_TTL = 5 * 60 * 1000; // 5 minutes13 14/**15 * Load problems from file (async)16 */17async function loadProblemsFromFile() {18 try {19 const filePath = path.join(__dirname, '../../scripts/fullProblems.json');20 const data = await fs.readFile(filePath, 'utf8');21 return JSON.parse(data);22 } catch (error) {23 logger.error('Error loading problems from file', error);24 return [];25 }26}27 28/**29 * Get cached problems or load from file30 */31async function getCachedProblems() {32 const now = Date.now();33 34 // Return cache if valid35 if (problemsCache && cacheTimestamp && (now - cacheTimestamp < CACHE_TTL)) {36 return problemsCache;37 }38 39 // Load fresh data40 problemsCache = await loadProblemsFromFile();41 cacheTimestamp = now;42 43 return problemsCache;44}45 46/**47 * Initialize cache on startup (optional)48 */49async function initializeCache() {50 try {51 problemsCache = await loadProblemsFromFile();52 cacheTimestamp = Date.now();53 logger.info(`Problems cache initialized with ${problemsCache.length} problems`);54 } catch (error) {55 logger.error('Failed to initialize problems cache', error);56 }57}58 59/**60 * Invalidate cache (call when problems are updated)61 */62function invalidateCache() {63 problemsCache = null;64 cacheTimestamp = null;65}66 67module.exports = {68 getCachedProblems,69 initializeCache,70 invalidateCache71};72 