Skip to main content

active_call/call/
sip.rs

1use crate::call::state::{CallProgress, LegShared};
2use crate::callrecord::CallRecordHangupReason;
3use crate::event::EventSender;
4use crate::media::TrackId;
5use crate::media::stream::MediaStream;
6use crate::useragent::invitation::PendingDialog;
7use anyhow::Result;
8use chrono::Utc;
9use rsipstack::dialog::DialogId;
10use rsipstack::dialog::dialog::{
11    Dialog, DialogState, DialogStateReceiver, DialogStateSender, TerminatedReason,
12};
13use rsipstack::dialog::dialog_layer::DialogLayer;
14use rsipstack::dialog::invitation::InviteOption;
15use std::collections::HashMap;
16use std::sync::Arc;
17use tokio_util::sync::CancellationToken;
18use tracing::{debug, info, warn};
19
20/// Remove `id` from the dialog layer and return the dialog, ready to be
21/// hung up. Shared by the dialog guards and `Invitation::hangup`.
22pub(crate) fn remove_dialog(layer: &DialogLayer, id: &DialogId) -> Option<Dialog> {
23    let dialog = layer.get_dialog(id)?;
24    layer.remove_dialog(id);
25    Some(dialog)
26}
27
28/// Reports transfer progress back to the referrer over the RFC 3515 implicit
29/// subscription created by an in-dialog REFER: `Event: refer` NOTIFYs sent on
30/// the parent dialog (100 Trying after the 202, then a terminal status).
31#[derive(Clone)]
32pub struct ReferProgressNotifier {
33    dialog_layer: Arc<DialogLayer>,
34    dialog_id: DialogId,
35    /// Set once the referrer shows it does not support refer subscriptions
36    /// (e.g. 405/501 on the first NOTIFY); further NOTIFYs are skipped.
37    disabled: Arc<std::sync::atomic::AtomicBool>,
38}
39
40impl std::fmt::Debug for ReferProgressNotifier {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("ReferProgressNotifier")
43            .field("dialog_id", &self.dialog_id)
44            .field("disabled", &self.disabled.load(std::sync::atomic::Ordering::Relaxed))
45            .finish()
46    }
47}
48
49impl ReferProgressNotifier {
50    pub fn new(dialog_layer: Arc<DialogLayer>, dialog_id: DialogId) -> Self {
51        Self {
52            dialog_layer,
53            dialog_id,
54            disabled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
55        }
56    }
57
58    async fn notify(&self, code: u16, sub_state: &str) {
59        if self.disabled.load(std::sync::atomic::Ordering::Relaxed) {
60            debug!(
61                id = %self.dialog_id,
62                code,
63                "refer notify skipped: referrer does not support refer subscriptions"
64            );
65            return;
66        }
67        let dialog = match self.dialog_layer.get_dialog(&self.dialog_id) {
68            Some(Dialog::Invite(dialog)) => dialog,
69            Some(_) => {
70                debug!(
71                    id = %self.dialog_id,
72                    "refer notify: dialog is not an invite dialog, skipping"
73                );
74                return;
75            }
76            None => {
77                debug!(
78                    id = %self.dialog_id,
79                    "refer notify: parent dialog gone, skipping"
80                );
81                return;
82            }
83        };
84        let status = match rsipstack::rsip::StatusCode::try_from(code) {
85            Ok(status) => status,
86            Err(_) => rsipstack::rsip::StatusCode::ServerInternalError,
87        };
88        match dialog.notify_refer(status, sub_state).await {
89            Ok(Some(response)) => {
90                // A referrer that rejects NOTIFY with 405/501 does not
91                // implement refer subscriptions (e.g. INVITE-mode bridges);
92                // stop sending further notifies for this transfer.
93                let response_code = u16::from(response.status_code().clone());
94                if matches!(response_code, 405 | 501) {
95                    self.disabled
96                        .store(true, std::sync::atomic::Ordering::Relaxed);
97                    info!(
98                        id = %self.dialog_id,
99                        code = response_code,
100                        "refer notify rejected, disabling further refer notifies"
101                    );
102                } else {
103                    info!(
104                        id = %self.dialog_id,
105                        code,
106                        sub_state,
107                        "refer notify sent"
108                    );
109                }
110            },
111            Ok(None) => warn!(
112                id = %self.dialog_id,
113                code,
114                "refer notify skipped: dialog not confirmed"
115            ),
116            Err(e) => warn!(
117                id = %self.dialog_id,
118                code,
119                "failed to send refer notify: {}",
120                e
121            ),
122        }
123    }
124
125    /// Transfer attempt accepted and in progress (sent right after the 202).
126    pub async fn trying(&self) {
127        self.notify(100, "active").await;
128    }
129
130    /// Terminal status of the transfer attempt: 2xx reports success, any
131    /// other code a failure (body is a `message/sipfrag` status line).
132    pub async fn finished(&self, code: u16) {
133        let sub_state = if (200..300).contains(&code) {
134            "terminated;reason=noresource".to_string()
135        } else {
136            format!("terminated;reason=SIP;cause={code}")
137        };
138        self.notify(code, &sub_state).await;
139    }
140}
141
142pub struct DialogStateReceiverGuard {
143    pub(super) dialog_layer: Arc<DialogLayer>,
144    pub(super) receiver: DialogStateReceiver,
145    pub(super) dialog_id: Option<DialogId>,
146    pub(super) hangup_headers: Option<Vec<rsipstack::rsip::Header>>,
147}
148
149impl DialogStateReceiverGuard {
150    pub fn new(
151        dialog_layer: Arc<DialogLayer>,
152        receiver: DialogStateReceiver,
153        hangup_headers: Option<Vec<rsipstack::rsip::Header>>,
154    ) -> Self {
155        Self {
156            dialog_layer,
157            receiver,
158            dialog_id: None,
159            hangup_headers,
160        }
161    }
162    pub async fn recv(&mut self) -> Option<DialogState> {
163        let state = self.receiver.recv().await;
164        if let Some(ref s) = state {
165            self.dialog_id = Some(s.id().clone());
166        }
167        state
168    }
169
170    fn take_dialog(&mut self) -> Option<Dialog> {
171        let id = self.dialog_id.take()?;
172        info!(%id, "dialog removed on  drop");
173        if let Some(dialog) = remove_dialog(&self.dialog_layer, &id) {
174            return Some(dialog);
175        }
176        // A client dialog is only re-registered under its tag-bearing id once
177        // do_invite's process_invite() fully completes; while still ringing
178        // it's registered under the pre-response id (empty remote tag). Our
179        // tracked `id` already reflects whatever tag the latest DialogState
180        // event carried (e.g. a 183's), so the exact-key lookup above misses
181        // it for any dialog hung up before it's confirmed. Fall back to a
182        // call-id scan, which is unaffected by that id mutation.
183        self.dialog_layer
184            .get_client_dialog_by_call_id(&id.call_id)
185            .into_iter()
186            .next()
187            .map(Dialog::Invite)
188    }
189
190    pub async fn drop_async(&mut self) {
191        if let Some(dialog) = self.take_dialog() {
192            if let Err(e) = dialog.hangup_with_headers(self.hangup_headers.take()).await {
193                warn!(id=%dialog.id(), "error hanging up dialog on drop: {}", e);
194            }
195        }
196    }
197}
198
199impl Drop for DialogStateReceiverGuard {
200    fn drop(&mut self) {
201        if let Some(dialog) = self.take_dialog() {
202            crate::spawn(async move {
203                if let Err(e) = dialog.hangup().await {
204                    warn!(id=%dialog.id(), "error hanging up dialog on drop: {}", e);
205                }
206            });
207        }
208    }
209}
210
211pub(super) struct InviteDialogStates {
212    pub is_client: bool,
213    pub session_id: String,
214    pub track_id: TrackId,
215    pub cancel_token: CancellationToken,
216    pub event_sender: EventSender,
217    /// Lock-free shared state of the leg this dialog belongs to.
218    pub leg: LegShared,
219    pub media_stream: Arc<MediaStream>,
220    pub terminated_reason: Option<TerminatedReason>,
221    pub has_early_media: bool,
222    /// Set once the initial INVITE's answer has been applied via
223    /// `DialogState::Confirmed`. rsipstack reuses the same `Confirmed` event
224    /// for the ACK of a re-INVITE we received (see `handle_reinvite`), but
225    /// in that case the body is the PBX's own locally-generated answer, not
226    /// a remote description — that re-invite was already fully handled via
227    /// `DialogState::Updated`/`handshake()`. Re-applying it here corrupts
228    /// the peer connection's remote SSRC/address with our own values.
229    initial_confirmed: bool,
230    /// Hangup intent carried by this leg (refer legs with `auto_hangup`),
231    /// reported on the leg's TrackEnd so the call actor can hang up.
232    pub hangup_reason: Option<CallRecordHangupReason>,
233    /// REFER notifier waiting for the dialog to return to the confirmed
234    /// state (the 202 reply transitions it back); the RFC 3515 Trying
235    /// NOTIFY is sent from the next `Confirmed` event.
236    pub pending_refer_notify: Option<Arc<ReferProgressNotifier>>,
237}
238
239impl InviteDialogStates {
240    pub(super) fn new(
241        is_client: bool,
242        session_id: String,
243        track_id: TrackId,
244        event_sender: EventSender,
245        media_stream: Arc<MediaStream>,
246        leg: LegShared,
247        cancel_token: CancellationToken,
248        hangup_reason: Option<CallRecordHangupReason>,
249    ) -> Self {
250        Self {
251            is_client,
252            session_id,
253            track_id,
254            cancel_token,
255            event_sender,
256            leg,
257            media_stream,
258            terminated_reason: None,
259            has_early_media: false,
260            initial_confirmed: false,
261            hangup_reason,
262            pending_refer_notify: None,
263        }
264    }
265}
266
267impl InviteDialogStates {
268    /// Called from `Drop` (synchronous context): everything used here is
269    /// lock-free (ArcSwap rcu/load + broadcast send), so no state or events
270    /// can be lost the way a failed `try_write` used to lose them.
271    pub(super) fn on_terminated(&mut self) {
272        // Release anyone deterministically waiting for this leg's teardown
273        // (`ActiveCall::do_hangup` waits for the BYE outcome before letting
274        // the session teardown cancel the token). `send_replace` (not
275        // `send`) so the value is recorded even when no receiver is alive
276        // yet — late subscribers must still observe the termination.
277        self.leg.terminated_tx.send_replace(true);
278        let term = CallProgress::termination(self.terminated_reason.as_ref());
279        let status_code = term.status_code;
280        let reason = term.hangup_reason;
281        self.leg.update_progress(|p| {
282            // A reason recorded before the dialog ended (our reject) comes
283            // with its own status; keep the pair.
284            if self.terminated_reason.is_some() || p.hangup_reason.is_none() {
285                p.last_status_code = status_code;
286            }
287            p.set_hangup_reason(reason.clone());
288        });
289        let progress = self.leg.progress.load_full();
290
291        // The auto-hangup intent (refer legs) must only fire when the refer
292        // leg was actually ANSWERED: if the transfer target rejected or timed
293        // out, the transfer failed and the caller stays in the original call.
294        let auto_hangup = self
295            .hangup_reason
296            .clone()
297            .filter(|_| progress.answer_time.is_some());
298        self.event_sender
299            .send(crate::event::SessionEvent::TrackEnd {
300                track_id: self.track_id.clone(),
301                timestamp: crate::media::get_timestamp(),
302                duration: progress
303                    .answer_time
304                    .map(|t| (Utc::now() - t).num_milliseconds())
305                    .unwrap_or_default() as u64,
306                ssrc: self.leg.ssrc,
307                play_id: None,
308                auto_hangup,
309            })
310            .ok();
311        // A superseded INVITE-mode bridge leg ends by internal replace, not
312        // by a real hangup — the client must not see a Hangup event (it
313        // would close the WebSocket and tear the whole session down).
314        if !progress.superseded {
315            let hangup_event = self
316                .leg
317                .build_hangup_event(self.track_id.clone(), Some(term.initiator.to_string()));
318            self.event_sender.send(hangup_event).ok();
319        }
320    }
321}
322
323impl Drop for InviteDialogStates {
324    fn drop(&mut self) {
325        self.on_terminated();
326        self.cancel_token.cancel();
327    }
328}
329
330impl DialogStateReceiverGuard {
331    pub(self) async fn dialog_event_loop(&mut self, states: &mut InviteDialogStates) -> Result<()> {
332        while let Some(event) = self.recv().await {
333            match event {
334                DialogState::Calling(dialog_id) => {
335                    info!(session_id=states.session_id, %dialog_id, "dialog calling");
336                    states
337                        .leg
338                        .update_progress(|p| p.session_id = dialog_id.to_string());
339                }
340                DialogState::Trying(_) => {}
341                DialogState::Early(dialog_id, resp) => {
342                    let code = resp.status_code.code();
343                    let body = resp.body();
344                    let answer = String::from_utf8_lossy(body);
345                    let has_sdp = !answer.is_empty();
346                    info!(session_id=states.session_id, %dialog_id, has_sdp=%has_sdp, "dialog early ({}): \n{}", code, answer);
347
348                    states.leg.update_progress(|p| p.on_early(code));
349
350                    if !states.is_client {
351                        continue;
352                    }
353
354                    states
355                        .event_sender
356                        .send(crate::event::SessionEvent::Ringing {
357                            track_id: states.track_id.clone(),
358                            timestamp: crate::media::get_timestamp(),
359                            early_media: has_sdp,
360                            refer: Some(states.leg.is_refer),
361                        })?;
362
363                    if has_sdp {
364                        states.has_early_media = true;
365                        states.leg.update_progress(|p| p.try_set_answer(&answer));
366                        states
367                            .media_stream
368                            .update_remote_description_provisional(
369                                &states.track_id,
370                                &answer.to_string(),
371                            )
372                            .await?;
373                    }
374                }
375                DialogState::Confirmed(dialog_id, msg) => {
376                    info!(session_id=states.session_id, %dialog_id, has_early_media=%states.has_early_media, "dialog confirmed");
377                    states
378                        .leg
379                        .update_progress(|p| p.on_confirmed(dialog_id.to_string()));
380                    if states.is_client && !states.initial_confirmed {
381                        states.initial_confirmed = true;
382                        let answer = String::from_utf8_lossy(msg.body());
383                        let answer = answer.trim();
384                        if !answer.is_empty() {
385                            if states.has_early_media {
386                                info!(
387                                    session_id = states.session_id,
388                                    "updating remote description with final answer after early media (force=true)"
389                                );
390                                // Force update when transitioning from early media (183) to confirmed (200 OK)
391                                // This ensures media parameters are properly updated even if SDP appears similar
392                                if let Err(e) = states
393                                    .media_stream
394                                    .update_remote_description_force(
395                                        &states.track_id,
396                                        &answer.to_string(),
397                                    )
398                                    .await
399                                {
400                                    tracing::warn!(
401                                        session_id = states.session_id,
402                                        "failed to force update remote description on confirmed: {}",
403                                        e
404                                    );
405                                }
406                            } else {
407                                if let Err(e) = states
408                                    .media_stream
409                                    .update_remote_description(
410                                        &states.track_id,
411                                        &answer.to_string(),
412                                    )
413                                    .await
414                                {
415                                    tracing::warn!(
416                                        session_id = states.session_id,
417                                        "failed to update remote description on confirmed: {}",
418                                        e
419                                    );
420                                }
421                            }
422                        }
423                    }
424                    // The dialog is back in the confirmed state (either the
425                    // initial ACK, or rsipstack returning from a mid-dialog
426                    // request like REFER) — flush the pending RFC 3515
427                    // Trying NOTIFY.
428                    if let Some(notifier) = states.pending_refer_notify.take() {
429                        notifier.trying().await;
430                    }
431                }
432                DialogState::Info(dialog_id, req, tx_handle) => {
433                    let body_str = String::from_utf8_lossy(req.body());
434                    info!(session_id=states.session_id, %dialog_id, body=%body_str, "dialog info received");
435                    if body_str.starts_with("Signal=") {
436                        let digit = body_str.trim_start_matches("Signal=").chars().next();
437                        if let Some(digit) = digit {
438                            states.event_sender.send(crate::event::SessionEvent::Dtmf {
439                                track_id: states.track_id.clone(),
440                                timestamp: crate::media::get_timestamp(),
441                                digit: digit.to_string(),
442                                refer: Some(states.leg.is_refer),
443                            })?;
444                        }
445                    }
446                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
447                }
448                DialogState::Message(dialog_id, req, tx_handle) => {
449                    let body_str = String::from_utf8_lossy(req.body()).to_string();
450                    let content_type = req.headers.iter().find_map(|h| {
451                        if let rsipstack::rsip::Header::ContentType(content_type) = h {
452                            Some(content_type.value().to_string())
453                        } else {
454                            None
455                        }
456                    });
457                    info!(
458                        session_id=states.session_id,
459                        %dialog_id,
460                        content_type=content_type.as_deref(),
461                        body=%body_str,
462                        "dialog message received"
463                    );
464                    states
465                        .event_sender
466                        .send(crate::event::SessionEvent::Message {
467                            track_id: states.track_id.clone(),
468                            timestamp: crate::media::get_timestamp(),
469                            body: body_str,
470                            content_type,
471                            refer: Some(states.leg.is_refer),
472                        })
473                        .ok();
474                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
475                }
476                DialogState::Updated(dialog_id, _req, tx_handle) => {
477                    info!(session_id = states.session_id, %dialog_id, "dialog update received");
478                    let mut answer_sdp = None;
479                    if let Some(sdp_body) = _req.body().get(..) {
480                        let sdp_str = String::from_utf8_lossy(sdp_body);
481                        if !sdp_str.is_empty()
482                            && (_req.method == rsipstack::rsip::Method::Invite
483                                || _req.method == rsipstack::rsip::Method::Update)
484                        {
485                            info!(session_id=states.session_id, %dialog_id, method=%_req.method, "handling re-invite/update offer");
486
487                            // Detect hold state from SDP
488                            let is_on_hold =
489                                crate::media::negotiate::detect_hold_state_from_sdp(&sdp_str);
490                            info!(session_id=states.session_id, %dialog_id, is_on_hold=%is_on_hold, "detected hold state from re-invite SDP");
491
492                            // Update media stream hold state + emit hold event
493                            apply_hold_state(states, is_on_hold).await;
494
495                            match states
496                                .media_stream
497                                .handshake(&states.track_id, sdp_str.to_string(), None)
498                                .await
499                            {
500                                Ok(sdp) => answer_sdp = Some(sdp),
501                                Err(e) => {
502                                    warn!(
503                                        session_id = states.session_id,
504                                        "failed to handle re-invite: {}", e
505                                    );
506                                }
507                            }
508                        } else {
509                            info!(session_id=states.session_id, %dialog_id, "updating remote description:\n{}", sdp_str);
510
511                            // Also check hold state for non-INVITE/UPDATE messages with SDP
512                            let is_on_hold =
513                                crate::media::negotiate::detect_hold_state_from_sdp(&sdp_str);
514                            apply_hold_state(states, is_on_hold).await;
515
516                            states
517                                .media_stream
518                                .update_remote_description(&states.track_id, &sdp_str.to_string())
519                                .await?;
520                        }
521                    }
522
523                    if let Some(sdp) = answer_sdp {
524                        tx_handle
525                            .respond(
526                                rsipstack::rsip::StatusCode::OK,
527                                Some(vec![rsipstack::rsip::Header::ContentType(
528                                    "application/sdp".to_string().into(),
529                                )]),
530                                Some(sdp.into()),
531                            )
532                            .await
533                            .ok();
534                    } else {
535                        tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
536                    }
537                }
538                DialogState::Options(dialog_id, _req, tx_handle) => {
539                    info!(session_id = states.session_id, %dialog_id, "dialog options received");
540                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
541                }
542                DialogState::Refer(dialog_id, req, tx_handle) => {
543                    let refer_to = req
544                        .headers
545                        .iter()
546                        .find_map(|h| {
547                            if let rsipstack::rsip::Header::ReferTo(h) = h {
548                                return Some(h.value().to_string());
549                            }
550                            None
551                        })
552                        .unwrap_or_default();
553                    let referred_by = req.headers.iter().find_map(|h| {
554                        if let rsipstack::rsip::Header::ReferredBy(h) = h {
555                            return Some(h.value().to_string());
556                        }
557                        None
558                    });
559                    // Blindly forward the REFER's custom headers onto the
560                    // transfer INVITE: INVITE-mode carriers (e.g. Aliyun CC)
561                    // attach routing data to the REFER (User-to-User,
562                    // X-ACC-Bizdata, X-AliyunIVR-*) and expect it to survive
563                    // the transfer hop. Protocol headers are typed (never
564                    // `Header::Other`), so collecting Other headers only is
565                    // inherently safe; User-to-User is added explicitly since
566                    // rsipstack types it; X-Referred-* are skipped because
567                    // do_refer regenerates them for the new hop.
568                    let mut extra_headers: HashMap<String, String> = req
569                        .headers
570                        .iter()
571                        .filter_map(|h| {
572                            if let rsipstack::rsip::Header::Other(name, value) = h {
573                                let name = name.to_string();
574                                if name.eq_ignore_ascii_case("X-Referred-To")
575                                    || name.eq_ignore_ascii_case("X-Referred-From")
576                                    || name.eq_ignore_ascii_case("X-Referred-Id")
577                                {
578                                    return None;
579                                }
580                                return Some((name, value.to_string()));
581                            }
582                            None
583                        })
584                        .collect();
585                    if let Some(user_to_user) = req.headers.iter().find_map(|h| {
586                        if let rsipstack::rsip::Header::UserToUser(h) = h {
587                            return Some(h.value().to_string());
588                        }
589                        None
590                    }) {
591                        extra_headers.insert("User-to-User".to_string(), user_to_user);
592                    }
593                    let extra_headers = (!extra_headers.is_empty()).then_some(extra_headers);
594                    info!(session_id = states.session_id, %dialog_id, %refer_to, "received REFER");
595                    tx_handle
596                        .reply(rsipstack::rsip::StatusCode::Other(202, "Accepted".into()))
597                        .await
598                        .ok();
599                    // RFC 3515: the 202 opens an implicit subscription; report
600                    // progress on the parent dialog. Whether the transfer is
601                    // actually attempted is decided by the call actor. The
602                    // Trying NOTIFY waits for the next Confirmed event — the
603                    // 202 itself flips the dialog back to confirmed, so this
604                    // is deterministic and free of state races.
605                    let notifier = Arc::new(ReferProgressNotifier::new(
606                        self.dialog_layer.clone(),
607                        dialog_id.clone(),
608                    ));
609                    states.pending_refer_notify = Some(notifier.clone());
610                    states
611                        .event_sender
612                        .send(crate::event::SessionEvent::TransferRequest {
613                            track_id: states.track_id.clone(),
614                            timestamp: crate::media::get_timestamp(),
615                            refer_to,
616                            referred_by,
617                            extra_headers,
618                            refer: Some(states.leg.is_refer),
619                            leg_session_id: Some(
620                                states.leg.progress.load_full().session_id.clone()
621                            ),
622                            notify: Some(notifier),
623                        })
624                        .ok();
625                }
626                DialogState::Notify(dialog_id, _req, tx_handle) => {
627                    info!(
628                        session_id = states.session_id,
629                        %dialog_id,
630                        "dialog notify received"
631                    );
632                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
633                }
634                DialogState::Terminated(dialog_id, reason) => {
635                    info!(
636                        session_id = states.session_id,
637                        ?dialog_id,
638                        ?reason,
639                        "dialog terminated"
640                    );
641                    states.terminated_reason = Some(reason.clone());
642                    return Ok(());
643                }
644                other_state => {
645                    info!(
646                        session_id = states.session_id,
647                        %other_state,
648                        "dialog received other state"
649                    );
650                }
651            }
652        }
653        Ok(())
654    }
655
656    pub(super) async fn process_dialog(&mut self, mut states: InviteDialogStates) {
657        let token = states.cancel_token.clone();
658        tokio::select! {
659            _ = token.cancelled() => {
660                // Our own teardown (reject/hangup) records its outcome on the
661                // leg before cancelling; only an unexplained cancel is the
662                // caller's.
663                if states.leg.progress.load().hangup_reason.is_none() {
664                    states.terminated_reason = Some(TerminatedReason::UacCancel);
665                }
666            }
667            _ = self.dialog_event_loop(&mut states) => {}
668        };
669
670        // Update hangup headers from the leg extras if available
671        let extras = states.leg.extras.load_full();
672        if let Some(headers) = crate::sip_util::hangup_headers_from_extras(&extras) {
673            match &mut self.hangup_headers {
674                Some(existing) => existing.extend(headers),
675                None => self.hangup_headers = Some(headers),
676            }
677        }
678
679        self.drop_async().await;
680    }
681}
682
683/// Apply a hold/resume transition to the media track and emit the Hold event.
684async fn apply_hold_state(states: &mut InviteDialogStates, is_on_hold: bool) {
685    if is_on_hold {
686        states
687            .media_stream
688            .hold_track(Some(states.track_id.clone()))
689            .await;
690    } else {
691        states
692            .media_stream
693            .resume_track(Some(states.track_id.clone()))
694            .await;
695    }
696    states
697        .event_sender
698        .send(crate::event::SessionEvent::Hold {
699            track_id: states.track_id.clone(),
700            timestamp: crate::media::get_timestamp(),
701            on_hold: is_on_hold,
702            refer: Some(states.leg.is_refer),
703        })
704        .ok();
705}
706
707#[derive(Clone)]
708pub struct Invitation {
709    pub dialog_layer: Arc<DialogLayer>,
710    pub pending_dialogs: Arc<std::sync::Mutex<HashMap<DialogId, PendingDialog>>>,
711    /// Maps the (short) public session id of an incoming call to the DialogId
712    /// captured when the INVITE arrived. Incoming sessions no longer reuse the
713    /// raw dialog-id string, so every session-id based lookup resolves here.
714    sessions: Arc<std::sync::Mutex<HashMap<String, DialogId>>>,
715}
716
717impl Invitation {
718    pub fn new(dialog_layer: Arc<DialogLayer>) -> Self {
719        Self {
720            dialog_layer,
721            pending_dialogs: Arc::new(std::sync::Mutex::new(HashMap::new())),
722            sessions: Arc::new(std::sync::Mutex::new(HashMap::new())),
723        }
724    }
725
726    pub fn register_session(&self, session_id: &str, dialog_id: &DialogId) {
727        self.sessions
728            .lock()
729            .map(|mut ss| ss.insert(session_id.to_string(), dialog_id.clone()))
730            .ok();
731    }
732
733    pub fn unregister_session(&self, session_id: &str) {
734        self.sessions
735            .lock()
736            .map(|mut ss| ss.remove(session_id))
737            .ok();
738    }
739
740    pub fn session_exists(&self, session_id: &str) -> bool {
741        self.sessions
742            .lock()
743            .map(|ss| ss.contains_key(session_id))
744            .unwrap_or(false)
745    }
746
747    pub fn add_pending(&self, dialog_id: DialogId, pending: PendingDialog) {
748        self.pending_dialogs
749            .lock()
750            .map(|mut ps| ps.insert(dialog_id, pending))
751            .ok();
752    }
753
754    pub fn get_pending_call(&self, dialog_id: &DialogId) -> Option<PendingDialog> {
755        self.pending_dialogs
756            .lock()
757            .ok()
758            .and_then(|mut ps| ps.remove(dialog_id))
759    }
760
761    pub fn has_pending_call(&self, dialog_id: &DialogId) -> bool {
762        self.pending_dialogs
763            .lock()
764            .ok()
765            .map(|ps| ps.contains_key(dialog_id))
766            .unwrap_or(false)
767    }
768
769    pub fn find_dialog_id_by_session_id(&self, session_id: &str) -> Option<DialogId> {
770        if let Some(id) = self
771            .sessions
772            .lock()
773            .ok()
774            .and_then(|ss| ss.get(session_id).cloned())
775        {
776            return Some(id);
777        }
778        self.pending_dialogs.lock().ok().and_then(|ps| {
779            ps.iter()
780                .find(|(id, _)| id.to_string() == session_id)
781                .map(|(id, _)| id.clone())
782        })
783    }
784
785    /// Reject a pending dialog or hang up an established one.
786    pub async fn hangup(
787        &self,
788        dialog_id: DialogId,
789        code: Option<rsipstack::rsip::StatusCode>,
790        reason: Option<String>,
791    ) -> Result<()> {
792        if let Some(call) = self.get_pending_call(&dialog_id) {
793            call.dialog.reject(code, reason).ok();
794        }
795        if let Some(dialog) = remove_dialog(&self.dialog_layer, &dialog_id) {
796            dialog.hangup().await.ok();
797        }
798        Ok(())
799    }
800
801    pub async fn invite(
802        &self,
803        invite_option: InviteOption,
804        state_sender: DialogStateSender,
805    ) -> Result<(DialogId, Option<Vec<u8>>), rsipstack::Error> {
806        let (dialog, resp) = self
807            .dialog_layer
808            .do_invite(invite_option, state_sender)
809            .await?;
810
811        let offer = match resp {
812            Some(resp) => match resp.status_code.kind() {
813                rsipstack::rsip::StatusCodeKind::Successful => {
814                    let offer = resp.body.clone();
815                    Some(offer)
816                }
817                _ => {
818                    let reason = resp
819                        .reason_phrase()
820                        .unwrap_or(&resp.status_code.to_string())
821                        .to_string();
822                    return Err(rsipstack::Error::DialogError(
823                        reason,
824                        dialog.id(),
825                        resp.status_code,
826                    ));
827                }
828            },
829            None => {
830                return Err(rsipstack::Error::DialogError(
831                    "no response received".to_string(),
832                    dialog.id(),
833                    rsipstack::rsip::StatusCode::NotAcceptableHere,
834                ));
835            }
836        };
837        Ok((dialog.id(), offer))
838    }
839}
840
841#[cfg(test)]
842mod tests {
843    use super::*;
844    use crate::call::state::CallProgress;
845    use crate::media::stream::MediaStreamBuilder;
846
847    // SDP used to simulate an early-media 183 Session Progress response.
848    const EARLY_MEDIA_SDP: &str = "v=0\r\n\
849        o=- 1000 1 IN IP4 192.168.1.100\r\n\
850        s=SIP Call\r\n\
851        t=0 0\r\n\
852        m=audio 10000 RTP/AVP 0\r\n\
853        c=IN IP4 192.168.1.100\r\n\
854        a=rtpmap:0 PCMU/8000\r\n\
855        a=sendrecv\r\n";
856
857    fn make_states(has_early_media: bool) -> InviteDialogStates {
858        let (event_tx, _event_rx) = tokio::sync::broadcast::channel(16);
859        let media_stream = Arc::new(
860            MediaStreamBuilder::new(event_tx.clone())
861                .with_id("test-stream".to_string())
862                .build(),
863        );
864        let cancel_token = CancellationToken::new();
865        let leg = LegShared::new(1000, true, CallProgress::default());
866
867        InviteDialogStates {
868            is_client: true,
869            session_id: "test-session".to_string(),
870            track_id: "test-track".to_string(),
871            cancel_token: cancel_token.clone(),
872            event_sender: event_tx.clone(),
873            leg,
874            media_stream,
875            terminated_reason: None,
876            has_early_media,
877            initial_confirmed: false,
878            hangup_reason: None,
879            pending_refer_notify: None,
880        }
881    }
882
883    /// Verify that when a 183 Session Progress with SDP arrives (`DialogState::Early`),
884    /// the early SDP is stored in the leg progress so it can serve as a fallback
885    /// when the final 200 OK has an empty body.
886    #[tokio::test]
887    async fn test_early_sdp_stored_in_leg_progress() {
888        let mut states = make_states(false);
889
890        // Simulate DialogState::Early with SDP body (183 Session Progress):
891        // same steps the Early branch performs.
892        let answer = EARLY_MEDIA_SDP.to_string();
893        let has_sdp = !answer.is_empty();
894        if states.is_client && has_sdp {
895            states.has_early_media = true;
896            states.leg.update_progress(|p| p.try_set_answer(&answer));
897        }
898
899        // Assert: early SDP is stored
900        let progress = states.leg.progress.load_full();
901        assert!(
902            progress.answer.is_some(),
903            "leg progress answer should be set after 183 with SDP"
904        );
905        assert_eq!(
906            progress.answer.as_deref().unwrap(),
907            EARLY_MEDIA_SDP,
908            "leg progress answer should contain the early SDP"
909        );
910        assert!(states.has_early_media, "has_early_media should be true");
911    }
912
913    /// Verify that when a 200 OK arrives with an empty body after early media has been
914    /// negotiated, the leg progress retains the early SDP (not overwritten with "").
915    ///
916    /// This is the regression test for the bug where a late 200 OK with empty body would
917    /// cause `SessionEvent::Answer { sdp: "" }` to be emitted, making the answer event
918    /// appear as if no SDP was negotiated.
919    #[tokio::test]
920    async fn test_confirmed_empty_body_keeps_early_sdp() {
921        let mut states = make_states(false);
922
923        // Step 1: simulate 183 with SDP → set has_early_media and progress answer
924        states.has_early_media = true;
925        states
926            .leg
927            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
928
929        // Step 2: simulate 200 OK with empty body (Confirmed handler logic)
930        states
931            .leg
932            .update_progress(|p| p.on_confirmed("dialog-1".to_string()));
933        // The Confirmed handler only calls update_remote_description when the body
934        // is non-empty; it does NOT overwrite the progress answer.
935        let confirmed_answer = String::new();
936        assert!(
937            confirmed_answer.trim().is_empty(),
938            "empty body must not be applied"
939        );
940
941        // Assert: leg progress still holds the early SDP
942        let progress = states.leg.progress.load_full();
943        assert!(
944            progress.answer.is_some(),
945            "answer must not be None after 200 OK with empty body"
946        );
947        let stored_answer = progress.answer.as_deref().unwrap();
948        assert!(
949            !stored_answer.is_empty(),
950            "answer must not be empty after 200 OK with empty body"
951        );
952        assert_eq!(
953            stored_answer, EARLY_MEDIA_SDP,
954            "answer should still be the early SDP after 200 OK with empty body"
955        );
956    }
957
958    /// Verify that `create_outgoing_sip_track`'s fallback logic works:
959    /// when the 200 OK body is empty but the leg progress has the early SDP,
960    /// the fallback path is taken and the early SDP is returned (not an empty string).
961    #[tokio::test]
962    async fn test_answer_fallback_to_early_sdp_when_200ok_empty() {
963        // Simulate what the Early (183) handler does: store the early SDP.
964        let states = make_states(true);
965        states
966            .leg
967            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
968
969        // Simulate what create_outgoing_sip_track does when 200 OK has empty body.
970        let early = states.leg.progress.load_full().answer.clone();
971        let raw_answer: Option<Vec<u8>> = Some(vec![]); // empty body from 200 OK
972
973        let (answer, already_applied) =
974            crate::call::state::resolve_final_answer(raw_answer, early.as_ref()).unwrap();
975
976        // The answer returned to setup_caller_track (and used in SessionEvent::Answer)
977        // must be the early SDP, not an empty string.
978        assert!(
979            !answer.is_empty(),
980            "Resolved answer must not be empty — should contain the early SDP"
981        );
982        assert_eq!(
983            answer, EARLY_MEDIA_SDP,
984            "Resolved answer should be the early SDP from the 183 handler"
985        );
986        assert!(
987            already_applied,
988            "remote_description_already_applied should be true when using early SDP fallback"
989        );
990    }
991
992    /// Verify the normal case: when 200 OK carries its own SDP body,
993    /// that SDP is used directly (not the early SDP) and remote description
994    /// should be applied.
995    #[tokio::test]
996    async fn test_answer_uses_200ok_sdp_when_present() {
997        const FINAL_SDP: &str = "v=0\r\n\
998            o=- 2000 2 IN IP4 10.0.0.1\r\n\
999            s=SIP Call\r\n\
1000            t=0 0\r\n\
1001            m=audio 20000 RTP/AVP 0\r\n\
1002            c=IN IP4 10.0.0.1\r\n\
1003            a=rtpmap:0 PCMU/8000\r\n\
1004            a=sendrecv\r\n";
1005
1006        let states = make_states(true);
1007        states
1008            .leg
1009            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
1010
1011        let early = states.leg.progress.load_full().answer.clone();
1012        let (answer, already_applied) = crate::call::state::resolve_final_answer(
1013            Some(FINAL_SDP.as_bytes().to_vec()),
1014            early.as_ref(),
1015        )
1016        .unwrap();
1017
1018        assert_eq!(
1019            answer, FINAL_SDP,
1020            "When 200 OK has SDP, it should be used (not the early SDP)"
1021        );
1022        assert!(
1023            !already_applied,
1024            "remote_description_already_applied should be false when 200 OK has SDP body"
1025        );
1026    }
1027
1028    /// Regression: `on_terminated` runs in a synchronous `Drop` context.
1029    /// The old implementation used `try_write` and silently dropped the
1030    /// status/reason updates AND the TrackEnd/Hangup events when the lock was
1031    /// contended. The lock-free (ArcSwap) implementation must always emit both
1032    /// events and record the termination, even while another task keeps
1033    /// mutating the progress concurrently.
1034    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1035    async fn test_on_terminated_always_emits_events_and_records_state() {
1036        use crate::event::SessionEvent;
1037        use std::sync::atomic::{AtomicBool, Ordering};
1038
1039        let mut states = make_states(false);
1040        states.terminated_reason = Some(TerminatedReason::UacCancel);
1041        let leg = states.leg.clone();
1042        let event_sender = states.event_sender.clone();
1043        let mut event_receiver = event_sender.subscribe();
1044
1045        // Hammer the progress concurrently, as a busy actor would.
1046        let stop = Arc::new(AtomicBool::new(false));
1047        let stop2 = stop.clone();
1048        let progress = leg.progress.clone();
1049        let writer = crate::spawn(async move {
1050            while !stop2.load(Ordering::Relaxed) {
1051                // Touch unrelated fields, like a busy actor would (never the
1052                // termination fields), so writers don't clobber each other.
1053                progress.rcu(|p| {
1054                    let mut p = CallProgress::clone(p);
1055                    p.answer_time.get_or_insert_with(chrono::Utc::now);
1056                    p
1057                });
1058                tokio::task::yield_now().await;
1059            }
1060        });
1061
1062        // Give the writer a moment to start contending.
1063        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1064
1065        // Synchronous drop, exactly like the real dialog task teardown.
1066        drop(states);
1067
1068        stop.store(true, Ordering::Relaxed);
1069        let _ = writer.await;
1070
1071        // Both events must have been emitted despite the concurrent writer.
1072        let mut saw_track_end = false;
1073        let mut saw_hangup = false;
1074        while let Ok(event) = event_receiver.try_recv() {
1075            match event {
1076                SessionEvent::TrackEnd { .. } => saw_track_end = true,
1077                SessionEvent::Hangup { refer, .. } => {
1078                    assert_eq!(refer, Some(true), "refer flag comes from the leg");
1079                    saw_hangup = true;
1080                }
1081                _ => {}
1082            }
1083        }
1084        assert!(
1085            saw_track_end,
1086            "TrackEnd must be emitted from on_terminated even under contention"
1087        );
1088        assert!(
1089            saw_hangup,
1090            "Hangup must be emitted from on_terminated even under contention"
1091        );
1092
1093        // The termination must be recorded (487 for UacCancel); the concurrent
1094        // writer only ever writes 100, so observing 487 proves the rcu landed.
1095        let progress = leg.progress.load_full();
1096        assert_eq!(progress.last_status_code, 487);
1097        assert_eq!(
1098            progress.hangup_reason,
1099            Some(crate::callrecord::CallRecordHangupReason::Canceled)
1100        );
1101    }
1102
1103    /// `on_terminated` must signal the leg's termination watch so
1104    /// `ActiveCall::do_hangup`'s deterministic-teardown wait is released as
1105    /// soon as the dialog task records the termination — and a waiter that
1106    /// starts after the fact must resolve immediately.
1107    #[tokio::test]
1108    async fn test_on_terminated_signals_leg_watch() {
1109        let states = make_states(false);
1110        let leg = states.leg.clone();
1111
1112        assert!(
1113            !*leg.terminated_tx.borrow(),
1114            "watch must start unsignalled"
1115        );
1116
1117        let waiter = crate::spawn({
1118            let leg = leg.clone();
1119            async move { leg.terminated().await }
1120        });
1121
1122        // Synchronous drop, exactly like the real dialog task teardown.
1123        drop(states);
1124
1125        assert!(
1126            *leg.terminated_tx.borrow(),
1127            "on_terminated must signal the watch"
1128        );
1129        tokio::time::timeout(std::time::Duration::from_millis(500), waiter)
1130            .await
1131            .expect("terminated() waiter must be released by the signal")
1132            .expect("waiter task must not panic");
1133
1134        // A waiter starting after the fact resolves immediately.
1135        tokio::time::timeout(std::time::Duration::from_millis(100), leg.terminated())
1136            .await
1137            .expect("terminated() must resolve immediately once signalled");
1138    }
1139
1140    /// Regression (production 2026-11-11, AI refer transfer): when session
1141    /// teardown wins the `process_dialog` select on a leg whose hangup reason
1142    /// was already recorded by `do_hangup` (ByRefer), `terminated_reason`
1143    /// stays `None` and the answered call's status (200) must NOT be
1144    /// overwritten with the unexplained-cancel mapping (487/500) — that
1145    /// overwrite flipped the CDR `isCall` to false for fully-connected
1146    /// transferred calls.
1147    #[tokio::test]
1148    async fn test_answered_leg_with_recorded_reason_keeps_status_on_unexplained_cancel() {
1149        let mut states = make_states(false);
1150        // The call was answered and do_hangup recorded the intent before the
1151        // teardown raced the dialog event loop.
1152        states.leg.update_progress(|p| {
1153            p.on_confirmed("dlg".to_string());
1154            p.set_hangup_reason(crate::callrecord::CallRecordHangupReason::ByRefer);
1155        });
1156        assert_eq!(states.leg.progress.load_full().last_status_code, 200);
1157
1158        // Cancelled branch won the select: no dialog-level reason recorded.
1159        states.terminated_reason = None;
1160
1161        states.on_terminated();
1162
1163        let progress = states.leg.progress.load_full();
1164        assert_eq!(
1165            progress.last_status_code, 200,
1166            "answered call must keep the confirmed status"
1167        );
1168        assert_eq!(
1169            progress.hangup_reason,
1170            Some(crate::callrecord::CallRecordHangupReason::ByRefer),
1171            "the first-recorded hangup reason must be preserved"
1172        );
1173    }
1174
1175    /// A minimal counting track that records how many times its remote
1176    /// description was (force-)updated, without touching any real media.
1177    struct CountingTrack {
1178        id: TrackId,
1179        config: crate::media::track::TrackConfig,
1180        processor_chain: crate::media::processor::ProcessorChain,
1181        updates: std::sync::Arc<std::sync::atomic::AtomicUsize>,
1182    }
1183
1184    #[async_trait::async_trait]
1185    impl crate::media::track::Track for CountingTrack {
1186        fn ssrc(&self) -> u32 {
1187            0
1188        }
1189        fn cancel_token(&self) -> tokio_util::sync::CancellationToken {
1190            tokio_util::sync::CancellationToken::new()
1191        }
1192        fn id(&self) -> &TrackId {
1193            &self.id
1194        }
1195        fn config(&self) -> &crate::media::track::TrackConfig {
1196            &self.config
1197        }
1198        fn processor_chain(&mut self) -> &mut crate::media::processor::ProcessorChain {
1199            &mut self.processor_chain
1200        }
1201        async fn handshake(
1202            &mut self,
1203            _offer: String,
1204            _timeout: Option<tokio::time::Duration>,
1205        ) -> Result<String> {
1206            Ok(String::new())
1207        }
1208        async fn update_remote_description(&mut self, _answer: &String) -> Result<()> {
1209            self.updates
1210                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1211            Ok(())
1212        }
1213        async fn update_remote_description_force(&mut self, _answer: &String) -> Result<()> {
1214            self.updates
1215                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1216            Ok(())
1217        }
1218        async fn start(
1219            &mut self,
1220            _event_sender: EventSender,
1221            _packet_sender: crate::media::track::TrackPacketSender,
1222        ) -> Result<()> {
1223            Ok(())
1224        }
1225        async fn stop(&self) -> Result<()> {
1226            Ok(())
1227        }
1228        async fn send_packet(&mut self, _packet: &crate::media::AudioFrame) -> Result<()> {
1229            Ok(())
1230        }
1231    }
1232
1233    /// Regression: a client dialog must apply its remote SDP answer exactly
1234    /// once. The `initial_confirmed` guard exists because the final `Confirmed`
1235    /// event fires both when the 200 OK is processed *and* again when the ACK
1236    /// for the re-INVITE completes; without the guard the answer would be
1237    /// re-applied (and a duplicate `TrackStart`/`SessionEvent::Answer` emitted).
1238    #[tokio::test]
1239    async fn test_confirmed_applies_remote_answer_only_once() {
1240        let mut states = make_states(false);
1241
1242        let updates = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1243        let track = CountingTrack {
1244            id: states.track_id.clone(),
1245            config: crate::media::track::TrackConfig::default(),
1246            processor_chain: crate::media::processor::ProcessorChain::new(16000),
1247            updates: updates.clone(),
1248        };
1249        states
1250            .media_stream
1251            .update_track(Box::new(track), None)
1252            .await;
1253
1254        let endpoint = {
1255            let mut builder = rsipstack::EndpointBuilder::new();
1256            builder.build()
1257        };
1258        let dialog_layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
1259
1260        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<DialogState>();
1261        let mut guard = DialogStateReceiverGuard::new(dialog_layer, rx, None);
1262
1263        let dialog_id = DialogId {
1264            call_id: "test-call-id".to_string(),
1265            local_tag: "test-local-tag".to_string(),
1266            remote_tag: "test-remote-tag".to_string(),
1267        };
1268
1269        let mut resp = rsipstack::rsip::Response::default();
1270        resp.body = EARLY_MEDIA_SDP.as_bytes().to_vec();
1271
1272        // Two Confirmed events (200 OK + re-INVITE ACK) must only apply once.
1273        tx.send(DialogState::Confirmed(dialog_id.clone(), resp.clone()))
1274            .unwrap();
1275        tx.send(DialogState::Confirmed(dialog_id, resp)).unwrap();
1276        drop(tx);
1277
1278        guard
1279            .dialog_event_loop(&mut states)
1280            .await
1281            .expect("dialog event loop must complete");
1282
1283        assert_eq!(
1284            updates.load(std::sync::atomic::Ordering::SeqCst),
1285            1,
1286            "remote answer must be applied exactly once, not on the re-INVITE ACK Confirmed event"
1287        );
1288    }
1289
1290    #[test]
1291    fn test_session_map_register_find_unregister() {
1292        let endpoint = {
1293            let mut builder = rsipstack::EndpointBuilder::new();
1294            builder.build()
1295        };
1296        let invitation = Invitation::new(Arc::new(DialogLayer::new(endpoint.inner.clone())));
1297
1298        let dialog_id = DialogId {
1299            call_id: "long-call-id-from-carrier".to_string(),
1300            local_tag: String::new(),
1301            remote_tag: "remote-tag".to_string(),
1302        };
1303
1304        assert!(!invitation.session_exists("s.3f9a2b1c4d5e"));
1305        assert!(
1306            invitation
1307                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1308                .is_none()
1309        );
1310
1311        invitation.register_session("s.3f9a2b1c4d5e", &dialog_id);
1312        assert!(invitation.session_exists("s.3f9a2b1c4d5e"));
1313        assert_eq!(
1314            invitation
1315                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1316                .unwrap(),
1317            dialog_id
1318        );
1319
1320        invitation.unregister_session("s.3f9a2b1c4d5e");
1321        assert!(!invitation.session_exists("s.3f9a2b1c4d5e"));
1322        assert!(
1323            invitation
1324                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1325                .is_none()
1326        );
1327        // Unregistering an unknown session is a no-op.
1328        invitation.unregister_session("s.unknown");
1329    }
1330
1331    /// The legacy fallback must keep resolving session ids that match a pending
1332    /// dialog's dialog-id string (e.g. sessions registered before the mapping
1333    /// table existed, or callers still using the raw dialog id).
1334    #[test]
1335    fn test_find_dialog_id_falls_back_to_pending_scan() {
1336        use rsipstack::dialog::dialog::DialogInner;
1337        use rsipstack::dialog::invite_dialog::InviteDialog;
1338        use rsipstack::rsip::typed::{CSeq, Contact, From, To, Via};
1339        use rsipstack::rsip::{Header, Request};
1340        use rsipstack::transaction::key::TransactionRole;
1341
1342        let endpoint = {
1343            let mut builder = rsipstack::EndpointBuilder::new();
1344            builder.build()
1345        };
1346        let invitation = Invitation::new(Arc::new(DialogLayer::new(endpoint.inner.clone())));
1347
1348        let dialog_id = DialogId {
1349            call_id: "legacy-call-id".to_string(),
1350            local_tag: String::new(),
1351            remote_tag: "remote-tag".to_string(),
1352        };
1353
1354        let initial_request = Request {
1355            method: rsipstack::rsip::Method::Invite,
1356            uri: rsipstack::rsip::Uri::try_from("sip:bob@example.com:5060").unwrap(),
1357            headers: vec![
1358                Via::parse("SIP/2.0/UDP alice.example.com:5060;branch=z9hG4bKnashds")
1359                    .unwrap()
1360                    .into(),
1361                CSeq::parse("1 INVITE").unwrap().into(),
1362                From::parse("Alice <sip:alice@example.com>;tag=remote-tag")
1363                    .unwrap()
1364                    .into(),
1365                To::parse("Bob <sip:bob@example.com>").unwrap().into(),
1366                Header::CallId("legacy-call-id".into()),
1367                Contact::parse("<sip:alice@alice.example.com:5060>")
1368                    .unwrap()
1369                    .into(),
1370                Header::MaxForwards("70".into()),
1371            ]
1372            .into(),
1373            version: rsipstack::rsip::Version::V2,
1374            body: vec![],
1375        };
1376
1377        let (state_sender, _state_receiver) = tokio::sync::mpsc::unbounded_channel();
1378        let (tu_sender, _tu_receiver) = tokio::sync::mpsc::unbounded_channel();
1379        let inner = std::sync::Arc::new(
1380            DialogInner::new(
1381                TransactionRole::Server,
1382                dialog_id.clone(),
1383                initial_request,
1384                endpoint.inner.clone(),
1385                state_sender,
1386                None,
1387                None,
1388                tu_sender,
1389            )
1390            .expect("failed to create dialog inner"),
1391        );
1392        let dialog = InviteDialog::from_inner(inner);
1393
1394        assert!(
1395            invitation
1396                .find_dialog_id_by_session_id(&dialog_id.to_string())
1397                .is_none()
1398        );
1399
1400        invitation.add_pending(
1401            dialog_id.clone(),
1402            PendingDialog {
1403                token: tokio_util::sync::CancellationToken::new(),
1404                dialog,
1405                state_receiver: {
1406                    let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
1407                    rx
1408                },
1409            },
1410        );
1411
1412        assert_eq!(
1413            invitation
1414                .find_dialog_id_by_session_id(&dialog_id.to_string())
1415                .unwrap(),
1416            dialog_id
1417        );
1418    }
1419}