-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
108 lines (91 loc) · 2.68 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const cors = require('cors');
// Initialize express app
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Middleware
app.use(cors({
origin: ['https://load-testing-frontend-jvh6pw9qc-suryas-projects-d138d765.vercel.app', 'http://localhost:3000'],
methods: ['GET', 'POST'],
credentials: true
}));
app.use(express.json());
// Store active load test sessions
const activeTests = new Map();
// WebSocket connection handling
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', (message) => {
const data = JSON.parse(message);
switch(data.type) {
case 'START_TEST':
handleTestStart(ws, data.payload);
break;
case 'STOP_TEST':
handleTestStop(ws, data.payload);
break;
default:
console.log('Unknown message type:', data.type);
}
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
// API Routes
app.post('/api/test/create', (req, res) => {
const testConfig = req.body;
const testId = Date.now().toString();
activeTests.set(testId, {
config: testConfig,
status: 'created',
metrics: {
requestCount: 0,
responseTime: [],
errors: []
}
});
res.json({ testId, status: 'created' });
});
app.get('/api/test/:testId', (req, res) => {
const { testId } = req.params;
const test = activeTests.get(testId);
if (!test) {
return res.status(404).json({ error: 'Test not found' });
}
res.json(test);
});
// Helper functions
function handleTestStart(ws, payload) {
const test = activeTests.get(payload.testId);
if (test) {
test.status = 'running';
// Here we'll later add logic to spawn load test workers
broadcastTestStatus(payload.testId);
}
}
function handleTestStop(ws, payload) {
const test = activeTests.get(payload.testId);
if (test) {
test.status = 'stopped';
broadcastTestStatus(payload.testId);
}
}
function broadcastTestStatus(testId) {
const test = activeTests.get(testId);
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'TEST_UPDATE',
payload: { testId, ...test }
}));
}
});
}
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});