diff --git a/.changeset/cancel-publisher-negotiation-on-close.md b/.changeset/cancel-publisher-negotiation-on-close.md new file mode 100644 index 000000000..ef119a05c --- /dev/null +++ b/.changeset/cancel-publisher-negotiation-on-close.md @@ -0,0 +1,7 @@ +--- +livekit: patch +livekit-capture: patch +livekit-ffi: patch +--- + +Cancel and join pending publisher negotiations when a room closes, including the debounce wait, so negotiation tasks no longer retain peer connection factories, media threads, and encoder resources after teardown. diff --git a/livekit/Cargo.toml b/livekit/Cargo.toml index 9910b2f96..fa1e747e5 100644 --- a/livekit/Cargo.toml +++ b/livekit/Cargo.toml @@ -80,9 +80,9 @@ livekit-token = { workspace = true } livekit-api = { workspace = true, default-features = false, features = ["services"] } # Enable data-stream test constructors (e.g. TextStreamReader::new_for_test) for our test suites. livekit-data-stream = { workspace = true, features = ["test-utils"] } -# Async test runtime + timers, needed by the peer_transport deadlock reproducer. +# Async test runtime + timers, including a paused clock for debounce cancellation tests. # (rt/time are already built elsewhere in the workspace, so no new crates enter the lockfile.) -tokio = { version = "1", features = ["rt", "macros", "time"] } +tokio = { version = "1", features = ["rt", "macros", "time", "test-util"] } anyhow = "1.0.99" test-log = "0.2.18" test-case = "3.3" diff --git a/livekit/src/rtc_engine/rtc_session.rs b/livekit/src/rtc_engine/rtc_session.rs index 96b41a19b..933e20aa7 100644 --- a/livekit/src/rtc_engine/rtc_session.rs +++ b/livekit/src/rtc_engine/rtc_session.rs @@ -16,6 +16,7 @@ use std::{ collections::{HashMap, HashSet, VecDeque}, convert::TryInto, fmt::Debug, + future::Future, sync::{ atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, Arc, @@ -115,6 +116,8 @@ enum NegotiationState { struct NegotiationQueue { state: Arc>, waker: Arc, + /// Taken and joined by [`RtcSession::close`] to release the task's session reference. + task: Mutex>>, task_running: AtomicBool, waiting_for_answer: AtomicBool, } @@ -124,6 +127,7 @@ impl NegotiationQueue { Self { state: Arc::new(Mutex::new(NegotiationState::Idle)), waker: Arc::new(Notify::new()), + task: Mutex::new(None), task_running: AtomicBool::new(false), waiting_for_answer: AtomicBool::new(false), } @@ -468,6 +472,7 @@ struct SessionInner { emitter: SessionEmitter, options: EngineOptions, + close_rx: watch::Receiver, negotiation_debouncer: Mutex>, negotiation_queue: NegotiationQueue, @@ -710,6 +715,7 @@ impl RtcSession { disconnecting: Default::default(), emitter, options, + close_rx: close_rx.clone(), negotiation_debouncer: Default::default(), negotiation_queue: NegotiationQueue::new(), pending_requests: Default::default(), @@ -870,10 +876,23 @@ impl RtcSession { /// Close the PeerConnections and the SignalClient pub async fn close(&self, reason: DisconnectReason) { + // Stop new negotiations before taking their handles, including requests racing close. + self.inner.closed.store(true, Ordering::Release); + let debouncer = self.inner.negotiation_debouncer.lock().take(); + let negotiation_task = self.inner.negotiation_queue.task.lock().take(); + // Close the tasks let handle = self.handle.lock().take(); - if let Some(handle) = handle { + if let Some(handle) = &handle { let _ = handle.close_tx.send(true); + } + if let Some(debouncer) = debouncer { + debouncer.cancel().await; + } + if let Some(task) = negotiation_task { + let _ = task.await; + } + if let Some(handle) = handle { let _ = handle.rtc_task.await; let _ = handle.signal_task.await; let _ = handle.dc_task.await; @@ -2576,6 +2595,10 @@ impl SessionInner { /// Start publisher negotiation fn publisher_negotiation_needed(self: &Arc) { + if self.closed.load(Ordering::Acquire) { + return; + } + let fast_publish = self.fast_publish.load(Ordering::Acquire); self.has_published.store(true, Ordering::Release); @@ -2595,6 +2618,10 @@ impl SessionInner { } fn queue_negotiation(self: &Arc) { + let mut task = self.negotiation_queue.task.lock(); + if self.closed.load(Ordering::Acquire) { + return; + } let mut state = self.negotiation_queue.state.lock(); match *state { @@ -2610,10 +2637,21 @@ impl SessionInner { drop(state); let session = self.clone(); - tokio::spawn(async move { - session.execute_negotiation_with_retry().await; + let mut close_rx = self.close_rx.clone(); + *task = Some(tokio::spawn(async move { + let completed = + cancel_on_close(&mut close_rx, session.execute_negotiation_with_retry()) + .await + .is_some(); + if !completed { + session + .negotiation_queue + .waiting_for_answer + .store(false, Ordering::Release); + *session.negotiation_queue.state.lock() = NegotiationState::Idle; + } session.negotiation_queue.task_running.store(false, Ordering::Release); - }); + })); } NegotiationState::InProgress => { log::debug!("queue_negotiation: marking for retry"); @@ -2671,16 +2709,21 @@ impl SessionInner { fn debounce_negotiation(self: &Arc) { let mut debouncer = self.negotiation_debouncer.lock(); + if self.closed.load(Ordering::Acquire) { + return; + } // call() returns an error if the debouncer has finished if debouncer.is_none() || debouncer.as_ref().unwrap().call().is_err() { let session = self.clone(); + let mut close_rx = self.close_rx.clone(); *debouncer = Some(debouncer::debounce(PUBLISHER_NEGOTIATION_FREQUENCY, async move { - log::debug!("negotiating the publisher (debounced)"); - if let Err(err) = + let negotiate = async { + log::debug!("negotiating the publisher (debounced)"); session.publisher_pc.create_and_send_offer(OfferOptions::default()).await - { + }; + if let Some(Err(err)) = cancel_on_close(&mut close_rx, negotiate).await { log::error!("failed to negotiate the publisher: {:?}", err); } })); @@ -2828,6 +2871,24 @@ impl Drop for PendingResponseGuard<'_, T> { } } +/// Runs `future` until completion or session closure, returning `None` on cancellation. +/// `close_rx` starts at `false` and signals closure with `true`. +/// `future` is the operation to run and is dropped if closure wins. +async fn cancel_on_close( + close_rx: &mut watch::Receiver, + future: impl Future, +) -> Option { + // If close_rx is already true, nothing to cancel + if *close_rx.borrow() { + return None; + } + + tokio::select! { + result = future => Some(result), + _ = close_rx.changed() => None, + } +} + /// Emit incoming data track packets as session events. pub fn handle_remote_dt_packets(dc: &DataChannel, emitter: WeakUnboundedSender) { let on_message: libwebrtc::data_channel::OnMessage = Box::new(move |buffer: DataBuffer| { @@ -2921,9 +2982,16 @@ fn uses_negotiated_data_channels( #[cfg(test)] mod tests { + use std::{future, sync::Arc, time::Duration}; + + use tokio::{ + sync::{oneshot, watch}, + time::timeout, + }; + use super::{ - parse_sdp_max_message_size, recovery_decision, uses_negotiated_data_channels, - DEFAULT_MAX_MESSAGE_SIZE, + cancel_on_close, parse_sdp_max_message_size, recovery_decision, + uses_negotiated_data_channels, DEFAULT_MAX_MESSAGE_SIZE, }; /// The server picks negotiated data channels from the protocol the client advertised, so a @@ -2939,6 +3007,123 @@ mod tests { /// `(connected, disconnect)` counts as sampled before a resume, for readability below. const SNAPSHOT: Option<(u32, u32)> = Some((7, 3)); + #[tokio::test] + async fn close_signal_releases_owner_held_by_pending_task() { + let (close_tx, mut close_rx) = watch::channel(false); + let owner = Arc::new(()); + let owner_dropped = Arc::downgrade(&owner); + let (started_tx, started_rx) = oneshot::channel(); + let task = tokio::spawn(async move { + let pending = async move { + let _owner = owner; + started_tx.send(()).unwrap(); + future::pending::<()>().await; + }; + assert!(cancel_on_close(&mut close_rx, pending).await.is_none()); + }); + + started_rx.await.unwrap(); + close_tx.send(true).unwrap(); + timeout(Duration::from_secs(1), task).await.unwrap().unwrap(); + assert!(owner_dropped.upgrade().is_none()); + } + + #[cfg(feature = "__lk-e2e-test")] + mod negotiation_lifecycle { + use std::{env, sync::atomic::Ordering}; + + use livekit_token::{AccessToken, VideoGrants}; + use tokio::sync::Notify; + + use super::*; + use crate::{rtc_engine::rtc_session::RtcSession, DisconnectReason}; + + /// Connects a real session and waits for its initial publisher negotiation to finish. + async fn session() -> RtcSession { + let room = format!("negotiation-lifecycle-{}", libwebrtc::native::create_random_uuid()); + let token = AccessToken::with_api_key( + &env::var("LIVEKIT_API_KEY").unwrap_or_else(|_| "devkey".into()), + &env::var("LIVEKIT_API_SECRET").unwrap_or_else(|_| "secret".into()), + ) + .with_identity("publisher") + .with_grants(VideoGrants { room_join: true, room, ..Default::default() }) + .to_jwt() + .unwrap(); + let (session, _, _) = RtcSession::connect( + &env::var("LIVEKIT_URL").unwrap_or_else(|_| "http://localhost:7880".into()), + &token, + Default::default(), + None, + ) + .await + .unwrap(); + + timeout(Duration::from_secs(5), async { + while session.inner.negotiation_queue.task_running.load(Ordering::Acquire) { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("initial publisher negotiation did not finish"); + session + } + + /// Exercises the real task registration, close, and session destruction paths. + async fn check_release(fast_publish: bool, wait_for_offer: bool) { + let session = session().await; + let dropped = Arc::downgrade(&session.inner); + session.inner.fast_publish.store(fast_publish, Ordering::Release); + + if !wait_for_offer { + // A lost signalling link must not mask the debounce delay with socket teardown. + session.inner.signal_client.close().await; + } + + // Withhold the offer from signalling so fast negotiation cannot receive an answer. + let offered = Arc::new(Notify::new()); + let offer_notification = offered.clone(); + session.inner.publisher_pc.on_offer(Some(Box::new(move |_| { + offer_notification.notify_one(); + }))); + session.publisher_negotiation_needed(); + if wait_for_offer { + timeout(Duration::from_secs(5), offered.notified()) + .await + .expect("publisher did not create an offer"); + assert!(session.inner.negotiation_queue.waiting_for_answer.load(Ordering::Acquire)); + // Another request must leave the retry pending when close cancels the task. + session.publisher_negotiation_needed(); + } + + timeout(Duration::from_secs(15), session.close(DisconnectReason::ClientInitiated)) + .await + .expect("session close did not finish"); + drop(session); + assert!( + dropped.upgrade().is_none(), + "publisher negotiation retained SessionInner after close" + ); + } + + /// Closing during the debounce timer must release the session before returning. + #[tokio::test] + async fn close_releases_session_during_debounce_wait() { + check_release(false, false).await; + } + + /// Closing before the spawned future is polled must release its session capture. + #[tokio::test] + async fn close_releases_session_before_fast_negotiation_starts() { + check_release(true, false).await; + } + + /// Closing must cancel both the unanswered offer and its queued retry. + #[tokio::test] + async fn close_releases_session_waiting_for_publisher_answer() { + check_release(true, true).await; + } + } + /// A subscriber left dead by a node failure keeps reporting `Connected` until ICE times /// out. Accepting that reports a recovery that did not happen — `Resumed`, and so /// `RoomEvent::Reconnected` with `ConnectionState::Connected`, for a session receiving no diff --git a/livekit/src/utils/debouncer.rs b/livekit/src/utils/debouncer.rs index 57993e97e..bec3ee49a 100644 --- a/livekit/src/utils/debouncer.rs +++ b/livekit/src/utils/debouncer.rs @@ -17,6 +17,7 @@ use std::time::Duration; use futures_util::Future; use thiserror::Error; use tokio::sync::{mpsc, oneshot}; +use tokio::task::JoinHandle; #[derive(Debug, Error)] pub enum DebounceError { @@ -27,6 +28,7 @@ pub enum DebounceError { pub struct Debouncer { cancel_tx: Option>, tx: mpsc::UnboundedSender<()>, + task: Option>, } pub fn debounce(duration: Duration, future: F) -> Debouncer @@ -35,8 +37,8 @@ where { let (tx, rx) = mpsc::unbounded_channel(); let (cancel_tx, cancel_rx) = oneshot::channel(); - tokio::spawn(debounce_task(duration, future, rx, cancel_rx)); - Debouncer { tx, cancel_tx: Some(cancel_tx) } + let task = tokio::spawn(debounce_task(duration, future, rx, cancel_rx)); + Debouncer { tx, cancel_tx: Some(cancel_tx), task: Some(task) } } async fn debounce_task( @@ -47,19 +49,32 @@ async fn debounce_task( ) where F: Future + Send + 'static, { - loop { - tokio::select! { - _ = &mut cancel_rx => break, - _ = rx.recv() => continue, - _ = tokio::time::sleep(duration) => { - future.await; - break; + let debounced = async move { + loop { + tokio::select! { + _ = rx.recv() => continue, + _ = tokio::time::sleep(duration) => break, } } + future.await; + }; + tokio::select! { + _ = &mut cancel_rx => {}, + _ = debounced => {}, } } impl Debouncer { + /// Cancels the timer or in-flight operation and waits for its task to release its captures. + pub(crate) async fn cancel(mut self) { + if let Some(cancel_tx) = self.cancel_tx.take() { + let _ = cancel_tx.send(()); + } + if let Some(task) = self.task.take() { + let _ = task.await; + } + } + pub fn call(&self) -> Result<(), mpsc::error::SendError<()>> { self.tx.send(()) } @@ -67,6 +82,50 @@ impl Debouncer { impl Drop for Debouncer { fn drop(&mut self) { - let _ = self.cancel_tx.take().unwrap().send(()); + if let Some(cancel_tx) = self.cancel_tx.take() { + let _ = cancel_tx.send(()); + } + } +} + +#[cfg(test)] +mod tests { + use std::{future, sync::Arc}; + + use tokio::time::Instant; + + use super::*; + + /// Cancellation must release the operation without advancing the debounce clock. + #[tokio::test(start_paused = true)] + async fn cancel_releases_captures_without_waiting_for_timer() { + let owner = Arc::new(()); + let dropped = Arc::downgrade(&owner); + let started = Instant::now(); + let debouncer = debounce(Duration::from_secs(60), async move { + let _owner = owner; + panic!("cancelled debounce must not run"); + }); + + debouncer.cancel().await; + assert!(dropped.upgrade().is_none()); + assert_eq!(started.elapsed(), Duration::ZERO); + } + + /// Cancellation must interrupt the operation even after the debounce timer fires. + #[tokio::test(start_paused = true)] + async fn cancel_releases_captures_of_in_flight_operation() { + let owner = Arc::new(()); + let dropped = Arc::downgrade(&owner); + let (started_tx, started_rx) = oneshot::channel(); + let debouncer = debounce(Duration::from_secs(1), async move { + let _owner = owner; + started_tx.send(()).unwrap(); + future::pending::<()>().await; + }); + started_rx.await.unwrap(); + + tokio::time::timeout(Duration::from_secs(1), debouncer.cancel()).await.unwrap(); + assert!(dropped.upgrade().is_none()); } }