EvalueTonSavoir/test/stressTest/main.js

194 lines
6.4 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-15 17:46:01 -05:00
const BASE_URL = 'http://localhost';
2024-11-15 19:35:41 -05:00
const user = { username: 'admin@example.com', password: 'adminPassword' };
2024-11-27 21:00:52 -05:00
const numberRooms = 10;
2024-11-27 18:36:59 -05:00
const usersPerRoom = 60;
2024-11-15 17:46:01 -05:00
const roomAssociations = {};
2024-11-27 21:00:52 -05:00
const maxMessages = 20;
const conversationInterval = 1000;
const batchSize = 20;
const batchDelay = 250;
/**
* 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');
}
console.log(`Room ${index + 1} created with ID: ${room.id}`);
// 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);
console.log(`Teacher connected to room ${room.id}`);
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-27 21:00:52 -05:00
console.log(`Total rooms created and connected: ${successfulRooms}`);
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
console.log('Adding users to room ' + roomId);
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-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
// Collect remaining participants for this room
const remainingParticipants = [
2024-11-27 18:36:59 -05:00
participants.watcher,
...participants.students
].filter(Boolean);
// Process participants in batches
2024-11-27 21:00:52 -05:00
for (let i = 0; i < remainingParticipants.length; i += batchSize) {
const batch = remainingParticipants.slice(i, i + batchSize);
const batchPromises = batch.map(participant =>
2024-11-27 18:36:59 -05:00
participant.connectToRoom(baseUrl)
.catch(err => {
console.warn(
`Failed to connect ${participant.username} in room ${roomId}:`,
err.message
);
return null;
})
);
await Promise.all(batchPromises);
await new Promise(resolve => setTimeout(resolve, batchDelay));
}
}
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 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);
2024-11-27 18:36:59 -05:00
await simulateParticipants();
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();