rsipstack 0.5.6

SIP Stack Rust library for building SIP applications
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
use clap::Parser;
use futures::future::{self, Future};
use parking_lot::Mutex;
use rsipstack::dialog::dialog::{
    Dialog, DialogState, DialogStateReceiver, DialogStateSender, TerminatedReason,
};
use rsipstack::dialog::dialog_layer::DialogLayer;
use rsipstack::dialog::invitation::InviteOption;
use rsipstack::dialog::DialogId;
use rsipstack::Result;
use rsipstack::{
    dialog::authenticate::Credential,
    transaction::TransactionReceiver,
    transport::{udp::UdpConnection, TransportLayer},
    EndpointBuilder, Error,
};
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::{
    atomic::{AtomicU64, Ordering},
    Arc,
};
use std::time::{Duration, Instant};
use tokio::{select, time::sleep};
use tokio_util::sync::CancellationToken;
use tracing::{debug, info};

#[derive(Parser, Debug)]
#[command(author, version, about = "SIP Benchmark User Agent for testing")]
struct Args {
    /// Mode: "server" (receive calls) or "client" (make calls)
    #[arg(short, long, default_value = "server")]
    mode: String,

    /// Local port to bind
    #[arg(short, long, default_value = "5060")]
    port: u16,

    /// Remote SIP server address (required for client mode, e.g., sip:server.com or server.com:5060)
    #[arg(short, long)]
    server: Option<String>,

    /// Number of concurrent calls to maintain (client mode only)
    #[arg(short, long, default_value = "10")]
    calls: u32,

    /// Call answer probability in percentage (server mode only)
    #[arg(short, long, default_value = "100")]
    answer: u8,
}

#[derive(Debug, Clone)]
struct Stats {
    total_calls: Arc<AtomicU64>,
    reject_calls: Arc<AtomicU64>,
    failed_calls: Arc<AtomicU64>,
    pending_calls: Arc<AtomicU64>,
    active_calls: Arc<Mutex<HashMap<DialogId, Instant>>>,
    calls_per_second: Arc<AtomicU64>,
}

impl Stats {
    fn new() -> Self {
        Self {
            total_calls: Arc::new(AtomicU64::new(0)),
            reject_calls: Arc::new(AtomicU64::new(0)),
            failed_calls: Arc::new(AtomicU64::new(0)),
            pending_calls: Arc::new(AtomicU64::new(0)),
            active_calls: Arc::new(Mutex::new(HashMap::new())),
            calls_per_second: Arc::new(AtomicU64::new(0)),
        }
    }
}

async fn run_server(
    dialog_layer: Arc<DialogLayer>,
    mut incoming: TransactionReceiver,
    state_sender: DialogStateSender,
    contact: rsipstack::sip::Uri,
    answer_prob: u8,
    stats: Stats,
) -> Result<()> {
    info!(answer_prob = %answer_prob, "Starting server mode");

    loop {
        while let Some(mut tx) = incoming.recv().await {
            match tx.original.method {
                rsipstack::sip::Method::Invite => {
                    stats.total_calls.fetch_add(1, Ordering::Relaxed);
                    let should_answer = rand::random_range(0..=99) < answer_prob as u64;
                    if !should_answer {
                        stats.reject_calls.fetch_add(1, Ordering::Relaxed);
                        tx.reply(rsipstack::sip::StatusCode::BusyHere).await.ok();
                        continue;
                    }
                    let mut dialog = dialog_layer
                        .get_or_create_server_invite(
                            &tx,
                            state_sender.clone(),
                            None,
                            Some(contact.clone()),
                        )
                        .unwrap();

                    tokio::spawn(async move {
                        dialog.handle(&mut tx).await.ok();
                    });
                }
                rsipstack::sip::Method::Bye => {
                    if let Ok(dialog_id) = DialogId::try_from(&tx) {
                        stats.active_calls.lock().remove(&dialog_id);
                        tx.reply(rsipstack::sip::StatusCode::OK).await.ok();
                        dialog_layer.remove_dialog(&dialog_id);
                    }
                }
                _ => {}
            }
        }
    }
}

type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

