diff --git a/app/api/socketio/route.js b/app/api/socketio/route.js index 0430ee8..116b356 100644 --- a/app/api/socketio/route.js +++ b/app/api/socketio/route.js @@ -9,19 +9,21 @@ const QUEUE_THRESHOLD = parseInt(process.env.QUEUE_THRESHOLD || "100", 10) const CONCURRENT_ACTIVE = parseInt(process.env.CONCURRENT_ACTIVE || "50", 10) const TOKEN_TTL_SECONDS = parseInt(process.env.TOKEN_TTL_SECONDS || `${15 * 60}`, 10) -// MySQL kapcsolat -let db = null - +// MySQL kapcsolat - minden híváskor új connection async function getDbConnection() { - if (!db && process.env.MYSQL_HOST) { - db = await mysql.createConnection({ + if (!process.env.MYSQL_HOST) return null + try { + const connection = await mysql.createConnection({ host: process.env.MYSQL_HOST, user: process.env.MYSQL_USER, password: process.env.MYSQL_PASSWORD, database: process.env.MYSQL_DATABASE, }) + return connection + } catch (error) { + console.error('MySQL connection error:', error) + return null } - return db } function ensureEvent(eventId) { @@ -137,6 +139,15 @@ async function evaluateQueue(eventId, io) { // If queue no longer needed, clear it if (ev.sockets.size < QUEUE_THRESHOLD) ev.queueOn = false + // Close database connection + if (connection) { + try { + await connection.end() + } catch (error) { + console.error('Error closing DB connection:', error) + } + } + // broadcast broadcastUpdate(eventId, io) } @@ -165,12 +176,12 @@ export async function GET(req) { global.io = io // Clean up all expired sessions on server start - const connection = await getDbConnection() - if (connection) { + const startupConnection = await getDbConnection() + if (startupConnection) { try { - const [result] = await connection.execute('DELETE FROM active_sessions WHERE expires_at < NOW()') + const [result] = await startupConnection.execute('DELETE FROM active_sessions WHERE expires_at < NOW()') console.log(`Server startup: Cleaned ${result.affectedRows} expired sessions`) - await connection.end() + await startupConnection.end() } catch (error) { console.error('Cleanup error on startup:', error) } @@ -276,6 +287,15 @@ export async function GET(req) { position: pos === -1 ? null : pos + 1, estimatedWait: pos === -1 ? null : (ev.active.size + pos) * TOKEN_TTL_SECONDS, }) + + // Close database connection + if (connection) { + try { + await connection.end() + } catch (error) { + console.error('Error closing DB connection:', error) + } + } }) socket.on("disconnect", () => {