xphone 0.6.0

SIP telephony library with event-driven API — handles SIP signaling, RTP media, codecs, and call state
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
//! Generic SUBSCRIBE/NOTIFY subscription manager (RFC 6665).
//!
//! Manages multiple concurrent SIP subscriptions from a single background thread.
//! Used by the BLF (watch/unwatch) API and the generic subscribe_event API.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crossbeam_channel::{Receiver, Sender};
use parking_lot::Mutex;
use tracing::{debug, info, warn};

use crate::error::{Error, Result};
use crate::transport::SipTransport;
use crate::types::{parse_subscription_state, NotifyEvent, SubState};

/// Unique subscription identifier.
pub type SubId = u64;

/// Command sent to the manager thread.
enum Command {
    Subscribe {
        id: SubId,
        uri: String,
        event: String,
        accept: String,
        callback: Arc<dyn Fn(NotifyEvent) + Send + Sync>,
    },
    Unsubscribe {
        id: SubId,
    },
    Notify {
        event: String,
        content_type: String,
        body: String,
        subscription_state: String,
        from_uri: String,
    },
    Stop,
}

/// Lifecycle state of a subscription.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LifecycleState {
    Pending,
    Active,
    Terminated,
}

/// Tracked state for one active subscription.
struct Subscription {
    id: SubId,
    uri: String,
    event: String,
    accept: String,
    callback: Arc<dyn Fn(NotifyEvent) + Send + Sync>,
    expires_at: Instant,
    expires_duration: Duration,
    initial_notify_received: bool,
    subscribe_ok_at: Option<Instant>,
    last_refresh_at: Option<Instant>,
    state: LifecycleState,
}

/// Manages all active SIP subscriptions from a single background thread.
pub struct SubscriptionManager {
    cmd_tx: Sender<Command>,
    next_id: AtomicU64,
    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
    error_cb: ErrorCallback,
}

impl SubscriptionManager {
    /// Creates a new manager and spawns the background thread.
    pub fn new(tr: Arc<dyn SipTransport>) -> Self {
        let (cmd_tx, cmd_rx) = crossbeam_channel::unbounded();
        let error_cb: ErrorCallback = Arc::new(Mutex::new(Vec::new()));
        let error_cb_clone = Arc::clone(&error_cb);

        let handle = std::thread::Builder::new()
            .name("subscription-mgr".into())
            .spawn(move || {
                subscription_loop(tr, cmd_rx, error_cb_clone);
            })
            .expect("failed to spawn subscription manager thread");

        Self {
            cmd_tx,
            next_id: AtomicU64::new(1),
            thread: Mutex::new(Some(handle)),
            error_cb,
        }
    }

    /// Subscribe to an event package. Returns a subscription ID.
    pub fn subscribe(
        &self,
        uri: &str,
        event: &str,
        accept: &str,
        callback: Arc<dyn Fn(NotifyEvent) + Send + Sync>,
    ) -> SubId {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let _ = self.cmd_tx.send(Command::Subscribe {
            id,
            uri: uri.to_string(),
            event: event.to_string(),
            accept: accept.to_string(),
            callback,
        });
        id
    }

    /// Unsubscribe by ID.
    pub fn unsubscribe(&self, id: SubId) {
        let _ = self.cmd_tx.send(Command::Unsubscribe { id });
    }

    /// Called by the transport layer when a subscription NOTIFY arrives.
    pub fn handle_notify(
        &self,
        event: String,
        content_type: String,
        body: String,
        subscription_state: String,
        from_uri: String,
    ) {
        let _ = self.cmd_tx.send(Command::Notify {
            event,
            content_type,
            body,
            subscription_state,
            from_uri,
        });
    }

    /// Sets the error callback.
    pub fn on_error<F: Fn(String, Error) + Send + Sync + 'static>(&self, f: F) {
        self.error_cb.lock().push(Arc::new(f));
    }

    /// Stops the manager thread and joins it.
    pub fn stop(&self) {
        let _ = self.cmd_tx.send(Command::Stop);
        if let Some(handle) = self.thread.lock().take() {
            let _ = handle.join();
        }
    }
}

