From fd81d7155c6e0af799aaa398aee21028ce535924 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:53:30 -0600 Subject: [PATCH] telephony: confirm incoming answers remotely --- crates/lxst-core/src/telephony.rs | 110 +++++- crates/lxst-telephony/src/lib.rs | 365 +++++++++++++++++- crates/lxst-telephony/src/tests.rs | 250 +++++++++++- .../tests/python_telephone_live_interop.rs | 25 +- 4 files changed, 716 insertions(+), 34 deletions(-) diff --git a/crates/lxst-core/src/telephony.rs b/crates/lxst-core/src/telephony.rs index 261c7a5..5719a42 100644 --- a/crates/lxst-core/src/telephony.rs +++ b/crates/lxst-core/src/telephony.rs @@ -104,11 +104,34 @@ impl TelephonyCall { self.ensure_profile(&mut actions); self.push_status_signal(SignallingStatus::Connecting, &mut actions); actions.push(TelephonyAction::OpenAudioPipelines); - self.push_status_signal(SignallingStatus::Established, &mut actions); - actions.push(TelephonyAction::StartAudioPipelines); + // Python LXST sends ESTABLISHED as the final half of the answer offer, + // then the outgoing peer echoes ESTABLISHED while opening its own + // pipelines. Keep the incoming call in CONNECTING until that remote + // echo is observed: local queue admission alone is not proof that the + // caller received the answer. + actions.push(TelephonyAction::SendSignal(Signal::from( + SignallingStatus::Established, + ))); actions } + /// Re-send the wire-compatible answer offer without reopening pipelines + /// or changing local state. The service bounds these retries and stops as + /// soon as the outgoing peer's ESTABLISHED echo is observed. + pub fn retry_answer(&self) -> Vec { + if self.role != CallRole::Incoming + || !self.answered + || self.status != SignallingStatus::Connecting + { + return Vec::new(); + } + + vec![ + TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)), + TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), + ] + } + pub fn receive_signal(&mut self, signal: Signal) -> Vec { if self.role == CallRole::Incoming && !self.answered && matches!(signal, Signal::Status(_)) { @@ -126,10 +149,16 @@ impl TelephonyCall { vec![TelephonyAction::IgnoreSignal(signal)] } Signal::Status(SignallingStatus::Available) => { + if self.status.wire_value() >= SignallingStatus::Available.wire_value() { + return vec![TelephonyAction::IgnoreSignal(signal)]; + } self.status = SignallingStatus::Available; vec![TelephonyAction::IdentifyLocalIdentity] } Signal::Status(SignallingStatus::Ringing) => { + if self.status.wire_value() >= SignallingStatus::Ringing.wire_value() { + return vec![TelephonyAction::IgnoreSignal(signal)]; + } let mut actions = Vec::new(); self.status = SignallingStatus::Ringing; self.ensure_profile(&mut actions); @@ -141,13 +170,37 @@ impl TelephonyCall { actions } Signal::Status(SignallingStatus::Connecting) => { + if self.role == CallRole::Outgoing + && self.status.wire_value() >= SignallingStatus::Connecting.wire_value() + { + // A delayed/retried CONNECTING must not regress an already + // established call. Re-echo ESTABLISHED so an incoming + // peer can recover if its first acknowledgement was lost. + return vec![TelephonyAction::SendSignal(Signal::from( + SignallingStatus::Established, + ))]; + } + if self.status.wire_value() >= SignallingStatus::Connecting.wire_value() { + return vec![TelephonyAction::IgnoreSignal(signal)]; + } self.status = SignallingStatus::Connecting; - vec![ + let mut actions = vec![ TelephonyAction::ResetDialingPipelines, TelephonyAction::OpenAudioPipelines, - ] + ]; + if self.role == CallRole::Outgoing { + // This mirrors Python Telephone.__open_pipelines(): the + // caller echoes ESTABLISHED after observing CONNECTING. + actions.push(TelephonyAction::SendSignal(Signal::from( + SignallingStatus::Established, + ))); + } + actions } Signal::Status(SignallingStatus::Established) => { + if self.status == SignallingStatus::Established { + return vec![TelephonyAction::IgnoreSignal(signal)]; + } self.status = SignallingStatus::Established; vec![TelephonyAction::StartAudioPipelines] } @@ -251,7 +304,7 @@ mod tests { ); let answer = call.answer(); - assert_eq!(call.status(), SignallingStatus::Established); + assert_eq!(call.status(), SignallingStatus::Connecting); assert!(call.answered()); assert_eq!(call.profile(), Some(Profile::DEFAULT)); assert_eq!( @@ -261,9 +314,14 @@ mod tests { TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)), TelephonyAction::OpenAudioPipelines, TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), - TelephonyAction::StartAudioPipelines, ] ); + + assert_eq!( + call.receive_signal(Signal::from(SignallingStatus::Established)), + vec![TelephonyAction::StartAudioPipelines] + ); + assert_eq!(call.status(), SignallingStatus::Established); } #[test] @@ -292,6 +350,7 @@ mod tests { vec![ TelephonyAction::ResetDialingPipelines, TelephonyAction::OpenAudioPipelines, + TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), ] ); assert_eq!( @@ -301,6 +360,45 @@ mod tests { assert_eq!(call.status(), SignallingStatus::Established); } + #[test] + fn answer_retry_and_established_echo_are_bounded_idempotent_transitions() { + let mut incoming = TelephonyCall::incoming(); + incoming.caller_identified(false, true); + incoming.answer(); + assert_eq!( + incoming.retry_answer(), + vec![ + TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)), + TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), + ] + ); + + assert_eq!( + incoming.receive_signal(Signal::from(SignallingStatus::Established)), + vec![TelephonyAction::StartAudioPipelines] + ); + assert!(incoming.retry_answer().is_empty()); + assert_eq!( + incoming.receive_signal(Signal::from(SignallingStatus::Established)), + vec![TelephonyAction::IgnoreSignal(Signal::from( + SignallingStatus::Established + ))] + ); + + let mut outgoing = TelephonyCall::outgoing(Some(Profile::DEFAULT)); + outgoing.receive_signal(Signal::from(SignallingStatus::Available)); + outgoing.receive_signal(Signal::from(SignallingStatus::Ringing)); + outgoing.receive_signal(Signal::from(SignallingStatus::Connecting)); + outgoing.receive_signal(Signal::from(SignallingStatus::Established)); + assert_eq!( + outgoing.receive_signal(Signal::from(SignallingStatus::Connecting)), + vec![TelephonyAction::SendSignal(Signal::from( + SignallingStatus::Established + ))] + ); + assert_eq!(outgoing.status(), SignallingStatus::Established); + } + #[test] fn profile_signals_select_or_switch_profile_by_call_status() { let mut call = TelephonyCall::outgoing(None); diff --git a/crates/lxst-telephony/src/lib.rs b/crates/lxst-telephony/src/lib.rs index d194f94..514ba55 100644 --- a/crates/lxst-telephony/src/lib.rs +++ b/crates/lxst-telephony/src/lib.rs @@ -14,7 +14,10 @@ use lxst_core::{ OpusEncoderState, Profile, RawAudioFrame, RawBitDepth, Signal, SignallingStatus, TELEPHONY_DESTINATION_NAME, TelephonyAction, TelephonyCall, }; -use lxst_rns::{InboundLxstPacket, LxstLinkIngress, LxstMediaEgress, queue_lxst_link_packet}; +use lxst_rns::{ + InboundLxstPacket, LxstLinkIngress, LxstMediaEgress, pack_lxst_link_packet, + queue_lxst_link_packet, +}; use rns_crypto::ed25519::Ed25519PublicKey; use rns_identity::destination::{ DestType, Destination, DestinationError, Direction, ProofStrategy, @@ -29,7 +32,7 @@ use rns_transport::messages::{ TransportQueryResponse, }; use thiserror::Error; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, oneshot}; use tokio::time::{Duration, Instant, timeout}; pub type LinkId = [u8; 16]; @@ -55,6 +58,8 @@ pub enum Error { NoActiveCall, #[error("active call is not established")] CallNotEstablished, + #[error("active call is not an incoming ringing call")] + CallNotAnswerable, #[error("requested media profile {requested:?} does not match active call profile {active:?}")] MediaProfileMismatch { active: Profile, requested: Profile }, #[error("active call is on a different link")] @@ -69,6 +74,8 @@ pub enum Error { ServiceEventClosed, #[error("LXST telephony service event queue is full")] ServiceEventFull, + #[error("LXST telephony service control queue is closed")] + ServiceControlClosed, #[error("Reticulum transport query channel closed")] TransportQueryClosed, #[error("unexpected Reticulum transport query response")] @@ -436,14 +443,46 @@ impl TelephonyRuntimeCore { Ok(()) } - pub fn answer_active(&mut self) -> Result, Error> { + pub fn answer_active( + &mut self, + expected_link_id: LinkId, + ) -> Result, Error> { let active = self.active_call.as_mut().ok_or(Error::NoActiveCall)?; + if active.link_id != expected_link_id { + return Err(Error::WrongActiveLink); + } + if active.call.role() != CallRole::Incoming + || active.call.status() != SignallingStatus::Ringing + { + return Err(Error::CallNotAnswerable); + } let link_id = active.link_id; let remote_identity = active.remote_identity; let actions = active.call.answer(); Ok(self.commands_from_actions(link_id, Some(remote_identity), actions)) } + fn retry_answer_active( + &self, + expected_link_id: LinkId, + ) -> Result, Error> { + let active = self.active_call.as_ref().ok_or(Error::NoActiveCall)?; + if active.link_id != expected_link_id { + return Err(Error::WrongActiveLink); + } + if active.call.role() != CallRole::Incoming + || !active.call.answered() + || active.call.status() != SignallingStatus::Connecting + { + return Err(Error::CallNotAnswerable); + } + Ok(self.commands_from_actions( + active.link_id, + Some(active.remote_identity), + active.call.retry_answer(), + )) + } + pub fn switch_active_profile( &mut self, profile: Profile, @@ -460,6 +499,31 @@ impl TelephonyRuntimeCore { } pub fn hangup_active(&mut self, ring_timeout: bool) -> Result, Error> { + self.terminate_active(ring_timeout, None) + } + + fn timeout_answer_active( + &mut self, + expected_link_id: LinkId, + ) -> Result, Error> { + let active = self.active_call.as_ref().ok_or(Error::NoActiveCall)?; + if active.link_id != expected_link_id { + return Err(Error::WrongActiveLink); + } + if active.call.role() != CallRole::Incoming + || !active.call.answered() + || active.call.status() != SignallingStatus::Connecting + { + return Err(Error::CallNotAnswerable); + } + self.terminate_active(false, Some(SignallingStatus::Connecting)) + } + + fn terminate_active( + &mut self, + ring_timeout: bool, + reason: Option, + ) -> Result, Error> { let Some(mut active) = self.active_call.take() else { return Err(Error::NoActiveCall); }; @@ -471,10 +535,7 @@ impl TelephonyRuntimeCore { active.call.hangup(ring_timeout), ); commands.push(TelephonyCommand::StopAudioPipelines { link_id }); - commands.push(TelephonyCommand::CallTerminated { - link_id, - reason: None, - }); + commands.push(TelephonyCommand::CallTerminated { link_id, reason }); self.pending_links.remove(&link_id); self.ingress.remove(&link_id); Ok(commands) @@ -674,7 +735,10 @@ pub enum TelephonyControl { profile: Option, discovery_timeout: Duration, }, - Answer, + Answer { + expected_link_id: LinkId, + reply: oneshot::Sender>, + }, Hangup { ring_timeout: bool, }, @@ -703,6 +767,24 @@ pub enum TelephonyControl { Shutdown, } +/// Submit an exact-link answer request and wait until the telephony service +/// has validated the active incoming call, atomically admitted its signalling +/// packets, and published the authoritative CONNECTING snapshot. +pub async fn request_answer( + control_tx: &mpsc::Sender, + expected_link_id: LinkId, +) -> Result { + let (reply, result) = oneshot::channel(); + control_tx + .send(TelephonyControl::Answer { + expected_link_id, + reply, + }) + .await + .map_err(|_| Error::ServiceControlClosed)?; + result.await.map_err(|_| Error::ServiceControlClosed)? +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OpusTransmitStreamStopReason { Requested, @@ -807,6 +889,8 @@ struct OutgoingDiscoveryState { pub struct TelephonyServiceConfig { pub poll_interval: Duration, pub incoming_ring_timeout: Option, + pub answer_retry_interval: Option, + pub answer_timeout: Option, pub outgoing_call_timeout: Option, pub media_frames_per_tick: usize, pub announce_on_start: bool, @@ -820,6 +904,8 @@ impl Default for TelephonyServiceConfig { Self { poll_interval: Duration::from_millis(20), incoming_ring_timeout: Some(Duration::from_secs(60)), + answer_retry_interval: Some(Duration::from_millis(750)), + answer_timeout: Some(Duration::from_secs(5)), outgoing_call_timeout: Some(Duration::from_secs(70)), media_frames_per_tick: 4, announce_on_start: true, @@ -864,6 +950,13 @@ struct TelephonyServiceTimeout { expires_at: Instant, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct TelephonyAnsweringState { + link_id: LinkId, + next_retry_at: Option, + expires_at: Option, +} + #[derive(Default)] struct TelephonyServiceMedia { opus_encoder: Option, @@ -1036,6 +1129,7 @@ pub struct TelephonyService { event_tx: mpsc::Sender, config: TelephonyServiceConfig, active_timeout: Option, + answering: Option, next_announce_at: Option, startup_announce_retries_remaining: u8, outgoing_discovery: Option, @@ -1125,6 +1219,7 @@ impl TelephonyService { event_tx, config, active_timeout: None, + answering: None, next_announce_at, startup_announce_retries_remaining, outgoing_discovery: None, @@ -1160,6 +1255,9 @@ impl TelephonyService { if !self.drive_ready().await { break; } + if !self.handle_due_answer_retry().await { + break; + } if !self.handle_due_timeout().await { break; } @@ -1216,6 +1314,7 @@ impl TelephonyService { let stream_events = self.media.clear_unless_established(None); let _ = emit_service_events(self.event_tx.clone(), stream_events).await; self.active_timeout = None; + self.answering = None; } fn deregister_destinations(&self) { @@ -1252,9 +1351,25 @@ impl TelephonyService { .start_outgoing_discovery(remote_identity, profile, discovery_timeout) .await; } - TelephonyControl::Answer => { - let commands = self.core.answer_active(); - self.control_commands(commands).await + TelephonyControl::Answer { + expected_link_id, + reply, + } => { + let result = self.answer_exact(expected_link_id).await; + let service_events_closed = matches!(result, Err(Error::ServiceEventClosed)); + let error_message = result.as_ref().err().map(ToString::to_string); + let _ = reply.send(result); + if let Some(message) = error_message { + if service_events_closed { + return false; + } + return emit_service_event( + self.event_tx.clone(), + TelephonyServiceEvent::Error { message }, + ) + .await; + } + return true; } TelephonyControl::Hangup { ring_timeout } => { if let Some(discovery) = self.outgoing_discovery.take() { @@ -1588,12 +1703,55 @@ impl TelephonyService { } } - async fn control_commands( + async fn answer_exact( &mut self, - commands: Result, Error>, + expected_link_id: LinkId, + ) -> Result { + let previous_active = self.core.active_call.clone(); + let commands = self.core.answer_active(expected_link_id)?; + let effects = match self.endpoint.execute_signalling_batch(&commands) { + Ok(effects) => effects, + Err(error) => { + // No packet was published because the endpoint reserves the + // complete batch first. Restore the exact pre-answer state so + // the caller can retry instead of leaving a local-only call. + self.core.active_call = previous_active; + return Err(error); + } + }; + + let now = Instant::now(); + self.answering = Some(TelephonyAnsweringState { + link_id: expected_link_id, + next_retry_at: self + .config + .answer_retry_interval + .filter(|interval| !interval.is_zero()) + .map(|interval| now + interval), + expires_at: self + .config + .answer_timeout + .filter(|duration| !duration.is_zero()) + .map(|duration| now + duration), + }); + self.publish_commands(commands, effects).await?; + + let active = self + .core + .snapshot() + .active_call + .ok_or(Error::NoActiveCall)?; + if active.link_id != expected_link_id { + return Err(Error::WrongActiveLink); + } + Ok(active) + } + + async fn publish_commands( + &mut self, + commands: Vec, + effects: Vec, ) -> Result<(), Error> { - let commands = commands?; - let effects = self.endpoint.execute_commands(&commands)?; let service_events = service_events_from_commands(&commands); let step = TelephonyStep::commands(commands); let stream_events = self.refresh_active_timeout(); @@ -1624,6 +1782,15 @@ impl TelephonyService { } } + async fn control_commands( + &mut self, + commands: Result, Error>, + ) -> Result<(), Error> { + let commands = commands?; + let effects = self.endpoint.execute_commands(&commands)?; + self.publish_commands(commands, effects).await + } + async fn send_raw_frames( &mut self, bit_depth: RawBitDepth, @@ -1853,6 +2020,16 @@ impl TelephonyService { fn refresh_active_timeout(&mut self) -> Vec { let snapshot = self.core.snapshot(); + if self.answering.is_some_and(|answering| { + !snapshot.active_call.as_ref().is_some_and(|active| { + active.link_id == answering.link_id + && active.role == CallRole::Incoming + && active.answered + && active.status == SignallingStatus::Connecting + }) + }) { + self.answering = None; + } let stream_events = self .media .clear_unless_established(snapshot.active_call.as_ref()); @@ -1893,6 +2070,99 @@ impl TelephonyService { stream_events } + async fn handle_due_answer_retry(&mut self) -> bool { + let Some(answering) = self.answering else { + return true; + }; + let now = Instant::now(); + + if answering + .expires_at + .is_some_and(|expires_at| now >= expires_at) + { + return self.timeout_answering(answering.link_id).await; + } + let Some(next_retry_at) = answering.next_retry_at else { + return true; + }; + if now < next_retry_at { + return true; + } + + let commands = match self.core.retry_answer_active(answering.link_id) { + Ok(commands) => commands, + Err(_) => { + self.answering = None; + return true; + } + }; + let effects = match self.endpoint.execute_signalling_batch(&commands) { + Ok(effects) => Some(effects), + Err(Error::TransportFull) => None, + Err(error) => { + let _ = emit_service_event( + self.event_tx.clone(), + TelephonyServiceEvent::Error { + message: error.to_string(), + }, + ) + .await; + None + } + }; + + if let Some(answering) = self.answering.as_mut() { + answering.next_retry_at = self + .config + .answer_retry_interval + .filter(|interval| !interval.is_zero()) + .map(|interval| now + interval); + } + + if let Some(effects) = effects { + if !emit_service_event( + self.event_tx.clone(), + TelephonyServiceEvent::Drive(TelephonyDriveStep { + step: TelephonyStep::commands(commands), + effects, + }), + ) + .await + { + return false; + } + } + true + } + + async fn timeout_answering(&mut self, link_id: LinkId) -> bool { + self.answering = None; + let commands = match self.core.timeout_answer_active(link_id) { + Ok(commands) => commands, + Err(_) => return true, + }; + let effect_count = commands.len(); + let (effects, endpoint_error) = match self.endpoint.execute_commands(&commands) { + Ok(effects) => (effects, None), + Err(error) => ( + vec![TelephonyCommandEffect::Noop; effect_count], + Some(error.to_string()), + ), + }; + + if self.publish_commands(commands, effects).await.is_err() { + return false; + } + if let Some(message) = endpoint_error { + return emit_service_event( + self.event_tx.clone(), + TelephonyServiceEvent::Error { message }, + ) + .await; + } + true + } + async fn handle_due_timeout(&mut self) -> bool { let Some(timeout_state) = self.active_timeout else { return true; @@ -2515,6 +2785,71 @@ impl TelephonyRnsEndpoint { .collect() } + /// Queue an answer/retry signalling batch without publishing a prefix. + /// + /// Answer correctness depends on CONNECTING and ESTABLISHED being admitted + /// together. Reserve every transport slot before sending either packet so + /// queue pressure cannot leave the remote peer in a half-transition while + /// the local core rolls back to RINGING. + fn execute_signalling_batch( + &mut self, + commands: &[TelephonyCommand], + ) -> Result, Error> { + let signal_commands = commands + .iter() + .filter_map(|command| match command { + TelephonyCommand::SendSignal { link_id, signal } => Some((*link_id, *signal)), + _ => None, + }) + .collect::>(); + + let mut packed = Vec::with_capacity(signal_commands.len()); + for (link_id, signal) in &signal_commands { + let link = if let Some(link) = self.manager.get_link_mut(link_id) { + link + } else { + self.outgoing_links + .get_mut(link_id) + .map(|state| &mut state.link) + .ok_or(Error::UnknownLink)? + }; + packed.push(pack_lxst_link_packet(link, &signalling_packet(*signal))?); + } + + let mut permits = Vec::with_capacity(packed.len()); + for _ in 0..packed.len() { + let permit = + self.transport_tx + .clone() + .try_reserve_owned() + .map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => Error::TransportFull, + mpsc::error::TrySendError::Closed(_) => Error::TransportClosed, + })?; + permits.push(permit); + } + + for (permit, packet) in permits.into_iter().zip(packed) { + permit.send(TransportMessage::Outbound(OutboundRequest { + raw: packet.raw, + destination_hash: packet.destination_hash, + })); + } + + Ok(commands + .iter() + .map(|command| match command { + TelephonyCommand::SendSignal { link_id, .. } => { + TelephonyCommandEffect::QueuedLinkPacket { + link_id: *link_id, + kind: QueuedLinkPacketKind::LxstData, + } + } + _ => TelephonyCommandEffect::Noop, + }) + .collect()) + } + fn try_recv_outgoing_event(&mut self) -> Result, Error> { let attempt_ids = self.outgoing_attempts.keys().copied().collect::>(); for link_id in attempt_ids { diff --git a/crates/lxst-telephony/src/tests.rs b/crates/lxst-telephony/src/tests.rs index b447876..8044e6d 100644 --- a/crates/lxst-telephony/src/tests.rs +++ b/crates/lxst-telephony/src/tests.rs @@ -178,6 +178,46 @@ fn established_outgoing_service_with_transport( ) } +fn ringing_incoming_service( + transport_capacity: usize, + event_capacity: usize, + config: TelephonyServiceConfig, +) -> ( + TelephonyService, + Link, + LinkId, + mpsc::Receiver, + mpsc::Receiver, +) { + let (sender, receiver) = active_link_pair(); + let link_id = sender.link_id; + let local_identity = Identity::new(); + let (transport_tx, transport_rx) = mpsc::channel(transport_capacity); + let mut endpoint = TelephonyRnsEndpoint::register(transport_tx, &local_identity).unwrap(); + let (_link_event_tx, link_event_rx) = mpsc::channel(4); + endpoint.outgoing_links.insert( + link_id, + OutgoingLinkState { + link: sender, + event_rx: link_event_rx, + }, + ); + + let mut core = TelephonyRuntimeCore::new(); + core.incoming_link_established(link_id); + core.caller_identified(link_id, identity(0x5A)).unwrap(); + + let (_control_tx, control_rx) = mpsc::channel(4); + let (event_tx, event_rx) = mpsc::channel(event_capacity); + ( + TelephonyService::with_config(endpoint, core, control_rx, event_tx, config), + receiver, + link_id, + transport_rx, + event_rx, + ) +} + fn queue_inbound_opus_frame( link_event_tx: &mpsc::Sender, receiver: &Link, @@ -353,7 +393,7 @@ fn incoming_call_identify_answer_and_hangup_emit_python_ordered_commands() { ); assert_eq!( - core.answer_active().unwrap(), + core.answer_active(link_id).unwrap(), vec![ TelephonyCommand::SelectProfile { link_id, @@ -368,9 +408,26 @@ fn incoming_call_identify_answer_and_hangup_emit_python_ordered_commands() { link_id, signal: Signal::from(SignallingStatus::Established), }, - TelephonyCommand::StartAudioPipelines { link_id }, ] ); + assert_eq!( + core.active_call().unwrap().call.status(), + SignallingStatus::Connecting + ); + + assert_eq!( + core.accept_lxst_plaintext( + link_id, + &packet([Signal::from(SignallingStatus::Established)]), + ) + .unwrap() + .commands, + vec![TelephonyCommand::StartAudioPipelines { link_id }] + ); + assert_eq!( + core.active_call().unwrap().call.status(), + SignallingStatus::Established + ); assert_eq!( core.hangup_active(false).unwrap(), @@ -386,6 +443,191 @@ fn incoming_call_identify_answer_and_hangup_emit_python_ordered_commands() { assert!(core.active_call().is_none()); } +#[test] +fn answer_admission_is_scoped_to_the_exact_ringing_incoming_link() { + let mut core = TelephonyRuntimeCore::new(); + let link_id = link(0xA1); + core.incoming_link_established(link_id); + core.caller_identified(link_id, identity(0xA2)).unwrap(); + + assert!(matches!( + core.answer_active(link(0xFF)), + Err(Error::WrongActiveLink) + )); + let active = core.active_call().unwrap(); + assert_eq!(active.call.status(), SignallingStatus::Ringing); + assert!(!active.call.answered()); + + core.answer_active(link_id).unwrap(); + assert!(matches!( + core.answer_active(link_id), + Err(Error::CallNotAnswerable) + )); + assert_eq!( + core.active_call().unwrap().call.status(), + SignallingStatus::Connecting + ); +} + +#[tokio::test] +async fn answer_control_acks_authoritative_connecting_after_atomic_admission() { + let (mut service, receiver, link_id, mut transport_rx, mut event_rx) = + ringing_incoming_service(8, 8, TelephonyServiceConfig::default()); + let _destination_registration = transport_rx.try_recv().unwrap(); + let (reply, result) = oneshot::channel(); + + assert!( + service + .handle_control(TelephonyControl::Answer { + expected_link_id: link_id, + reply, + }) + .await + ); + let snapshot = result.await.unwrap().unwrap(); + assert_eq!(snapshot.link_id, link_id); + assert_eq!(snapshot.role, CallRole::Incoming); + assert_eq!(snapshot.status, SignallingStatus::Connecting); + assert!(snapshot.answered); + + let mut signals = Vec::new(); + for _ in 0..2 { + let (_header, encrypted) = take_outbound(&mut transport_rx); + signals.extend( + LxstPacket::decode(&receiver.decrypt(&encrypted).unwrap()) + .unwrap() + .signals, + ); + } + assert_eq!( + signals, + vec![ + Signal::from(SignallingStatus::Connecting), + Signal::from(SignallingStatus::Established), + ] + ); + + let events = collect_ready_service_events(&mut event_rx); + assert!(matches!( + events.last(), + Some(TelephonyServiceEvent::Snapshot(snapshot)) + if snapshot.active_call.as_ref().is_some_and(|active| { + active.link_id == link_id + && active.status == SignallingStatus::Connecting + && active.answered + }) + )); +} + +#[tokio::test] +async fn answered_service_starts_media_only_after_remote_established_echo() { + let (mut service, _receiver, link_id, mut transport_rx, mut event_rx) = + ringing_incoming_service(8, 12, TelephonyServiceConfig::default()); + let _destination_registration = transport_rx.try_recv().unwrap(); + let answer = service.answer_exact(link_id).await.unwrap(); + assert_eq!(answer.status, SignallingStatus::Connecting); + assert!(service.answering.is_some()); + let _ = collect_ready_service_events(&mut event_rx); + + let step = service + .core + .accept_lxst_plaintext( + link_id, + &packet([Signal::from(SignallingStatus::Established)]), + ) + .unwrap(); + assert_eq!( + step.commands, + vec![TelephonyCommand::StartAudioPipelines { link_id }] + ); + let effects = service.endpoint.execute_commands(&step.commands).unwrap(); + service + .publish_commands(step.commands, effects) + .await + .unwrap(); + + assert!(service.answering.is_none()); + let active = service.core.snapshot().active_call.unwrap(); + assert_eq!(active.link_id, link_id); + assert_eq!(active.status, SignallingStatus::Established); + let events = collect_ready_service_events(&mut event_rx); + assert!(events.iter().any(|event| matches!( + event, + TelephonyServiceEvent::Drive(TelephonyDriveStep { step, .. }) + if step.commands == vec![TelephonyCommand::StartAudioPipelines { link_id }] + ))); + assert!(matches!( + events.last(), + Some(TelephonyServiceEvent::Snapshot(snapshot)) + if snapshot.active_call.as_ref().is_some_and(|active| { + active.link_id == link_id && active.status == SignallingStatus::Established + }) + )); +} + +#[tokio::test] +async fn answer_transport_backpressure_rolls_back_without_publishing_a_prefix() { + let (mut service, _receiver, link_id, mut transport_rx, _event_rx) = + ringing_incoming_service(1, 8, TelephonyServiceConfig::default()); + + assert!(matches!( + service.answer_exact(link_id).await, + Err(Error::TransportFull) + )); + let active = service.core.active_call().unwrap(); + assert_eq!(active.call.status(), SignallingStatus::Ringing); + assert!(!active.call.answered()); + assert!(service.answering.is_none()); + + assert!(matches!( + transport_rx.try_recv().unwrap(), + TransportMessage::RegisterDestination { .. } + )); + assert!(transport_rx.try_recv().is_err()); +} + +#[tokio::test] +async fn answering_retries_are_bounded_and_timeout_terminates_connecting_call() { + let config = TelephonyServiceConfig { + answer_retry_interval: Some(Duration::from_millis(10)), + answer_timeout: Some(Duration::from_millis(40)), + ..TelephonyServiceConfig::default() + }; + let (mut service, _receiver, link_id, mut transport_rx, mut event_rx) = + ringing_incoming_service(16, 16, config); + let _destination_registration = transport_rx.try_recv().unwrap(); + service.answer_exact(link_id).await.unwrap(); + let _ = collect_ready_service_events(&mut event_rx); + let _ = take_outbound(&mut transport_rx); + let _ = take_outbound(&mut transport_rx); + + service.answering.as_mut().unwrap().next_retry_at = Some(Instant::now()); + assert!(service.handle_due_answer_retry().await); + assert!(matches!( + event_rx.try_recv().unwrap(), + TelephonyServiceEvent::Drive(_) + )); + let _ = take_outbound(&mut transport_rx); + let _ = take_outbound(&mut transport_rx); + + service.answering.as_mut().unwrap().expires_at = Some(Instant::now()); + assert!(service.handle_due_answer_retry().await); + assert!(service.core.active_call().is_none()); + assert!(service.answering.is_none()); + let events = collect_ready_service_events(&mut event_rx); + assert!(events.iter().any(|event| matches!( + event, + TelephonyServiceEvent::CallTerminated { + link_id: terminated, + reason: Some(SignallingStatus::Connecting), + } if *terminated == link_id + ))); + assert!(matches!( + events.last(), + Some(TelephonyServiceEvent::Snapshot(snapshot)) if snapshot.active_call.is_none() + )); +} + #[test] fn blocked_or_busy_incoming_call_sends_busy_and_tears_down() { let blocked = identity(0x44); @@ -472,6 +714,10 @@ fn outgoing_signalling_from_lxst_packets_drives_call_setup() { vec![ TelephonyCommand::ResetDialingPipelines { link_id }, TelephonyCommand::OpenAudioPipelines { link_id }, + TelephonyCommand::SendSignal { + link_id, + signal: Signal::from(SignallingStatus::Established), + }, ] ); diff --git a/crates/lxst-telephony/tests/python_telephone_live_interop.rs b/crates/lxst-telephony/tests/python_telephone_live_interop.rs index 62bd4f3..803c5e0 100644 --- a/crates/lxst-telephony/tests/python_telephone_live_interop.rs +++ b/crates/lxst-telephony/tests/python_telephone_live_interop.rs @@ -1165,18 +1165,19 @@ async fn rust_to_rust_call_establishes_through_python_transport_hub() { |event| matches!(event, TelephonyServiceEvent::IncomingCall { .. }), ) .await; - match incoming { + let incoming_link_id = match incoming { TelephonyServiceEvent::IncomingCall { - remote_identity, .. - } => assert_eq!(remote_identity, caller.identity.hash), + link_id, + remote_identity, + } => { + assert_eq!(remote_identity, caller.identity.hash); + link_id + } other => panic!("expected IncomingCall, got {other:?}"), - } - - callee - .control_tx - .send(TelephonyControl::Answer) + }; + lxst_telephony::request_answer(&callee.control_tx, incoming_link_id) .await - .expect("send callee Answer control"); + .expect("answer callee call"); wait_matching_service_event( &mut caller.event_rx, @@ -1618,8 +1619,9 @@ async fn python_outgoing_call_establishes_when_rust_answers_without_audio() { tokio::time::sleep(Duration::from_millis(50)).await; } + let link_id = core.active_call().expect("active incoming call").link_id; let commands = core - .answer_active() + .answer_active(link_id) .expect("answer active Rust incoming call"); endpoint .execute_commands(&commands) @@ -1841,8 +1843,9 @@ async fn python_hangup_after_rust_answer_ends_rust_call_without_audio() { tokio::time::sleep(Duration::from_millis(50)).await; } + let link_id = core.active_call().expect("active incoming call").link_id; let commands = core - .answer_active() + .answer_active(link_id) .expect("answer active Rust incoming call"); endpoint .execute_commands(&commands)