CoolFace
Apppublic

sanket3280/code-execution

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
codeStream.service.js126 linesDownload Raw Back to services
1const redis = require('../utils/redis');2const CodeHistory = require('../models/CodeHistory');3const UserCode = require('../models/UserCode');4 5/**6 * Stream code change to spectators7 */8async function streamCodeChange(io, participantId, problemId, code, changeType, language, challengeId) {9  try {10    // Save to Redis cache11    const cacheKey = `code:${participantId}:${problemId}`;12    await redis.set(cacheKey, {13      code,14      language: language || 'javascript',15      lastUpdate: Date.now(),16      participantId,17      problemId18    }, 24 * 60 * 60);19 20    // Broadcast to spectators watching this participant21    const participantRoom = `participant:${participantId}:${problemId}`;22    io.to(participantRoom).emit('spectator:codeUpdate', {23      participantId,24      problemId,25      code,26      changeType: changeType || 'typing',27      timestamp: Date.now(),28      language: language || 'javascript'29    });30 31    // Save snapshot to database (async, don't wait)32    saveCodeSnapshot(participantId, problemId, code, changeType, language, challengeId).catch(err => {33      console.error('Error saving code snapshot:', err);34    });35 36    return { success: true };37  } catch (error) {38    console.error('Error streaming code change:', error);39    return { success: false, error: error.message };40  }41}42 43/**44 * Get cached code45 */46async function getCachedCode(participantId, problemId) {47  try {48    // Try Redis first49    const cacheKey = `code:${participantId}:${problemId}`;50    const cached = await redis.get(cacheKey);51    52    if (cached) {53      return cached;54    }55 56    // Fallback to database57    const userCode = await UserCode.findOne({58      userId: participantId,59      problemId60    }).sort({ updatedAt: -1 }).lean();61 62    if (userCode) {63      return {64        code: userCode.code,65        language: userCode.language,66        lastUpdate: userCode.updatedAt,67        participantId,68        problemId69      };70    }71 72    return null;73  } catch (error) {74    console.error('Error getting cached code:', error);75    return null;76  }77}78 79/**80 * Save code snapshot to database81 */82async function saveCodeSnapshot(participantId, problemId, code, changeType, language, challengeId) {83  try {84    // Calculate delta85    const previousCode = await CodeHistory.findOne({86      participantId,87      problemId,88      challengeId89    }).sort({ timestamp: -1 }).lean();90 91    let linesChanged = 0;92    let deltaSize = 0;93 94    if (previousCode) {95      const prevLines = previousCode.code.split('\n').length;96      const currLines = code.split('\n').length;97      linesChanged = Math.abs(currLines - prevLines);98      deltaSize = code.length - previousCode.code.length;99    }100 101    // Create snapshot102    await CodeHistory.create({103      challengeId,104      participantId,105      problemId,106      code,107      language: language || 'javascript',108      changeType: changeType || 'typing',109      linesChanged,110      deltaSize,111      timestamp: new Date()112    });113 114    return { success: true };115  } catch (error) {116    console.error('Error saving code snapshot:', error);117    return { success: false, error: error.message };118  }119}120 121module.exports = {122  streamCodeChange,123  getCachedCode,124  saveCodeSnapshot125};126