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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use crate::core::load_tester::LoadTester;
use crate::integrations::websocket::{
    CommandResponseStatus, DistributedTestConfig, SyncState, TestCommandType, WebSocketMessage,
    WorkerCapabilities, WorkerInfo, WorkerLoad, WorkerStatus,
};
use crate::metrics::stats::StatsCollector;
use crate::utils::memory_info::get_system_memory_info;
use anyhow::Result;
use chrono::Utc;
use futures::{SinkExt, StreamExt};
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::sync::{broadcast, RwLock};
use tokio::time::{interval, sleep, timeout};
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
use uuid::Uuid;

#[derive(Debug, Clone)]
pub struct WorkerConfig {
    pub worker_id: String,
    pub coordinator_host: String,
    pub coordinator_port: u16,
    pub max_concurrent_requests: usize,
    pub max_rps: Option<u64>,
    pub heartbeat_interval_secs: u64,
    pub metrics_interval_secs: u64,
    pub connection_retry_interval_secs: u64,
    pub max_connection_retries: u32,
    pub connection_timeout_secs: u64,
}

impl Default for WorkerConfig {
    fn default() -> Self {
        Self {
            worker_id: format!("worker-{}", Uuid::new_v4()),
            coordinator_host: "localhost".to_string(),
            coordinator_port: 9630,
            max_concurrent_requests: 1000,
            max_rps: Some(10000),
            heartbeat_interval_secs: 10,
            metrics_interval_secs: 5,
            connection_retry_interval_secs: 5,
            max_connection_retries: 10,
            connection_timeout_secs: 30,
        }
    }
}

pub struct DistributedWorker {
    config: WorkerConfig,
    status: Arc<RwLock<WorkerStatus>>,
    current_load: Arc<RwLock<WorkerLoad>>,
    stats_collector: Arc<StatsCollector>,
    current_test: Arc<RwLock<Option<Arc<LoadTester>>>>,
    shutdown_sender: Option<broadcast::Sender<()>>,
}

impl DistributedWorker {
    pub fn new(config: WorkerConfig, stats_collector: Arc<StatsCollector>) -> Self {
        Self {
            config,
            status: Arc::new(RwLock::new(WorkerStatus::Idle)),
            current_load: Arc::new(RwLock::new(WorkerLoad {
                current_rps: 0.0,
                active_connections: 0,
                memory_usage_mb: 0,
                cpu_usage_percent: 0.0,
                total_requests_sent: 0,
                errors_count: 0,
            })),
            stats_collector,
            current_test: Arc::new(RwLock::new(None)),
            shutdown_sender: None,
        }
    }

    async fn connect_with_retry(
        &self,
        coordinator_url: &str,
    ) -> Result<WebSocketStream<MaybeTlsStream<TcpStream>>> {
        let mut retry_count = 0;
        let max_retries = self.config.max_connection_retries;
        let retry_interval = Duration::from_secs(self.config.connection_retry_interval_secs);
        let connection_timeout = Duration::from_secs(self.config.connection_timeout_secs);

        loop {
            match timeout(connection_timeout, connect_async(coordinator_url)).await {
                Ok(Ok((ws_stream, _))) => {
                    if retry_count > 0 {
                        println!(
                            "🔗 Reconnected to coordinator after {} attempts",
                            retry_count + 1
                        );
                    }
                    return Ok(ws_stream);
                }
                Ok(Err(e)) => {
                    retry_count += 1;
                    if retry_count > max_retries {
                        return Err(anyhow::anyhow!(
                            "Failed to connect to coordinator after {} attempts: {}",
                            max_retries,
                            e
                        ));
                    }

                    println!(
                        "⚠️  Connection attempt {} failed: {} (retrying in {}s)",
                        retry_count,
                        e,
                        retry_interval.as_secs()
                    );

                    sleep(retry_interval).await;
                }
                Err(_) => {
                    retry_count += 1;
                    if retry_count > max_retries {
                        return Err(anyhow::anyhow!(
                            "Connection timeout after {} attempts ({}s timeout)",
                            max_retries,
                            connection_timeout.as_secs()
                        ));
                    }

                    println!(
                        "⚠️  Connection attempt {} timed out after {}s (retrying in {}s)",
                        retry_count,
                        connection_timeout.as_secs(),
                        retry_interval.as_secs()
                    );

                    sleep(retry_interval).await;
                }
            }
        }
    }

