pulzr 0.3.2

A http load testing tool for performance testing.
Documentation
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use crate::port_utils::find_available_port;
use crate::stats::{LiveMetrics, StatsCollector};
use anyhow::Result;
use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{broadcast, Mutex};
use tokio::time::{interval, Duration};
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::protocol::Message;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum WebSocketMessage {
    // Original WebUI messages
    #[serde(rename = "test_started")]
    TestStarted {
        timestamp: chrono::DateTime<chrono::Utc>,
        config: TestConfig,
    },
    #[serde(rename = "metrics_update")]
    MetricsUpdate {
        timestamp: chrono::DateTime<chrono::Utc>,
        metrics: LiveMetrics,
    },
    #[serde(rename = "request_log")]
    RequestLog {
        timestamp: chrono::DateTime<chrono::Utc>,
        log: crate::stats::RequestResult,
    },
    #[serde(rename = "test_completed")]
    TestCompleted {
        timestamp: chrono::DateTime<chrono::Utc>,
        summary: crate::stats::FinalSummary,
    },
    #[serde(rename = "error_event")]
    ErrorEvent {
        timestamp: chrono::DateTime<chrono::Utc>,
        error: String,
    },

    // Distributed load testing messages
    #[serde(rename = "worker_join_request")]
    WorkerJoinRequest {
        timestamp: chrono::DateTime<chrono::Utc>,
        worker_id: String,
        worker_info: WorkerInfo,
    },
    #[serde(rename = "worker_join_response")]
    WorkerJoinResponse {
        timestamp: chrono::DateTime<chrono::Utc>,
        worker_id: String,
        accepted: bool,
        coordinator_id: String,
        message: String,
    },
    #[serde(rename = "worker_heartbeat")]
    WorkerHeartbeat {
        timestamp: chrono::DateTime<chrono::Utc>,
        worker_id: String,
        status: WorkerStatus,
        current_load: WorkerLoad,
    },
    #[serde(rename = "test_command")]
    TestCommand {
        timestamp: chrono::DateTime<chrono::Utc>,
        command_id: String,
        command_type: TestCommandType,
        test_config: DistributedTestConfig,
        target_workers: Vec<String>, // Empty means all workers
    },
    #[serde(rename = "test_command_response")]
    TestCommandResponse {
        timestamp: chrono::DateTime<chrono::Utc>,
        command_id: String,
        worker_id: String,
        status: CommandResponseStatus,
        message: String,
    },
    #[serde(rename = "worker_metrics")]
    WorkerMetrics {
        timestamp: chrono::DateTime<chrono::Utc>,
        worker_id: String,
        metrics: LiveMetrics,
        worker_load: WorkerLoad,
    },
    #[serde(rename = "coordinator_status")]
    CoordinatorStatus {
        timestamp: chrono::DateTime<chrono::Utc>,
        coordinator_id: String,
        connected_workers: Vec<String>,
        test_status: CoordinatorTestStatus,
    },
    #[serde(rename = "worker_disconnect")]
    WorkerDisconnect {
        timestamp: chrono::DateTime<chrono::Utc>,
        worker_id: String,
        reason: String,
    },
    #[serde(rename = "worker_failure")]
    WorkerFailure {
        timestamp: chrono::DateTime<chrono::Utc>,
        worker_id: String,
        reason: String,
        last_seen: u64, // seconds since last heartbeat
        worker_info: WorkerInfo,
    },
    #[serde(rename = "worker_warning")]
    WorkerWarning {
        timestamp: chrono::DateTime<chrono::Utc>,
        worker_id: String,
        warning_type: String,
        message: String,
    },
    #[serde(rename = "load_rebalanced")]
    LoadRebalanced {
        timestamp: chrono::DateTime<chrono::Utc>,
        active_workers: Vec<String>,
        new_distribution: crate::distributed::load_balancer::LoadDistribution,
        reason: String,
    },
    #[serde(rename = "aggregated_metrics")]
    AggregatedMetrics {
        timestamp: chrono::DateTime<chrono::Utc>,
        aggregated_metrics: crate::metrics::distributed_stats::AggregatedMetrics,
    },

    // Synchronization messages for coordinated test execution
    #[serde(rename = "sync_prepare")]
    SyncPrepare {
        timestamp: chrono::DateTime<chrono::Utc>,
        test_id: String,
        coordinator_id: String,
        target_workers: Vec<String>,
        sync_timeout_secs: u64,
    },
    #[serde(rename = "sync_ready")]
    SyncReady {
        timestamp: chrono::DateTime<chrono::Utc>,
        test_id: String,
        worker_id: String,
        ready_for_start: bool,
        preparation_time_ms: u64,
    },
    #[serde(rename = "sync_start")]
    SyncStart {
        timestamp: chrono::DateTime<chrono::Utc>,
        test_id: String,
        coordinator_id: String,
        target_workers: Vec<String>,
        start_timestamp: chrono::DateTime<chrono::Utc>,
    },
    #[serde(rename = "sync_stop")]
    SyncStop {
        timestamp: chrono::DateTime<chrono::Utc>,
        test_id: String,
        coordinator_id: String,
        target_workers: Vec<String>,
        stop_timestamp: chrono::DateTime<chrono::Utc>,
    },
    #[serde(rename = "sync_status")]
    SyncStatus {
        timestamp: chrono::DateTime<chrono::Utc>,
        test_id: String,
        worker_id: String,
        sync_state: SyncState,
        message: String,
    },
    #[serde(rename = "sync_timeout")]
    SyncTimeout {
        timestamp: chrono::DateTime<chrono::Utc>,
        test_id: String,
        coordinator_id: String,
        timeout_reason: String,
        failed_workers: Vec<String>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestConfig {
    pub url: String,
    pub concurrent_requests: usize,
    pub rps: Option<u64>,
    pub duration_secs: u64,
    pub total_requests: Option<u64>,
    pub method: String,
    pub user_agent_mode: String,
}

// Distributed load testing data structures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerInfo {
    pub hostname: String,
    pub ip_address: String,
    pub port: u16,
    pub capabilities: WorkerCapabilities,
    pub version: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerCapabilities {
    pub max_concurrent_requests: usize,
    pub max_rps: Option<u64>,
    pub supported_protocols: Vec<String>,
    pub available_memory_mb: u64,
    pub cpu_cores: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WorkerStatus {
    Idle,
    Preparing,
    Running,
    Paused,
    Error,
    Disconnecting,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerLoad {
    pub current_rps: f64,
    pub active_connections: usize,
    pub memory_usage_mb: u64,
    pub cpu_usage_percent: f64,
    pub total_requests_sent: u64,
    pub errors_count: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TestCommandType {
    Start,
    Stop,
    Pause,
    Resume,
    UpdateConfig,
    Shutdown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributedTestConfig {
    pub test_id: String,
    pub base_config: TestConfig,
    pub worker_assignments: Vec<WorkerAssignment>,
    pub coordination_settings: CoordinationSettings,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerAssignment {
    pub worker_id: String,
    pub concurrent_requests: usize,
    pub rps: Option<u64>,
    pub duration_secs: Option<u64>,
    pub start_delay_secs: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationSettings {
    pub synchronized_start: bool,
    pub synchronized_stop: bool,
    pub sync_timeout_secs: u64,
    pub max_sync_wait_secs: u64,
    pub heartbeat_interval_secs: u64,
    pub metrics_reporting_interval_secs: u64,
    pub timeout_secs: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CommandResponseStatus {
    Acknowledged,
    Started,
    Completed,
    Failed,
    Rejected,
    PrepareReceived,
    ReadyToStart,
    SyncTimeout,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SyncState {
    Idle,
    Preparing,
    Ready,
    Starting,
    Running,
    Stopping,
    Stopped,
    Failed,
    TimedOut,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CoordinatorTestStatus {
    Idle,
    Preparing,
    Running,
    Paused,
    Stopping,
    Completed,
    Failed,
}

pub struct WebSocketServer {
    port: u16,
    actual_port: Option<u16>,
    stats_collector: Arc<StatsCollector>,
    message_sender: broadcast::Sender<WebSocketMessage>,
    last_test_config: Arc<Mutex<Option<TestConfig>>>,
    last_summary: Arc<Mutex<Option<crate::stats::FinalSummary>>>,
}

impl WebSocketServer {
    pub fn new(port: u16, stats_collector: Arc<StatsCollector>) -> Self {
        let (message_sender, _) = broadcast::channel(1000);

        Self {
            port,
            actual_port: None,
            stats_collector,
            message_sender,
            last_test_config: Arc::new(Mutex::new(None)),
            last_summary: Arc::new(Mutex::new(None)),
        }
    }

    pub fn get_message_sender(&self) -> broadcast::Sender<WebSocketMessage> {
        self.message_sender.clone()
    }

    pub fn get_last_test_config(&self) -> Arc<Mutex<Option<TestConfig>>> {
        Arc::clone(&self.last_test_config)
    }

    pub async fn start(&mut self) -> Result<u16> {
        let actual_port = find_available_port(self.port, 50).ok_or_else(|| {
            anyhow::anyhow!("Could not find available port starting from {}", self.port)
        })?;

        self.actual_port = Some(actual_port);

        let addr = SocketAddr::from(([127, 0, 0, 1], actual_port));
        let listener = TcpListener::bind(&addr).await?;

        if actual_port != self.port {
            println!(
                "WebSocket server listening on: ws://{} (auto-selected from preferred port {})",
                addr, self.port
            );
        } else {
            println!("WebSocket server listening on: ws://{addr}");
        }

        let stats_collector = Arc::clone(&self.stats_collector);
        let message_sender = self.message_sender.clone();

        tokio::spawn(async move {
            let mut interval = interval(Duration::from_secs(1));

            loop {
                interval.tick().await;
                let metrics = stats_collector.get_live_metrics().await;

                let message = WebSocketMessage::MetricsUpdate {
                    timestamp: chrono::Utc::now(),
                    metrics,
                };

                let _ = message_sender.send(message);
            }
        });

        let message_sender_clone = self.message_sender.clone();
        let last_test_config_clone = Arc::clone(&self.last_test_config);
        let last_summary_clone = Arc::clone(&self.last_summary);
        tokio::spawn(async move {
            while let Ok((stream, _)) = listener.accept().await {
                let message_receiver = message_sender_clone.subscribe();
                let config_state = Arc::clone(&last_test_config_clone);
                let summary_state = Arc::clone(&last_summary_clone);
                tokio::spawn(handle_connection(
                    stream,
                    message_receiver,
                    config_state,
                    summary_state,
                ));
            }
        });

        Ok(actual_port)
    }

    pub fn send_test_started(&self, config: TestConfig) {
        // Store config for late-connecting clients; clear previous summary (new run)
        let config_clone = config.clone();
        let state = Arc::clone(&self.last_test_config);
        let summary_state = Arc::clone(&self.last_summary);
        tokio::spawn(async move {
            *state.lock().await = Some(config_clone);
            *summary_state.lock().await = None;
        });
        let message = WebSocketMessage::TestStarted {
            timestamp: chrono::Utc::now(),
            config,
        };
        let _ = self.message_sender.send(message);
    }

    pub fn send_test_completed(&self, summary: crate::stats::FinalSummary) {
        // Store summary so late-connecting browsers can see the result
        let summary_clone = summary.clone();
        let summary_state = Arc::clone(&self.last_summary);
        tokio::spawn(async move {
            *summary_state.lock().await = Some(summary_clone);
        });
        let message = WebSocketMessage::TestCompleted {
            timestamp: chrono::Utc::now(),
            summary,
        };
        let _ = self.message_sender.send(message);
    }

    pub fn send_error(&self, error: String) {
        let message = WebSocketMessage::ErrorEvent {
            timestamp: chrono::Utc::now(),
            error,
        };
        let _ = self.message_sender.send(message);
    }

    pub fn get_actual_port(&self) -> Option<u16> {
        self.actual_port
    }
}

async fn handle_connection(
    stream: TcpStream,
    mut message_receiver: broadcast::Receiver<WebSocketMessage>,
    last_test_config: Arc<Mutex<Option<TestConfig>>>,
    last_summary: Arc<Mutex<Option<crate::stats::FinalSummary>>>,
) {
    let ws_stream = match accept_async(stream).await {
        Ok(ws_stream) => ws_stream,
        Err(e) => {
            eprintln!("WebSocket connection error: {e}");
            return;
        }
    };

    let (mut ws_sender, mut ws_receiver) = ws_stream.split();

    // Replay test_started if a test is already running or has completed
    if let Some(config) = last_test_config.lock().await.clone() {
        let replay = WebSocketMessage::TestStarted {
            timestamp: chrono::Utc::now(),
            config,
        };
        if let Ok(json) = serde_json::to_string(&replay) {
            let _ = ws_sender.send(Message::Text(json.into())).await;
        }
    }
    // Replay test_completed so browsers connecting after the test see the summary
    if let Some(summary) = last_summary.lock().await.clone() {
        let replay = WebSocketMessage::TestCompleted {
            timestamp: chrono::Utc::now(),
            summary,
        };
        if let Ok(json) = serde_json::to_string(&replay) {
            let _ = ws_sender.send(Message::Text(json.into())).await;
        }
    }

    let receive_task = tokio::spawn(async move {
        while let Some(msg) = ws_receiver.next().await {
            match msg {
                Ok(Message::Text(text)) => {
                    println!("Received: {text}");
                }
                Ok(Message::Close(_)) => {
                    println!("WebSocket connection closed");
                    break;
                }
                Err(e) => {
                    eprintln!("WebSocket error: {e}");
                    break;
                }
                _ => {}
            }
        }
    });

    let send_task = tokio::spawn(async move {
        while let Ok(message) = message_receiver.recv().await {
            let json = match serde_json::to_string(&message) {
                Ok(json) => json,
                Err(e) => {
                    eprintln!("Failed to serialize message: {e}");
                    continue;
                }
            };

            if let Err(e) = ws_sender.send(Message::Text(json.into())).await {
                eprintln!("Failed to send WebSocket message: {e}");
                break;
            }
        }
    });

    tokio::select! {
        _ = receive_task => {},
        _ = send_task => {},
    }
}