async fn run_client(
    dialog_layer: Arc<DialogLayer>,
    contact: rsipstack::sip::Uri,
    credential: Option<Credential>,
    concurrent_calls: u32,
    state_sender: DialogStateSender,
    stats: Stats,
) -> Result<()> {
    info!(concurrent_calls = %concurrent_calls, "Starting client mode");

    // Use a rate limiter to ensure stable call creation
    let max_calls_per_cycle = 100; // Increased to 20 (was 5)
    let cycle_duration = Duration::from_millis(10); // Reduced to 50ms (was 100ms)

    loop {
        let start_time = Instant::now();

        // Calculate how many calls we need to create to maintain target concurrency
        let calls_to_create;
        {
            let dialogs = stats.active_calls.lock();
            let in_flight = stats.pending_calls.load(Ordering::Relaxed) as usize;
            let occupied = dialogs
                .len()
                .saturating_add(in_flight)
                .min(concurrent_calls as usize);
            calls_to_create = concurrent_calls as usize - occupied;
        }
        let calls_to_create_now = calls_to_create.min(max_calls_per_cycle);

        // Create new calls if needed
        if calls_to_create_now > 0 {
            info!(creating = %calls_to_create_now, concurrent = %concurrent_calls, "Creating new calls to maintain concurrency");

            // Prepare call creation futures
            for _ in 0..calls_to_create_now {
                let dialog_layer = dialog_layer.clone();
                let contact = contact.clone();
                let credential = credential.clone();
                let state_sender = state_sender.clone();
                let stats = stats.clone();
                stats.pending_calls.fetch_add(1, Ordering::Relaxed);

                let invite_loop = async move {
                    let invite_option = InviteOption {
                        callee: contact.clone(),
                        caller: contact.clone(),
                        contact,
                        credential,
                        ..Default::default()
                    };
                    stats.total_calls.fetch_add(1, Ordering::Relaxed);

                    match dialog_layer.do_invite(invite_option, state_sender).await {
                        Ok((dialog, _)) => {
                            // Get dialog ID and add to active calls tracking
                            let dialog_id = dialog.id();
                            stats
                                .active_calls
                                .lock()
                                .insert(dialog_id.clone(), Instant::now());
                            stats.pending_calls.fetch_sub(1, Ordering::Relaxed);

                            // Return the dialog for call management
                            Some((dialog_id, dialog))
                        }
                        Err(_) => {
                            stats.failed_calls.fetch_add(1, Ordering::Relaxed);
                            stats.pending_calls.fetch_sub(1, Ordering::Relaxed);
                            None
                        }
                    }
                };
                tokio::spawn(async move {
                    let dialog = match invite_loop.await {
                        Some((_, dialog)) => dialog,
                        None => return,
                    };
                    let duration = Duration::from_secs(rand::random_range(3..=10));
                    sleep(duration).await;
                    dialog.bye().await.ok();
                });
            }
        }

        // Sleep for the remainder of the cycle to maintain a consistent pace
        let elapsed = start_time.elapsed();
        if elapsed < cycle_duration {
            sleep(cycle_duration - elapsed).await;
        }
    }
}

async fn update_stats(dialog_layer: Arc<DialogLayer>, stats: Stats) {
    let mut last_total = stats.total_calls.load(Ordering::SeqCst);
    let mut last_time = Instant::now();

    loop {
        sleep(Duration::from_secs(1)).await;
        let current_total = stats.total_calls.load(Ordering::Relaxed);
        let current_time = Instant::now();
        let elapsed = current_time.duration_since(last_time).as_secs();

        if elapsed > 0 {
            let cps = (current_total - last_total) / elapsed;
            stats.calls_per_second.store(cps, Ordering::Relaxed);
            last_total = current_total;
            last_time = current_time;
        }

        // Print stats
        println!("\x1B[2J\x1B[1;1H"); // Clear screen and move cursor to top
        println!("=== SIP Benchmark UA Stats ===");

        // Get active calls count from the HashMap
        let active_calls_count = stats.active_calls.lock().len();
        println!("Dialogs: {}", dialog_layer.len());
        println!("Active Calls: {}", active_calls_count);
        println!(
            "Rejected Calls: {}",
            stats.reject_calls.load(Ordering::Relaxed)
        );
        println!(
            "Failed Calls: {}",
            stats.failed_calls.load(Ordering::Relaxed)
        );
        println!("Total Calls: {}", stats.total_calls.load(Ordering::Relaxed));
        println!(
            "Calls/Second: {}",
            stats.calls_per_second.load(Ordering::Relaxed)
        );
        println!("============================");
    }
}

