Refactor socket handling and integrate database for event management

- Removed old socket handling code and replaced it with a new implementation in `app/api/socketio/route.js`.
- Added MySQL database integration for managing active sessions and queue entries.
- Implemented event retrieval and ticket purchasing APIs in `app/api/events/route.js` and `app/api/purchase/route.js`.
- Created database schema for events, tickets, active sessions, and orders in `database/schema.sql`.
- Updated front-end to handle event data fetching and ticket purchasing with improved UI components.
- Removed unused SVG files from the public directory.
This commit is contained in:
2025-09-19 19:02:15 +02:00
parent cb326f7190
commit 2c5461b0e0
12 changed files with 574 additions and 236 deletions

View File

@@ -1,13 +1,29 @@
import { Server } from 'socket.io'
import jwt from 'jsonwebtoken'
import mysql from 'mysql2/promise'
// Simple in-memory structures keyed by eventId
// Simple in-memory structures keyed by eventId (for fast access)
const events = {}
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
async function getDbConnection() {
if (!db && process.env.MYSQL_HOST) {
db = await mysql.createConnection({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
})
}
return db
}
function ensureEvent(eventId) {
if (!events[eventId]) {
events[eventId] = {
@@ -34,29 +50,59 @@ function broadcastUpdate(eventId, io) {
}
}
function evaluateQueue(eventId, io) {
async function evaluateQueue(eventId, io) {
const ev = events[eventId]
if (!ev) return
const connection = await getDbConnection()
// ensure active set size <= CONCURRENT_ACTIVE
while (ev.active.size < CONCURRENT_ACTIVE && ev.queue.length > 0) {
const next = ev.queue.shift()
if (!next) break
// sign token
const expiresAt = new Date(Date.now() + TOKEN_TTL_SECONDS * 1000)
const token = jwt.sign({ sid: next, eventId }, process.env.JWT_SECRET || "dev-secret", {
expiresIn: TOKEN_TTL_SECONDS,
})
ev.active.add(next)
io.to(next).emit("granted", { token, expiresAt: new Date(Date.now() + TOKEN_TTL_SECONDS * 1000).toISOString() })
// Save to database
if (connection) {
try {
await connection.execute(
'INSERT INTO active_sessions (event_id, socket_id, jwt_token, expires_at) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE jwt_token = VALUES(jwt_token), expires_at = VALUES(expires_at)',
[eventId, next, token, expiresAt]
)
} catch (error) {
console.error('DB error saving active session:', error)
}
}
io.to(next).emit("granted", { token, expiresAt: expiresAt.toISOString() })
}
// If too many active (rare), revoke oldest
if (ev.active.size > CONCURRENT_ACTIVE) {
const toRevoke = Array.from(ev.active).slice(CONCURRENT_ACTIVE)
toRevoke.forEach((sid) => {
for (const sid of toRevoke) {
ev.active.delete(sid)
io.to(sid).emit("revoked")
})
// Remove from database
if (connection) {
try {
await connection.execute(
'DELETE FROM active_sessions WHERE event_id = ? AND socket_id = ?',
[eventId, sid]
)
} catch (error) {
console.error('DB error removing active session:', error)
}
}
}
}
// If queue no longer needed, clear it
@@ -98,18 +144,50 @@ export async function GET(req) {
ev.sockets.add(socket.id)
socket.join(eventId)
const connection = await getDbConnection()
// Get event threshold from database
let eventThreshold = QUEUE_THRESHOLD
if (connection) {
try {
const [rows] = await connection.execute(
'SELECT max_concurrent_users FROM events WHERE id = ?',
[eventId]
)
if (rows.length > 0) {
eventThreshold = rows[0].max_concurrent_users
}
} catch (error) {
console.error('DB error getting event:', error)
}
}
// compute counts
const activeCount = ev.sockets.size
// turn on queue if threshold reached
if (activeCount >= QUEUE_THRESHOLD) ev.queueOn = true
if (activeCount >= eventThreshold) ev.queueOn = true
// if queueOn and socket not active, add to queue
if (ev.queueOn && !ev.active.has(socket.id)) {
if (!ev.queue.includes(socket.id)) ev.queue.push(socket.id)
if (!ev.queue.includes(socket.id)) {
ev.queue.push(socket.id)
// Save queue position to database
if (connection) {
try {
await connection.execute(
'INSERT INTO queue_entries (event_id, socket_id, position) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE position = VALUES(position)',
[eventId, socket.id, ev.queue.length]
)
} catch (error) {
console.error('DB error saving queue entry:', error)
}
}
}
}
// evaluate granting
evaluateQueue(eventId, io)
await evaluateQueue(eventId, io)
// send initial update
const pos = ev.queue.indexOf(socket.id)