Spaces:
Runtime error
Runtime error
| import http from 'http'; | |
| const TARGET_URL = 'http://localhost:5001/api/healthz'; // Corrected endpoint | |
| const CONCURRENT_REQUESTS = 50; | |
| const TOTAL_REQUESTS = 500; | |
| async function sendRequest(id) { | |
| return new Promise((resolve) => { | |
| const start = Date.now(); | |
| const req = http.get(TARGET_URL, (res) => { | |
| let data = ''; | |
| res.on('data', (chunk) => { data += chunk; }); | |
| res.on('end', () => { | |
| resolve({ | |
| id, | |
| status: res.statusCode, | |
| duration: Date.now() - start | |
| }); | |
| }); | |
| }); | |
| req.on('error', (err) => { | |
| resolve({ id, status: 'ERROR', error: err.message, duration: Date.now() - start }); | |
| }); | |
| }); | |
| } | |
| async function runLoadTest() { | |
| console.log(`--- Starting Load Test: ${TOTAL_REQUESTS} total requests, ${CONCURRENT_REQUESTS} concurrent ---`); | |
| const startTime = Date.now(); | |
| let completed = 0; | |
| let results = []; | |
| const batches = Math.ceil(TOTAL_REQUESTS / CONCURRENT_REQUESTS); | |
| for (let i = 0; i < batches; i++) { | |
| const batchSize = Math.min(CONCURRENT_REQUESTS, TOTAL_REQUESTS - completed); | |
| const batchPromises = []; | |
| for (let j = 0; j < batchSize; j++) { | |
| batchPromises.push(sendRequest(completed + j)); | |
| } | |
| const batchResults = await Promise.all(batchPromises); | |
| results = results.concat(batchResults); | |
| completed += batchSize; | |
| process.stdout.write(`\rProgress: ${completed}/${TOTAL_REQUESTS} requests completed...`); | |
| } | |
| const totalTime = Date.now() - startTime; | |
| const successes = results.filter(r => r.status === 200).length; | |
| const errors = results.filter(r => r.status === 'ERROR' || r.status >= 400).length; | |
| const avgDuration = results.reduce((acc, r) => acc + r.duration, 0) / results.length; | |
| console.log("\n\n--- Load Test Results ---"); | |
| console.log(`Total Time: ${totalTime}ms`); | |
| console.log(`Successes: ${successes}`); | |
| console.log(`Errors: ${errors}`); | |
| console.log(`Average Latency: ${avgDuration.toFixed(2)}ms`); | |
| console.log(`Throughput: ${(TOTAL_REQUESTS / (totalTime / 1000)).toFixed(2)} requests/sec`); | |
| if (errors > 0) { | |
| console.warn("WARNING: Some requests failed during the load test."); | |
| } else { | |
| console.log("✓ All requests completed successfully under load."); | |
| } | |
| } | |
| // First, check if server is running | |
| const check = http.get('http://localhost:5001/api/clients', { | |
| headers: { 'Authorization': 'Bearer test' } // Just to see if it responds | |
| }, (res) => { | |
| runLoadTest(); | |
| }).on('error', (err) => { | |
| console.error("Error: API server is not running on port 5001. Please start it first."); | |
| process.exit(1); | |
| }); | |