diff --git a/client/src/pages/Student/JoinRoom/JoinRoom.tsx b/client/src/pages/Student/JoinRoom/JoinRoom.tsx index d647c29..4372655 100644 --- a/client/src/pages/Student/JoinRoom/JoinRoom.tsx +++ b/client/src/pages/Student/JoinRoom/JoinRoom.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react'; -import { Socket } from 'socket.io-client'; +import { io,Socket } from 'socket.io-client'; //import { ENV_VARIABLES } from '../../../constants'; import StudentModeQuiz from '../../../components/StudentModeQuiz/StudentModeQuiz'; @@ -34,7 +34,15 @@ const JoinRoom: React.FC = () => { }, []); const handleCreateSocket = () => { - const socket = webSocketService.connect(`/api/room/${roomName}/socket`); + debugger; + const socket = io('/', { + path: `/api/room/${roomName}/socket`, + transports: ['websocket'], + autoConnect: true, + reconnection: true, + reconnectionAttempts: 5, + reconnectionDelay: 1000, + }); socket.on('join-success', () => { setIsWaitingForTeacher(true); diff --git a/nginx/conf.d/default.conf b/nginx/conf.d/default.conf index c454326..509a0a4 100644 --- a/nginx/conf.d/default.conf +++ b/nginx/conf.d/default.conf @@ -1,16 +1,10 @@ js_import njs/main.js; -js_set $quiz_room_host main.getQuizRoomHost; map $http_upgrade $connection_upgrade { default upgrade; '' close; } -# Cache for room information -# keyval_zone zone=rooms:10m; -# keyval_zone zone=room_hosts:10m; -# keyval $room_id $room_info zone=rooms; - upstream frontend { server frontend:5173; } @@ -21,40 +15,45 @@ upstream backend { server { listen 80; - + + set $proxy_target ""; + location /api { - rewrite /backend/(.*) /$1 break; - proxy_pass http://backend; - } - - location /socket.io { - rewrite /backend/(.*) /$1 break; proxy_pass http://backend; proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; - proxy_hide_header 'Access-Control-Allow-Origin'; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } - - location /quiz/([^/]+)/socket { - # Routing logic + + # Game WebSocket routing + location ~/api/room/([^/]+)/socket { set $room_id $1; js_content main.routeWebSocket; + } - #Proxy headers + # WebSocket proxy location + location @websocket_proxy { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; - proxy_read_timeout 3600s; - proxy_send_timeout 3600s; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + # Timeouts + proxy_connect_timeout 7m; + proxy_send_timeout 7m; + proxy_read_timeout 7m; proxy_buffering off; + + proxy_pass $proxy_target; } - + location / { proxy_pass http://frontend; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } - -} +} \ No newline at end of file diff --git a/nginx/njs/main.js b/nginx/njs/main.js index 436625b..82b6548 100644 --- a/nginx/njs/main.js +++ b/nginx/njs/main.js @@ -1,43 +1,54 @@ async function fetchRoomInfo(r) { try { // Make request to API to get room info - let res = await r.subrequest(`/api/room/${r.variables.room_id}`); + let res = await r.subrequest('/api/room/' + r.variables.room_id, { + method: 'GET' + }); if (res.status !== 200) { r.error(`Failed to fetch room info: ${res.status}`); return null; } - - return JSON.parse(res.responseText); + + let room = JSON.parse(res.responseText); + r.error(`Debug: Room info: ${JSON.stringify(room)}`); // Debug log + return room; } catch (error) { r.error(`Error fetching room info: ${error}`); return null; } } -// Main routing function for WebSocket connections async function routeWebSocket(r) { try { const roomInfo = await fetchRoomInfo(r); if (!roomInfo || !roomInfo.host) { + r.error(`Debug: Invalid room info: ${JSON.stringify(roomInfo)}`); r.return(404, 'Room not found or invalid'); return; } - // Route the WebSocket connection to the room's host - r.internalRedirect(`@quiz_room_${roomInfo.host}`); + // Make sure the host includes protocol if not already present + let proxyUrl = roomInfo.host; + if (!proxyUrl.startsWith('http://') && !proxyUrl.startsWith('https://')) { + proxyUrl = 'http://' + proxyUrl; + } + r.error(`Debug: Original URL: ${r.uri}`); + r.error(`Debug: Setting proxy target to: ${proxyUrl}`); + r.error(`Debug: Headers: ${JSON.stringify(r.headersIn)}`); + + // Set the proxy target variable + r.variables.proxy_target = proxyUrl; + + // Redirect to the websocket proxy + r.internalRedirect('@websocket_proxy'); + } catch (error) { r.error(`WebSocket routing error: ${error}`); r.return(500, 'Internal routing error'); } } -// Helper function to get room host for dynamic upstream -function getQuizRoomHost(r) { - const roomInfo = JSON.parse(r.variables.room_info); - return roomInfo.host || ''; -} - -export default { routeWebSocket, getQuizRoomHost }; \ No newline at end of file +export default { routeWebSocket }; \ No newline at end of file diff --git a/quizRoom/app.ts b/quizRoom/app.ts index f6ec1dc..6848a0c 100644 --- a/quizRoom/app.ts +++ b/quizRoom/app.ts @@ -9,7 +9,7 @@ const port = 4500; // Create HTTP and WebSocket server const server = http.createServer(); const ioOptions: Partial = { - path: "/socket.io", + path: '/api/room/975239/socket', // TODO : use env variable to set room id cors: { origin: "*", methods: ["GET", "POST"], diff --git a/server/controllers/rooms.js b/server/controllers/rooms.js index d969776..af65b39 100644 --- a/server/controllers/rooms.js +++ b/server/controllers/rooms.js @@ -6,7 +6,7 @@ const DockerRoomProvider = require('../roomsProviders/docker-provider.js'); //const KubernetesRoomProvider = require('../roomsProviders/kubernetes-provider'); const NB_CODE_CHARS = 6; -const DEFAULT_HOST = "localhost:4500" +const DEFAULT_HOST = "172.18.0.5:4500" // must be room ip not name class RoomsController { constructor(options = {}, roomRepository) { diff --git a/server/routers/rooms.js b/server/routers/rooms.js index 3321f95..df63a91 100644 --- a/server/routers/rooms.js +++ b/server/routers/rooms.js @@ -43,7 +43,7 @@ router.delete("/:id", async (req, res) => { router.get("/:id", async (req, res) => { try { - const data = await roomsController.getRoomStatus(); + const data = await roomsController.getRoomStatus(req.params.id); res.json(data); } catch (error) { res.status(500).json({ error: "Failed to list room infos" });