EvalueTonSavoir/test/stressTest/main.js

259 lines
8.6 KiB
JavaScript
Raw Normal View History

2024-11-27 18:36:59 -05:00
import { attemptLoginOrRegister, createRoomContainer } from './utility/apiServices.js';
2024-11-15 17:46:01 -05:00
import { Student } from './class/student.js';
import { Teacher } from './class/teacher.js';
2024-11-27 18:36:59 -05:00
import { Watcher } from './class/watcher.js';
2024-11-27 21:09:24 -05:00
import dotenv from 'dotenv';
import generateMetricsReport from './utility/metrics_generator.js';
2024-11-27 21:09:24 -05:00
// Load environment variables
dotenv.config();
const BASE_URL = process.env.BASE_URL || 'http://localhost';
2024-11-28 15:09:22 -05:00
const user = {
username: process.env.USER_EMAIL || 'admin@admin.com',
password: process.env.USER_PASSWORD || 'admin'
2024-11-27 21:09:24 -05:00
};
const numberRooms = parseInt(process.env.NUMBER_ROOMS || '4');
2024-11-27 21:09:24 -05:00
const usersPerRoom = parseInt(process.env.USERS_PER_ROOM || '60');
2024-11-15 17:46:01 -05:00
const roomAssociations = {};
2024-11-27 21:09:24 -05:00
const maxMessages = parseInt(process.env.MAX_MESSAGES || '20');
const conversationInterval = parseInt(process.env.CONVERSATION_INTERVAL || '1000');
2024-11-28 15:09:22 -05:00
const batchSize = 5;
const batchDelay = 250;
const roomDelay = 500;
2024-11-27 21:00:52 -05:00
/**
* Creates a room and immediately connects a teacher to it.
*/
async function createRoomWithTeacher(token, index) {
try {
const room = await createRoomContainer(BASE_URL, token);
if (!room?.id) {
throw new Error('Room creation failed');
}
// Initialize room associations
roomAssociations[room.id] = { watcher: null, teacher: null, students: [] };
// Create and connect teacher immediately
const teacher = new Teacher(`teacher_${index}`, room.id);
roomAssociations[room.id].teacher = teacher;
// Connect teacher to room
await teacher.connectToRoom(BASE_URL);
return room.id;
} catch (err) {
console.warn(`Failed to create/connect room ${index + 1}:`, err.message);
return null;
}
}
2024-11-27 18:36:59 -05:00
/**
2024-11-27 21:00:52 -05:00
* Creates rooms and connects teachers with controlled concurrency.
2024-11-27 18:36:59 -05:00
*/
async function createRoomContainers() {
console.log('Attempting login or register to get token');
const token = await attemptLoginOrRegister(BASE_URL, user.username, user.password);
if (!token) throw new Error('Failed to login or register.');
2024-11-27 21:00:52 -05:00
console.log('Room creation with immediate teacher connection');
const roomPromises = Array.from({ length: numberRooms }, (_, index) =>
createRoomWithTeacher(token, index)
);
2024-11-15 17:46:01 -05:00
2024-11-27 21:00:52 -05:00
const results = await Promise.allSettled(roomPromises);
const successfulRooms = results.filter(r => r.status === 'fulfilled' && r.value).length;
2024-11-27 18:36:59 -05:00
2024-11-28 17:56:56 -05:00
console.log(`Total rooms created and connected (${numberRooms}): ${successfulRooms}`);
2024-11-27 21:00:52 -05:00
console.log('Finished room creation and teacher connection');
2024-11-15 17:46:01 -05:00
}
2024-11-27 18:36:59 -05:00
/**
2024-11-27 21:00:52 -05:00
* Adds remaining participants (watcher, students) to rooms.
2024-11-27 18:36:59 -05:00
*/
2024-11-27 21:00:52 -05:00
function addRemainingUsers() {
console.log('Adding remaining room participants');
2024-11-27 18:36:59 -05:00
Object.keys(roomAssociations).forEach((roomId, roomIndex) => {
const participants = roomAssociations[roomId];
2024-11-27 21:00:52 -05:00
// Add watcher
2024-11-27 18:36:59 -05:00
participants.watcher = new Watcher(`watcher_${roomIndex}`, roomId);
// Add students
for (let i = 0; i < usersPerRoom - 2; i++) {
participants.students.push(new Student(`student_${roomIndex}_${i}`, roomId));
2024-11-15 17:46:01 -05:00
}
});
2024-11-27 21:00:52 -05:00
console.log('Finished adding remaining room participants');
2024-11-27 18:36:59 -05:00
}
2024-11-15 17:46:01 -05:00
2024-11-27 18:36:59 -05:00
/**
2024-11-27 21:00:52 -05:00
* Connects remaining participants to their respective rooms.
2024-11-27 18:36:59 -05:00
*/
2024-11-27 21:00:52 -05:00
async function connectRemainingParticipants(baseUrl) {
console.log('Connecting remaining participants in batches');
2024-11-28 15:09:22 -05:00
2024-11-27 18:36:59 -05:00
for (const [roomId, participants] of Object.entries(roomAssociations)) {
console.log(`Processing room ${roomId}`);
2024-11-27 21:00:52 -05:00
const remainingParticipants = [
2024-11-27 18:36:59 -05:00
participants.watcher,
...participants.students
].filter(Boolean);
2024-11-28 15:09:22 -05:00
// Connect in smaller batches with longer delays
2024-11-27 21:00:52 -05:00
for (let i = 0; i < remainingParticipants.length; i += batchSize) {
const batch = remainingParticipants.slice(i, i + batchSize);
2024-11-28 15:09:22 -05:00
// Add connection timeout handling
2024-11-27 21:00:52 -05:00
const batchPromises = batch.map(participant =>
2024-11-28 15:09:22 -05:00
Promise.race([
participant.connectToRoom(baseUrl),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Connection timeout')), 10000)
)
]).catch(err => {
console.warn(
`Failed to connect ${participant.username} in room ${roomId}:`,
err.message
);
return null;
})
2024-11-27 18:36:59 -05:00
);
await Promise.all(batchPromises);
2024-11-28 15:09:22 -05:00
// Cleanup disconnected sockets
batch.forEach(participant => {
if (!participant.socket?.connected) {
participant.disconnect();
}
});
2024-11-27 18:36:59 -05:00
await new Promise(resolve => setTimeout(resolve, batchDelay));
}
2024-11-28 15:09:22 -05:00
// Add delay between rooms
await new Promise(resolve => setTimeout(resolve, roomDelay));
2024-11-27 18:36:59 -05:00
}
2024-11-27 21:00:52 -05:00
console.log('Finished connecting remaining participants');
2024-11-15 17:46:01 -05:00
}
2024-11-27 21:00:52 -05:00
// Rest of the code remains the same
2024-11-27 18:36:59 -05:00
async function simulateParticipants() {
const conversationPromises = Object.entries(roomAssociations).map(async ([roomId, participants]) => {
const { teacher, students } = participants;
2024-11-15 17:46:01 -05:00
2024-11-27 18:36:59 -05:00
if (!teacher || students.length === 0) {
console.warn(`Room ${roomId} has no teacher or students to simulate.`);
return;
}
2024-11-26 17:04:22 -05:00
2024-11-27 18:36:59 -05:00
console.log(`Starting simulation for room ${roomId}`);
2024-11-26 17:04:22 -05:00
2024-11-27 18:36:59 -05:00
await new Promise(resolve => setTimeout(resolve, 2000));
for (let i = 0; i < maxMessages; i++) {
const teacherMessage = `Message ${i + 1} from ${teacher.username}`;
teacher.broadcastMessage(teacherMessage);
await new Promise(resolve => setTimeout(resolve, conversationInterval));
2024-11-26 17:04:22 -05:00
}
2024-11-27 18:36:59 -05:00
console.log(`Finished simulation for room ${roomId}`);
});
await Promise.all(conversationPromises);
2024-11-15 17:46:01 -05:00
}
2024-11-27 18:36:59 -05:00
function disconnectParticipants() {
console.time('Disconnecting participants');
Object.values(roomAssociations).forEach(participants => {
participants.teacher?.disconnect();
participants.watcher?.disconnect();
participants.students.forEach(student => student.disconnect());
2024-11-15 17:46:01 -05:00
});
2024-11-27 18:36:59 -05:00
console.timeEnd('Disconnecting participants');
console.log('All participants disconnected successfully.');
2024-11-15 17:46:01 -05:00
}
async function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function generateExecutionData() {
2024-11-28 17:56:56 -05:00
console.log('Generating execution data');
const allRoomsData = {};
for (const [roomId, participants] of Object.entries(roomAssociations)) {
if (participants.watcher?.roomRessourcesData.length > 0) {
// Add phase markers to the data
const data = participants.watcher.roomRessourcesData;
const simulationStartIdx = 20; // Assuming first 20 samples are baseline
const simulationEndIdx = data.length - 20; // Last 20 samples are post-simulation
data.forEach((sample, index) => {
if (index < simulationStartIdx) {
sample.phase = 'baseline';
} else if (index > simulationEndIdx) {
sample.phase = 'post-simulation';
} else {
sample.phase = 'simulation';
}
});
allRoomsData[roomId] = data;
}
}
const result = await generateMetricsReport(allRoomsData);
console.log(`Generated metrics in ${result.outputDir}`);
console.log('Finished generating execution data');
2024-11-28 17:56:56 -05:00
}
2024-11-15 17:46:01 -05:00
async function main() {
try {
2024-11-27 18:36:59 -05:00
await createRoomContainers();
2024-11-27 21:00:52 -05:00
addRemainingUsers();
await connectRemainingParticipants(BASE_URL);
// Wait for initial baseline metrics
console.log('Collecting baseline metrics...');
await wait(5000);
2024-11-27 18:36:59 -05:00
await simulateParticipants();
console.log('Waiting for system to stabilize...');
await wait(5000); // 5 second delay
await generateExecutionData();
2024-11-27 18:36:59 -05:00
console.log('All tasks completed successfully!');
2024-11-15 17:46:01 -05:00
} catch (error) {
2024-11-26 17:04:22 -05:00
console.error('Error:', error.message);
2024-11-15 17:46:01 -05:00
}
}
2024-11-27 18:36:59 -05:00
// Graceful shutdown handlers
2024-11-15 17:46:01 -05:00
process.on('SIGINT', () => {
2024-11-26 17:04:22 -05:00
console.log('Process interrupted (Ctrl+C).');
2024-11-27 18:36:59 -05:00
disconnectParticipants();
2024-11-15 19:35:41 -05:00
process.exit(0);
2024-11-15 17:46:01 -05:00
});
2024-11-27 18:36:59 -05:00
process.on('exit', disconnectParticipants);
process.on('uncaughtException', err => {
2024-11-26 17:04:22 -05:00
console.error('Uncaught Exception:', err);
2024-11-27 18:36:59 -05:00
disconnectParticipants();
2024-11-26 17:04:22 -05:00
process.exit(1);
});
2024-11-27 18:36:59 -05:00
2024-11-26 17:04:22 -05:00
process.on('unhandledRejection', (reason, promise) => {
2024-11-27 18:36:59 -05:00
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
disconnectParticipants();
2024-11-26 17:04:22 -05:00
process.exit(1);
});
2024-11-15 17:46:01 -05:00
2024-11-27 21:00:52 -05:00
main();