rustpbx 0.4.7

A SIP PBX implementation in Rust
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! Regression tests for the CallApp framework.
//!
//! All tests run against [`MockCallStack`] — no SIP socket, DB, or real media.

#[cfg(test)]
mod tests {
    use crate::call::app::testing::MockCallStack;
    use crate::call::app::{
        AppAction, ApplicationContext, CallApp, CallAppType, CallController, DtmfCollectConfig,
    };
    use crate::call::domain::CallCommand;
    use anyhow::Result;
    use async_trait::async_trait;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    // ── shared helpers ────────────────────────────────────────────────────────

    /// Log of events seen by an app, used to assert execution order.
    type EventLog = Arc<Mutex<Vec<String>>>;

    fn new_log() -> EventLog {
        Arc::new(Mutex::new(Vec::new()))
    }

    fn logged(log: &EventLog) -> Vec<String> {
        log.lock().unwrap().clone()
    }

    // ── 1. Basic lifecycle ────────────────────────────────────────────────────

    /// App that answers, plays one audio clip, then hangs up when playback ends.
    struct GreetAndHangupApp;

    #[async_trait]
    impl CallApp for GreetAndHangupApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Custom
        }
        fn name(&self) -> &str {
            "greet-and-hangup"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            ctrl.play_audio("sounds/hello.wav", false).await?;
            Ok(AppAction::Continue)
        }

        async fn on_audio_complete(
            &mut self,
            _track_id: String,
            _ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            Ok(AppAction::Hangup {
                reason: None,
                code: None,
            })
        }
    }

    #[tokio::test]
    async fn test_basic_lifecycle() {
        let mut stack = MockCallStack::run(Box::new(GreetAndHangupApp), "1001", "1002");

        // App should immediately answer on enter
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        // App should play a prompt
        stack
            .assert_cmd(100, "PlayPrompt", |c| matches!(c, CallCommand::Play { .. }))
            .await;

        // Simulate audio finishing — app should hang up
        stack.audio_complete("default");
        stack
            .assert_cmd(100, "Hangup", |c| matches!(c, CallCommand::Hangup(_)))
            .await;
    }

    // ── 2. DTMF routing ───────────────────────────────────────────────────────

    struct DtmfMenuApp;

    #[async_trait]
    impl CallApp for DtmfMenuApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Ivr
        }
        fn name(&self) -> &str {
            "dtmf-menu"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            Ok(AppAction::Continue)
        }

        async fn on_dtmf(
            &mut self,
            digit: String,
            _ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            match digit.as_str() {
                "1" => Ok(AppAction::Transfer("sip:sales@pbx".to_string())),
                "9" => Ok(AppAction::Hangup {
                    reason: None,
                    code: None,
                }),
                _ => Ok(AppAction::Continue),
            }
        }
    }

    #[tokio::test]
    async fn test_dtmf_ignored_digit() {
        let mut stack = MockCallStack::run(Box::new(DtmfMenuApp), "1001", "8000");
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        // Press an unmapped digit → no new command
        stack.dtmf("5");
        tokio::time::sleep(Duration::from_millis(30)).await;
        assert!(
            stack.drain_cmds().is_empty(),
            "expected no command for unmapped digit"
        );
    }

    #[tokio::test]
    async fn test_dtmf_hangup_digit() {
        let mut stack = MockCallStack::run(Box::new(DtmfMenuApp), "1001", "8000");
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        stack.dtmf("9");
        stack
            .assert_cmd(100, "Hangup", |c| matches!(c, CallCommand::Hangup(_)))
            .await;
    }

    // ── 3. Remote hangup handled gracefully ───────────────────────────────────

    struct WaitForeverApp;

    #[async_trait]
    impl CallApp for WaitForeverApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Custom
        }
        fn name(&self) -> &str {
            "wait-forever"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            Ok(AppAction::Continue)
        }
    }

    #[tokio::test]
    async fn test_remote_hangup_exits_loop() {
        let mut stack = MockCallStack::run(Box::new(WaitForeverApp), "1001", "9000");
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        // Remote party hangs up — loop should exit cleanly
        stack.remote_hangup();
        stack
            .join()
            .await
            .expect("loop should exit without error after remote hangup");
    }

    // ── 4. AppAction::Chain ───────────────────────────────────────────────────

    /// First app in chain — plays a greeting then chains to SecondApp.
    struct FirstApp;

    #[async_trait]
    impl CallApp for FirstApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Ivr
        }
        fn name(&self) -> &str {
            "first"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            Ok(AppAction::Continue)
        }

        async fn on_audio_complete(
            &mut self,
            _id: String,
            _ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            Ok(AppAction::Chain(Box::new(SecondApp)))
        }
    }

    /// Second app — just hangs up immediately on enter.
    struct SecondApp;

    #[async_trait]
    impl CallApp for SecondApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Voicemail
        }
        fn name(&self) -> &str {
            "second"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.hangup(None, None).await?;
            Ok(AppAction::Exit)
        }
    }

    #[tokio::test]
    async fn test_chain() {
        let mut stack = MockCallStack::run(Box::new(FirstApp), "1001", "1002");

        // First app answers
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        // Trigger chain
        stack.audio_complete("default");

        // Second app hangs up
        stack
            .assert_cmd(100, "Hangup", |c| matches!(c, CallCommand::Hangup(_)))
            .await;
    }

    // ── 5. Named timers: set_timeout + on_timeout ─────────────────────────────

    struct TimerApp {
        log: EventLog,
        fired_count: usize,
    }

    #[async_trait]
    impl CallApp for TimerApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Queue
        }
        fn name(&self) -> &str {
            "timer"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            ctrl.set_timeout("tick", Duration::from_millis(20));
            self.log.lock().unwrap().push("enter".into());
            Ok(AppAction::Continue)
        }

        async fn on_timeout(
            &mut self,
            id: String,
            _ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            self.log.lock().unwrap().push(format!("timeout:{id}"));
            self.fired_count += 1;
            if self.fired_count >= 1 {
                Ok(AppAction::Hangup {
                    reason: None,
                    code: None,
                })
            } else {
                Ok(AppAction::Continue)
            }
        }
    }

    #[tokio::test]
    async fn test_set_timeout_fires_on_timeout() {
        let log = new_log();
        let app = TimerApp {
            log: log.clone(),
            fired_count: 0,
        };
        let mut stack = MockCallStack::run(Box::new(app), "1001", "2001");

        // App answers on enter
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        // Timer fires after 20ms → on_timeout → Hangup
        stack
            .assert_cmd(200, "Hangup from timer", |c| {
                matches!(c, CallCommand::Hangup(_))
            })
            .await;

        assert_eq!(logged(&log), vec!["enter", "timeout:tick"]);
    }

    // ── 6. cancel_timeout suppresses fire ────────────────────────────────────

    struct CancelTimerApp {
        log: EventLog,
    }

    #[async_trait]
    impl CallApp for CancelTimerApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Custom
        }
        fn name(&self) -> &str {
            "cancel-timer"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            ctrl.set_timeout("never", Duration::from_millis(20));
            ctrl.cancel_timeout("never"); // immediately suppress
            self.log.lock().unwrap().push("enter".into());
            Ok(AppAction::Continue)
        }

        async fn on_timeout(
            &mut self,
            id: String,
            _ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            self.log.lock().unwrap().push(format!("timeout:{id}"));
            Ok(AppAction::Hangup {
                reason: None,
                code: None,
            })
        }
    }

    #[tokio::test]
    async fn test_cancel_timeout_suppresses_fire() {
        let log = new_log();
        let app = CancelTimerApp { log: log.clone() };
        let mut stack = MockCallStack::run(Box::new(app), "1001", "2002");

        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        // Wait 60ms — cancelled timer must NOT fire
        tokio::time::sleep(Duration::from_millis(60)).await;
        assert!(
            stack.drain_cmds().is_empty(),
            "cancelled timer must not produce a command"
        );
        assert!(
            !logged(&log).iter().any(|e| e.starts_with("timeout:")),
            "on_timeout must not be called"
        );

        stack.cancel();
        let _ = stack.join().await;
    }

    // ── 7. inter_digit_timeout in collect_dtmf ────────────────────────────────

    /// App that uses collect_dtmf with a 30ms inter-digit gap.
    struct CollectApp {
        log: EventLog,
    }

    #[async_trait]
    impl CallApp for CollectApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Ivr
        }
        fn name(&self) -> &str {
            "collect"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            let digits = ctrl
                .collect_dtmf(DtmfCollectConfig {
                    min_digits: 1,
                    max_digits: 4,
                    timeout: Duration::from_millis(500),
                    terminator: None,
                    play_prompt: None,
                    inter_digit_timeout: Some(Duration::from_millis(40)),
                })
                .await?;
            self.log.lock().unwrap().push(format!("collected:{digits}"));
            Ok(AppAction::Hangup {
                reason: None,
                code: None,
            })
        }
    }

    #[tokio::test]
    async fn test_collect_dtmf_inter_digit_timeout() {
        let log = new_log();
        let app = CollectApp { log: log.clone() };
        let mut stack = MockCallStack::run(Box::new(app), "1001", "3001");

        // AcceptCall first
        stack
            .assert_cmd(200, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        // Send two digits quickly
        stack.dtmf("4");
        tokio::time::sleep(Duration::from_millis(10)).await;
        stack.dtmf("2");

        // Pause longer than inter_digit_timeout (40ms) → collection completes
        tokio::time::sleep(Duration::from_millis(60)).await;

        // App should now hang up
        stack
            .assert_cmd(200, "Hangup", |c| matches!(c, CallCommand::Hangup(_)))
            .await;

        assert!(logged(&log).contains(&"collected:42".to_string()));
    }

    // ── 8. System cancellation ────────────────────────────────────────────────

    #[tokio::test]
    async fn test_cancel_exits_cleanly() {
        let mut stack = MockCallStack::run(Box::new(WaitForeverApp), "1001", "9999");
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        stack.cancel();
        stack
            .join()
            .await
            .expect("cancelled loop should exit without error");
    }

    // ── 9. Transfer sends TransferTarget ─────────────────────────────────────

    struct TransferApp;

    #[async_trait]
    impl CallApp for TransferApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Ivr
        }
        fn name(&self) -> &str {
            "transfer"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            Ok(AppAction::Continue)
        }

        async fn on_dtmf(
            &mut self,
            digit: String,
            _ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            if digit == "1" {
                Ok(AppAction::Transfer("sip:2001@pbx".to_string()))
            } else {
                Ok(AppAction::Continue)
            }
        }
    }

    #[tokio::test]
    async fn test_transfer_sends_transfer_target() {
        let mut stack = MockCallStack::run(Box::new(TransferApp), "1001", "8000");
        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        stack.dtmf("1");

        stack
            .assert_cmd(
                200,
                "TransferTarget",
                |c| matches!(c, CallCommand::Transfer { target, .. } if target == "sip:2001@pbx"),
            )
            .await;

        stack.join().await.expect("loop exits after transfer");
    }

    // ── 10. collect_dtmf with terminator ──────────────────────────────────────

    struct CollectTerminatorApp {
        log: EventLog,
    }

    #[async_trait]
    impl CallApp for CollectTerminatorApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Ivr
        }
        fn name(&self) -> &str {
            "collect-term"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            let digits = ctrl
                .collect_dtmf(DtmfCollectConfig {
                    min_digits: 1,
                    max_digits: 8,
                    timeout: Duration::from_millis(500),
                    terminator: Some('#'),
                    play_prompt: None,
                    inter_digit_timeout: None,
                })
                .await?;
            self.log.lock().unwrap().push(format!("collected:{digits}"));
            Ok(AppAction::Hangup {
                reason: None,
                code: None,
            })
        }
    }

    #[tokio::test]
    async fn test_collect_dtmf_terminator_stops_collection() {
        let log = new_log();
        let app = CollectTerminatorApp { log: log.clone() };
        let mut stack = MockCallStack::run(Box::new(app), "1001", "4001");

        stack
            .assert_cmd(200, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        stack.dtmf("4").dtmf("2").dtmf("#");

        stack
            .assert_cmd(300, "Hangup", |c| matches!(c, CallCommand::Hangup(_)))
            .await;

        assert!(
            logged(&log).contains(&"collected:42".to_string()),
            "terminator should stop collection and exclude '#': {:?}",
            logged(&log)
        );
    }

    // ── 11. collect_dtmf hangup during collection ──────────────────────────────

    struct CollectHangupApp;

    #[async_trait]
    impl CallApp for CollectHangupApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Ivr
        }
        fn name(&self) -> &str {
            "collect-hangup"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            let _digits = ctrl
                .collect_dtmf(DtmfCollectConfig {
                    min_digits: 1,
                    max_digits: 4,
                    timeout: Duration::from_secs(10),
                    terminator: None,
                    play_prompt: None,
                    inter_digit_timeout: None,
                })
                .await?;
            Ok(AppAction::Exit)
        }
    }

    #[tokio::test]
    async fn test_collect_dtmf_exits_on_remote_hangup() {
        let mut stack = MockCallStack::run(Box::new(CollectHangupApp), "1001", "5001");

        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        tokio::time::sleep(Duration::from_millis(20)).await;
        stack.remote_hangup();

        let result = stack.join().await;
        assert!(
            result.is_err(),
            "hangup during collection should propagate as error"
        );
    }

    // ── 12. play_audio prompt before collect_dtmf ────────────────────────────

    struct CollectWithPromptApp {
        log: EventLog,
    }

    #[async_trait]
    impl CallApp for CollectWithPromptApp {
        fn app_type(&self) -> CallAppType {
            CallAppType::Ivr
        }
        fn name(&self) -> &str {
            "collect-prompt"
        }

        async fn on_enter(
            &mut self,
            ctrl: &mut CallController,
            _ctx: &ApplicationContext,
        ) -> Result<AppAction> {
            ctrl.answer().await?;
            let digits = ctrl
                .collect_dtmf(DtmfCollectConfig {
                    min_digits: 1,
                    max_digits: 3,
                    timeout: Duration::from_millis(500),
                    terminator: Some('#'),
                    play_prompt: Some("sounds/enter_pin.wav".to_string()),
                    inter_digit_timeout: Some(Duration::from_millis(50)),
                })
                .await?;
            self.log.lock().unwrap().push(format!("pin:{digits}"));
            Ok(AppAction::Hangup {
                reason: None,
                code: None,
            })
        }
    }

    #[tokio::test]
    async fn test_collect_dtmf_plays_prompt_then_collects() {
        let log = new_log();
        let app = CollectWithPromptApp { log: log.clone() };
        let mut stack = MockCallStack::run(Box::new(app), "1001", "6001");

        stack
            .assert_cmd(100, "AcceptCall", |c| {
                matches!(c, CallCommand::Answer { .. })
            })
            .await;

        stack
            .assert_cmd(200, "PlayPrompt-pin", |c| {
                matches!(c, CallCommand::Play { .. })
            })
            .await;

        stack.dtmf("7").dtmf("8").dtmf("9");

        stack
            .assert_cmd(300, "Hangup", |c| matches!(c, CallCommand::Hangup(_)))
            .await;

        assert!(
            logged(&log).contains(&"pin:789".to_string()),
            "expected digits 789: {:?}",
            logged(&log)
        );
    }
}