    pub async fn start(&mut self) -> Result<()> {
        println!("Starting distributed worker: {}", self.config.worker_id);
        println!(
            "Connecting to coordinator: {}:{}",
            self.config.coordinator_host, self.config.coordinator_port
        );

        let coordinator_url = format!(
            "ws://{}:{}",
            self.config.coordinator_host, self.config.coordinator_port
        );

        // Connection with retry logic
        let ws_stream = self.connect_with_retry(&coordinator_url).await?;
        println!("✅ Connected to coordinator successfully");

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

        // Send join request
        let worker_info = self.get_worker_info().await?;
        let join_request = WebSocketMessage::WorkerJoinRequest {
            timestamp: Utc::now(),
            worker_id: self.config.worker_id.clone(),
            worker_info,
        };

        let join_json = serde_json::to_string(&join_request)?;
        ws_sender
            .send(tokio_tungstenite::tungstenite::protocol::Message::Text(
                join_json.into(),
            ))
            .await?;

        // Create shutdown channel
        let (shutdown_sender, mut shutdown_receiver) = broadcast::channel(1);
        self.shutdown_sender = Some(shutdown_sender);

        // We need to handle sending in the message loop instead of separate tasks
        // since SplitSink cannot be cloned

        // Start load monitoring task
        self.start_load_monitoring().await;

        // Handle incoming messages
        let status = Arc::clone(&self.status);
        let current_test = Arc::clone(&self.current_test);
        let stats_collector = Arc::clone(&self.stats_collector);
        let worker_id = self.config.worker_id.clone();

        let message_handler = tokio::spawn(async move {
            while let Some(msg) = ws_receiver.next().await {
                match msg {
                    Ok(tokio_tungstenite::tungstenite::protocol::Message::Text(text)) => {
                        if let Ok(message) = serde_json::from_str::<WebSocketMessage>(&text) {
                            handle_coordinator_message(
                                message,
                                &status,
                                &current_test,
                                &stats_collector,
                                &worker_id,
                                &mut ws_sender,
                            )
                            .await;
                        }
                    }
                    Ok(tokio_tungstenite::tungstenite::protocol::Message::Close(_)) => {
                        println!("Coordinator connection closed");
                        break;
                    }
                    Err(e) => {
                        eprintln!("WebSocket error: {}", e);
                        break;
                    }
                    _ => {}
                }
            }
        });

        // Wait for shutdown signal or connection loss
        tokio::select! {
            _ = message_handler => {
                println!("Connection to coordinator lost");
            }
            _ = shutdown_receiver.recv() => {
                println!("Shutdown signal received");
            }
        }

        Ok(())
    }

    async fn get_worker_info(&self) -> Result<WorkerInfo> {
        let hostname = hostname::get()
            .unwrap_or_else(|_| "unknown".into())
            .to_string_lossy()
            .to_string();

        let ip_address = local_ip_address::local_ip()
            .map(|ip| ip.to_string())
            .unwrap_or_else(|_| "127.0.0.1".to_string());

        let memory_info = get_system_memory_info().unwrap_or_default();
        let available_memory_mb = memory_info.total_mb as u64;

        let cpu_cores = num_cpus::get() as u32;

        let capabilities = WorkerCapabilities {
            max_concurrent_requests: self.config.max_concurrent_requests,
            max_rps: self.config.max_rps,
            supported_protocols: vec!["HTTP/1.1".to_string(), "HTTP/2".to_string()],
            available_memory_mb,
            cpu_cores,
        };

        Ok(WorkerInfo {
            hostname,
            ip_address,
            port: 0, // Worker doesn't listen on a port
            capabilities,
            version: env!("CARGO_PKG_VERSION").to_string(),
        })
    }

    // TODO: Implement heartbeat and metrics in a more appropriate way
    // The current approach doesn't work because SplitSink cannot be cloned

    async fn start_load_monitoring(&self) {
        let current_load = Arc::clone(&self.current_load);
        let stats_collector = Arc::clone(&self.stats_collector);

        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 memory_info = get_system_memory_info().unwrap_or_default();

                let mut load_guard = current_load.write().await;
                load_guard.current_rps = metrics.current_rps;
                load_guard.active_connections = metrics.requests_sent as usize;
                load_guard.memory_usage_mb = memory_info.used_mb as u64;
                load_guard.cpu_usage_percent = 0.0; // TODO: Implement CPU monitoring
                load_guard.total_requests_sent = metrics.requests_sent;
                load_guard.errors_count = metrics.requests_failed;
            }
        });
    }

    pub async fn shutdown(&self) {
        if let Some(sender) = &self.shutdown_sender {
            let _ = sender.send(());
        }

        // Stop current test if running
        let mut test_guard = self.current_test.write().await;
        if test_guard.is_some() {
            *test_guard = None;
        }

        let mut status_guard = self.status.write().await;
        *status_guard = WorkerStatus::Disconnecting;
    }

    pub async fn get_status(&self) -> WorkerStatus {
        self.status.read().await.clone()
    }
}