impl Drop for SubscriptionManager {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Shared error callback type.
type ErrorCallback = Arc<Mutex<Vec<Arc<dyn Fn(String, Error) + Send + Sync>>>>;

/// Default SUBSCRIBE Expires value.
const DEFAULT_EXPIRES: u32 = 600;

/// Timeout for initial NOTIFY after SUBSCRIBE 200 OK.
const INITIAL_NOTIFY_TIMEOUT: Duration = Duration::from_secs(5);

/// Background thread event loop.
fn subscription_loop(
    tr: Arc<dyn SipTransport>,
    cmd_rx: Receiver<Command>,
    error_cb: ErrorCallback,
) {
    let mut subs: HashMap<SubId, Subscription> = HashMap::new();
    let tick = Duration::from_millis(500);

    loop {
        match cmd_rx.recv_timeout(tick) {
            Ok(Command::Stop) | Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
                // Unsubscribe all before exiting.
                for sub in subs.values() {
                    if sub.state == LifecycleState::Active {
                        let _ = do_unsubscribe(&tr, &sub.uri, &sub.event, &sub.accept);
                    }
                }
                return;
            }
            Ok(Command::Subscribe {
                id,
                uri,
                event,
                accept,
                callback,
            }) => {
                handle_subscribe(&tr, &error_cb, &mut subs, id, uri, event, accept, callback);
            }
            Ok(Command::Unsubscribe { id }) => {
                if let Some(sub) = subs.remove(&id) {
                    if sub.state == LifecycleState::Active {
                        let _ = do_unsubscribe(&tr, &sub.uri, &sub.event, &sub.accept);
                    }
                    info!(id = id, uri = %sub.uri, "subscription removed");
                }
            }
            Ok(Command::Notify {
                event,
                content_type,
                body,
                subscription_state,
                from_uri,
            }) => {
                handle_incoming_notify(
                    &tr,
                    &error_cb,
                    &mut subs,
                    &event,
                    &content_type,
                    &body,
                    &subscription_state,
                    &from_uri,
                );
            }
            Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
        }

        // Periodic maintenance: refresh + initial NOTIFY timeout.
        let now = Instant::now();
        let mut to_refresh = Vec::new();
        let mut timed_out = Vec::new();

        for sub in subs.values() {
            if sub.state != LifecycleState::Active {
                continue;
            }
            // Refresh at 50% of expiry, with 30s minimum cooldown on failure.
            let half_expiry = sub.expires_duration / 2;
            let midpoint = sub.expires_at - half_expiry;
            if now >= midpoint && now < sub.expires_at {
                let cooldown_ok = sub
                    .last_refresh_at
                    .map(|t| now.duration_since(t) >= Duration::from_secs(30))
                    .unwrap_or(true);
                if cooldown_ok {
                    to_refresh.push(sub.id);
                }
            }

            // Initial NOTIFY timeout.
            if !sub.initial_notify_received {
                if let Some(ok_at) = sub.subscribe_ok_at {
                    if now.duration_since(ok_at) >= INITIAL_NOTIFY_TIMEOUT {
                        timed_out.push(sub.id);
                    }
                }
            }
        }

        for id in to_refresh {
            if let Some(sub) = subs.get_mut(&id) {
                debug!(id = id, uri = %sub.uri, "refreshing subscription");
                sub.last_refresh_at = Some(Instant::now());
                match do_subscribe(&tr, &sub.uri, &sub.event, &sub.accept, DEFAULT_EXPIRES) {
                    Ok(granted) => {
                        let dur = Duration::from_secs(granted as u64);
                        sub.expires_duration = dur;
                        sub.expires_at = Instant::now() + dur;
                    }
                    Err(e) => {
                        warn!(id = id, error = %e, "subscription refresh failed");
                    }
                }
            }
        }

        for id in timed_out {
            if let Some(sub) = subs.get_mut(&id) {
                warn!(id = id, uri = %sub.uri, "initial NOTIFY timeout — marking Unknown");
                sub.initial_notify_received = true; // Stop re-checking.
                                                    // Fire callback with empty body so consumer knows the subscription exists.
                let notify = NotifyEvent {
                    event: sub.event.clone(),
                    content_type: String::new(),
                    body: String::new(),
                    subscription_state: SubState::Active {
                        expires: sub.expires_duration.as_secs() as u32,
                    },
                };
                (sub.callback)(notify);
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn handle_subscribe(
    tr: &Arc<dyn SipTransport>,
    error_cb: &ErrorCallback,
    subs: &mut HashMap<SubId, Subscription>,
    id: SubId,
    uri: String,
    event: String,
    accept: String,
    callback: Arc<dyn Fn(NotifyEvent) + Send + Sync>,
) {
    info!(id = id, uri = %uri, event = %event, "sending SUBSCRIBE");
    match do_subscribe(tr, &uri, &event, &accept, DEFAULT_EXPIRES) {
        Ok(granted) => {
            let dur = Duration::from_secs(granted as u64);
            subs.insert(
                id,
                Subscription {
                    id,
                    uri,
                    event,
                    accept,
                    callback,
                    expires_at: Instant::now() + dur,
                    expires_duration: dur,
                    initial_notify_received: false,
                    subscribe_ok_at: Some(Instant::now()),
                    last_refresh_at: None,
                    state: LifecycleState::Active,
                },
            );
            info!(id = id, expires = granted, "subscription active");
        }
        Err(e) => {
            warn!(id = id, error = %e, "SUBSCRIBE failed");
            let cbs = error_cb.lock().clone();
            for f in &cbs {
                f(uri.clone(), e.clone());
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn handle_incoming_notify(
    tr: &Arc<dyn SipTransport>,
    error_cb: &ErrorCallback,
    subs: &mut HashMap<SubId, Subscription>,
    event: &str,
    content_type: &str,
    body: &str,
    subscription_state_header: &str,
    from_uri: &str,
) {
    let sub_state = parse_subscription_state(subscription_state_header);

    // Match to subscription by event header + URI (for multiple subs with same event).
    let event_base = event.split(';').next().unwrap_or("").trim();
    let sub = subs.values_mut().find(|s| {
        s.event.eq_ignore_ascii_case(event_base)
            && s.state != LifecycleState::Terminated
            && (from_uri.is_empty() || from_uri.contains(&s.uri))
    });

    let Some(sub) = sub else {
        debug!(event = %event, "NOTIFY for unknown subscription — ignoring");
        return;
    };

    sub.initial_notify_received = true;

    // Update subscription state based on Subscription-State header.
    match &sub_state {
        SubState::Active { expires } => {
            let dur = Duration::from_secs(*expires as u64);
            sub.expires_duration = dur;
            sub.expires_at = Instant::now() + dur;
            sub.state = LifecycleState::Active;
        }
        SubState::Pending => {
            sub.state = LifecycleState::Pending;
        }
        SubState::Terminated { reason } => {
            info!(id = sub.id, reason = %reason, "subscription terminated by server");
            sub.state = LifecycleState::Terminated;

            // Auto-re-subscribe on deactivated/timeout.
            if reason == "deactivated" || reason == "timeout" {
                let uri = sub.uri.clone();
                let event_str = sub.event.clone();
                let accept = sub.accept.clone();
                let id = sub.id;
                info!(id = id, reason = %reason, "auto-re-subscribing");
                match do_subscribe(tr, &uri, &event_str, &accept, DEFAULT_EXPIRES) {
                    Ok(granted) => {
                        let dur = Duration::from_secs(granted as u64);
                        sub.expires_at = Instant::now() + dur;
                        sub.expires_duration = dur;
                        sub.state = LifecycleState::Active;
                        sub.subscribe_ok_at = Some(Instant::now());
                        sub.initial_notify_received = false;
                    }
                    Err(e) => {
                        warn!(id = id, error = %e, "auto-re-subscribe failed");
                        let cbs = error_cb.lock().clone();
                        for f in &cbs {
                            f(uri.clone(), e.clone());
                        }
                    }
                }
                return; // Don't fire callback for the terminating NOTIFY.
            }

            // Permanent failure — fire error callback (don't fire subscription callback).
            if reason == "rejected" || reason == "noresource" {
                let cbs = error_cb.lock().clone();
                for f in &cbs {
                    f(
                        sub.uri.clone(),
                        Error::Other(format!("subscription rejected: {}", reason)),
                    );
                }
                return;
            }
        }
    }

    // Fire the subscription callback.
    let notify = NotifyEvent {
        event: event.to_string(),
        content_type: content_type.to_string(),
        body: body.to_string(),
        subscription_state: sub_state,
    };
    (sub.callback)(notify);
}

/// Sends a SUBSCRIBE and returns the server-granted Expires value.
fn do_subscribe(
    tr: &Arc<dyn SipTransport>,
    uri: &str,
    event: &str,
    accept: &str,
    expires: u32,
) -> Result<u32> {
    let mut headers = HashMap::new();
    headers.insert("Event".to_string(), event.to_string());
    headers.insert("Accept".to_string(), accept.to_string());
    headers.insert("Expires".to_string(), expires.to_string());

    let resp = tr.send_subscribe(uri, &headers, Duration::from_secs(10))?;
    if resp.status_code >= 200 && resp.status_code < 300 {
        // Parse Expires from response; fall back to our requested value.
        let granted = resp.header("Expires").parse::<u32>().unwrap_or(expires);
        Ok(granted)
    } else if resp.status_code == 489 {
        Err(Error::Other(format!(
            "Bad Event: server does not support '{}' event package",
            event
        )))
    } else {
        Err(Error::Other(format!(
            "SUBSCRIBE rejected: {} {}",
            resp.status_code, resp.reason
        )))
    }
}

/// Sends a SUBSCRIBE with Expires=0 to unsubscribe.
fn do_unsubscribe(tr: &Arc<dyn SipTransport>, uri: &str, event: &str, accept: &str) -> Result<()> {
    info!(uri = %uri, event = %event, "unsubscribing (Expires=0)");
    let mut headers = HashMap::new();
    headers.insert("Event".to_string(), event.to_string());
    headers.insert("Accept".to_string(), accept.to_string());
    headers.insert("Expires".to_string(), "0".to_string());

    let _ = tr.send_subscribe(uri, &headers, Duration::from_secs(5))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock::transport::MockTransport;

    fn test_tr() -> Arc<MockTransport> {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // for SUBSCRIBE
        tr
    }

    #[test]
    fn subscribe_sends_subscribe() {
        let tr = test_tr();
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let _id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(|_| {}),
        );
        std::thread::sleep(Duration::from_millis(200));

        assert!(
            tr.count_sent("SUBSCRIBE") >= 1,
            "expected SUBSCRIBE, got {}",
            tr.count_sent("SUBSCRIBE")
        );
        mgr.stop();
    }

    #[test]
    fn unsubscribe_sends_expires_zero() {
        let tr = test_tr();
        tr.respond_with(200, "OK"); // for unsubscribe
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(|_| {}),
        );
        std::thread::sleep(Duration::from_millis(200));

        mgr.unsubscribe(id);
        std::thread::sleep(Duration::from_millis(200));

        // Should have sent at least 2 SUBSCRIBEs (initial + unsubscribe).
        assert!(
            tr.count_sent("SUBSCRIBE") >= 2,
            "expected >= 2 SUBSCRIBEs (initial + unsubscribe), got {}",
            tr.count_sent("SUBSCRIBE")
        );
        mgr.stop();
    }

    #[test]
    fn notify_fires_callback() {
        let tr = test_tr();
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let (tx, rx) = crossbeam_channel::bounded(1);
        let _id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(move |notify| {
                let _ = tx.send(notify);
            }),
        );
        std::thread::sleep(Duration::from_millis(200));

        mgr.handle_notify(
            "dialog".into(),
            "application/dialog-info+xml".into(),
            "<dialog-info/>".into(),
            "active;expires=600".into(),
            "sip:1001@pbx.local".into(),
        );

        let notify = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_eq!(notify.event, "dialog");
        assert_eq!(notify.body, "<dialog-info/>");
        assert_eq!(notify.subscription_state, SubState::Active { expires: 600 });
        mgr.stop();
    }

    #[test]
    fn terminated_deactivated_resubscribes() {
        let tr = test_tr();
        tr.respond_with(200, "OK"); // for re-subscribe
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let _id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(|_| {}),
        );
        std::thread::sleep(Duration::from_millis(200));

        let initial_count = tr.count_sent("SUBSCRIBE");

        mgr.handle_notify(
            "dialog".into(),
            "application/dialog-info+xml".into(),
            "".into(),
            "terminated;reason=deactivated".into(),
            "sip:1001@pbx.local".into(),
        );
        std::thread::sleep(Duration::from_millis(300));

        // Should have sent another SUBSCRIBE for re-subscribe.
        assert!(
            tr.count_sent("SUBSCRIBE") > initial_count,
            "expected re-subscribe after deactivated"
        );
        mgr.stop();
    }

    #[test]
    fn terminated_rejected_fires_error() {
        let tr = test_tr();
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let (err_tx, err_rx) = crossbeam_channel::bounded(1);
        mgr.on_error(move |uri, _err| {
            let _ = err_tx.send(uri);
        });

        let _id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(|_| {}),
        );
        std::thread::sleep(Duration::from_millis(200));

        mgr.handle_notify(
            "dialog".into(),
            "".into(),
            "".into(),
            "terminated;reason=rejected".into(),
            "sip:1001@pbx.local".into(),
        );

        let uri = err_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(uri.contains("1001"));
        mgr.stop();
    }

    #[test]
    fn pending_state_keeps_subscription() {
        let tr = test_tr();
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let (tx, rx) = crossbeam_channel::bounded(1);
        let _id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(move |notify| {
                let _ = tx.send(notify.subscription_state);
            }),
        );
        std::thread::sleep(Duration::from_millis(200));

        mgr.handle_notify(
            "dialog".into(),
            "".into(),
            "".into(),
            "pending".into(),
            "sip:1001@pbx.local".into(),
        );

        let state = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_eq!(state, SubState::Pending);
        mgr.stop();
    }

    #[test]
    fn stop_is_idempotent() {
        let tr = test_tr();
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);
        mgr.stop();
        mgr.stop(); // should not panic
    }

    #[test]
    fn multiple_subscriptions() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK");
        tr.respond_with(200, "OK");
        tr.respond_with(200, "OK");

        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let (tx1, rx1) = crossbeam_channel::bounded(1);
        let (tx2, rx2) = crossbeam_channel::bounded(1);

        mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(move |n| {
                let _ = tx1.send(n.body);
            }),
        );
        mgr.subscribe(
            "sip:1002@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(move |n| {
                let _ = tx2.send(n.body);
            }),
        );
        std::thread::sleep(Duration::from_millis(300));

        // NOTIFY for 1002 — should route to second subscription.
        mgr.handle_notify(
            "dialog".into(),
            "application/dialog-info+xml".into(),
            "body-for-1002".into(),
            "active;expires=600".into(),
            "sip:1002@pbx.local".into(),
        );

        let result = rx2.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_eq!(result, "body-for-1002");

        // NOTIFY for 1001 — should route to first subscription.
        mgr.handle_notify(
            "dialog".into(),
            "application/dialog-info+xml".into(),
            "body-for-1001".into(),
            "active;expires=600".into(),
            "sip:1001@pbx.local".into(),
        );

        let result = rx1.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_eq!(result, "body-for-1001");

        mgr.stop();
    }

    #[test]
    fn notify_for_unknown_event_ignored() {
        let tr = test_tr();
        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let _id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(|_| {}),
        );
        std::thread::sleep(Duration::from_millis(200));

        // NOTIFY for "presence" should not crash.
        mgr.handle_notify(
            "presence".into(),
            "application/pidf+xml".into(),
            "<presence/>".into(),
            "active;expires=300".into(),
            "sip:someone@pbx.local".into(),
        );
        std::thread::sleep(Duration::from_millis(100));

        mgr.stop();
    }

    #[test]
    fn subscribe_failure_fires_error() {
        // No response queued → send_subscribe will fail.
        let tr = Arc::new(MockTransport::new());
        tr.fail_next(1); // fail the SUBSCRIBE

        let mgr = SubscriptionManager::new(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let (err_tx, err_rx) = crossbeam_channel::bounded(1);
        mgr.on_error(move |uri, _err| {
            let _ = err_tx.send(uri);
        });

        let _id = mgr.subscribe(
            "sip:1001@pbx.local",
            "dialog",
            "application/dialog-info+xml",
            Arc::new(|_| {}),
        );

        let uri = err_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(uri.contains("1001"));
        mgr.stop();
    }
}