From bcba52b2766e9bb31503aae37f0f2dc0ef058afa Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:13:06 +0000 Subject: [PATCH 1/8] feat(dialog): capture coherent snapshots with recovery metadata --- src/dialog/client_dialog.rs | 17 ++- src/dialog/dialog.rs | 165 ++++++++++++++++++++-- src/dialog/dialog_layer.rs | 1 + src/dialog/invite_dialog.rs | 29 ++-- src/dialog/lifecycle.rs | 65 +++++++-- src/dialog/mod.rs | 1 + src/dialog/server_dialog.rs | 17 ++- src/dialog/snapshot.rs | 49 +++++++ src/dialog/tests/test_bye_during_ack.rs | 28 ++++ src/dialog/tests/test_snapshot_restore.rs | 102 +++++++++++++ src/transaction/invite_usage.rs | 10 +- 11 files changed, 433 insertions(+), 51 deletions(-) create mode 100644 src/dialog/snapshot.rs diff --git a/src/dialog/client_dialog.rs b/src/dialog/client_dialog.rs index 5e6a1598..ebc4b058 100644 --- a/src/dialog/client_dialog.rs +++ b/src/dialog/client_dialog.rs @@ -579,10 +579,7 @@ impl ClientInviteDialog { return Ok(()); } - self.inner - .remote_seq - .compare_exchange(remote_seq, cseq, Ordering::Relaxed, Ordering::Relaxed) - .ok(); + self.inner.admit_remote_seq(cseq, &tx.original.method).ok(); if self.inner.is_confirmed() { match tx.original.method { @@ -615,13 +612,12 @@ impl ClientInviteDialog { } async fn handle_bye(&mut self, tx: &mut Transaction) -> Result<()> { - self.inner.record_remote_bye( + debug!(id = %self.id(), uri = %tx.original.uri, "received bye"); + self.inner.terminate_remote_bye( + TerminatedReason::UasBye, tx.original_received_at .unwrap_or_else(super::lifecycle::LifecycleTime::now), ); - debug!(id = %self.id(), uri = %tx.original.uri, "received bye"); - self.inner - .transition(DialogState::Terminated(self.id(), TerminatedReason::UasBye)); tx.reply(crate::sip::StatusCode::OK).await?; Ok(()) } @@ -665,7 +661,10 @@ impl ClientInviteDialog { } async fn handle_reinvite(&mut self, tx: &mut Transaction) -> Result<()> { - self.inner.process_reinvite(tx, false).await + self.inner.begin_negotiation(); + let result = self.inner.process_reinvite(tx, false).await; + self.inner.finish_negotiation(); + result } async fn handle_refer(&mut self, tx: &mut Transaction) -> Result<()> { diff --git a/src/dialog/dialog.rs b/src/dialog/dialog.rs index fdd19832..faddf34e 100644 --- a/src/dialog/dialog.rs +++ b/src/dialog/dialog.rs @@ -453,6 +453,8 @@ pub struct SessionIdState { } #[derive(Clone, Debug)] pub struct DialogSnapshot { + /// Captured with routing, CSeq, lifecycle facts, and transaction admission. + pub runtime: super::snapshot::DialogSnapshotRuntime, pub state: DialogSnapshotState, pub role: TransactionRole, pub id: DialogId, @@ -473,6 +475,13 @@ pub struct DialogSnapshot { /// RFC 7989 Session-ID state, preserved across snapshot restore. pub session_id: Option, } +impl DialogSnapshot { + /// Only confirmed snapshots with no unfinished signaling can be resumed. + pub fn is_quiescent(&self) -> bool { + self.state == DialogSnapshotState::Confirmed && self.runtime.pending.is_empty() + } +} + impl DialogInner { #[allow(clippy::too_many_arguments)] pub fn new( @@ -600,10 +609,12 @@ impl DialogInner { { return; } + let _snapshot_gate = self.state.lock(); let mut state = self.session_id.lock(); if let Some(sid) = state.as_mut() { if sid.local != uuid { sid.remote = Some(uuid); + self.lifecycle.lock().revision += 1; } } } @@ -638,13 +649,45 @@ impl DialogInner { self.local_seq.load(Ordering::Relaxed) } pub fn increment_local_seq(&self) -> u32 { - // Return this caller's reservation, not a subsequent caller's value. + let _snapshot_gate = self.state.lock(); + self.increment_local_seq_locked() + } + + fn increment_local_seq_locked(&self) -> u32 { + self.lifecycle.lock().revision += 1; self.local_seq .fetch_add(1, Ordering::Relaxed) .wrapping_add(1) } + pub(crate) fn admit_remote_seq( + &self, + cseq: u32, + method: &Method, + ) -> core::result::Result { + let _snapshot_gate = self.state.lock(); + let previous = self.remote_seq.load(Ordering::Relaxed); + if cseq < previous { + return Err(previous); + } + if *method == Method::Bye && (_snapshot_gate.is_confirmed() || _snapshot_gate.waiting_ack()) + { + let mut lifecycle = self.lifecycle.lock(); + if !lifecycle.pending_remote_bye { + lifecycle.pending_remote_bye = true; + lifecycle.revision += 1; + } + } + if cseq != previous { + self.remote_seq.store(cseq, Ordering::Relaxed); + self.lifecycle.lock().revision += 1; + } + Ok(previous) + } + pub fn update_remote_tag(&self, tag: &str) -> Result<()> { + let _snapshot_gate = self.state.lock(); + self.lifecycle.lock().revision += 1; self.id.lock().remote_tag = tag.to_string(); if self.role == TransactionRole::Client { @@ -837,9 +880,19 @@ impl DialogInner { &self, uri: crate::sip::Uri, contact: Option, + ) { + let _snapshot_gate = self.state.lock(); + self.set_remote_target_locked(uri, contact); + } + + fn set_remote_target_locked( + &self, + uri: crate::sip::Uri, + contact: Option, ) { *self.remote_uri.lock() = uri; *self.remote_contact.lock() = contact; + self.lifecycle.lock().revision += 1; } pub(super) fn is_target_refresh(method: &Method) -> bool { @@ -885,11 +938,12 @@ impl DialogInner { } pub(super) fn accept_target_refresh(&self, cseq: u32, target: &RemoteTarget) { + let _snapshot_gate = self.state.lock(); let mut last = self.remote_target_cseq.lock(); if last.is_some_and(|accepted| cseq <= accepted) { return; } - self.set_remote_target(target.uri.clone(), Some(target.contact.clone())); + self.set_remote_target_locked(target.uri.clone(), Some(target.contact.clone())); *last = Some(cseq); } @@ -924,7 +978,9 @@ impl DialogInner { .collect(); new_route_set.reverse(); + let _snapshot_gate = self.state.lock(); *self.route_set.lock() = new_route_set; + self.lifecycle.lock().revision += 1; } pub(super) fn make_request_with_vias( @@ -935,12 +991,13 @@ impl DialogInner { headers: Option>, body: Option>, ) -> Result { + let _snapshot_gate = self.state.lock(); let mut out: Vec
= Vec::new(); // --- system headers first --- let cseq_header = CSeq { - seq: cseq.unwrap_or_else(|| self.increment_local_seq()), + seq: cseq.unwrap_or_else(|| self.increment_local_seq_locked()), method: method.clone(), }; @@ -1267,6 +1324,22 @@ impl DialogInner { &self, request: Request, options: Option, + ) -> Result> { + let negotiation = Self::is_target_refresh(&request.method); + if negotiation { + self.begin_negotiation(); + } + let result = self.send_dialog_request_inner(request, options).await; + if negotiation { + self.finish_negotiation(); + } + result + } + + async fn send_dialog_request_inner( + &self, + request: Request, + options: Option, ) -> Result> { let method = request.method().to_owned(); let key = TransactionKey::from_request(&request, TransactionRole::Client)?; @@ -1747,10 +1820,15 @@ impl DialogInner { } } + /// Capture a single revision. Mutate dialogs through their methods; direct + /// writes to DialogInner public fields bypass these synchronization guarantees. pub fn snapshot(&self) -> DialogSnapshot { + let state_guard = self.state.lock(); + let usage = self.invite_usage.lock(); + let lifecycle = self.lifecycle.lock(); let id = self.id.lock().clone(); - let state = match &*self.state.lock() { + let state = match &*state_guard { DialogState::Calling(_) => DialogSnapshotState::Calling, DialogState::Trying(_) => DialogSnapshotState::Trying, DialogState::Early(_, _) => DialogSnapshotState::Early, @@ -1768,6 +1846,20 @@ impl DialogInner { }; DialogSnapshot { + runtime: super::snapshot::DialogSnapshotRuntime { + revision: lifecycle.revision + usage.revision, + lifecycle: lifecycle.facts.clone(), + pending: super::snapshot::DialogPendingState { + local_invite: usage.client_pending, + remote_invite: usage.server_pending, + remote_invite_awaiting_ack: usage.server_waiting_ack != 0, + initial_ack: lifecycle.pending_initial_ack, + negotiations: lifecycle.negotiations, + remote_termination: lifecycle.pending_remote_bye + && !state_guard.is_terminated(), + local_termination: lifecycle.emitted & 2 != 0 && !state_guard.is_terminated(), + }, + }, state, role: self.role, @@ -1804,6 +1896,10 @@ impl DialogInner { return Ok(None); } + if !snapshot.runtime.pending.is_empty() { + return Err(crate::Error::Error("dialog snapshot contains unfinished signaling; application recovery policy is required".into())); + } + // Ensure To has tag let mut to = snapshot.to.clone(); let to_tag = match snapshot.role { @@ -1830,6 +1926,7 @@ impl DialogInner { } let role = snapshot.role; + let lifecycle = super::lifecycle::LifecycleState::restored(&snapshot.runtime)?; let initial_request = Mutex::new(Self::build_restored_initial_request( role, @@ -1870,7 +1967,7 @@ impl DialogInner { endpoint_inner, state_sender, - lifecycle: Mutex::new(super::lifecycle::LifecycleState::default()), + lifecycle: Mutex::new(lifecycle), tu_sender, initial_request, @@ -1958,6 +2055,29 @@ impl DialogInner { version: Version::V2, } } + pub(crate) fn complete_initial_ack(&self) { + let _snapshot_gate = self.state.lock(); + let mut lifecycle = self.lifecycle.lock(); + if lifecycle.pending_initial_ack { + lifecycle.pending_initial_ack = false; + lifecycle.revision += 1; + } + } + + pub(crate) fn begin_negotiation(&self) { + let _snapshot_gate = self.state.lock(); + let mut lifecycle = self.lifecycle.lock(); + lifecycle.negotiations += 1; + lifecycle.revision += 1; + } + + pub(crate) fn finish_negotiation(&self) { + let _snapshot_gate = self.state.lock(); + let mut lifecycle = self.lifecycle.lock(); + lifecycle.negotiations -= 1; + lifecycle.revision += 1; + } + pub(crate) fn record_initial_acceptance( &self, response: &Response, @@ -1986,15 +2106,21 @@ impl DialogInner { ); } - pub(crate) fn record_remote_bye(&self, time: super::lifecycle::LifecycleTime) { - let state = self.state.lock(); + pub(crate) fn terminate_remote_bye( + &self, + reason: TerminatedReason, + time: super::lifecycle::LifecycleTime, + ) { + let id = self.id.lock().clone(); + let mut state = self.state.lock(); if !state.is_terminated() { self.lifecycle.lock().emit( - self.id.lock().clone(), + id.clone(), self.role, time, super::lifecycle::DialogLifecycleKind::RemoteByeReceived, ); + self.transition_locked(&mut state, DialogState::Terminated(id, reason)); } } @@ -2042,6 +2168,11 @@ impl DialogInner { // Publish the full dialog key before notifying the application. A // concurrent handler cannot inspect the state until this lock releases. register(); + { + let mut lifecycle = self.lifecycle.lock(); + lifecycle.pending_initial_ack = true; + lifecycle.revision += 1; + } if let DialogState::Confirmed(id, response) = &confirmed { self.lifecycle.lock().emit( id.clone(), @@ -2092,6 +2223,7 @@ impl DialogInner { }, ); } + self.lifecycle.lock().revision += 1; *old_state = state.clone(); // Try to send state update, but don't fail if channel is closed self.state_sender.send(state).ok(); @@ -2099,6 +2231,23 @@ impl DialogInner { #[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))] pub async fn process_transaction_handle( + &self, + tx: &mut Transaction, + rx: TransactionCommandReceiver, + ) -> Result<()> { + let negotiation = tx.original.method == Method::Update; + if negotiation { + self.begin_negotiation(); + } + let result = self.process_transaction_handle_inner(tx, rx).await; + if negotiation { + self.finish_negotiation(); + } + result + } + + #[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))] + async fn process_transaction_handle_inner( &self, tx: &mut Transaction, mut rx: TransactionCommandReceiver, diff --git a/src/dialog/dialog_layer.rs b/src/dialog/dialog_layer.rs index d7a9649b..6b039bad 100644 --- a/src/dialog/dialog_layer.rs +++ b/src/dialog/dialog_layer.rs @@ -557,6 +557,7 @@ impl DialogLayer { }; inner.credential = credential; + inner.lifecycle.lock().sender = self.inner.lifecycle_sender.lock().clone(); let inner = Arc::new(inner); let dialog = Dialog::from_inner(inner.role, inner.clone()); diff --git a/src/dialog/invite_dialog.rs b/src/dialog/invite_dialog.rs index 4ff5113e..4544f538 100644 --- a/src/dialog/invite_dialog.rs +++ b/src/dialog/invite_dialog.rs @@ -398,6 +398,9 @@ impl InviteDialog { }) .await; ack.finish(); + if msg.is_some() { + self.inner.complete_initial_ack(); + } let cancelled = established?; let Some(msg) = msg else { break }; if matches!(&msg, SipMessage::Response(r) if r.status_code.kind() != StatusCodeKind::Provisional) @@ -530,14 +533,14 @@ impl InviteDialog { fn update_remote_target_from_2xx(&self, resp: &Response) -> Result<()> { self.inner.update_route_set_from_response(resp); let contact = resp.contact_header()?; - self.inner.remote_contact.lock().replace(contact.clone()); let contact_uri = resp .typed_contact_headers()? .first() .map(|c| c.uri.clone()) .ok_or_else(|| crate::Error::Error("missing Contact header".to_string()))?; - *self.inner.remote_uri.lock() = contact_uri; + self.inner + .set_remote_target(contact_uri, Some(contact.clone())); Ok(()) } @@ -867,11 +870,7 @@ impl InviteDialog { let sequence = if matches!(tx.original.method, Method::Ack | Method::Cancel) { Ok(self.inner.remote_seq.load(Ordering::Relaxed)) } else { - self.inner - .remote_seq - .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |remote_seq| { - (cseq >= remote_seq).then_some(cseq) - }) + self.inner.admit_remote_seq(cseq, &tx.original.method) }; if let Err(remote_seq) = sequence { match self.role() { @@ -1017,17 +1016,16 @@ impl InviteDialog { } async fn handle_bye(&mut self, tx: &mut Transaction) -> Result<()> { - self.inner.record_remote_bye( - tx.original_received_at - .unwrap_or_else(super::lifecycle::LifecycleTime::now), - ); debug!(id = %self.id(), uri = %tx.original.uri, "received bye"); let reason = match self.role() { TransactionRole::Server => TerminatedReason::UacBye, TransactionRole::Client => TerminatedReason::UasBye, }; - self.inner - .transition(DialogState::Terminated(self.id(), reason)); + self.inner.terminate_remote_bye( + reason, + tx.original_received_at + .unwrap_or_else(super::lifecycle::LifecycleTime::now), + ); tx.reply(StatusCode::OK).await?; Ok(()) } @@ -1135,7 +1133,10 @@ impl InviteDialog { } async fn handle_reinvite(&mut self, tx: &mut Transaction) -> Result<()> { - self.inner.process_reinvite(tx, true).await + self.inner.begin_negotiation(); + let result = self.inner.process_reinvite(tx, true).await; + self.inner.finish_negotiation(); + result } async fn handle_invite(&mut self, tx: &mut Transaction) -> Result<()> { diff --git a/src/dialog/lifecycle.rs b/src/dialog/lifecycle.rs index c0e10c29..6e110ac8 100644 --- a/src/dialog/lifecycle.rs +++ b/src/dialog/lifecycle.rs @@ -32,8 +32,9 @@ //! application. An accepted CANCEL followed by a late 2xx is cleanup, not a new //! accepted call. Fork branches discarded by the dialog are not reported. //! -//! Subscriptions apply to newly created dialogs, not previously created or -//! restored ones. The existing `DialogState` channel is unchanged. An unbounded +//! Subscriptions apply to subsequently created or restored dialogs. Restoring +//! a snapshot retains fact sequence numbers without replaying notifications. +//! The existing `DialogState` channel is unchanged. An unbounded //! receiver avoids SIP backpressure; applications must drain or drop it. use super::{dialog::TerminatedReason, DialogId}; @@ -108,9 +109,50 @@ pub(crate) struct LifecycleState { pub sender: Option, pub sequence: u64, pub emitted: u8, + pub revision: u64, + pub pending_initial_ack: bool, + pub pending_remote_bye: bool, + pub negotiations: u32, + pub facts: alloc::vec::Vec, } impl LifecycleState { + pub fn restored(runtime: &super::snapshot::DialogSnapshotRuntime) -> crate::Result { + let mut state = Self { + revision: runtime.revision, + ..Self::default() + }; + for fact in &runtime.lifecycle { + let bit = match &fact.kind { + DialogLifecycleKind::InviteAccepted { status } + if status.kind() == crate::sip::StatusCodeKind::Successful => + { + 1 + } + DialogLifecycleKind::LocalTerminationRequested => 2, + DialogLifecycleKind::RemoteByeReceived => 4, + // A confirmed snapshot cannot already contain a terminal fact. + _ => { + return Err(crate::Error::Error( + "invalid snapshot lifecycle fact".into(), + )) + } + }; + if state.emitted & bit != 0 || fact.sequence != state.sequence + 1 { + return Err(crate::Error::Error( + "invalid snapshot lifecycle sequence".into(), + )); + } + state.emitted |= bit; + state.sequence = fact.sequence; + } + if runtime.revision < state.sequence || runtime.revision == u64::MAX { + return Err(crate::Error::Error("invalid snapshot revision".into())); + } + state.facts = runtime.lifecycle.clone(); + Ok(state) + } + pub fn emit( &mut self, id: DialogId, @@ -118,7 +160,6 @@ impl LifecycleState { time: LifecycleTime, kind: DialogLifecycleKind, ) { - let Some(sender) = &self.sender else { return }; let bit = match &kind { DialogLifecycleKind::InviteAccepted { .. } => 1, DialogLifecycleKind::LocalTerminationRequested => 2, @@ -130,12 +171,20 @@ impl LifecycleState { } self.emitted |= bit; self.sequence += 1; - let _ = sender.send(DialogLifecycleEvent { - dialog_id: id, - role, + self.revision += 1; + self.facts.push(super::snapshot::DialogLifecycleRecord { sequence: self.sequence, - occurred_at: time, - kind, + since_unix_epoch: time.since_unix_epoch, + kind: kind.clone(), }); + if let Some(sender) = &self.sender { + let _ = sender.send(DialogLifecycleEvent { + dialog_id: id, + role, + sequence: self.sequence, + occurred_at: time, + kind, + }); + } } } diff --git a/src/dialog/mod.rs b/src/dialog/mod.rs index 0b3f1372..fe4dffd5 100644 --- a/src/dialog/mod.rs +++ b/src/dialog/mod.rs @@ -16,6 +16,7 @@ pub mod publication; pub mod registration; pub mod reinvite; pub mod server_dialog; +pub mod snapshot; pub mod subscription; #[cfg(test)] diff --git a/src/dialog/server_dialog.rs b/src/dialog/server_dialog.rs index caa4ba46..821ecd32 100644 --- a/src/dialog/server_dialog.rs +++ b/src/dialog/server_dialog.rs @@ -673,10 +673,7 @@ impl ServerInviteDialog { // discard old request return Ok(()); } - self.inner - .remote_seq - .compare_exchange(remote_seq, cseq, Ordering::Relaxed, Ordering::Relaxed) - .ok(); + self.inner.admit_remote_seq(cseq, &tx.original.method).ok(); if self.inner.is_confirmed() { match tx.original.method { @@ -745,13 +742,12 @@ impl ServerInviteDialog { } async fn handle_bye(&mut self, tx: &mut Transaction) -> Result<()> { - self.inner.record_remote_bye( + debug!(id = %self.id(), uri = %tx.original.uri, "received bye"); + self.inner.terminate_remote_bye( + TerminatedReason::UacBye, tx.original_received_at .unwrap_or_else(super::lifecycle::LifecycleTime::now), ); - debug!(id = %self.id(), uri = %tx.original.uri, "received bye"); - self.inner - .transition(DialogState::Terminated(self.id(), TerminatedReason::UacBye)); tx.reply(crate::sip::StatusCode::OK).await?; Ok(()) } @@ -854,7 +850,10 @@ impl ServerInviteDialog { } async fn handle_reinvite(&mut self, tx: &mut Transaction) -> Result<()> { - self.inner.process_reinvite(tx, true).await + self.inner.begin_negotiation(); + let result = self.inner.process_reinvite(tx, true).await; + self.inner.finish_negotiation(); + result } async fn handle_invite(&mut self, tx: &mut Transaction) -> Result<()> { diff --git a/src/dialog/snapshot.rs b/src/dialog/snapshot.rs new file mode 100644 index 00000000..deae0464 --- /dev/null +++ b/src/dialog/snapshot.rs @@ -0,0 +1,49 @@ +//! Recovery metadata captured together with the dialog's routing state. +use super::lifecycle::DialogLifecycleKind; +use alloc::vec::Vec; +use core::time::Duration; + +/// A persisted fact deliberately excludes process-local monotonic time. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct DialogLifecycleRecord { + pub sequence: u64, + pub since_unix_epoch: Option, + pub kind: DialogLifecycleKind, +} + +/// In-flight work is recorded for recovery decisions, not replayed as SIP +/// transactions. Interrupted application handlers remain pending conservatively. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct DialogPendingState { + pub local_invite: bool, + pub remote_invite: bool, + pub remote_invite_awaiting_ack: bool, + pub initial_ack: bool, + pub negotiations: u32, + pub local_termination: bool, + pub remote_termination: bool, +} + +impl DialogPendingState { + pub fn is_empty(&self) -> bool { + !self.local_invite + && !self.remote_invite + && !self.remote_invite_awaiting_ack + && !self.initial_ack + && self.negotiations == 0 + && !self.local_termination + && !self.remote_termination + } +} + +/// Versioned metadata for a single coherent dialog snapshot. This is not a +/// storage schema: applications own serialization and migrations of old records. +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct DialogSnapshotRuntime { + pub revision: u64, + pub pending: DialogPendingState, + pub lifecycle: Vec, +} diff --git a/src/dialog/tests/test_bye_during_ack.rs b/src/dialog/tests/test_bye_during_ack.rs index 90c35eeb..a2afd4f0 100644 --- a/src/dialog/tests/test_bye_during_ack.rs +++ b/src/dialog/tests/test_bye_during_ack.rs @@ -507,3 +507,31 @@ async fn lifecycle_closed_receiver_does_not_prevent_remote_bye() -> crate::Resul assert!(call.dialog.state().is_terminated()); Ok(()) } + +#[tokio::test] +async fn snapshot_records_initial_ack_until_it_completes() -> crate::Result<()> { + let mut call = start_observed(true, false, true).await?; + let accepted = call.facts.try_recv().unwrap(); + let before = call.dialog.snapshot(); + assert!(before.runtime.pending.initial_ack); + assert!(!before.is_quiescent()); + assert_eq!( + before.runtime.lifecycle[0].since_unix_epoch, + accepted.occurred_at.since_unix_epoch + ); + let restore = DialogLayer::new(EndpointBuilder::new().build().inner); + let (sender, _) = unbounded_channel(); + assert!(restore + .restore_from_snapshot(before.clone(), sender) + .is_err()); + call.release.cancel(); + request(&call.peer, Method::Ack).await; + tokio::time::timeout(Duration::from_secs(2), &mut call.join) + .await + .unwrap() + .unwrap()?; + let after = call.dialog.snapshot(); + assert!(after.is_quiescent()); + assert!(after.runtime.revision > before.runtime.revision); + Ok(()) +} diff --git a/src/dialog/tests/test_snapshot_restore.rs b/src/dialog/tests/test_snapshot_restore.rs index d46c9bd6..04fec3d7 100644 --- a/src/dialog/tests/test_snapshot_restore.rs +++ b/src/dialog/tests/test_snapshot_restore.rs @@ -120,3 +120,105 @@ async fn snapshot_restore_still_skips_non_confirmed_states() -> crate::Result<() assert!(layer.is_empty()); Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshots_never_mix_target_uri_and_contact() -> crate::Result<()> { + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let original = snapshot(TransactionRole::Client); + let (states, _) = unbounded_channel(); + layer.restore_from_snapshot(original.clone(), states)?; + let Some(Dialog::Invite(dialog)) = layer.get_dialog(&original.id) else { + unreachable!() + }; + let uri = Uri::try_from("sip:target0@example.com")?; + dialog.inner.set_remote_target( + uri.clone(), + Some(crate::sip::headers::untyped::Contact::from( + crate::sip::typed::Contact::from(uri), + )), + ); + let writer = dialog.clone(); + let task = std::thread::spawn(move || { + for n in 1..5000 { + let uri = Uri::try_from(format!("sip:target{n}@example.com").as_str()).unwrap(); + writer.inner.set_remote_target( + uri.clone(), + Some(crate::sip::headers::untyped::Contact::from( + crate::sip::typed::Contact::from(uri), + )), + ); + writer.inner.update_remote_tag(&format!("tag{n}")).unwrap(); + writer.inner.increment_local_seq(); + } + }); + let mut revision = 0; + for _ in 0..5000 { + let current = dialog.snapshot(); + use crate::sip::prelude::ToTypedHeader; + assert_eq!( + current.remote_uri, + current.remote_contact.as_ref().unwrap().typed()?.uri + ); + assert_eq!(current.id.remote_tag, current.to.tag().unwrap().value()); + assert!(current.runtime.revision >= revision); + revision = current.runtime.revision; + } + task.join().unwrap(); + Ok(()) +} + +#[tokio::test] +async fn snapshot_restore_retains_facts_without_replaying_them() -> crate::Result<()> { + use crate::dialog::dialog::{DialogState, TerminatedReason}; + use crate::dialog::lifecycle::{ + dialog_lifecycle_channel, DialogLifecycleKind as K, LifecycleTime, + }; + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let original = snapshot(TransactionRole::Client); + let (states, _) = unbounded_channel(); + layer.restore_from_snapshot(original.clone(), states.clone())?; + let Some(Dialog::Invite(dialog)) = layer.get_dialog(&original.id) else { + unreachable!() + }; + dialog + .inner + .record_initial_acceptance(&crate::sip::Response::default(), LifecycleTime::now()); + let saved = dialog.snapshot(); + // Response::default() is 200 OK; this is an already established dialog. + assert_eq!(saved.runtime.lifecycle.len(), 1); + assert!(saved.is_quiescent()); + let restored = DialogLayer::new(EndpointBuilder::new().build().inner); + let (sender, mut events) = dialog_lifecycle_channel(); + restored.set_lifecycle_events(Some(sender)); + assert!(restored.restore_from_snapshot(saved, states)?); + assert!(events.try_recv().is_err()); + let Some(Dialog::Invite(dialog)) = restored.get_dialog(&original.id) else { + unreachable!() + }; + dialog.inner.transition(DialogState::Terminated( + dialog.id(), + TerminatedReason::Timeout, + )); + let event = events.try_recv().unwrap(); + assert_eq!(event.sequence, 2); + assert!(matches!(event.kind, K::DialogTerminated { .. })); + assert_eq!(dialog.snapshot().runtime.lifecycle.len(), 2); + Ok(()) +} + +#[tokio::test] +async fn unfinished_or_corrupt_snapshot_is_not_silently_resumed() -> crate::Result<()> { + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let (states, _) = unbounded_channel(); + let mut pending = snapshot(TransactionRole::Client); + pending.runtime.pending.negotiations = 1; + assert!(!pending.is_quiescent()); + assert!(layer + .restore_from_snapshot(pending, states.clone()) + .is_err()); + let mut invalid = snapshot(TransactionRole::Client); + invalid.runtime.revision = u64::MAX; + assert!(layer.restore_from_snapshot(invalid, states).is_err()); + assert!(layer.is_empty()); + Ok(()) +} diff --git a/src/transaction/invite_usage.rs b/src/transaction/invite_usage.rs index 5d743ef7..0aba0b93 100644 --- a/src/transaction/invite_usage.rs +++ b/src/transaction/invite_usage.rs @@ -6,9 +6,10 @@ use crate::prelude::*; #[derive(Default)] pub(crate) struct InviteUsage { - client_pending: bool, - server_pending: bool, - server_waiting_ack: usize, + pub(crate) revision: u64, + pub(crate) client_pending: bool, + pub(crate) server_pending: bool, + pub(crate) server_waiting_ack: usize, } enum Phase { @@ -36,6 +37,7 @@ impl InviteReservation { { return Err(TransactionRole::Server); } + state.revision += 1; let phase = match role { TransactionRole::Client => { state.client_pending = true; @@ -66,6 +68,7 @@ impl InviteReservation { TransactionState::Completed | TransactionState::Accepted, ) => { let mut usage = self.usage.lock(); + usage.revision += 1; usage.server_pending = false; usage.server_waiting_ack += 1; self.phase = Some(Phase::ServerWaitingAck); @@ -77,6 +80,7 @@ impl InviteReservation { fn release(&mut self) { if let Some(phase) = self.phase.take() { let mut usage = self.usage.lock(); + usage.revision += 1; match phase { Phase::ClientPending => usage.client_pending = false, Phase::ServerPending => usage.server_pending = false, From 2f19887ed59a11ffc92a105e8bc984df29ba77b5 Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:52:52 +0000 Subject: [PATCH 2/8] fix(dialog): expose lifecycle record reconstruction Add a public constructor for non-exhaustive lifecycle records so applications can reconstruct persisted history. Keep restore-time history validation unchanged. Exercise the API from an external integration test across two restores, including absent timestamps and invalid history. Verify the constructor documentation and Embassy build. --- src/dialog/snapshot.rs | 36 +++++++++++ tests/snapshot_reconstruction.rs | 105 +++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+) create mode 100644 tests/snapshot_reconstruction.rs diff --git a/src/dialog/snapshot.rs b/src/dialog/snapshot.rs index deae0464..d36eea38 100644 --- a/src/dialog/snapshot.rs +++ b/src/dialog/snapshot.rs @@ -12,6 +12,42 @@ pub struct DialogLifecycleRecord { pub kind: DialogLifecycleKind, } +impl DialogLifecycleRecord { + /// Reconstruct a fact from application-owned storage. + /// + /// Preserves the supplied sequence and optional wall-clock timestamp; it + /// does not generate a new event or time. The complete history is validated + /// when restoring a confirmed snapshot through + /// [`DialogLayer::restore_from_snapshot`](super::dialog_layer::DialogLayer::restore_from_snapshot). + /// + /// ``` + /// use core::time::Duration; + /// use rsipstack::dialog::{ + /// lifecycle::DialogLifecycleKind, + /// snapshot::DialogLifecycleRecord, + /// }; + /// use rsipstack::sip::StatusCode; + /// + /// let record = DialogLifecycleRecord::new( + /// 1, + /// Some(Duration::from_millis(1_700_000_000_123)), + /// DialogLifecycleKind::InviteAccepted { status: StatusCode::OK }, + /// ); + /// assert_eq!(record.sequence, 1); + /// ``` + pub fn new( + sequence: u64, + since_unix_epoch: Option, + kind: DialogLifecycleKind, + ) -> Self { + Self { + sequence, + since_unix_epoch, + kind, + } + } +} + /// In-flight work is recorded for recovery decisions, not replayed as SIP /// transactions. Interrupted application handlers remain pending conservatively. #[derive(Clone, Debug, Default, PartialEq, Eq)] diff --git a/tests/snapshot_reconstruction.rs b/tests/snapshot_reconstruction.rs new file mode 100644 index 00000000..d10efb4a --- /dev/null +++ b/tests/snapshot_reconstruction.rs @@ -0,0 +1,105 @@ +//! Exercise reconstruction through the public API, as a downstream crate. +#![cfg(feature = "platform-tokio")] + +use rsipstack::{ + dialog::{ + dialog::{Dialog, DialogSnapshot, DialogSnapshotState}, + dialog_layer::DialogLayer, + lifecycle::{dialog_lifecycle_channel, DialogLifecycleKind}, + snapshot::{DialogLifecycleRecord, DialogSnapshotRuntime}, + DialogId, + }, + sip::{prelude::ToTypedHeader, StatusCode}, + transaction::key::TransactionRole, + EndpointBuilder, +}; +use std::time::Duration; + +type TestResult = Result>; + +fn snapshot(history: Vec) -> TestResult { + let mut runtime = DialogSnapshotRuntime::default(); + runtime.revision = 42; + runtime.lifecycle = history; + Ok(DialogSnapshot { + runtime, + state: DialogSnapshotState::Confirmed, + role: TransactionRole::Client, + id: DialogId { + call_id: "stored-call".into(), + local_tag: "local".into(), + remote_tag: "remote".into(), + }, + from: rsipstack::sip::headers::From::from(";tag=local").typed()?, + to: rsipstack::sip::headers::To::from(";tag=remote").typed()?, + local_cseq: 7, + remote_cseq: 3, + local_contact: Some("sip:alice@127.0.0.1:5060".try_into()?), + remote_uri: "sip:bob@127.0.0.1:5061".try_into()?, + remote_contact: None, + route_set: vec![], + supports_100rel: false, + session_id: None, + }) +} + +#[tokio::test] +async fn external_application_can_reconstruct_persisted_lifecycle_history() -> TestResult { + // These are application-decoded storage fields, not records cloned from a + // live dialog. Both clock-bearing and clockless persisted facts are valid. + for stored_timestamp in [Some(Duration::new(1_700_000_000, 123_456_789)), None] { + let history = vec![DialogLifecycleRecord::new( + 1, + stored_timestamp, + DialogLifecycleKind::InviteAccepted { + status: StatusCode::OK, + }, + )]; + let mut saved = snapshot(history)?; + // A second restart must retain the reconstructed history as well. + for _ in 0..2 { + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let (sender, mut events) = dialog_lifecycle_channel(); + layer.set_lifecycle_events(Some(sender)); + let (states, _receiver) = layer.new_dialog_state_channel(); + let id = saved.id.clone(); + assert!(layer.restore_from_snapshot(saved, states)?); + assert!(events.try_recv().is_err(), "restore must not replay facts"); + let Some(Dialog::Invite(dialog)) = layer.get_dialog(&id) else { + panic!("restored dialog is missing"); + }; + saved = dialog.snapshot(); + assert!(saved.is_quiescent()); + assert_eq!(saved.runtime.revision, 42); + assert_eq!(saved.runtime.lifecycle.len(), 1); + let fact = &saved.runtime.lifecycle[0]; + assert_eq!(fact.sequence, 1); + assert_eq!(fact.since_unix_epoch, stored_timestamp); + assert!(matches!( + fact.kind, + DialogLifecycleKind::InviteAccepted { + status: StatusCode::OK + } + )); + } + } + Ok(()) +} + +#[tokio::test] +async fn reconstructed_records_still_pass_through_restore_validation() -> TestResult { + for (sequence, status) in [(2, StatusCode::OK), (1, StatusCode::BusyHere)] { + let record = DialogLifecycleRecord::new( + sequence, + None, + DialogLifecycleKind::InviteAccepted { status }, + ); + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let (states, _receiver) = layer.new_dialog_state_channel(); + assert!(layer + .restore_from_snapshot(snapshot(vec![record])?, states) + .is_err()); + assert!(layer.is_empty()); + } + Ok(()) +} From 2c05a1fd7f99b71eb32b2d505eada1eb231909a2 Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Fri, 6 Nov 2026 10:11:12 +0000 Subject: [PATCH 3/8] feat(dialog)!: add snapshot builder and document 0.9 migration Make DialogSnapshot non-exhaustive and require explicit state, CSeq counters and recovery metadata through its public builder. Preserve optional stored values and validate confirmed lifecycle history without discarding pending work. Document the proposed 0.9.0 release gate, legacy storage migration and changed restore behavior. Exercise downstream reconstruction and snapshot admission around the upstream re-INVITE handlers. --- CHANGELOG.md | 13 ++ MIGRATING-0.9.md | 101 ++++++++++ src/dialog/dialog.rs | 19 ++ src/dialog/snapshot.rs | 151 ++++++++++++++ src/dialog/tests/test_reinvite_control.rs | 17 ++ tests/snapshot_reconstruction.rs | 231 +++++++++++++++++++--- 6 files changed, 507 insertions(+), 25 deletions(-) create mode 100644 MIGRATING-0.9.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 47edbdb9..09005d6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## Unreleased — proposed 0.9.0 + +- **Breaking (requires maintainer approval for 0.9.0):** `DialogSnapshot` adds + coherent `runtime` metadata and becomes `#[non_exhaustive]`. External callers + must use `DialogSnapshot::builder(...)` and include `..` in destructuring + patterns. State, both CSeq values and runtime metadata must be explicit. +- **Recovery behavior:** confirmed snapshots with unfinished signaling or invalid + lifecycle history are rejected. Stored transactions and handlers are not + replayed. Lifecycle records can be reconstructed with `DialogLifecycleRecord::new`. +- See [the migration guide](MIGRATING-0.9.md) for storage defaults, legacy-record + handling, and the release compatibility plan. The release target is proposed; + this change does not itself bump or publish the package version. + ## 0.8.1 Fourteen fixes and additions merged (#223–#236). diff --git a/MIGRATING-0.9.md b/MIGRATING-0.9.md new file mode 100644 index 00000000..a1a9b151 --- /dev/null +++ b/MIGRATING-0.9.md @@ -0,0 +1,101 @@ +# Snapshot migration for the proposed 0.9.0 release + +These changes require a breaking release. The proposed target is **0.9.0**, +subject to maintainer approval; this document does not announce a release or +change the package version. Do not backport this API change into 0.8.x. + +## Constructing and reading snapshots + +`DialogSnapshot` now includes coherent runtime metadata and is +`#[non_exhaustive]`. Adding `runtime` breaks old struct literals and exhaustive +patterns. The attribute also prevents external struct literals, even if they +include `runtime`. Replace them with `DialogSnapshot::builder(...)`; adding +`runtime: DialogSnapshotRuntime::default()` to a literal is not sufficient. + +Supply the stored identity, role, From/To headers, remote URI, state, both CSeq +counters, and runtime metadata. The builder requires state, counters and runtime +explicitly: it never assumes a stored dialog was confirmed or quiescent. Copy +optional stored contacts, routes, 100rel support and Session-ID through their +builder methods too. Omitting those optional settings yields `None`, no routes, +`false`, and `None`, respectively; it does not recover their persisted values. + +This example illustrates an application-approved migration of a legacy, +confirmed record known to have been captured with no signaling in flight: + +```rust +use rsipstack::{ + dialog::{ + dialog::{DialogSnapshot, DialogSnapshotState}, + snapshot::DialogSnapshotRuntime, + DialogId, + }, + sip::{headers, prelude::ToTypedHeader}, + transaction::key::TransactionRole, +}; + +let snapshot = DialogSnapshot::builder( + DialogId { + call_id: "stored-call".into(), + local_tag: "local".into(), + remote_tag: "remote".into(), + }, + TransactionRole::Client, + headers::From::from(";tag=local").typed()?, + headers::To::from(";tag=remote").typed()?, + "sip:bob@example.com".try_into()?, +) +.state(DialogSnapshotState::Confirmed) +.local_cseq(42) +.remote_cseq(7) +.local_contact(Some("sip:alice@example.com".try_into()?)) +// The application has established that this legacy record was quiescent. +.runtime(DialogSnapshotRuntime::default()) +.build()?; + +// Field access is unchanged. Patterns must allow future fields. +let DialogSnapshot { id, runtime, .. } = snapshot; +assert_eq!(id.call_id, "stored-call"); +assert!(runtime.lifecycle.is_empty()); +# Ok::<(), Box>(()) +``` + +The builder checks required inputs and the lifecycle history of confirmed +snapshots. It also represents pending and non-confirmed snapshots so applications +can inspect or store them. `build()` succeeding does **not** guarantee that +restore will resume the dialog. Public fields remain mutable, so restore retains +its own validation. + +## Storage and recovery behavior + +The application owns serialization, storage schema versions and migrations. +`runtime.revision` identifies a dialog state revision, **not a storage schema**. +Persist the complete runtime metadata, including pending operations and lifecycle +records. Reconstruct individual facts with +`DialogLifecycleRecord::new(sequence, since_unix_epoch, kind)`. Preserve their +sequence and optional wall-clock time; do not invent timestamps or acceptance +events during migration. Restoring retains the history without replaying it to +notification consumers. Monotonic timestamps are process-local and not stored. + +For a pre-0.9 record without runtime metadata, explicitly passing +`DialogSnapshotRuntime::default()` represents revision zero, no recorded history, +and no pending operations. This is appropriate only when the application's +existing capture contract or other reliable evidence establishes that signaling +was quiescent. Missing metadata alone does not establish that fact. Empty history +means no history was retained; it is not evidence that the call was never answered. +If quiescence cannot be established, apply an explicit application recovery policy +instead of silently resuming the call. Never discard known pending work or use a +default to hide corrupt metadata. + +Calls to `dialog.snapshot()` and `layer.restore_from_snapshot(snapshot, sender)` +keep their signatures. The restore behavior changes as follows: + +- A confirmed snapshot with non-empty `runtime.pending` returns an error. SIP + transactions, outstanding ACKs and application handlers are not replayed. +- Invalid confirmed lifecycle history or revision returns an error. +- Non-confirmed snapshots are still skipped with `Ok(false)`. +- An already registered dialog is still retained and restore returns `Ok(false)`. + +Future optional fields may have safe defaults without breaking builder callers. +New data required for safe recovery must instead have an explicit migration or +compatibility plan. `#[non_exhaustive]` protects source construction and matching; +it is not a promise that every future persisted record can be silently migrated. diff --git a/src/dialog/dialog.rs b/src/dialog/dialog.rs index faddf34e..b5b9d1da 100644 --- a/src/dialog/dialog.rs +++ b/src/dialog/dialog.rs @@ -451,7 +451,12 @@ pub struct SessionIdState { pub local: String, pub remote: Option, } +/// A coherent snapshot for application-owned storage and recovery. +/// +/// Use [`Self::builder`] to reconstruct stored data. Direct field access remains +/// available; destructuring outside this crate must include `..`. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct DialogSnapshot { /// Captured with routing, CSeq, lifecycle facts, and transaction admission. pub runtime: super::snapshot::DialogSnapshotRuntime, @@ -476,6 +481,20 @@ pub struct DialogSnapshot { pub session_id: Option, } impl DialogSnapshot { + /// Reconstruct a snapshot without depending on its complete field list. + /// + /// State, both CSeq values, and runtime metadata must be supplied explicitly + /// before building. See [`super::snapshot`] for the 0.9 migration guide. + pub fn builder( + id: DialogId, + role: TransactionRole, + from: crate::sip::typed::From, + to: crate::sip::typed::To, + remote_uri: crate::sip::Uri, + ) -> super::snapshot::DialogSnapshotBuilder { + super::snapshot::DialogSnapshotBuilder::new(id, role, from, to, remote_uri) + } + /// Only confirmed snapshots with no unfinished signaling can be resumed. pub fn is_quiescent(&self) -> bool { self.state == DialogSnapshotState::Confirmed && self.runtime.pending.is_empty() diff --git a/src/dialog/snapshot.rs b/src/dialog/snapshot.rs index d36eea38..75c89e23 100644 --- a/src/dialog/snapshot.rs +++ b/src/dialog/snapshot.rs @@ -1,8 +1,159 @@ //! Recovery metadata captured together with the dialog's routing state. +#![doc = include_str!("../../MIGRATING-0.9.md")] +use super::dialog::{DialogSnapshot, DialogSnapshotState, SessionIdState}; use super::lifecycle::DialogLifecycleKind; +use super::DialogId; +use crate::sip::{headers::Route, typed, Uri}; +use crate::transaction::key::TransactionRole; use alloc::vec::Vec; use core::time::Duration; +/// Reconstruct application-owned snapshot data through [`DialogSnapshot::builder`]. +/// +/// State, CSeq values and runtime metadata have no implicit defaults. Optional +/// contacts and Session-ID default to `None`, routes to an empty vector, and +/// 100rel support to `false`. Preserve all stored values when rebuilding a +/// snapshot; defaults do not migrate storage or infer missing recovery data. +#[derive(Clone, Debug)] +#[must_use] +pub struct DialogSnapshotBuilder { + id: DialogId, + role: TransactionRole, + from: typed::From, + to: typed::To, + remote_uri: Uri, + state: Option, + local_cseq: Option, + remote_cseq: Option, + runtime: Option, + local_contact: Option, + remote_contact: Option, + route_set: Vec, + supports_100rel: bool, + session_id: Option, +} + +impl DialogSnapshotBuilder { + pub(crate) fn new( + id: DialogId, + role: TransactionRole, + from: typed::From, + to: typed::To, + remote_uri: Uri, + ) -> Self { + Self { + id, + role, + from, + to, + remote_uri, + state: None, + local_cseq: None, + remote_cseq: None, + runtime: None, + local_contact: None, + remote_contact: None, + route_set: Vec::new(), + supports_100rel: false, + session_id: None, + } + } + + /// Set the persisted dialog state; building does not imply confirmation. + pub fn state(mut self, state: DialogSnapshotState) -> Self { + self.state = Some(state); + self + } + + /// Set the persisted local sequence counter, without resetting it. + pub fn local_cseq(mut self, cseq: u32) -> Self { + self.local_cseq = Some(cseq); + self + } + + /// Set the persisted remote sequence counter, including an explicit zero. + pub fn remote_cseq(mut self, cseq: u32) -> Self { + self.remote_cseq = Some(cseq); + self + } + + /// Set recovery metadata, preserving pending operations and lifecycle facts. + /// + /// For pre-0.9 records, pass `DialogSnapshotRuntime::default()` only after + /// the application has established that no signaling was in flight. Missing + /// metadata alone is not evidence of a quiescent dialog. + pub fn runtime(mut self, runtime: DialogSnapshotRuntime) -> Self { + self.runtime = Some(runtime); + self + } + + pub fn local_contact(mut self, contact: Option) -> Self { + self.local_contact = contact; + self + } + + pub fn remote_contact( + mut self, + contact: Option, + ) -> Self { + self.remote_contact = contact; + self + } + + pub fn route_set(mut self, routes: Vec) -> Self { + self.route_set = routes; + self + } + + pub fn supports_100rel(mut self, supported: bool) -> Self { + self.supports_100rel = supported; + self + } + + pub fn session_id(mut self, session_id: Option) -> Self { + self.session_id = session_id; + self + } + + /// Check required inputs and the lifecycle history of a confirmed snapshot. + /// + /// This does not restore a dialog or prove it can be resumed. In particular, + /// pending operations and non-confirmed states remain representable for + /// application recovery decisions. Restore still rejects confirmed snapshots + /// with pending signaling and skips non-confirmed snapshots. Mutable public + /// fields are rechecked at restore time. + pub fn build(self) -> crate::Result { + let snapshot = DialogSnapshot { + id: self.id, + role: self.role, + from: self.from, + to: self.to, + remote_uri: self.remote_uri, + state: self + .state + .ok_or_else(|| crate::Error::Error("snapshot state is required".into()))?, + local_cseq: self + .local_cseq + .ok_or_else(|| crate::Error::Error("snapshot local CSeq is required".into()))?, + remote_cseq: self + .remote_cseq + .ok_or_else(|| crate::Error::Error("snapshot remote CSeq is required".into()))?, + runtime: self.runtime.ok_or_else(|| { + crate::Error::Error("snapshot runtime metadata is required".into()) + })?, + local_contact: self.local_contact, + remote_contact: self.remote_contact, + route_set: self.route_set, + supports_100rel: self.supports_100rel, + session_id: self.session_id, + }; + if snapshot.state == DialogSnapshotState::Confirmed { + super::lifecycle::LifecycleState::restored(&snapshot.runtime)?; + } + Ok(snapshot) + } +} + /// A persisted fact deliberately excludes process-local monotonic time. #[derive(Clone, Debug)] #[non_exhaustive] diff --git a/src/dialog/tests/test_reinvite_control.rs b/src/dialog/tests/test_reinvite_control.rs index de660bea..94981d7f 100644 --- a/src/dialog/tests/test_reinvite_control.rs +++ b/src/dialog/tests/test_reinvite_control.rs @@ -77,6 +77,10 @@ async fn deferred_ack_waits_for_answer_and_retransmits_identically() -> crate::R peer.send_to(success.to_string().as_bytes(), address) .await?; assert_eq!(received_offer.recv().await.unwrap().body, OFFER); + let during_answer = dialog.snapshot(); + assert_eq!(during_answer.runtime.pending.negotiations, 1); + assert!(during_answer.runtime.pending.local_invite); + assert!(!during_answer.is_quiescent()); peer.send_to(success.to_string().as_bytes(), address) .await?; let overlapping = dialog.prepare_reinvite(None, Some(OFFER.to_vec()))?; @@ -100,6 +104,7 @@ async fn deferred_ack_waits_for_answer_and_retransmits_identically() -> crate::R assert_eq!(ack.body, ANSWER); assert_eq!(ack.cseq_header()?.seq()?, sequence); assert_eq!(pending.await.unwrap()?.unwrap().status_code.code(), 200); + assert!(dialog.snapshot().is_quiescent()); peer.send_to(success.to_string().as_bytes(), address) .await?; let (repeated, _) = recv_request(&peer, Method::Ack).await; @@ -161,6 +166,7 @@ async fn cancelled_reinvite_waits_for_provisional_and_preserves_session() -> cra recv_request(&peer, Method::Ack).await; assert_eq!(pending.await.unwrap()?.unwrap().status_code.code(), 487); assert!(matches!(dialog.state(), DialogState::Confirmed(..))); + assert!(dialog.snapshot().is_quiescent()); Ok(()) } @@ -612,6 +618,10 @@ async fn incoming_offerless_reinvite_exposes_only_matching_ack_answer() -> crate .await .unwrap(); receive_response(&peer, Method::Invite, 200).await?; + let awaiting_ack = dialog.snapshot(); + assert_eq!(awaiting_ack.runtime.pending.negotiations, 1); + assert!(awaiting_ack.runtime.pending.remote_invite_awaiting_ack); + assert!(!awaiting_ack.is_quiescent()); let mut ack = request; ack.method = Method::Ack; ack.headers.unique_push(Header::CSeq("9 ACK".into())); @@ -634,5 +644,12 @@ async fn incoming_offerless_reinvite_exposes_only_matching_ack_answer() -> crate assert_eq!(received.body, ANSWER); assert_eq!(received.cseq_header()?.seq()?, 10); assert!(dialog.state().is_confirmed()); + tokio::time::timeout(Duration::from_secs(1), async { + while !dialog.snapshot().is_quiescent() { + tokio::task::yield_now().await; + } + }) + .await + .expect("matching ACK must finish the snapshot negotiation"); Ok(()) } diff --git a/tests/snapshot_reconstruction.rs b/tests/snapshot_reconstruction.rs index d10efb4a..98bc8d9d 100644 --- a/tests/snapshot_reconstruction.rs +++ b/tests/snapshot_reconstruction.rs @@ -3,10 +3,10 @@ use rsipstack::{ dialog::{ - dialog::{Dialog, DialogSnapshot, DialogSnapshotState}, + dialog::{Dialog, DialogSnapshot, DialogSnapshotState, SessionIdState}, dialog_layer::DialogLayer, lifecycle::{dialog_lifecycle_channel, DialogLifecycleKind}, - snapshot::{DialogLifecycleRecord, DialogSnapshotRuntime}, + snapshot::{DialogLifecycleRecord, DialogSnapshotBuilder, DialogSnapshotRuntime}, DialogId, }, sip::{prelude::ToTypedHeader, StatusCode}, @@ -17,30 +17,31 @@ use std::time::Duration; type TestResult = Result>; -fn snapshot(history: Vec) -> TestResult { - let mut runtime = DialogSnapshotRuntime::default(); - runtime.revision = 42; - runtime.lifecycle = history; - Ok(DialogSnapshot { - runtime, - state: DialogSnapshotState::Confirmed, - role: TransactionRole::Client, - id: DialogId { +fn builder() -> TestResult { + Ok(DialogSnapshot::builder( + DialogId { call_id: "stored-call".into(), local_tag: "local".into(), remote_tag: "remote".into(), }, - from: rsipstack::sip::headers::From::from(";tag=local").typed()?, - to: rsipstack::sip::headers::To::from(";tag=remote").typed()?, - local_cseq: 7, - remote_cseq: 3, - local_contact: Some("sip:alice@127.0.0.1:5060".try_into()?), - remote_uri: "sip:bob@127.0.0.1:5061".try_into()?, - remote_contact: None, - route_set: vec![], - supports_100rel: false, - session_id: None, - }) + TransactionRole::Client, + rsipstack::sip::headers::From::from(";tag=local").typed()?, + rsipstack::sip::headers::To::from(";tag=remote").typed()?, + "sip:bob@127.0.0.1:5061".try_into()?, + )) +} + +fn snapshot(history: Vec) -> TestResult { + let mut runtime = DialogSnapshotRuntime::default(); + runtime.revision = 42; + runtime.lifecycle = history; + Ok(builder()? + .state(DialogSnapshotState::Confirmed) + .local_cseq(7) + .remote_cseq(3) + .local_contact(Some("sip:alice@127.0.0.1:5060".try_into()?)) + .runtime(runtime) + .build()?) } #[tokio::test] @@ -96,10 +97,190 @@ async fn reconstructed_records_still_pass_through_restore_validation() -> TestRe ); let layer = DialogLayer::new(EndpointBuilder::new().build().inner); let (states, _receiver) = layer.new_dialog_state_channel(); - assert!(layer - .restore_from_snapshot(snapshot(vec![record])?, states) - .is_err()); + // Builder and restore both validate: public fields remain mutable. + assert!(snapshot(vec![record.clone()]).is_err()); + let mut corrupted = snapshot(vec![])?; + corrupted.runtime.lifecycle.push(record); + assert!(layer.restore_from_snapshot(corrupted, states).is_err()); assert!(layer.is_empty()); } Ok(()) } + +#[test] +fn builder_requires_recovery_inputs_instead_of_guessing_defaults() -> TestResult { + let base = builder()?; + let state = DialogSnapshotState::Confirmed; + let runtime = DialogSnapshotRuntime::default(); + for (builder, missing) in [ + ( + base.clone() + .local_cseq(1) + .remote_cseq(0) + .runtime(runtime.clone()), + "state", + ), + ( + base.clone() + .state(state) + .remote_cseq(0) + .runtime(runtime.clone()), + "local CSeq", + ), + ( + base.clone().state(state).local_cseq(1).runtime(runtime), + "remote CSeq", + ), + ( + base.state(state).local_cseq(1).remote_cseq(0), + "runtime metadata", + ), + ] { + let error = builder + .build() + .expect_err("required input must not default"); + assert!(error.to_string().contains(missing), "{error}"); + } + Ok(()) +} + +#[tokio::test] +async fn explicit_legacy_migration_uses_only_optional_defaults() -> TestResult { + let saved = builder()? + .state(DialogSnapshotState::Confirmed) + .local_cseq(42) + .remote_cseq(0) + // The application has established that the legacy record was quiescent. + .runtime(DialogSnapshotRuntime::default()) + .build()?; + assert!(saved.local_contact.is_none()); + assert!(saved.remote_contact.is_none()); + assert!(saved.route_set.is_empty()); + assert!(!saved.supports_100rel); + assert!(saved.session_id.is_none()); + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let (states, _) = layer.new_dialog_state_channel(); + let id = saved.id.clone(); + assert!(layer.restore_from_snapshot(saved, states)?); + let Some(Dialog::Invite(dialog)) = layer.get_dialog(&id) else { + panic!("restored dialog missing"); + }; + let saved = dialog.snapshot(); + assert_eq!(saved.local_cseq, 42); + assert_eq!(saved.remote_cseq, 0); + assert_eq!(saved.runtime.revision, 0); + assert!(saved.runtime.lifecycle.is_empty()); + Ok(()) +} + +#[test] +fn builder_preserves_all_supplied_fields_and_allows_non_exhaustive_patterns() -> TestResult { + let mut stored = snapshot(vec![DialogLifecycleRecord::new( + 1, + Some(Duration::from_nanos(123)), + DialogLifecycleKind::InviteAccepted { + status: StatusCode::OK, + }, + )])?; + stored.remote_contact = Some(rsipstack::sip::headers::Contact::from( + "", + )); + stored.route_set = vec![rsipstack::sip::Route::from("")]; + stored.supports_100rel = true; + stored.session_id = Some(SessionIdState { + local: "0123456789abcdef0123456789abcdef".into(), + remote: Some("abcdef0123456789abcdef0123456789".into()), + }); + // A persistence adapter must explicitly map every stored field. Exercise + // both roles without deriving either role or state from default values. + for role in [TransactionRole::Client, TransactionRole::Server] { + stored.role = role; + let DialogSnapshot { + id, + role, + from, + to, + remote_uri, + state, + local_cseq, + remote_cseq, + local_contact, + remote_contact, + route_set, + supports_100rel, + session_id, + runtime, + .. + } = stored.clone(); + let rebuilt = DialogSnapshot::builder(id, role, from, to, remote_uri) + .state(state) + .local_cseq(local_cseq) + .remote_cseq(remote_cseq) + .local_contact(local_contact) + .remote_contact(remote_contact) + .route_set(route_set) + .supports_100rel(supports_100rel) + .session_id(session_id) + .runtime(runtime) + .build()?; + assert_eq!(format!("{rebuilt:?}"), format!("{stored:?}")); + } + Ok(()) +} + +#[tokio::test] +async fn builder_preserves_each_pending_flag_and_restore_refuses_to_resume() -> TestResult { + for flag in 0..7 { + let mut runtime = DialogSnapshotRuntime::default(); + match flag { + 0 => runtime.pending.local_invite = true, + 1 => runtime.pending.remote_invite = true, + 2 => runtime.pending.remote_invite_awaiting_ack = true, + 3 => runtime.pending.initial_ack = true, + 4 => runtime.pending.negotiations = 2, + 5 => runtime.pending.local_termination = true, + _ => runtime.pending.remote_termination = true, + } + let saved = builder()? + .state(DialogSnapshotState::Confirmed) + .local_cseq(7) + .remote_cseq(3) + .runtime(runtime.clone()) + .build()?; + assert_eq!(saved.runtime.pending, runtime.pending); + assert!(!saved.is_quiescent()); + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let (states, _) = layer.new_dialog_state_channel(); + let error = layer.restore_from_snapshot(saved, states).unwrap_err(); + assert!(error.to_string().contains("unfinished signaling")); + assert!(layer.is_empty()); + } + Ok(()) +} + +#[tokio::test] +async fn builder_keeps_non_confirmed_snapshots_inspectable() -> TestResult { + use rsipstack::dialog::dialog::TerminatedReason; + let mut runtime = DialogSnapshotRuntime::default(); + runtime.revision = 1; + runtime.lifecycle.push(DialogLifecycleRecord::new( + 1, + None, + DialogLifecycleKind::DialogTerminated { + reason: TerminatedReason::Timeout, + }, + )); + let saved = builder()? + .state(DialogSnapshotState::Terminated) + .local_cseq(7) + .remote_cseq(3) + .runtime(runtime) + .build()?; + assert_eq!(saved.runtime.lifecycle.len(), 1); + assert!(!saved.is_quiescent()); + let layer = DialogLayer::new(EndpointBuilder::new().build().inner); + let (states, _) = layer.new_dialog_state_channel(); + assert!(!layer.restore_from_snapshot(saved, states)?); + assert!(layer.is_empty()); + Ok(()) +} From ec078e425f75e9b180107f0c893cd46b1575a78f Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:08:23 +0000 Subject: [PATCH 4/8] feat(dialog): add opt-in durable signaling checkpoints --- src/dialog/client_dialog.rs | 7 + src/dialog/dialog.rs | 43 +- src/dialog/dialog_layer.rs | 24 + src/dialog/invitation.rs | 4 + src/dialog/invite_dialog.rs | 60 ++- src/dialog/lifecycle.rs | 15 +- src/dialog/mod.rs | 1 + src/dialog/persistence.rs | 297 +++++++++++++ src/dialog/server_dialog.rs | 14 + src/dialog/tests/mod.rs | 1 + src/dialog/tests/test_persistence.rs | 630 +++++++++++++++++++++++++++ src/transaction/transaction.rs | 98 ++++- tests/interop/README.md | 11 + tests/interop/checkpoints.rs | 53 +++ tests/interop/mod.rs | 2 + 15 files changed, 1250 insertions(+), 10 deletions(-) create mode 100644 src/dialog/persistence.rs create mode 100644 src/dialog/tests/test_persistence.rs create mode 100644 tests/interop/checkpoints.rs diff --git a/src/dialog/client_dialog.rs b/src/dialog/client_dialog.rs index ebc4b058..786caaee 100644 --- a/src/dialog/client_dialog.rs +++ b/src/dialog/client_dialog.rs @@ -558,6 +558,7 @@ impl ClientInviteDialog { /// * `UPDATE` - Handles session updates /// * `INVITE` - Handles re-INVITE (when confirmed) pub async fn handle(&mut self, tx: &mut Transaction) -> Result<()> { + self.inner.bind_persistence(tx); trace!( id = %self.id(), method = %tx.original.method, @@ -664,6 +665,12 @@ impl ClientInviteDialog { self.inner.begin_negotiation(); let result = self.inner.process_reinvite(tx, false).await; self.inner.finish_negotiation(); + self.inner + .checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; result } diff --git a/src/dialog/dialog.rs b/src/dialog/dialog.rs index b5b9d1da..c1aed319 100644 --- a/src/dialog/dialog.rs +++ b/src/dialog/dialog.rs @@ -342,6 +342,8 @@ pub struct DialogInner { pub(super) endpoint_inner: EndpointInnerRef, pub(super) state_sender: DialogStateSender, pub(crate) lifecycle: Mutex, + pub(crate) persistence: Mutex>>, + pub(crate) persistence_owner: Mutex>, pub(super) tu_sender: TransactionEventSender, /// RFC 7989 Session-ID state; `None` when the dialog does not participate /// (no UUID supplied by the application and none received from the peer). @@ -566,6 +568,8 @@ impl DialogInner { route_set: Mutex::new(route_set), endpoint_inner, state_sender, + persistence: Mutex::new(None), + persistence_owner: Mutex::new(alloc::sync::Weak::new()), lifecycle: Mutex::new(super::lifecycle::LifecycleState::default()), tu_sender, state: Mutex::new(DialogState::Calling(id)), @@ -823,6 +827,7 @@ impl DialogInner { } } + self.bind_persistence(&tx); match tx.send().await { Ok(_) => { debug!( @@ -867,6 +872,7 @@ impl DialogInner { if let Some(cred) = &self.credential { let new_seq = self.increment_local_seq(); tx = handle_client_authenticate(new_seq, &tx, resp, cred).await?; + self.bind_persistence(&tx); tx.send().await?; continue; } else { @@ -888,6 +894,7 @@ impl DialogInner { _ => break, } } + tx.check_persistence()?; Ok(None) } @@ -1351,6 +1358,11 @@ impl DialogInner { let result = self.send_dialog_request_inner(request, options).await; if negotiation { self.finish_negotiation(); + self.checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; } result } @@ -1373,6 +1385,7 @@ impl DialogInner { ); tx.defer_success_ack = options.as_ref().is_some_and(|o| o.answer_handler.is_some()); tx.force_success_ack = options.is_some() && !tx.defer_success_ack; + self.bind_persistence(&tx); self.reserve_invite(&tx)?; if let Some(route) = tx.original.route_header() { @@ -1594,6 +1607,7 @@ impl DialogInner { tx.defer_success_ack = options.as_ref().is_some_and(|o| o.answer_handler.is_some()); tx.force_success_ack = options.is_some() && !tx.defer_success_ack; + self.bind_persistence(&tx); self.reserve_invite(&tx)?; tx.send().await?; cancel_watch = options.as_ref().map(|o| { @@ -1690,6 +1704,7 @@ impl DialogInner { _ => break, } } + tx.check_persistence()?; Ok(None) } @@ -1732,6 +1747,11 @@ impl DialogInner { } self.record_local_termination(); } + self.checkpoint( + super::persistence::DialogCheckpointReason::LocalTerminationRequested, + None, + ) + .await?; let initial_ack = self.initial_ack.lock().clone(); let reinvite_ack = self.reinvite_ack.lock().clone(); for ack in [initial_ack, reinvite_ack].into_iter().flatten() { @@ -1747,6 +1767,8 @@ impl DialogInner { let result = self.do_request(request).await; let id = self.id.lock().clone(); self.transition(DialogState::Terminated(id, reason)); + self.checkpoint(super::persistence::DialogCheckpointReason::Terminated, None) + .await?; result.map(|_| ()) } @@ -1843,11 +1865,15 @@ impl DialogInner { /// writes to DialogInner public fields bypass these synchronization guarantees. pub fn snapshot(&self) -> DialogSnapshot { let state_guard = self.state.lock(); + self.snapshot_locked(&state_guard) + } + + pub(crate) fn snapshot_locked(&self, state_guard: &DialogState) -> DialogSnapshot { let usage = self.invite_usage.lock(); let lifecycle = self.lifecycle.lock(); let id = self.id.lock().clone(); - let state = match &*state_guard { + let state = match state_guard { DialogState::Calling(_) => DialogSnapshotState::Calling, DialogState::Trying(_) => DialogSnapshotState::Trying, DialogState::Early(_, _) => DialogSnapshotState::Early, @@ -1986,6 +2012,8 @@ impl DialogInner { endpoint_inner, state_sender, + persistence: Mutex::new(None), + persistence_owner: Mutex::new(alloc::sync::Weak::new()), lifecycle: Mutex::new(lifecycle), tu_sender, @@ -2244,6 +2272,13 @@ impl DialogInner { } self.lifecycle.lock().revision += 1; *old_state = state.clone(); + if state.is_terminated() { + self.enqueue_checkpoint_locked( + old_state, + super::persistence::DialogCheckpointReason::Terminated, + None, + ); + } // Try to send state update, but don't fail if channel is closed self.state_sender.send(state).ok(); } @@ -2261,6 +2296,11 @@ impl DialogInner { let result = self.process_transaction_handle_inner(tx, rx).await; if negotiation { self.finish_negotiation(); + self.checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; } result } @@ -2271,6 +2311,7 @@ impl DialogInner { tx: &mut Transaction, mut rx: TransactionCommandReceiver, ) -> Result<()> { + self.bind_persistence(tx); let target = if Self::is_target_refresh(&tx.original.method) { match Self::parse_target_refresh_contact(&tx.original) { Ok(target) => target, diff --git a/src/dialog/dialog_layer.rs b/src/dialog/dialog_layer.rs index 6b039bad..d481b907 100644 --- a/src/dialog/dialog_layer.rs +++ b/src/dialog/dialog_layer.rs @@ -34,6 +34,8 @@ use tracing::debug; /// * `last_seq` uses atomic operations for lock-free increments /// * `dialogs` uses RwLock for concurrent read access with exclusive writes pub struct DialogLayerInner { + pub(super) persistence_config: + crate::platform::sync::Mutex>, pub(super) lifecycle_sender: crate::platform::sync::Mutex>, pub(super) last_seq: AtomicU32, @@ -143,6 +145,7 @@ impl DialogLayer { endpoint, inner: Arc::new(DialogLayerInner { last_seq: AtomicU32::new(0), + persistence_config: crate::platform::sync::Mutex::new(None), lifecycle_sender: crate::platform::sync::Mutex::new(None), dialogs: RwMap::new(), }), @@ -161,6 +164,22 @@ impl DialogLayer { *self.inner.lifecycle_sender.lock() = sender; } + /// Configure optional durable checkpoints for subsequently created/restored + /// INVITE dialogs. Existing dialogs retain their configuration. + pub fn set_persistence( + &self, + config: Option, + ) -> Result<()> { + if let Some(config) = &config { + config.validate()?; + self.endpoint + .record_receipt_times + .store(true, Ordering::Relaxed); + } + *self.inner.persistence_config.lock() = config; + Ok(()) + } + pub fn get_or_create_server_invite( &self, tx: &Transaction, @@ -223,6 +242,10 @@ impl DialogLayer { let dialog = InviteDialog::from_inner(Arc::new(dlg_inner)); dialog.inner.lifecycle.lock().sender = self.inner.lifecycle_sender.lock().clone(); *tx.initial_dialog.lock() = Some(Arc::downgrade(&dialog.inner)); + dialog + .inner + .configure_persistence(self.inner.persistence_config.lock().clone()); + dialog.inner.bind_persistence(tx); dialog.inner.reserve_invite(tx)?; dialog.inner.set_server_connection(tx.connection.clone()); self.inner @@ -559,6 +582,7 @@ impl DialogLayer { inner.credential = credential; inner.lifecycle.lock().sender = self.inner.lifecycle_sender.lock().clone(); let inner = Arc::new(inner); + inner.configure_persistence(self.inner.persistence_config.lock().clone()); let dialog = Dialog::from_inner(inner.role, inner.clone()); let key = dialog.id().to_string(); diff --git a/src/dialog/invitation.rs b/src/dialog/invitation.rs index 594f9e18..ad9616e9 100644 --- a/src/dialog/invitation.rs +++ b/src/dialog/invitation.rs @@ -901,6 +901,10 @@ impl DialogLayer { } let dialog = InviteDialog::from_inner(Arc::new(dlg_inner)); dialog.inner.lifecycle.lock().sender = self.inner.lifecycle_sender.lock().clone(); + dialog + .inner + .configure_persistence(self.inner.persistence_config.lock().clone()); + dialog.inner.bind_persistence(&tx); dialog.inner.reserve_invite(&tx)?; Ok((dialog, tx)) } diff --git a/src/dialog/invite_dialog.rs b/src/dialog/invite_dialog.rs index 4544f538..c78e9619 100644 --- a/src/dialog/invite_dialog.rs +++ b/src/dialog/invite_dialog.rs @@ -78,6 +78,15 @@ impl InviteDialog { self.inner.state.lock().clone() } + /// Inspect checkpoint progress and any permanent storage failure. + pub fn persistence_status(&self) -> Option { + self.inner + .persistence + .lock() + .as_ref() + .map(|runtime| runtime.status.lock().clone()) + } + pub fn snapshot(&self) -> super::dialog::DialogSnapshot { self.inner.snapshot() } @@ -259,7 +268,7 @@ impl InviteDialog { StatusCode::ServerInternalError, )); } - { + let deferred = { // Decided under the state lock, so `process_invite` either sees // the deferred CANCEL after leaving Calling or we see it left. let state = self.inner.state.lock(); @@ -268,16 +277,27 @@ impl InviteDialog { self.inner.record_local_termination(); self.inner.cancel_requested.store(true, Ordering::SeqCst); self.inner.cancel_deferred.store(true, Ordering::SeqCst); - return Ok(()); + true } DialogState::Trying(_) | DialogState::Early(_, _) => { self.inner.record_local_termination(); self.inner.cancel_requested.store(true, Ordering::SeqCst); + false } _ => return Ok(()), } + }; + self.inner + .checkpoint( + super::persistence::DialogCheckpointReason::LocalTerminationRequested, + None, + ) + .await?; + if deferred { + Ok(()) + } else { + self.send_cancel().await } - self.send_cancel().await } /// Send the CANCEL `cancel()` deferred in Calling, once the INVITE got a @@ -375,7 +395,10 @@ impl InviteDialog { self.inner.reserve_invite(tx)?; self.inner.transition(DialogState::Calling(self.id())); let mut auth = AuthRetry::new(); - tx.track_receipt_times(self.inner.lifecycle.lock().sender.is_some()); + self.inner.bind_persistence(tx); + tx.track_receipt_times( + self.inner.lifecycle.lock().sender.is_some() || self.inner.persistence.lock().is_some(), + ); tx.send().await?; // Record the flow the INVITE actually went out on, so later // in-dialog requests (BYE / re-INVITE / INFO) reuse it instead of @@ -397,9 +420,18 @@ impl InviteDialog { } }) .await; + tx.check_persistence()?; ack.finish(); if msg.is_some() { self.inner.complete_initial_ack(); + if self.inner.is_confirmed() || self.inner.is_terminated() { + self.inner + .checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; + } } let cancelled = established?; let Some(msg) = msg else { break }; @@ -452,7 +484,11 @@ impl InviteDialog { ) .await?; self.inner.reserve_invite(tx)?; - tx.track_receipt_times(self.inner.lifecycle.lock().sender.is_some()); + self.inner.bind_persistence(tx); + tx.track_receipt_times( + self.inner.lifecycle.lock().sender.is_some() + || self.inner.persistence.lock().is_some(), + ); tx.send().await?; self.inner.set_server_connection(tx.connection.clone()); self.inner.update_remote_tag("").ok(); @@ -846,6 +882,7 @@ impl InviteDialog { /// Handle an incoming transaction routed to this dialog. pub async fn handle(&mut self, tx: &mut Transaction) -> Result<()> { + self.inner.bind_persistence(tx); trace!( id = %self.id(), method = %tx.original.method, @@ -1136,6 +1173,12 @@ impl InviteDialog { self.inner.begin_negotiation(); let result = self.inner.process_reinvite(tx, true).await; self.inner.finish_negotiation(); + self.inner + .checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; result } @@ -1178,8 +1221,15 @@ impl InviteDialog { SipMessage::Response(_) => {} } } + tx.check_persistence()?; let answered_2xx = self.inner.waiting_ack(); self.inner.end_session_without_ack(tx, answered_2xx).await; + self.inner + .checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; Ok::<(), crate::Error>(()) }; match handle_loop.await { diff --git a/src/dialog/lifecycle.rs b/src/dialog/lifecycle.rs index 6e110ac8..d2dc547f 100644 --- a/src/dialog/lifecycle.rs +++ b/src/dialog/lifecycle.rs @@ -3,6 +3,8 @@ //! Unlike `DialogState`, these are facts, not requests for application action. //! Delivery never awaits application code or storage. Events are not a durable //! journal: a closed receiver drops notifications without affecting SIP. +//! Explicitly enabling persistence holds delivery until a covering checkpoint +//! commits; the notification receiver itself still cannot delay SIP. //! //! Configure the layer before creating calls: //! @@ -114,6 +116,8 @@ pub(crate) struct LifecycleState { pub pending_remote_bye: bool, pub negotiations: u32, pub facts: alloc::vec::Vec, + pub defer_delivery: bool, + pub undelivered: alloc::vec::Vec, } impl LifecycleState { @@ -177,14 +181,19 @@ impl LifecycleState { since_unix_epoch: time.since_unix_epoch, kind: kind.clone(), }); - if let Some(sender) = &self.sender { - let _ = sender.send(DialogLifecycleEvent { + if self.sender.is_some() { + let event = DialogLifecycleEvent { dialog_id: id, role, sequence: self.sequence, occurred_at: time, kind, - }); + }; + if self.defer_delivery { + self.undelivered.push(event); + } else if let Some(sender) = &self.sender { + let _ = sender.send(event); + } } } } diff --git a/src/dialog/mod.rs b/src/dialog/mod.rs index fe4dffd5..f0b71f94 100644 --- a/src/dialog/mod.rs +++ b/src/dialog/mod.rs @@ -12,6 +12,7 @@ pub mod dialog_layer; pub mod invitation; pub mod invite_dialog; pub mod lifecycle; +pub mod persistence; pub mod publication; pub mod registration; pub mod reinvite; diff --git a/src/dialog/persistence.rs b/src/dialog/persistence.rs new file mode 100644 index 00000000..55c42528 --- /dev/null +++ b/src/dialog/persistence.rs @@ -0,0 +1,297 @@ +//! Opt-in durable checkpoints. Storage remains application-owned. +//! +//! Each dialog has one serial worker. A callback runs without a dialog state +//! lock and may inspect snapshots. It must not await another SIP operation on +//! the same dialog: that operation would wait behind this callback. +//! +//! Returning `Ok(())` promises the application has durably committed the supplied +//! snapshot and any related application state. No serialization or database is +//! chosen by the stack. Applications choose which message fields to serialize; +//! SIP messages may include authentication headers. Media policy remains external. +//! +//! Failure or timeout poisons this dialog's persistence worker. No subsequent +//! protected sends are permitted. A timeout cannot undo a database write that +//! has already started; recovery must inspect storage. Ordinary lifecycle events +//! are released only after the checkpoint covering them succeeds. The legacy +//! `DialogState` channel is still a protocol channel, not a durable commit feed. +//! +//! Enable this explicitly before creating or restoring calls: +//! +//! ```rust,no_run +//! use std::sync::Arc; +//! use rsipstack::dialog::{dialog_layer::DialogLayer, persistence::*}; +//! # fn configure(layer: &DialogLayer, store: Arc) -> rsipstack::Result<()> { +//! layer.set_persistence(Some(DialogPersistenceConfig::new(store)))?; +//! # Ok(()) +//! # } +//! ``` +//! +//! Protected boundaries are the first outgoing request of each dialog-owned +//! transaction (including authentication retries), an incoming final response +//! before its ACK, a locally generated final response before transport send, +//! local termination intent, and completed signaling/terminal state. A wire +//! response and its later acknowledgment are separate checkpoints. Provisional +//! responses and transaction-generated CANCEL acknowledgments do not wait for +//! storage. Pure transaction/proxy users are unaffected. +//! +//! A commit cannot be atomic with network transmission. A crash after commit +//! but before send leaves an intended message with an unknown send outcome. +//! Recovery must use the pending markers and application policy; the stack does +//! not replay in-flight transactions. A successful `accept()`/`reject()` only +//! queues a response: the transaction driver performs its checkpoint. Errors +//! from asynchronous/terminal writes are exposed by `persistence_status()`. +//! After failure, remove the dialog from the layer and reconcile stored state; +//! there is no automatic retry or fail-open mode. The application must keep its +//! async runtime alive long enough to finish accepted writes during shutdown. +//! +//! Handlers must yield rather than block an executor, and must not panic. Use +//! an application-owned incarnation key alongside dialog ID/revision for +//! snapshot idempotency across process restarts. Multiple checkpoints may share +//! a revision: it versions dialog state, not a storage operation. Deduplicate +//! message-related work with its own request/operation identity as well. +//! A new lifecycle notification is not an +//! exactly-once external side effect; persist an application outbox if needed. +//! Early checkpoints may have an empty remote tag; correlate them with the +//! later established dialog using that same application call/incarnation key. + +use super::{ + dialog::{DialogInner, DialogSnapshot}, + lifecycle::DialogLifecycleEvent, +}; +use crate::{ + platform::{mpsc, sync::Mutex}, + prelude::*, + sip::SipMessage, +}; +use alloc::sync::Weak; +use async_trait::async_trait; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum DialogCheckpointReason { + /// Before the first send of a transaction, including authenticated retries. + OutgoingRequest, + /// Local hangup/cancellation intent, before waiting for an ACK or peer. + LocalTerminationRequested, + /// Before sending a final response to an incoming request. + BeforeResponse, + /// A successful INVITE response was received; before its automatic ACK. + /// Includes re-INVITEs and fork cleanup; lifecycle facts identify initial acceptance. + BeforeAck, + /// A completed ACK/negotiation permits future quiescent restoration. + SignalingCompleted, + /// The dialog ended, including local rejection and protocol timeout. + Terminated, +} + +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct DialogCheckpoint { + pub reason: DialogCheckpointReason, + pub snapshot: DialogSnapshot, + /// Intended or observed SIP message, when the checkpoint protects a send. + /// This lets the application commit its SDP or request metadata atomically. + pub message: Option, +} + +#[async_trait] +pub trait DialogPersistence: Send + Sync { + async fn save(&self, checkpoint: DialogCheckpoint) -> crate::Result<()>; +} + +#[derive(Clone)] +pub struct DialogPersistenceConfig { + pub handler: Arc, + pub timeout: Duration, +} + +impl DialogPersistenceConfig { + pub fn new(handler: Arc) -> Self { + Self { + handler, + timeout: Duration::from_secs(5), + } + } + + pub(crate) fn validate(&self) -> crate::Result<()> { + if self.timeout.is_zero() { + return Err(crate::Error::Error( + "persistence timeout must be positive".into(), + )); + } + Ok(()) + } +} + +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct DialogPersistenceStatus { + pub last_committed_revision: Option, + pub failure: Option, +} + +type CommitResult = core::result::Result<(), String>; +pub(crate) type CommitReceiver = mpsc::UnboundedReceiver; + +struct Work { + checkpoint: DialogCheckpoint, + reply: mpsc::UnboundedSender, +} + +pub(crate) struct PersistenceRuntime { + sender: mpsc::UnboundedSender>, + pub status: Arc>, +} + +impl PersistenceRuntime { + #[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))] + pub fn start(dialog: Weak, config: DialogPersistenceConfig) -> Arc { + let (sender, mut receiver) = mpsc::unbounded_channel::>(); + let status = Arc::new(Mutex::new(DialogPersistenceStatus::default())); + let worker_status = status.clone(); + // The worker never owns a strong dialog reference while awaiting storage. + // Dropping the dialog queues a stop marker; pending writes have finite timeouts. + crate::platform::spawn(async move { + while let Some(Some(work)) = receiver.recv().await { + let revision = work.checkpoint.snapshot.runtime.revision; + let sequence = work + .checkpoint + .snapshot + .runtime + .lifecycle + .last() + .map_or(0, |fact| fact.sequence); + let previous = worker_status.lock().clone(); + let result = if let Some(error) = previous.failure { + Err(error) + } else if previous + .last_committed_revision + .is_some_and(|r| r > revision) + { + Err("checkpoint revision moved backwards".into()) + } else if work.checkpoint.reason == DialogCheckpointReason::Terminated + && previous.last_committed_revision == Some(revision) + { + Ok(()) + } else { + match crate::platform::timeout( + config.timeout, + config.handler.save(work.checkpoint), + ) + .await + { + Ok(Ok(())) => Ok(()), + Ok(Err(error)) => Err(format!("dialog persistence failed: {error}")), + Err(_) => { + Err("dialog persistence timed out; commit outcome is unknown".into()) + } + } + }; + match &result { + Ok(()) => { + worker_status.lock().last_committed_revision = Some(revision); + if let Some(dialog) = dialog.upgrade() { + dialog.release_committed_facts(sequence); + } + } + Err(error) => { + worker_status.lock().failure = Some(error.clone()); + tracing::warn!(%error, revision, "dialog persistence stopped"); + } + } + let _ = work.reply.send(result); + } + }); + Arc::new(Self { sender, status }) + } + + /// Enqueue while the snapshot gate is held; user code runs in the worker. + pub fn submit(&self, checkpoint: DialogCheckpoint) -> CommitReceiver { + let (reply, receiver) = mpsc::unbounded_channel(); + if let Some(error) = self.status.lock().failure.clone() { + let _ = reply.send(Err(error)); + return receiver; + } + if let Err(error) = self.sender.send(Some(Work { checkpoint, reply })) { + if let Some(work) = error.0 { + let _ = work + .reply + .send(Err("dialog persistence worker stopped".into())); + } + } + receiver + } +} + +impl DialogInner { + pub(crate) fn configure_persistence(self: &Arc, config: Option) { + if let Some(config) = config { + *self.persistence_owner.lock() = Arc::downgrade(self); + self.lifecycle.lock().defer_delivery = true; + *self.persistence.lock() = + Some(PersistenceRuntime::start(Arc::downgrade(self), config)); + } + } + + pub(crate) fn bind_persistence(&self, tx: &crate::transaction::transaction::Transaction) { + *tx.persistence_dialog.lock() = self.persistence_owner.lock().clone(); + } + + pub(crate) fn release_committed_facts(&self, sequence: u64) { + let _state = self.state.lock(); + let mut lifecycle = self.lifecycle.lock(); + let mut waiting: Vec = Vec::new(); + for event in core::mem::take(&mut lifecycle.undelivered) { + if event.sequence <= sequence { + if let Some(sender) = &lifecycle.sender { + let _ = sender.send(event); + } + } else { + waiting.push(event); + } + } + lifecycle.undelivered = waiting; + } + + #[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))] + pub(crate) async fn checkpoint( + &self, + reason: DialogCheckpointReason, + message: Option, + ) -> crate::Result<()> { + let receiver = { + let state = self.state.lock(); + self.enqueue_checkpoint_locked(&state, reason, message) + }; + if let Some(mut receiver) = receiver { + receiver + .recv() + .await + .unwrap_or_else(|| Err("dialog persistence worker stopped".into())) + .map_err(crate::Error::Error)?; + } + Ok(()) + } + + pub(crate) fn enqueue_checkpoint_locked( + &self, + state: &super::dialog::DialogState, + reason: DialogCheckpointReason, + message: Option, + ) -> Option { + let runtime = self.persistence.lock().clone()?; + Some(runtime.submit(DialogCheckpoint { + reason, + snapshot: self.snapshot_locked(state), + message, + })) + } +} + +impl Drop for PersistenceRuntime { + fn drop(&mut self) { + // Also works on runtimes whose channels do not close on last-sender drop. + // FIFO drains already accepted writes before stopping the worker. + let _ = self.sender.send(None); + } +} diff --git a/src/dialog/server_dialog.rs b/src/dialog/server_dialog.rs index 821ecd32..fbb123d2 100644 --- a/src/dialog/server_dialog.rs +++ b/src/dialog/server_dialog.rs @@ -653,6 +653,7 @@ impl ServerInviteDialog { /// * `UPDATE` - Handles session updates /// * `INVITE` - Handles initial INVITE or re-INVITE pub async fn handle(&mut self, tx: &mut Transaction) -> Result<()> { + self.inner.bind_persistence(tx); debug!( id = %self.id(), method = %tx.original.method, @@ -853,6 +854,12 @@ impl ServerInviteDialog { self.inner.begin_negotiation(); let result = self.inner.process_reinvite(tx, true).await; self.inner.finish_negotiation(); + self.inner + .checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; result } @@ -895,8 +902,15 @@ impl ServerInviteDialog { SipMessage::Response(_) => {} } } + tx.check_persistence()?; let answered_2xx = self.inner.waiting_ack(); self.inner.end_session_without_ack(tx, answered_2xx).await; + self.inner + .checkpoint( + super::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; Ok::<(), crate::Error>(()) }; match handle_loop.await { diff --git a/src/dialog/tests/mod.rs b/src/dialog/tests/mod.rs index f30db8a0..b39813bf 100644 --- a/src/dialog/tests/mod.rs +++ b/src/dialog/tests/mod.rs @@ -13,6 +13,7 @@ mod test_in_dialog_provisional; mod test_in_dialog_via; mod test_invite_auth_challenge; mod test_invite_overlap; +mod test_persistence; mod test_prack; mod test_proxy_headers; mod test_refer; diff --git a/src/dialog/tests/test_persistence.rs b/src/dialog/tests/test_persistence.rs new file mode 100644 index 00000000..14d19952 --- /dev/null +++ b/src/dialog/tests/test_persistence.rs @@ -0,0 +1,630 @@ +//! Wire-level checks for storage barriers, failures, and teardown races. +use crate::dialog::{ + dialog::DialogStateReceiver, + dialog_layer::DialogLayer, + invitation::{InviteAsyncResult, InviteOption}, + invite_dialog::InviteDialog, + lifecycle::{dialog_lifecycle_channel, DialogLifecycleKind, DialogLifecycleReceiver}, + persistence::{ + DialogCheckpoint, DialogCheckpointReason as Reason, DialogPersistence, + DialogPersistenceConfig, + }, +}; +use crate::sip::{prelude::HeadersExt, Method, Request, SipMessage, StatusCode, Uri}; +use crate::transport::{udp::UdpConnection, TransportLayer}; +use crate::EndpointBuilder; +use async_trait::async_trait; +use std::{ + sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, Mutex, + }, + time::Duration, +}; +use tokio::{net::UdpSocket, sync::mpsc::unbounded_channel, task::JoinHandle}; +use tokio_util::sync::CancellationToken; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Gate { + Never, + InitialRequest, + Answer, + ByeResponse, + UasResponse, + Info, +} + +struct Storage { + gate: Gate, + entered: CancellationToken, + release: CancellationToken, + fail: AtomicBool, + committed: Mutex>, + attempts: Mutex>, + inspecting: Mutex>>, + active: AtomicUsize, + max_active: AtomicUsize, +} + +impl Storage { + fn new(gate: Gate) -> Arc { + Arc::new(Self { + gate, + entered: CancellationToken::new(), + release: CancellationToken::new(), + fail: AtomicBool::new(false), + committed: Mutex::new(Vec::new()), + attempts: Mutex::new(Vec::new()), + inspecting: Mutex::new(None), + active: AtomicUsize::new(0), + max_active: AtomicUsize::new(0), + }) + } + fn matches(&self, c: &DialogCheckpoint) -> bool { + match self.gate { + Gate::Never => false, + Gate::InitialRequest => { + c.reason == Reason::OutgoingRequest + && matches!(&c.message, Some(SipMessage::Request(r)) if r.method == Method::Invite) + } + Gate::Answer => c.reason == Reason::BeforeAck, + Gate::ByeResponse => { + c.reason == Reason::BeforeResponse + && matches!(&c.message, Some(SipMessage::Response(r)) if r.cseq_header().unwrap().method().unwrap() == Method::Bye) + } + Gate::UasResponse => { + c.reason == Reason::BeforeResponse + && matches!(&c.message, Some(SipMessage::Response(r)) if r.status_code == StatusCode::OK && r.cseq_header().unwrap().method().unwrap() == Method::Invite) + } + Gate::Info => { + c.reason == Reason::OutgoingRequest + && matches!(&c.message, Some(SipMessage::Request(r)) if r.method == Method::Info) + } + } + } + fn config(self: &Arc, timeout: Duration) -> DialogPersistenceConfig { + DialogPersistenceConfig { + handler: self.clone(), + timeout, + } + } +} + +struct Active<'a>(&'a AtomicUsize); +impl Drop for Active<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} + +#[async_trait] +impl DialogPersistence for Storage { + async fn save(&self, c: DialogCheckpoint) -> crate::Result<()> { + let active = self.active.fetch_add(1, Ordering::SeqCst) + 1; + let _active = Active(&self.active); + self.max_active.fetch_max(active, Ordering::SeqCst); + let inspect = self + .inspecting + .lock() + .unwrap() + .as_ref() + .and_then(std::sync::Weak::upgrade); + if let Some(dialog) = inspect { + // A callback must be able to inspect the dialog: no state lock is held. + assert!(dialog.snapshot().runtime.revision >= c.snapshot.runtime.revision); + } + self.attempts.lock().unwrap().push(c.clone()); + if self.matches(&c) { + self.entered.cancel(); + self.release.cancelled().await; + } + if self.fail.load(Ordering::SeqCst) { + return Err(crate::Error::Error("test storage failure".into())); + } + self.committed.lock().unwrap().push(c); + Ok(()) + } +} + +struct Call { + peer: UdpSocket, + local: std::net::SocketAddr, + dialog: InviteDialog, + facts: DialogLifecycleReceiver, + _states: DialogStateReceiver, + task: JoinHandle, + router: JoinHandle<()>, + endpoint: JoinHandle>, + stop: CancellationToken, +} + +impl Drop for Call { + fn drop(&mut self) { + self.stop.cancel(); + self.task.abort(); + self.router.abort(); + self.endpoint.abort(); + } +} + +async fn start(storage: Arc, timeout: Duration) -> crate::Result { + let stop = CancellationToken::new(); + let transport = TransportLayer::new(stop.child_token()); + let udp = + UdpConnection::create_connection("127.0.0.1:0".parse()?, None, Some(stop.child_token())) + .await?; + let local = udp.get_addr().get_socketaddr()?; + transport.add_transport(udp.into()); + let endpoint = EndpointBuilder::new() + .with_transport_layer(transport) + .with_cancel_token(stop.child_token()) + .build(); + let layer = Arc::new(DialogLayer::new(endpoint.inner.clone())); + let (sender, facts) = dialog_lifecycle_channel(); + layer.set_lifecycle_events(Some(sender)); + layer.set_persistence(Some(storage.config(timeout)))?; + let mut incoming = endpoint.incoming_transactions()?; + let endpoint_ref = endpoint.inner.clone(); + let endpoint = tokio::spawn(async move { endpoint_ref.serve().await }); + let routing = layer.clone(); + let router = tokio::spawn(async move { + while let Some(mut tx) = incoming.recv().await { + if let Some(mut dialog) = routing.match_dialog(&tx) { + let _ = dialog.handle(&mut tx).await; + } else { + let _ = tx.reply(StatusCode::CallTransactionDoesNotExist).await; + } + } + }); + let peer = UdpSocket::bind("127.0.0.1:0").await?; + let option = InviteOption { + caller: Uri::try_from("sip:alice@example.com")?, + callee: Uri::try_from(format!("sip:bob@{}", peer.local_addr()?).as_str())?, + contact: Uri::try_from(format!("sip:alice@{local}").as_str())?, + ..Default::default() + }; + let (sender, states) = unbounded_channel(); + let (dialog, task) = layer.do_invite_async(option, sender)?; + *storage.inspecting.lock().unwrap() = Some(Arc::downgrade(&dialog.inner)); + Ok(Call { + peer, + local, + dialog, + facts, + _states: states, + task, + router, + endpoint, + stop, + }) +} + +async fn receive(peer: &UdpSocket) -> SipMessage { + let mut bytes = [0u8; 8192]; + let (len, _) = tokio::time::timeout(Duration::from_secs(2), peer.recv_from(&mut bytes)) + .await + .expect("SIP receive timeout") + .unwrap(); + SipMessage::try_from(&bytes[..len]).unwrap() +} + +async fn request(peer: &UdpSocket, method: Method) -> Request { + let SipMessage::Request(r) = receive(peer).await else { + panic!("expected request") + }; + assert_eq!(r.method, method); + r +} + +fn response(request: &Request, contact: &str) -> String { + let to = request.to_header().unwrap(); + let to = if to.tag().unwrap().is_some() { + to.value().to_string() + } else { + format!("{};tag=peer", to.value()) + }; + format!("SIP/2.0 200 OK\r\nVia: {}\r\nFrom: {}\r\nTo: {to}\r\nCall-ID: {}\r\nCSeq: {}\r\nContact: <{contact}>\r\nContent-Length: 0\r\n\r\n", + request.via_header().unwrap().value(), request.from_header().unwrap().value(), request.call_id_header().unwrap().value(), request.cseq_header().unwrap().value()) +} + +async fn answer(call: &Call, invite: &Request) { + call.peer + .send_to( + response( + invite, + &format!("sip:bob@{}", call.peer.local_addr().unwrap()), + ) + .as_bytes(), + call.local, + ) + .await + .unwrap(); +} + +async fn established(call: &mut Call) -> Request { + let invite = request(&call.peer, Method::Invite).await; + answer(call, &invite).await; + request(&call.peer, Method::Ack).await; + tokio::time::timeout(Duration::from_secs(2), &mut call.task) + .await + .unwrap() + .unwrap() + .unwrap(); + invite +} + +async fn send_bye(call: &Call, invite: &Request, seq: u32) -> Vec { + let bytes = format!("BYE sip:alice@{} SIP/2.0\r\nVia: SIP/2.0/UDP {};branch=z9hG4bK-peer-bye{seq}\r\nFrom: ;tag=peer\r\nTo: {}\r\nCall-ID: {}\r\nCSeq: {seq} BYE\r\nMax-Forwards: 70\r\nContent-Length: 0\r\n\r\n", + call.local, call.peer.local_addr().unwrap(), invite.from_header().unwrap().value(), invite.call_id_header().unwrap().value()).into_bytes(); + call.peer.send_to(&bytes, call.local).await.unwrap(); + bytes +} + +async fn silent(peer: &UdpSocket) { + let mut bytes = [0u8; 8192]; + assert!( + tokio::time::timeout(Duration::from_millis(40), peer.recv_from(&mut bytes)) + .await + .is_err(), + "SIP escaped the persistence barrier" + ); +} + +async fn entered(store: &Storage) { + tokio::time::timeout(Duration::from_secs(2), store.entered.cancelled()) + .await + .unwrap(); +} + +#[tokio::test] +async fn persistence_initial_invite_waits_for_durable_write() -> crate::Result<()> { + let store = Storage::new(Gate::InitialRequest); + let call = start(store.clone(), Duration::from_secs(2)).await?; + entered(&store).await; + silent(&call.peer).await; + store.release.cancel(); + let invite = request(&call.peer, Method::Invite).await; + let saved = store.committed.lock().unwrap(); + assert_eq!(saved[0].snapshot.local_cseq, invite.cseq_header()?.seq()?); + assert_eq!(store.max_active.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[tokio::test] +async fn persistence_failed_initial_write_sends_nothing() -> crate::Result<()> { + let store = Storage::new(Gate::Never); + store.fail.store(true, Ordering::SeqCst); + let mut call = start(store, Duration::from_secs(1)).await?; + assert!(tokio::time::timeout(Duration::from_secs(2), &mut call.task) + .await + .unwrap() + .unwrap() + .is_err()); + silent(&call.peer).await; + assert!(call.dialog.persistence_status().unwrap().failure.is_some()); + Ok(()) +} + +#[tokio::test] +async fn persistence_timeout_poisoning_is_bounded() -> crate::Result<()> { + let store = Storage::new(Gate::InitialRequest); + let mut call = start(store.clone(), Duration::from_millis(30)).await?; + assert!(tokio::time::timeout(Duration::from_secs(1), &mut call.task) + .await + .unwrap() + .unwrap() + .is_err()); + silent(&call.peer).await; + store.release.cancel(); + assert_eq!(store.active.load(Ordering::SeqCst), 0); + assert!(call + .dialog + .persistence_status() + .unwrap() + .failure + .unwrap() + .contains("timed out")); + Ok(()) +} + +#[tokio::test] +async fn persistence_answer_waits_before_ack_and_fact_delivery() -> crate::Result<()> { + let store = Storage::new(Gate::Answer); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + let invite = request(&call.peer, Method::Invite).await; + answer(&call, &invite).await; + entered(&store).await; + assert!(call.dialog.state().is_confirmed()); + assert!(call.dialog.snapshot().runtime.pending.initial_ack); + assert!(call.facts.try_recv().is_err()); + silent(&call.peer).await; + let original_time = call.dialog.snapshot().runtime.lifecycle[0].since_unix_epoch; + store.release.cancel(); + request(&call.peer, Method::Ack).await; + let fact = tokio::time::timeout(Duration::from_secs(1), call.facts.recv()) + .await + .unwrap() + .unwrap(); + assert!(matches!( + fact.kind, + DialogLifecycleKind::InviteAccepted { .. } + )); + assert_eq!(fact.occurred_at.since_unix_epoch, original_time); + Ok(()) +} + +#[tokio::test] +async fn persistence_bye_during_answer_commit_keeps_original_facts() -> crate::Result<()> { + let store = Storage::new(Gate::Answer); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + let invite = request(&call.peer, Method::Invite).await; + answer(&call, &invite).await; + entered(&store).await; + send_bye(&call, &invite, 2).await; + tokio::time::timeout(Duration::from_secs(1), async { + while !call.dialog.state().is_terminated() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let before = call.dialog.snapshot(); + assert_eq!(before.runtime.lifecycle.len(), 3); + assert!(call.facts.try_recv().is_err()); + silent(&call.peer).await; + store.release.cancel(); + let messages = [receive(&call.peer).await, receive(&call.peer).await]; + assert!(messages + .iter() + .any(|m| matches!(m, SipMessage::Request(r) if r.method == Method::Ack))); + assert!(messages + .iter() + .any(|m| matches!(m, SipMessage::Response(r) if r.status_code == StatusCode::OK))); + for expected in 1..=3 { + let fact = tokio::time::timeout(Duration::from_secs(1), call.facts.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(fact.sequence, expected); + assert_eq!( + fact.occurred_at.since_unix_epoch, + before.runtime.lifecycle[(expected - 1) as usize].since_unix_epoch + ); + } + assert_eq!(store.max_active.load(Ordering::SeqCst), 1); + let revisions: Vec<_> = store + .committed + .lock() + .unwrap() + .iter() + .map(|c| c.snapshot.runtime.revision) + .collect(); + assert!(revisions.windows(2).all(|w| w[0] <= w[1])); + Ok(()) +} + +#[tokio::test] +async fn persistence_failed_answer_commit_returns_without_ack() -> crate::Result<()> { + let store = Storage::new(Gate::Answer); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + let invite = request(&call.peer, Method::Invite).await; + answer(&call, &invite).await; + entered(&store).await; + store.fail.store(true, Ordering::SeqCst); + store.release.cancel(); + assert!(tokio::time::timeout(Duration::from_secs(1), &mut call.task) + .await + .unwrap() + .unwrap() + .is_err()); + silent(&call.peer).await; + answer(&call, &invite).await; + silent(&call.peer).await; + assert!(call.facts.try_recv().is_err()); + Ok(()) +} + +#[tokio::test] +async fn persistence_failed_bye_response_is_not_cached_for_retransmit() -> crate::Result<()> { + let store = Storage::new(Gate::ByeResponse); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + let invite = established(&mut call).await; + let bye = send_bye(&call, &invite, 2).await; + entered(&store).await; + silent(&call.peer).await; + store.fail.store(true, Ordering::SeqCst); + store.release.cancel(); + tokio::time::timeout(Duration::from_secs(1), async { + while call.dialog.persistence_status().unwrap().failure.is_none() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + call.peer.send_to(&bye, call.local).await?; + silent(&call.peer).await; + Ok(()) +} + +#[tokio::test] +async fn persistence_concurrent_requests_commit_reserved_cseq_before_send() -> crate::Result<()> { + let store = Storage::new(Gate::Info); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + established(&mut call).await; + let first = call.dialog.clone(); + let second = call.dialog.clone(); + let a = tokio::spawn(async move { first.info(None, None).await }); + let b = tokio::spawn(async move { second.info(None, None).await }); + entered(&store).await; + silent(&call.peer).await; + store.release.cancel(); + let one = request(&call.peer, Method::Info).await; + let two = request(&call.peer, Method::Info).await; + assert_ne!(one.cseq_header()?.seq()?, two.cseq_header()?.seq()?); + for req in [one, two] { + let seq = req.cseq_header()?.seq()?; + assert!(store.committed.lock().unwrap().iter().any(|c| c.reason == Reason::OutgoingRequest + && c.snapshot.local_cseq >= seq && matches!(&c.message, Some(SipMessage::Request(r)) if r.cseq_header().unwrap().seq().unwrap() == seq))); + call.peer + .send_to(response(&req, "sip:bob@example.com").as_bytes(), call.local) + .await?; + } + tokio::time::timeout(Duration::from_secs(1), a) + .await + .unwrap() + .unwrap()?; + tokio::time::timeout(Duration::from_secs(1), b) + .await + .unwrap() + .unwrap()?; + assert_eq!(store.max_active.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[tokio::test] +async fn persistence_worker_releases_dialog_and_handler_after_teardown() -> crate::Result<()> { + use crate::dialog::dialog::DialogInner; + use crate::dialog::DialogId; + use crate::transaction::key::TransactionRole; + // Isolate worker ownership from the INVITE Accepted transaction's Timer M. + // That transaction intentionally retains its dialog to clean up forked 2xx. + let store = Storage::new(Gate::Never); + let req = super::test_dialog_states::create_invite_request("alice", "bob", "worker"); + let (states, _) = unbounded_channel(); + let (transactions, _) = unbounded_channel(); + let dialog = Arc::new(DialogInner::new( + TransactionRole::Client, + DialogId::try_from((&req, TransactionRole::Client))?, + req, + EndpointBuilder::new().build().inner, + states, + None, + None, + transactions, + )?); + dialog.configure_persistence(Some(store.config(Duration::from_secs(1)))); + dialog.checkpoint(Reason::SignalingCompleted, None).await?; + let weak = Arc::downgrade(&dialog); + drop(dialog); + tokio::time::timeout(Duration::from_secs(1), async { + while weak.upgrade().is_some() || Arc::strong_count(&store) != 1 { + tokio::task::yield_now().await; + } + }) + .await + .expect("persistence worker retained a dialog or storage handler"); + Ok(()) +} + +#[tokio::test] +async fn persistence_uas_saves_before_200_and_after_ack() -> crate::Result<()> { + let stop = CancellationToken::new(); + let (dialog, mut tx, _states, peer) = + super::test_accept_before_handle::incoming_invite(&stop).await?; + let store = Storage::new(Gate::UasResponse); + dialog + .inner + .configure_persistence(Some(store.config(Duration::from_secs(2)))); + let (sender, mut facts) = dialog_lifecycle_channel(); + dialog.inner.lifecycle.lock().sender = Some(sender); + let invite = tx.original.clone(); + let destination = crate::transport::SipAddr::try_from(&invite.uri)?.get_socketaddr()?; + dialog.accept(None, None)?; + let mut handler = dialog.clone(); + let task = tokio::spawn(async move { handler.handle(&mut tx).await }); + entered(&store).await; + silent(&peer).await; + assert!(facts.try_recv().is_err()); + store.release.cancel(); + let SipMessage::Response(response) = receive(&peer).await else { + panic!("expected 200") + }; + assert_eq!(response.status_code, StatusCode::OK); + let event = tokio::time::timeout(Duration::from_secs(1), facts.recv()) + .await + .unwrap() + .unwrap(); + assert!(matches!( + event.kind, + DialogLifecycleKind::InviteAccepted { .. } + )); + let ack = format!("ACK {} SIP/2.0\r\nVia: SIP/2.0/UDP {};branch=z9hG4bK-ack\r\nFrom: {}\r\nTo: {}\r\nCall-ID: {}\r\nCSeq: 1 ACK\r\nMax-Forwards: 70\r\nContent-Length: 0\r\n\r\n", + invite.uri, peer.local_addr()?, response.from_header()?.value(), response.to_header()?.value(), response.call_id_header()?.value()); + peer.send_to(ack.as_bytes(), destination).await?; + tokio::time::timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap()?; + let committed = store.committed.lock().unwrap(); + assert!(committed.last().unwrap().snapshot.is_quiescent()); + assert_eq!( + committed.last().unwrap().snapshot.runtime.lifecycle.len(), + 1 + ); + assert!(committed + .iter() + .any(|c| c.reason == Reason::BeforeResponse && !c.snapshot.is_quiescent())); + stop.cancel(); + Ok(()) +} + +#[tokio::test] +async fn persistence_uas_failed_write_never_sends_or_caches_200() -> crate::Result<()> { + let stop = CancellationToken::new(); + let (dialog, mut tx, _states, peer) = + super::test_accept_before_handle::incoming_invite(&stop).await?; + let store = Storage::new(Gate::UasResponse); + dialog + .inner + .configure_persistence(Some(store.config(Duration::from_secs(2)))); + dialog.accept(None, None)?; + let mut handler = dialog.clone(); + let task = tokio::spawn(async move { + let result = handler.handle(&mut tx).await; + (result, tx.last_response.take()) + }); + entered(&store).await; + store.fail.store(true, Ordering::SeqCst); + store.release.cancel(); + let (result, last_response) = tokio::time::timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap(); + assert!(result.is_err()); + assert!(last_response.is_none()); + silent(&peer).await; + assert!(dialog.snapshot().runtime.lifecycle.is_empty()); + stop.cancel(); + Ok(()) +} + +#[tokio::test] +async fn persistence_request_is_not_sent_if_peer_ends_during_commit() -> crate::Result<()> { + let store = Storage::new(Gate::Info); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + let invite = established(&mut call).await; + let dialog = call.dialog.clone(); + let task = tokio::spawn(async move { dialog.info(None, None).await }); + entered(&store).await; + send_bye(&call, &invite, 2).await; + tokio::time::timeout(Duration::from_secs(1), async { + while !call.dialog.state().is_terminated() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + store.release.cancel(); + assert!(tokio::time::timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap() + .is_err()); + let SipMessage::Response(response) = receive(&call.peer).await else { + panic!("expected BYE response") + }; + assert_eq!(response.status_code, StatusCode::OK); + assert_eq!(response.cseq_header()?.method()?, Method::Bye); + silent(&call.peer).await; + Ok(()) +} diff --git a/src/transaction/transaction.rs b/src/transaction/transaction.rs index dfd46ead..ccb03635 100644 --- a/src/transaction/transaction.rs +++ b/src/transaction/transaction.rs @@ -188,6 +188,8 @@ pub struct Transaction { pub timer_g: Option, // server invite only (non-2xx final response retransmits per RFC 6026 §7.1) pub timer_l: Option, // server invite only (Accepted-state 64*T1 per RFC 6026 §7.1) pub timer_m: Option, // client invite only (Accepted-state 64*T1 per RFC 6026 §7.2) + pub(crate) persistence_dialog: Mutex>, + persistence_sent: bool, pub(crate) original_received_at: Option, receipt_times: Option>, last_received_at: Option, @@ -233,6 +235,8 @@ impl Transaction { timer_d: None, timer_k: None, timer_g: None, + persistence_dialog: Mutex::new(alloc::sync::Weak::new()), + persistence_sent: false, original_received_at: None, receipt_times: None, last_received_at: None, @@ -250,6 +254,19 @@ impl Transaction { tx } + pub(crate) fn check_persistence(&self) -> Result<()> { + let dialog = self.persistence_dialog.lock().upgrade(); + if let Some(dialog) = dialog { + let runtime = dialog.persistence.lock().clone(); + if let Some(runtime) = runtime { + if let Some(error) = runtime.status.lock().failure.clone() { + return Err(Error::Error(error)); + } + } + } + Ok(()) + } + pub(crate) fn track_receipt_times(&mut self, enabled: bool) { if enabled && self.receipt_times.is_none() { let receipts = Arc::new(super::receipt::ReceiptTimes::default()); @@ -306,6 +323,30 @@ impl Transaction { } // send client request pub async fn send(&mut self) -> Result<()> { + self.check_persistence()?; + if !self.persistence_sent { + let dialog = self.persistence_dialog.lock().upgrade(); + if let Some(dialog) = dialog { + dialog + .checkpoint( + crate::dialog::persistence::DialogCheckpointReason::OutgoingRequest, + Some(self.original.clone().into()), + ) + .await?; + if dialog.is_terminated() + && !matches!( + self.original.method, + Method::Bye | Method::Cancel | Method::Ack + ) + && self.original.to_header()?.tag()?.is_some() + { + return Err(Error::Error( + "dialog terminated while saving request".into(), + )); + } + } + self.persistence_sent = true; + } match self.transaction_type { TransactionType::ClientInvite | TransactionType::ClientNonInvite => {} _ => { @@ -500,6 +541,7 @@ impl Transaction { /// is acceptable. Prefer the `TransactionEvent::Respond` channel for /// cancellation-aware integration. pub async fn respond(&mut self, response: Response) -> Result<()> { + self.check_persistence()?; match self.transaction_type { TransactionType::ServerInvite | TransactionType::ServerNonInvite => {} _ => { @@ -550,6 +592,17 @@ impl Transaction { } else { response.to_owned().into() }; + if new_state != TransactionState::Trying && new_state != TransactionState::Proceeding { + let dialog = self.persistence_dialog.lock().upgrade(); + if let Some(dialog) = dialog { + dialog + .checkpoint( + crate::dialog::persistence::DialogCheckpointReason::BeforeResponse, + Some(response.clone()), + ) + .await?; + } + } trace!(key = %self.key, response = %response, "responding"); match response.clone() { @@ -598,7 +651,23 @@ impl Transaction { } } guard.0 = None; - self.transition(new_state).map(|_| ()) + let final_response = !matches!( + new_state, + TransactionState::Trying | TransactionState::Proceeding + ); + self.transition(new_state)?; + if final_response { + let dialog = self.persistence_dialog.lock().upgrade(); + if let Some(dialog) = dialog { + dialog + .checkpoint( + crate::dialog::persistence::DialogCheckpointReason::SignalingCompleted, + None, + ) + .await?; + } + } + Ok(()) } fn add_ack_cseq_route(&self, dialog_id: &DialogId) -> Option<(DialogId, u32)> { @@ -713,6 +782,7 @@ impl Transaction { /// inappropriate retransmits. Do not place inside `tokio::select!` /// unless this hazard is acceptable. pub async fn send_ack(&mut self, mut connection: Option) -> Result<()> { + self.check_persistence()?; if self.transaction_type != TransactionType::ClientInvite { return Err(Error::TransactionError( "send_ack is only valid for client invite transactions".to_string(), @@ -804,6 +874,7 @@ impl Transaction { ack.to_owned().into() }; + self.check_persistence()?; match ack.clone() { SipMessage::Request(ref ack_req) => self.last_ack.replace(ack_req.clone()), _ => None, @@ -889,10 +960,16 @@ impl Transaction { &mut self, mut observer: impl FnMut(&Response, crate::dialog::lifecycle::LifecycleTime) + Send, ) -> Option { + if self.check_persistence().is_err() { + return None; + } while let Some(event) = self.tu_receiver.recv().await { if let Some(result) = self.dispatch_event_observed(event, &mut observer).await { return result; } + if self.check_persistence().is_err() { + return None; + } } None } @@ -1301,6 +1378,23 @@ impl Transaction { self.last_received_at .unwrap_or_else(crate::dialog::lifecycle::LifecycleTime::now), ); + let dialog = self.persistence_dialog.lock().upgrade(); + if let Some(dialog) = dialog { + if resp.status_code.kind() == StatusCodeKind::Successful + && self.original.method == Method::Invite + { + if let Err(error) = dialog + .checkpoint( + crate::dialog::persistence::DialogCheckpointReason::BeforeAck, + Some(resp.clone().into()), + ) + .await + { + tracing::warn!(%error, "INVITE checkpoint failed before ACK"); + return None; + } + } + } if auto_ack_client_invite { if let Err(e) = self.send_ack(connection).await { warn!( @@ -1323,6 +1417,7 @@ impl Transaction { key: &TransactionKey, duration: &Duration, ) -> Result<()> { + self.check_persistence()?; if let Some(last_response) = &self.last_response { if let Some(connection) = &self.connection { let last_response = @@ -1347,6 +1442,7 @@ impl Transaction { } async fn on_timer(&mut self, timer: TransactionTimer) -> Result<()> { + self.check_persistence()?; match self.state { TransactionState::Calling | TransactionState::Trying | TransactionState::Proceeding if self.state != TransactionState::Proceeding diff --git a/tests/interop/README.md b/tests/interop/README.md index 9cbd3443..eb540ab7 100644 --- a/tests/interop/README.md +++ b/tests/interop/README.md @@ -51,6 +51,17 @@ PJSUA_BIN=/absolute/path/to/pjsua SIPP_BIN=/absolute/path/to/sipp \ ``` The binaries must support the flags and CLI used by the pinned versions below. + +To exercise the opt-in dialog persistence barriers against the same peers: + +```sh +RSIPSTACK_INTEROP_CHECKPOINTS=1 bash scripts/interop/run.sh regression +``` + +Each scenario writes `checkpoints.log`; the test handler syncs each checkpoint +to disk before acknowledging it and rejects backwards revisions. This is a +test journal, not a production storage format. The regular library tests cover +blocked writes, failures, timeouts, concurrent BYE, and lifecycle delivery. To prepare peers without running the suite, use `bash scripts/interop/build-pjsua.sh` and `bash scripts/interop/build-sipp.sh`. Set `JOBS=2` to limit build concurrency. With Rust dependencies and peers already cached, `CARGO_NET_OFFLINE=true bash diff --git a/tests/interop/checkpoints.rs b/tests/interop/checkpoints.rs new file mode 100644 index 00000000..a81e3af0 --- /dev/null +++ b/tests/interop/checkpoints.rs @@ -0,0 +1,53 @@ +//! Optional real-file persistence for the existing external-peer scenarios. +use super::*; +use rsipstack::dialog::persistence::{ + DialogCheckpoint, DialogPersistence, DialogPersistenceConfig, +}; +use std::collections::BTreeMap; + +struct Journal { + file: File, + revisions: BTreeMap, +} + +struct Storage(Mutex); + +#[async_trait::async_trait] +impl DialogPersistence for Storage { + async fn save(&self, checkpoint: DialogCheckpoint) -> rsipstack::Result<()> { + // These tiny loopback fixtures deliberately use a synchronous file. + // Production handlers should use async storage or a blocking executor. + let mut journal = self.0.lock().unwrap_or_else(|p| p.into_inner()); + let id = checkpoint.snapshot.id.to_string(); + let revision = checkpoint.snapshot.runtime.revision; + if journal + .revisions + .get(&id) + .is_some_and(|previous| *previous > revision) + { + return Err(rsipstack::Error::Error( + "checkpoint revision moved backwards".into(), + )); + } + writeln!(journal.file, "{checkpoint:?}")?; + journal.file.sync_all()?; + journal.revisions.insert(id, revision); + Ok(()) + } +} + +pub(super) fn configure(layer: &DialogLayer, dir: &Path) -> TestResult { + if std::env::var_os("RSIPSTACK_INTEROP_CHECKPOINTS").as_deref() + == Some(std::ffi::OsStr::new("1")) + { + layer + .set_persistence(Some(DialogPersistenceConfig::new(Arc::new(Storage( + Mutex::new(Journal { + file: File::create(dir.join("checkpoints.log")).required()?, + revisions: BTreeMap::new(), + }), + ))))) + .required()?; + } + Ok(()) +} diff --git a/tests/interop/mod.rs b/tests/interop/mod.rs index 8d303085..8e80be5b 100644 --- a/tests/interop/mod.rs +++ b/tests/interop/mod.rs @@ -4,6 +4,7 @@ mod failure; pub use failure::{Failure, Required, TestResult}; mod applications; mod b2bua; +mod checkpoints; mod faults; mod pjsip; mod proxy; @@ -513,6 +514,7 @@ impl Stack { .with_transport_inspector(Box::new(Received(inspector))) .build(); let layer = Arc::new(DialogLayer::new(endpoint.inner.clone())); + checkpoints::configure(&layer, dir)?; let mut transactions = endpoint.incoming_transactions().required()?; tasks.push(errors.spawn("endpoint serve", async move { endpoint.inner.serve().await.required() From 580189e570c1684ab57847782046831d8da76aab Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Fri, 6 Nov 2026 10:15:46 +0000 Subject: [PATCH 5/8] test(dialog): cover checkpoints with controlled re-INVITEs Verify that incoming re-INVITE responses wait for storage and that ACK completion produces a quiescent checkpoint. Exercise successful and failed commits before a deferred outgoing ACK handler. Clarify that the interop checkpoint switch configures in-process dialog peers, not the standalone proxy and B2BUA applications. --- src/dialog/tests/test_persistence.rs | 165 +++++++++++++++++++++++++++ tests/interop/README.md | 10 +- 2 files changed, 171 insertions(+), 4 deletions(-) diff --git a/src/dialog/tests/test_persistence.rs b/src/dialog/tests/test_persistence.rs index 14d19952..8d907c99 100644 --- a/src/dialog/tests/test_persistence.rs +++ b/src/dialog/tests/test_persistence.rs @@ -29,6 +29,7 @@ enum Gate { Never, InitialRequest, Answer, + ReinviteAnswer, ByeResponse, UasResponse, Info, @@ -68,6 +69,9 @@ impl Storage { && matches!(&c.message, Some(SipMessage::Request(r)) if r.method == Method::Invite) } Gate::Answer => c.reason == Reason::BeforeAck, + Gate::ReinviteAnswer => { + c.reason == Reason::BeforeAck && c.snapshot.runtime.pending.negotiations != 0 + } Gate::ByeResponse => { c.reason == Reason::BeforeResponse && matches!(&c.message, Some(SipMessage::Response(r)) if r.cseq_header().unwrap().method().unwrap() == Method::Bye) @@ -628,3 +632,164 @@ async fn persistence_request_is_not_sent_if_peer_ends_during_commit() -> crate:: silent(&call.peer).await; Ok(()) } + +#[tokio::test] +async fn persistence_incoming_reinvite_saves_response_and_ack_completion() -> crate::Result<()> { + use crate::dialog::dialog::DialogState; + let store = Storage::new(Gate::UasResponse); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + let initial = established(&mut call).await; + store.committed.lock().unwrap().clear(); + let remote = call.peer.local_addr()?; + let invite = Request::try_from(format!( + "INVITE sip:alice@{} SIP/2.0\r\nVia: SIP/2.0/UDP {remote};branch=z9hG4bK-persist-reinvite\r\nFrom: ;tag=peer\r\nTo: {}\r\nCall-ID: {}\r\nCSeq: 10 INVITE\r\nContact: \r\nMax-Forwards: 70\r\nContent-Length: 0\r\n\r\n", + call.local, initial.from_header()?.value(), initial.call_id_header()?.value() + ).as_str())?; + call.peer + .send_to(invite.to_string().as_bytes(), call.local) + .await?; + let handle = tokio::time::timeout(Duration::from_secs(2), async { + while let Some(state) = call._states.recv().await { + if let DialogState::Updated(_, _, handle) = state { + return handle; + } + } + panic!("missing re-INVITE handle"); + }) + .await + .unwrap(); + handle.respond(StatusCode::OK, None, None).await?; + entered(&store).await; + let pending_revision = { + let attempts = store.attempts.lock().unwrap(); + let before = attempts.last().unwrap(); + assert_eq!(before.reason, Reason::BeforeResponse); + assert_eq!(before.snapshot.runtime.pending.negotiations, 1); + assert!(!before.snapshot.is_quiescent()); + before.snapshot.runtime.revision + }; + silent(&call.peer).await; + store.release.cancel(); + let SipMessage::Response(response) = receive(&call.peer).await else { + panic!("expected re-INVITE response"); + }; + assert_eq!(response.status_code, StatusCode::OK); + assert_eq!(response.cseq_header()?.seq()?, 10); + let mut ack = invite; + ack.method = Method::Ack; + ack.cseq_header_mut()?.mut_method(Method::Ack)?; + call.peer + .send_to(ack.to_string().as_bytes(), call.local) + .await?; + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let completed = store.committed.lock().unwrap().iter().any(|checkpoint| { + checkpoint.reason == Reason::SignalingCompleted + && checkpoint.snapshot.is_quiescent() + && checkpoint.snapshot.runtime.revision > pending_revision + }); + if completed { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("matching ACK must produce a quiescent checkpoint"); + assert!(call.dialog.snapshot().is_quiescent()); + Ok(()) +} + +#[tokio::test] +async fn persistence_reinvite_commit_precedes_deferred_ack_handler() -> crate::Result<()> { + use crate::dialog::reinvite::{AckBody, InviteAnswerHandler, ReinviteOptions}; + use crate::sip::{Header, Response}; + struct DeferredAnswer { + entered: CancellationToken, + release: CancellationToken, + } + const SDP: &[u8] = b"v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nc=IN IP4 127.0.0.1\r\nt=0 0\r\nm=audio 10000 RTP/AVP 0\r\n"; + #[async_trait] + impl InviteAnswerHandler for DeferredAnswer { + async fn answer(&self, _: Response) -> crate::Result { + self.entered.cancel(); + self.release.cancelled().await; + Ok(AckBody::sdp(SDP.to_vec())) + } + fn fallback_answer(&self, _: &Response) -> AckBody { + AckBody::sdp(SDP.to_vec()) + } + } + for fail in [false, true] { + let store = Storage::new(Gate::ReinviteAnswer); + let mut call = start(store.clone(), Duration::from_secs(2)).await?; + established(&mut call).await; + store.committed.lock().unwrap().clear(); + let handler = Arc::new(DeferredAnswer { + entered: CancellationToken::new(), + release: CancellationToken::new(), + }); + let options = ReinviteOptions { + answer_handler: Some(handler.clone()), + ..Default::default() + }; + let dialog = call.dialog.clone(); + let invite = dialog.prepare_reinvite(None, None)?; + let sender = tokio::spawn(async move { dialog.send_reinvite(invite, options).await }); + let invite = request(&call.peer, Method::Invite).await; + let mut success = Response::try_from( + response(&invite, &format!("sip:bob@{}", call.peer.local_addr()?)).as_str(), + )?; + success.body = SDP.to_vec(); + success + .headers + .unique_push(Header::ContentType("application/sdp".into())); + success + .headers + .unique_push(Header::ContentLength((SDP.len() as u32).into())); + call.peer + .send_to(success.to_string().as_bytes(), call.local) + .await?; + entered(&store).await; + assert!( + !handler.entered.is_cancelled(), + "answer handler ran before storage committed" + ); + assert!(!call.dialog.snapshot().is_quiescent()); + silent(&call.peer).await; + store.fail.store(fail, Ordering::SeqCst); + store.release.cancel(); + if fail { + assert!(tokio::time::timeout(Duration::from_secs(2), sender) + .await + .unwrap() + .unwrap() + .is_err()); + assert!(!handler.entered.is_cancelled()); + assert!(call.dialog.persistence_status().unwrap().failure.is_some()); + silent(&call.peer).await; + } else { + tokio::time::timeout(Duration::from_secs(2), handler.entered.cancelled()) + .await + .unwrap(); + silent(&call.peer).await; + handler.release.cancel(); + let ack = request(&call.peer, Method::Ack).await; + assert_eq!(ack.body, SDP); + assert_eq!( + tokio::time::timeout(Duration::from_secs(2), sender) + .await + .unwrap() + .unwrap()? + .unwrap() + .status_code, + StatusCode::OK + ); + assert!(store.committed.lock().unwrap().iter().any(|checkpoint| { + checkpoint.reason == Reason::SignalingCompleted + && checkpoint.snapshot.is_quiescent() + })); + } + } + Ok(()) +} diff --git a/tests/interop/README.md b/tests/interop/README.md index eb540ab7..38dc4c38 100644 --- a/tests/interop/README.md +++ b/tests/interop/README.md @@ -58,10 +58,12 @@ To exercise the opt-in dialog persistence barriers against the same peers: RSIPSTACK_INTEROP_CHECKPOINTS=1 bash scripts/interop/run.sh regression ``` -Each scenario writes `checkpoints.log`; the test handler syncs each checkpoint -to disk before acknowledging it and rejects backwards revisions. This is a -test journal, not a production storage format. The regular library tests cover -blocked writes, failures, timeouts, concurrent BYE, and lifecycle delivery. +In-process dialog-peer scenarios write `checkpoints.log`; the test handler syncs +each checkpoint to disk before acknowledging it and rejects backwards revisions. +The standalone proxy/B2BUA applications use their own dialog layers and are not +configured by this switch. This is a test journal, not a production storage +format. The regular library tests cover blocked writes, failures, timeouts, +concurrent BYE, lifecycle delivery, and application-controlled re-INVITEs. To prepare peers without running the suite, use `bash scripts/interop/build-pjsua.sh` and `bash scripts/interop/build-sipp.sh`. Set `JOBS=2` to limit build concurrency. With Rust dependencies and peers already cached, `CARGO_NET_OFFLINE=true bash From 84fa9064977a4d3b452e55d89c4e13e9c14fb80b Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Fri, 6 Nov 2026 10:21:52 +0000 Subject: [PATCH 6/8] test(interop): wait for callee ACK before exercising BYE loss The caller can report CONFIRMED before the proxy forwards ACK. Wait for a SIPp receive marker before requesting hangup, so this scenario tests retransmission of BYE instead of racing it with the initial ACK. --- tests/interop/applications.rs | 5 ++++- tests/interop/scenarios/application_lost_bye_response.xml | 1 + tests/interop/sipp.rs | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/interop/applications.rs b/tests/interop/applications.rs index 71c34b25..3e1c2f4d 100644 --- a/tests/interop/applications.rs +++ b/tests/interop/applications.rs @@ -500,7 +500,7 @@ pub async fn lost_bye_response(mode: &str, name: &str) -> TestResult { std::fs::create_dir_all(dir.join(peer)).required()?; } let unused: Uri = "sip:unused@127.0.0.1:9".parse().required()?; - let callee = super::sipp::Sipp::start( + let mut callee = super::sipp::Sipp::start( "application_lost_bye_response", "udp", &dir.join("callee"), @@ -511,6 +511,9 @@ pub async fn lost_bye_response(mode: &str, name: &str) -> TestResult { let mut caller = Peer::start("udp", &dir.join("caller")).await?; caller.command(&format!("m\n{}\n", app.uri)).await?; caller.wait_text("state changed to CONFIRMED").await?; + // CONFIRMED at the caller does not prove that the callee received ACK. + // Independent proxy tasks can forward BYE first if hangup starts now. + callee.marker("APPLICATION_ACK_RECEIVED").await?; caller.command("h\n").await?; callee.finish().await?; caller.wait_text("Response msg 200/BYE").await?; diff --git a/tests/interop/scenarios/application_lost_bye_response.xml b/tests/interop/scenarios/application_lost_bye_response.xml index 016a8000..685ae94b 100644 --- a/tests/interop/scenarios/application_lost_bye_response.xml +++ b/tests/interop/scenarios/application_lost_bye_response.xml @@ -43,6 +43,7 @@ a=rtpmap:0 PCMU/8000 a=inactive ]]> + diff --git a/tests/interop/sipp.rs b/tests/interop/sipp.rs index e0bc6606..974bc8cc 100644 --- a/tests/interop/sipp.rs +++ b/tests/interop/sipp.rs @@ -162,7 +162,7 @@ impl Sipp { message } - async fn marker(&mut self, marker: &str) -> TestResult { + pub(super) async fn marker(&mut self, marker: &str) -> TestResult { until_result(marker, || { let text = match std::fs::read_to_string(&self.log) { Ok(text) => text, From 3a77a7f6cd4a9e4eefe36174d16e3dade6ee0cd7 Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:47:00 +0000 Subject: [PATCH 7/8] fix(dialog): persist final responses and refreshed targets before ACK --- CHANGELOG.md | 5 + src/dialog/dialog.rs | 44 +++++ src/dialog/persistence.rs | 6 +- src/transaction/transaction.rs | 7 +- tests/dialog_checkpoint_boundaries.rs | 230 ++++++++++++++++++++++++++ 5 files changed, 285 insertions(+), 7 deletions(-) create mode 100644 tests/dialog_checkpoint_boundaries.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 09005d6e..429c6c18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased — proposed 0.9.0 +- Opt-in persistence now saves every INVITE final response before its ACK, + including rejection and authentication challenges. A successful re-INVITE + checkpoint contains the accepted Contact and the observed response in one + coherent snapshot boundary. Failed writes continue to block protected sends. + - **Breaking (requires maintainer approval for 0.9.0):** `DialogSnapshot` adds coherent `runtime` metadata and becomes `#[non_exhaustive]`. External callers must use `DialogSnapshot::builder(...)` and include `..` in destructuring diff --git a/src/dialog/dialog.rs b/src/dialog/dialog.rs index c1aed319..eeb78fb2 100644 --- a/src/dialog/dialog.rs +++ b/src/dialog/dialog.rs @@ -956,6 +956,50 @@ impl DialogInner { })) } + /// Preserve the observed final response and its accepted target together. + /// Initial INVITE confirmation is installed by its response observer; + /// a re-INVITE may refresh only its own established dialog, not another fork. + #[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))] + pub(crate) async fn checkpoint_invite_response( + &self, + request: &Request, + response: &Response, + ) -> Result<()> { + let in_dialog = request + .to_header()? + .tag()? + .is_some_and(|tag| !tag.value().is_empty()); + let target = if in_dialog + && response.status_code.kind() == StatusCodeKind::Successful + && DialogId::try_from((response, TransactionRole::Client)) + .is_ok_and(|id| id == *self.id.lock()) + && response.cseq_header()?.seq()? == request.cseq_header()?.seq()? + { + Self::parse_target_refresh_contact(response)? + } else { + None + }; + let receiver = { + let state = self.state.lock(); + if let Some(target) = target { + self.set_remote_target_locked(target.uri, Some(target.contact)); + } + self.enqueue_checkpoint_locked( + &state, + super::persistence::DialogCheckpointReason::BeforeAck, + Some(response.clone().into()), + ) + }; + if let Some(mut receiver) = receiver { + receiver + .recv() + .await + .unwrap_or_else(|| Err("dialog persistence worker stopped".into())) + .map_err(crate::Error::Error)?; + } + Ok(()) + } + fn refresh_target_from_response(&self, response: &Response) -> Result<()> { if let Some(target) = Self::parse_target_refresh_contact(response)? { self.set_remote_target(target.uri, Some(target.contact)); diff --git a/src/dialog/persistence.rs b/src/dialog/persistence.rs index 55c42528..48853b8a 100644 --- a/src/dialog/persistence.rs +++ b/src/dialog/persistence.rs @@ -75,8 +75,10 @@ pub enum DialogCheckpointReason { LocalTerminationRequested, /// Before sending a final response to an incoming request. BeforeResponse, - /// A successful INVITE response was received; before its automatic ACK. - /// Includes re-INVITEs and fork cleanup; lifecycle facts identify initial acceptance. + /// An INVITE final response was received; before its automatic ACK. + /// Includes failures/challenges, re-INVITEs, and fork cleanup. A successful + /// re-INVITE's snapshot already contains its accepted Contact. The message + /// preserves the observed response; lifecycle facts identify initial acceptance. BeforeAck, /// A completed ACK/negotiation permits future quiescent restoration. SignalingCompleted, diff --git a/src/transaction/transaction.rs b/src/transaction/transaction.rs index ccb03635..bbb6ad17 100644 --- a/src/transaction/transaction.rs +++ b/src/transaction/transaction.rs @@ -1380,14 +1380,11 @@ impl Transaction { ); let dialog = self.persistence_dialog.lock().upgrade(); if let Some(dialog) = dialog { - if resp.status_code.kind() == StatusCodeKind::Successful + if resp.status_code.kind() != StatusCodeKind::Provisional && self.original.method == Method::Invite { if let Err(error) = dialog - .checkpoint( - crate::dialog::persistence::DialogCheckpointReason::BeforeAck, - Some(resp.clone().into()), - ) + .checkpoint_invite_response(&self.original, &resp) .await { tracing::warn!(%error, "INVITE checkpoint failed before ACK"); diff --git a/tests/dialog_checkpoint_boundaries.rs b/tests/dialog_checkpoint_boundaries.rs new file mode 100644 index 00000000..0069deec --- /dev/null +++ b/tests/dialog_checkpoint_boundaries.rs @@ -0,0 +1,230 @@ +//! Public storage hooks must observe final responses and refreshed targets before ACK. +use rsipstack::{ + dialog::{ + dialog::{Dialog, DialogSnapshot, DialogSnapshotState}, + dialog_layer::DialogLayer, + invitation::InviteOption, + invite_dialog::InviteDialog, + persistence::{ + DialogCheckpoint, DialogCheckpointReason, DialogPersistence, DialogPersistenceConfig, + }, + reinvite::ReinviteOptions, + DialogId, + }, + sip::{Header, HeadersExt, Method, Request, SipMessage, StatusCode, ToTypedHeader}, + transaction::key::TransactionRole, + transaction::EndpointBuilder, + transport::{udp::UdpConnection, TransportLayer}, +}; +use std::{sync::Arc, time::Duration}; +use tokio::{net::UdpSocket, sync::mpsc}; +use tokio_util::sync::CancellationToken; +type Result = std::result::Result>; +const WAIT: Duration = Duration::from_secs(2); + +struct Storage { + checkpoints: mpsc::UnboundedSender, + release: CancellationToken, + fail: bool, +} +#[async_trait::async_trait] +impl DialogPersistence for Storage { + async fn save(&self, checkpoint: DialogCheckpoint) -> rsipstack::Result<()> { + let wait = checkpoint.reason == DialogCheckpointReason::BeforeAck; + self.checkpoints.send(checkpoint).ok(); + if wait { + self.release.cancelled().await; + if self.fail { + return Err(rsipstack::Error::Error("injected write failure".into())); + } + } + Ok(()) + } +} +struct Stop(CancellationToken); +impl Drop for Stop { + fn drop(&mut self) { + self.0.cancel(); + } +} + +async fn boundary(role: Option, status: StatusCode, fail: bool) -> Result<()> { + let stop = Stop(CancellationToken::new()); + let transport = TransportLayer::new(stop.0.clone()); + let udp = UdpConnection::create_connection("127.0.0.1:0".parse()?, None, Some(stop.0.clone())) + .await?; + let local = udp.get_addr().get_socketaddr()?; + transport.add_transport(udp.into()); + let endpoint = Arc::new( + EndpointBuilder::new() + .with_transport_layer(transport) + .with_cancel_token(stop.0.clone()) + .build(), + ); + let layer = Arc::new(DialogLayer::new(endpoint.inner.clone())); + let (sender, mut checkpoints) = mpsc::unbounded_channel(); + let storage = Arc::new(Storage { + checkpoints: sender, + release: CancellationToken::new(), + fail, + }); + layer.set_persistence(Some(DialogPersistenceConfig::new(storage.clone())))?; + let serving = endpoint.clone(); + tokio::spawn(async move { serving.serve().await }); + let peer = UdpSocket::bind("127.0.0.1:0").await?; + let refreshed = UdpSocket::bind("127.0.0.1:0").await?; + let target = format!("sip:peer@{}", peer.local_addr()?); + let new_target = format!("sip:refreshed@{}", refreshed.local_addr()?); + let (states, _events) = mpsc::unbounded_channel(); + let dialog: InviteDialog; + if let Some(role) = role { + let local_uri = format!(";tag=local"); + let remote_uri = format!("<{target}>;tag=remote"); + let (from, to) = if role == TransactionRole::Client { + (local_uri, remote_uri) + } else { + (remote_uri, local_uri) + }; + let snapshot = DialogSnapshot::builder( + DialogId { + call_id: "checkpoints".into(), + local_tag: "local".into(), + remote_tag: "remote".into(), + }, + role, + rsipstack::sip::From::from(from).typed()?, + rsipstack::sip::To::from(to).typed()?, + target.as_str().try_into()?, + ) + .state(DialogSnapshotState::Confirmed) + .local_cseq(1) + .remote_cseq(1) + .runtime(Default::default()) + .local_contact(Some(format!("sip:local@{local}").as_str().try_into()?)) + .remote_contact(Some(format!("<{target}>").into())) + .build()?; + let id = snapshot.id.clone(); + assert!(layer.restore_from_snapshot(snapshot, states)?); + let Some(Dialog::Invite(d)) = layer.get_dialog(&id) else { + panic!("missing restored dialog") + }; + dialog = d; + let request = dialog.prepare_reinvite(None, Some(b"v=0\r\n".to_vec()))?; + let operation = dialog.clone(); + tokio::spawn(async move { + operation + .send_reinvite(request, ReinviteOptions::default()) + .await + }); + } else { + let (d, _task) = layer.do_invite_async( + InviteOption { + caller: "sip:local@example.com".try_into()?, + callee: target.as_str().try_into()?, + contact: format!("sip:local@{local}").as_str().try_into()?, + ..Default::default() + }, + states, + )?; + dialog = d; + } + let mut bytes = [0; 8192]; + let (n, source) = tokio::time::timeout(WAIT, peer.recv_from(&mut bytes)).await??; + let invite: Request = SipMessage::try_from(&bytes[..n])?.try_into()?; + assert_eq!(invite.method, Method::Invite); + let mut response = endpoint.inner.make_response(&invite, status.clone(), None); + if role.is_none() { + response + .headers + .unique_push(Header::To(format!("<{target}>;tag=remote").into())); + } + response + .headers + .push(Header::Contact(format!("<{new_target}>").into())); + response.headers.push(Header::Reason( + "SIP;cause=488;text=\"response must be durable\"".into(), + )); + peer.send_to(response.to_string().as_bytes(), source) + .await?; + let checkpoint = tokio::time::timeout(WAIT, async { + loop { + let c = checkpoints.recv().await.expect("storage channel closed"); + if c.reason == DialogCheckpointReason::BeforeAck { + break c; + } + } + }) + .await?; + assert_eq!( + checkpoint.message, + Some(SipMessage::Response(response.clone())) + ); + if role.is_some() { + assert_eq!( + checkpoint.snapshot.remote_uri.to_string(), + if status == StatusCode::OK { + new_target.clone() + } else { + target.clone() + } + ); + assert!(checkpoint.snapshot.runtime.pending.negotiations > 0); + } + let ack_peer = if status == StatusCode::OK { + &refreshed + } else { + &peer + }; + assert!( + tokio::time::timeout(Duration::from_millis(40), ack_peer.recv_from(&mut bytes)) + .await + .is_err(), + "ACK escaped before commit" + ); + storage.release.cancel(); + if fail { + tokio::time::timeout(WAIT, async { + while dialog.persistence_status().unwrap().failure.is_none() { + tokio::task::yield_now().await; + } + }) + .await?; + assert!( + tokio::time::timeout(Duration::from_millis(80), ack_peer.recv_from(&mut bytes)) + .await + .is_err(), + "failed checkpoint still sent ACK" + ); + } else { + let (n, _) = tokio::time::timeout(WAIT, ack_peer.recv_from(&mut bytes)).await??; + let ack: Request = SipMessage::try_from(&bytes[..n])?.try_into()?; + assert_eq!(ack.method, Method::Ack); + assert_eq!(ack.cseq_header()?.seq()?, invite.cseq_header()?.seq()?); + } + Ok(()) +} +#[tokio::test] +async fn initial_rejection_is_committed_before_ack() -> Result<()> { + boundary(None, StatusCode::NotAcceptableHere, false).await +} +#[tokio::test] +async fn rejected_reinvite_keeps_previous_target_before_ack() -> Result<()> { + boundary( + Some(TransactionRole::Client), + StatusCode::NotAcceptableHere, + false, + ) + .await +} +#[tokio::test] +async fn uac_refresh_target_is_committed_before_ack() -> Result<()> { + boundary(Some(TransactionRole::Client), StatusCode::OK, false).await +} +#[tokio::test] +async fn uas_refresh_target_is_committed_before_ack() -> Result<()> { + boundary(Some(TransactionRole::Server), StatusCode::OK, false).await +} +#[tokio::test] +async fn failed_rejection_checkpoint_prevents_ack() -> Result<()> { + boundary(None, StatusCode::NotAcceptableHere, true).await +} From ef5dffcbf751b59a486b6ae22fccfdaa3c78082e Mon Sep 17 00:00:00 2001 From: Fedor Kiselev <116813641+FedorKiselev76@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:18:46 +0000 Subject: [PATCH 8/8] test(dialog): build registry and routing snapshots through the public API --- tests/dialog_registry_identity.rs | 27 ++++++++--------- tests/dialog_remote_cseq.rs | 25 +++++++--------- tests/dialog_routing.rs | 48 ++++++++++++++++--------------- 3 files changed, 48 insertions(+), 52 deletions(-) diff --git a/tests/dialog_registry_identity.rs b/tests/dialog_registry_identity.rs index 29c6efb3..0632a478 100644 --- a/tests/dialog_registry_identity.rs +++ b/tests/dialog_registry_identity.rs @@ -58,23 +58,20 @@ async fn incoming_request_matching_uses_all_identity_components() -> rsipstack:: } fn snapshot(id: DialogId) -> rsipstack::Result { - Ok(DialogSnapshot { - state: DialogSnapshotState::Confirmed, - role: TransactionRole::Client, - from: rsipstack::sip::From::from(format!(";tag={}", id.local_tag)) + DialogSnapshot::builder( + id.clone(), + TransactionRole::Client, + rsipstack::sip::From::from(format!(";tag={}", id.local_tag)) .typed()?, - to: rsipstack::sip::To::from(format!(";tag={}", id.remote_tag)) + rsipstack::sip::To::from(format!(";tag={}", id.remote_tag)) .typed()?, - id, - local_cseq: 1, - remote_cseq: 0, - local_contact: None, - remote_uri: "sip:remote@127.0.0.1:5060".try_into()?, - remote_contact: None, - route_set: vec![], - supports_100rel: false, - session_id: None, - }) + "sip:remote@127.0.0.1:5060".try_into()?, + ) + .state(DialogSnapshotState::Confirmed) + .local_cseq(1) + .remote_cseq(0) + .runtime(Default::default()) + .build() } #[tokio::test] diff --git a/tests/dialog_remote_cseq.rs b/tests/dialog_remote_cseq.rs index 746f83a8..fe6d1b15 100644 --- a/tests/dialog_remote_cseq.rs +++ b/tests/dialog_remote_cseq.rs @@ -30,21 +30,18 @@ async fn reject_stale(role: TransactionRole, legacy: bool) -> rsipstack::Result< } else { (remote, local) }; - let snapshot = DialogSnapshot { - id: id.clone(), + let snapshot = DialogSnapshot::builder( + id.clone(), role, - state: DialogSnapshotState::Confirmed, - from: rsipstack::sip::From::from(from).typed()?, - to: rsipstack::sip::To::from(to).typed()?, - local_cseq: 1, - remote_cseq: 10, - local_contact: None, - remote_uri: "sip:remote@127.0.0.1".try_into()?, - remote_contact: None, - route_set: vec![], - supports_100rel: false, - session_id: None, - }; + rsipstack::sip::From::from(from).typed()?, + rsipstack::sip::To::from(to).typed()?, + "sip:remote@127.0.0.1".try_into()?, + ) + .state(DialogSnapshotState::Confirmed) + .local_cseq(1) + .remote_cseq(10) + .runtime(Default::default()) + .build()?; let (states, mut events) = unbounded_channel(); assert!(layer.restore_from_snapshot(snapshot, states)?); let Some(Dialog::Invite(mut dialog)) = layer.get_dialog(&id) else { diff --git a/tests/dialog_routing.rs b/tests/dialog_routing.rs index 3c23c987..f2eda92b 100644 --- a/tests/dialog_routing.rs +++ b/tests/dialog_routing.rs @@ -77,34 +77,36 @@ impl Fixture { } else { (remote_from, local_from) }; - let snapshot = DialogSnapshot { - id: DialogId { + let snapshot = DialogSnapshot::builder( + DialogId { call_id: "route-contract".into(), local_tag: "local".into(), remote_tag: "remote".into(), }, role, - state: DialogSnapshotState::Confirmed, - from: rsipstack::sip::headers::From::from(from).typed()?, - to: rsipstack::sip::headers::To::from(to).typed()?, - remote_uri: target.clone(), - local_cseq: 1, - remote_cseq: 10, - local_contact: Some(Uri::try_from(format!("sip:caller@{address}").as_str())?), - remote_contact: Some(format!("<{target}>").into()), - route_set: vec![format!( - "<{proxy}{}>{}", - if strict { "" } else { ";lr" }, - if multiple { - ", ;x=keep" - } else { - "" - } - ) - .into()], - supports_100rel: false, - session_id: None, - }; + rsipstack::sip::From::from(from).typed()?, + rsipstack::sip::To::from(to).typed()?, + target.clone(), + ) + .state(DialogSnapshotState::Confirmed) + .local_cseq(1) + .remote_cseq(10) + .runtime(Default::default()) + .local_contact(Some(Uri::try_from( + format!("sip:caller@{address}").as_str(), + )?)) + .remote_contact(Some(format!("<{target}>").into())) + .route_set(vec![format!( + "<{proxy}{}>{}", + if strict { "" } else { ";lr" }, + if multiple { + ", ;x=keep" + } else { + "" + } + ) + .into()]) + .build()?; let (states, _receiver) = mpsc::unbounded_channel(); let id = snapshot.id.clone(); assert!(layer.restore_from_snapshot_with_credential(