File size: 2,622 Bytes
1804b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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);
});