async fn handle_coordinator_message(
    message: WebSocketMessage,
    status: &Arc<RwLock<WorkerStatus>>,
    current_test: &Arc<RwLock<Option<Arc<LoadTester>>>>,
    stats_collector: &Arc<StatsCollector>,
    worker_id: &str,
    ws_sender: &mut futures::stream::SplitSink<
        WebSocketStream<MaybeTlsStream<TcpStream>>,
        tokio_tungstenite::tungstenite::protocol::Message,
    >,
) {
    match message {
        WebSocketMessage::WorkerJoinResponse {
            accepted, message, ..
        } => {
            if accepted {
                println!("Successfully joined coordinator: {}", message);
                let mut status_guard = status.write().await;
                *status_guard = WorkerStatus::Idle;
            } else {
                eprintln!("Failed to join coordinator: {}", message);
                let mut status_guard = status.write().await;
                *status_guard = WorkerStatus::Error;
            }
        }
        WebSocketMessage::TestCommand {
            command_id,
            command_type,
            test_config,
            target_workers,
            ..
        } => {
            // Check if this command is for us
            if !target_workers.is_empty() && !target_workers.contains(&worker_id.to_string()) {
                return;
            }

            let response_status = match command_type {
                TestCommandType::Start => {
                    handle_start_command(
                        test_config,
                        status,
                        current_test,
                        stats_collector,
                        ws_sender,
                        worker_id,
                    )
                    .await
                }
                TestCommandType::Stop => handle_stop_command(status, current_test).await,
                TestCommandType::Pause => handle_pause_command(status).await,
                TestCommandType::Resume => handle_resume_command(status).await,
                _ => CommandResponseStatus::Rejected,
            };

            let response = WebSocketMessage::TestCommandResponse {
                timestamp: Utc::now(),
                command_id,
                worker_id: worker_id.to_string(),
                status: response_status,
                message: "Command processed".to_string(),
            };

            let json = match serde_json::to_string(&response) {
                Ok(json) => json,
                Err(e) => {
                    eprintln!("Failed to serialize response: {}", e);
                    return;
                }
            };

            if let Err(e) = ws_sender
                .send(tokio_tungstenite::tungstenite::protocol::Message::Text(
                    json.into(),
                ))
                .await
            {
                eprintln!("Failed to send command response: {}", e);
            }
        }
        WebSocketMessage::SyncStart {
            test_id,
            start_timestamp,
            ..
        } => {
            handle_sync_start(
                test_id,
                start_timestamp,
                status,
                current_test,
                ws_sender,
                worker_id,
            )
            .await;
        }
        WebSocketMessage::SyncStop {
            test_id,
            stop_timestamp,
            ..
        } => {
            handle_sync_stop(
                test_id,
                stop_timestamp,
                status,
                current_test,
                ws_sender,
                worker_id,
            )
            .await;
        }
        _ => {
            // Handle other message types as needed
        }
    }
}

async fn handle_start_command(
    test_config: DistributedTestConfig,
    status: &Arc<RwLock<WorkerStatus>>,
    _current_test: &Arc<RwLock<Option<Arc<LoadTester>>>>,
    _stats_collector: &Arc<StatsCollector>,
    ws_sender: &mut futures::stream::SplitSink<
        WebSocketStream<MaybeTlsStream<TcpStream>>,
        tokio_tungstenite::tungstenite::protocol::Message,
    >,
    worker_id: &str,
) -> CommandResponseStatus {
    let mut status_guard = status.write().await;
    if !matches!(*status_guard, WorkerStatus::Idle) {
        return CommandResponseStatus::Rejected;
    }

    // Check if this is a synchronized test
    if test_config.coordination_settings.synchronized_start {
        *status_guard = WorkerStatus::Preparing;
        drop(status_guard);

        println!(
            "📋 Preparing for synchronized test: {}",
            test_config.test_id
        );

        // Send readiness signal to coordinator
        let ready_signal = WebSocketMessage::SyncStatus {
            timestamp: Utc::now(),
            test_id: test_config.test_id.clone(),
            worker_id: worker_id.to_string(),
            sync_state: SyncState::Ready,
            message: "Worker ready for synchronized start".to_string(),
        };

        if let Ok(json) = serde_json::to_string(&ready_signal) {
            let _ = ws_sender
                .send(tokio_tungstenite::tungstenite::protocol::Message::Text(
                    json.into(),
                ))
                .await;
        }

        println!(
            "✅ Ready for synchronized start of test: {}",
            test_config.test_id
        );
        CommandResponseStatus::Started
    } else {
        *status_guard = WorkerStatus::Running;
        drop(status_guard);

        // TODO: Create and start LoadTester with the distributed test config
        // For now, we'll acknowledge the command
        println!(
            "Starting distributed test (unsynchronized): {}",
            test_config.test_id
        );

        CommandResponseStatus::Started
    }
}

