Was able to show a VERY guided demo

This commit is contained in:
Gabriel Matte 2024-11-10 22:52:04 -05:00
parent 678d1c2250
commit d563459aa6
6 changed files with 61 additions and 43 deletions

View file

@ -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);

View file

@ -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;
}
}
}

View file

@ -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 };
export default { routeWebSocket };

View file

@ -9,7 +9,7 @@ const port = 4500;
// Create HTTP and WebSocket server
const server = http.createServer();
const ioOptions: Partial<ServerOptions> = {
path: "/socket.io",
path: '/api/room/975239/socket', // TODO : use env variable to set room id
cors: {
origin: "*",
methods: ["GET", "POST"],

View file

@ -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) {

View file

@ -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" });