async fn process_dialog_state(
    dialog_layer: Arc<DialogLayer>,
    mut state_receiver: DialogStateReceiver,
    stats: Stats,
) -> Result<()> {
    while let Some(state) = state_receiver.recv().await {
        match state {
            DialogState::Calling(id) => match dialog_layer.get_dialog(&id) {
                Some(dialog) => match dialog {
                    Dialog::ServerInvite(dialog) => {
                        dialog.accept(None, None).ok();
                    }
                    _ => {}
                },
                None => {}
            },
            DialogState::Confirmed(id, _) => {
                stats.active_calls.lock().insert(id, Instant::now());
            }
            DialogState::Terminated(id, status) => {
                match status {
                    TerminatedReason::UacOther(status) => {
                        info!(id = %id, status = %status, "dialog terminated");
                    }
                    TerminatedReason::UasOther(status) => {
                        info!(id = %id, status = %status, "dialog terminated");
                    }
                    _ => {}
                }
                dialog_layer.remove_dialog(&id);
                // Remove from active calls tracking
                stats.active_calls.lock().remove(&id);
            }
            _ => {
                debug!(state = %state, "Dialog state update");
            }
        }
    }
    Ok(())
}

fn parse_server_uri(server: &str) -> Result<rsipstack::sip::Uri> {
    // If the server string doesn't start with "sip:", add it
    let server_str = if !server.starts_with("sip:") {
        format!("sip:{}", server)
    } else {
        server.to_string()
    };

    // Parse the URI
    let uri = rsipstack::sip::Uri::try_from(server_str.as_str())
        .map_err(|e| Error::Error(format!("Invalid server URI: {}", e)))?;

    // If no port is specified, use default SIP port
    if uri.host_with_port.port.is_none() {
        let mut uri = uri;
        uri.host_with_port.port = Some(5060.into());
        Ok(uri)
    } else {
        Ok(uri)
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::ERROR)
        .with_file(true)
        .with_line_number(true)
        .with_timer(tracing_subscriber::fmt::time::LocalTime::rfc_3339())
        .try_init()
        .ok();

    let args = Args::parse();

    // Validate arguments
    if args.mode == "client" && args.server.is_none() {
        return Err(Error::Error(
            "Server address is required in client mode".to_string(),
        ));
    }

    if args.answer > 100 {
        return Err(Error::Error(
            "Probability must be between 0 and 100".to_string(),
        ));
    }

    let token = CancellationToken::new();
    let transport_layer = TransportLayer::new(token.clone());

    // Setup UDP connection
    let addr = format!("0.0.0.0:{}", args.port);
    let connection =
        UdpConnection::create_connection(addr.parse()?, None, Some(token.child_token())).await?;
    transport_layer.add_transport(connection.into());

    let endpoint = EndpointBuilder::new()
        .with_cancel_token(token.clone())
        .with_transport_layer(transport_layer)
        .build();

    let first_addr = endpoint
        .get_addrs()
        .first()
        .ok_or(Error::Error("no address found".to_string()))?
        .clone();

    let contact = rsipstack::sip::Uri {
        scheme: Some(rsipstack::sip::Scheme::Sip),
        auth: None,
        host_with_port: first_addr.addr.into(),
        params: vec![],
        headers: vec![],
    };

    let incoming = endpoint.incoming_transactions()?;
    let dialog_layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
    let (state_sender, state_receiver) = dialog_layer.new_dialog_state_channel();
    let stats = Stats::new();

    let mode_handler: BoxFuture<Result<()>> = match args.mode.as_str() {
        "server" => Box::pin(run_server(
            dialog_layer.clone(),
            incoming,
            state_sender.clone(),
            contact,
            args.answer,
            stats.clone(),
        )),
        "client" => {
            let server_uri = parse_server_uri(args.server.as_ref().unwrap())?;
            Box::pin(run_client(
                dialog_layer.clone(),
                server_uri,
                None,
                args.calls,
                state_sender.clone(),
                stats.clone(),
            ))
        }
        _ => Box::pin(future::err(Error::Error(
            "Invalid mode. Use 'server' or 'client'".to_string(),
        ))),
    };

    select! {
        _ = endpoint.serve() => {
            info!("Endpoint finished");
        }
        r = mode_handler => {
            info!(result = ?r, "Mode handler finished");
        }
        r = process_dialog_state(dialog_layer.clone(), state_receiver, stats.clone()) => {
            info!(result = ?r, "Dialog state handler finished");
        }
        _ = update_stats(dialog_layer.clone(),stats) => {
            info!("Stats updater finished");
        }
    }

    Ok(())
}