async fn handle_stop_command(
    status: &Arc<RwLock<WorkerStatus>>,
    current_test: &Arc<RwLock<Option<Arc<LoadTester>>>>,
) -> CommandResponseStatus {
    let mut status_guard = status.write().await;
    *status_guard = WorkerStatus::Idle;
    drop(status_guard);

    let mut test_guard = current_test.write().await;
    *test_guard = None;

    println!("Stopped distributed test");
    CommandResponseStatus::Completed
}

async fn handle_pause_command(status: &Arc<RwLock<WorkerStatus>>) -> CommandResponseStatus {
    let mut status_guard = status.write().await;
    if matches!(*status_guard, WorkerStatus::Running) {
        *status_guard = WorkerStatus::Paused;
        println!("Paused distributed test");
        CommandResponseStatus::Acknowledged
    } else {
        CommandResponseStatus::Rejected
    }
}

async fn handle_resume_command(status: &Arc<RwLock<WorkerStatus>>) -> CommandResponseStatus {
    let mut status_guard = status.write().await;
    if matches!(*status_guard, WorkerStatus::Paused) {
        *status_guard = WorkerStatus::Running;
        println!("Resumed distributed test");
        CommandResponseStatus::Acknowledged
    } else {
        CommandResponseStatus::Rejected
    }
}

async fn handle_sync_start(
    test_id: String,
    start_timestamp: chrono::DateTime<chrono::Utc>,
    status: &Arc<RwLock<WorkerStatus>>,
    _current_test: &Arc<RwLock<Option<Arc<LoadTester>>>>,
    ws_sender: &mut futures::stream::SplitSink<
        WebSocketStream<MaybeTlsStream<TcpStream>>,
        tokio_tungstenite::tungstenite::protocol::Message,
    >,
    worker_id: &str,
) {
    println!(
        "🚀 Received synchronized start signal for test: {}",
        test_id
    );

    // Calculate delay until start time
    let now = Utc::now();
    let delay = start_timestamp.signed_duration_since(now);

    if delay.num_milliseconds() > 0 {
        println!(
            "⏱️  Waiting {}ms for synchronized start",
            delay.num_milliseconds()
        );
        tokio::time::sleep(tokio::time::Duration::from_millis(
            delay.num_milliseconds() as u64
        ))
        .await;
    }

    // Update status to running
    {
        let mut status_guard = status.write().await;
        *status_guard = WorkerStatus::Running;
    }

    println!("✅ Started synchronized test: {}", test_id);

    // Send sync status update
    let sync_status = WebSocketMessage::SyncStatus {
        timestamp: Utc::now(),
        test_id,
        worker_id: worker_id.to_string(),
        sync_state: SyncState::Running,
        message: "Synchronized start completed".to_string(),
    };

    if let Ok(json) = serde_json::to_string(&sync_status) {
        let _ = ws_sender
            .send(tokio_tungstenite::tungstenite::protocol::Message::Text(
                json.into(),
            ))
            .await;
    }
}

async fn handle_sync_stop(
    test_id: String,
    stop_timestamp: chrono::DateTime<chrono::Utc>,
    status: &Arc<RwLock<WorkerStatus>>,
    _current_test: &Arc<RwLock<Option<Arc<LoadTester>>>>,
    ws_sender: &mut futures::stream::SplitSink<
        WebSocketStream<MaybeTlsStream<TcpStream>>,
        tokio_tungstenite::tungstenite::protocol::Message,
    >,
    worker_id: &str,
) {
    println!("🛑 Received synchronized stop signal for test: {}", test_id);

    // Calculate delay until stop time
    let now = Utc::now();
    let delay = stop_timestamp.signed_duration_since(now);

    if delay.num_milliseconds() > 0 {
        println!(
            "⏱️  Waiting {}ms for synchronized stop",
            delay.num_milliseconds()
        );
        tokio::time::sleep(tokio::time::Duration::from_millis(
            delay.num_milliseconds() as u64
        ))
        .await;
    }

    // Stop the current test
    {
        let mut status_guard = status.write().await;
        *status_guard = WorkerStatus::Idle;
    }

    {
        let mut test_guard = _current_test.write().await;
        *test_guard = None;
    }

    println!("✅ Stopped synchronized test: {}", test_id);

    // Send sync status update
    let sync_status = WebSocketMessage::SyncStatus {
        timestamp: Utc::now(),
        test_id,
        worker_id: worker_id.to_string(),
        sync_state: SyncState::Idle,
        message: "Synchronized stop completed".to_string(),
    };

    if let Ok(json) = serde_json::to_string(&sync_status) {
        let _ = ws_sender
            .send(tokio_tungstenite::tungstenite::protocol::Message::Text(
                json.into(),
            ))
            .await;
    }
}