From 11bde3e58d81ab35228cad1193393c7456d5d54e Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:42:33 -0700 Subject: [PATCH] fix(ffi): preserve cancelled reads and accepts on release Backport the ownership fixes from #5140 and #5172 while retaining release runtime, configuration, and listener APIs. Validate the UniFFI cancel/free interval directly and keep synchronous listener cancellation independent of parked foreign calls. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: GPT-6 --- rs/moq-ffi/src/ffi.rs | 185 ++++++++++++++++++++--------------- rs/moq-ffi/src/server.rs | 201 ++++++++++++++++++++++++++++++++------- rs/moq-ffi/src/test.rs | 195 ++++++++++++++++++++++++++++++++++--- 3 files changed, 458 insertions(+), 123 deletions(-) diff --git a/rs/moq-ffi/src/ffi.rs b/rs/moq-ffi/src/ffi.rs index 16019d1bb0d..53aed49d321 100644 --- a/rs/moq-ffi/src/ffi.rs +++ b/rs/moq-ffi/src/ffi.rs @@ -3,19 +3,36 @@ use std::sync::Arc; use crate::error::MoqError; -/// A dedicated runtime thread, so a foreign caller's thread never has to drive our futures. +/// A dedicated runtime thread, which drives the I/O and timers every call registers and runs +/// the background work spawned onto it. /// /// wasm32 has neither threads nor a tokio driver. uniffi's `RustFuture` is polled by the -/// JS event loop instead, so [`Task::run`] awaits in place there. +/// JS event loop instead. #[cfg(not(target_arch = "wasm32"))] static RUNTIME: std::sync::OnceLock = std::sync::OnceLock::new(); -/// The runtime thread and the handle every call spawns onto. +/// The runtime thread and the handle used by calls and background work. #[cfg(not(target_arch = "wasm32"))] pub(crate) struct Runtime { handle: tokio::runtime::Handle, /// Taken by [`shutdown`], so the thread is stopped and joined once. thread: std::sync::Mutex>, + /// Set by [`shutdown`] to wake the [`Task::run`] calls parked in place, so they observe + /// [`Polls::stopped`] and resolve `Cancelled`. + stopped: tokio::sync::watch::Sender, + /// The [`Task::run`] polls in flight on host threads, which [`shutdown`] waits out. + polls: std::sync::Mutex, + /// Notified when the last in-flight poll finishes. + idle: std::sync::Condvar, +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Polls { + active: usize, + /// Set by [`shutdown`]: no poll may start once the drivers are about to stop, because a + /// tokio timer polled after its driver is gone panics rather than erroring. + stopped: bool, } #[cfg(not(target_arch = "wasm32"))] @@ -60,6 +77,9 @@ pub(crate) fn runtime() -> &'static Runtime { Runtime { handle, thread: std::sync::Mutex::new(Some(Thread { stop, join })), + stopped: tokio::sync::watch::Sender::new(false), + polls: Default::default(), + idle: Default::default(), } }) } @@ -73,10 +93,70 @@ pub(crate) fn shutdown() { let Some(thread) = runtime.thread.lock().unwrap().take() else { return; }; + // Before the thread stops, so no call awaited in place polls the runtime after it is gone. + let mut polls = runtime.polls.lock().unwrap(); + polls.stopped = true; + drop(runtime.idle.wait_while(polls, |polls| polls.active > 0).unwrap()); + // Outside the lock: a waker may poll inline, which takes it. + runtime.stopped.send_replace(true); let _ = thread.stop.send(()); let _ = thread.join.join(); } +/// Resolves once [`shutdown`] has run. +#[cfg(not(target_arch = "wasm32"))] +async fn stopped() { + let mut stopped = runtime().stopped.subscribe(); + // `Err` only when the sender is dropped, which a static never is. + let _ = stopped.wait_for(|&stopped| stopped).await; +} + +/// wasm32's runtime is the JS event loop, which never stops under us. +#[cfg(target_arch = "wasm32")] +async fn stopped() { + std::future::pending().await +} + +/// Marks a [`Task::run`] poll in flight, so [`shutdown`] waits for it to finish. +#[cfg(not(target_arch = "wasm32"))] +struct Polling; + +#[cfg(not(target_arch = "wasm32"))] +impl Polling { + /// `None` once [`shutdown`] has begun. + fn start() -> Option { + let mut polls = runtime().polls.lock().unwrap(); + if polls.stopped { + return None; + } + polls.active += 1; + Some(Self) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Polling { + fn drop(&mut self) { + let runtime = runtime(); + let mut polls = runtime.polls.lock().unwrap(); + polls.active -= 1; + if polls.active == 0 { + runtime.idle.notify_all(); + } + } +} + +/// wasm32's runtime is the JS event loop, which never stops under us. +#[cfg(target_arch = "wasm32")] +struct Polling; + +#[cfg(target_arch = "wasm32")] +impl Polling { + fn start() -> Option { + Some(Self) + } +} + /// Enter the runtime context, so a handle built outside [`Task::run`] can still spawn. /// /// A no-op on wasm32, where the JS event loop is the only runtime. @@ -209,48 +289,36 @@ impl Task { } } - /// Spawn an async closure on the runtime. + /// Run an async closure against the state, awaiting it in place. /// /// The closure receives a [Guard] which derefs to `T`. /// If two calls are made concurrently, the second waits for the first to finish. - #[cfg(not(target_arch = "wasm32"))] - pub async fn run(&self, f: F) -> Result - where - R: Send + 'static, - F: FnOnce(Guard) -> Fut + Send + 'static, - Fut: Future> + Send + 'static, - { - let cancel = self.cancel.subscribe(); - let state = self.state.clone(); - - let handle = runtime().spawn(async move { Self::drive(cancel, state, f).await }); - - // Dropping a JoinHandle detaches its task rather than stopping it, so a caller - // that gives up (an `asyncio.wait_for` timeout, a cancelled Swift/Kotlin task) - // would leave the closure running with the state lock held. It then consumes - // the very event the next call is waiting for, and that call blocks behind it - // meanwhile. Tie the work to the caller's future instead. - let _abort = AbortOnDrop(handle.abort_handle()); - - match handle.await { - Ok(result) => result, - Err(e) if e.is_cancelled() => Err(MoqError::Cancelled), - Err(e) => Err(e.into()), - } - } - - /// Run an async closure, awaiting it in place. /// - /// Unlike the native path this does not detach, so dropping the returned future - /// cancels the work rather than leaving it running on a runtime thread. - #[cfg(target_arch = "wasm32")] + /// Not spawned: a foreign cancel (uniffi's `rust_future_cancel`) only stops polling, and the + /// future is dropped later at `rust_future_free`. Spawned work would keep running until then + /// and take the very event the next call is waiting for. Each poll enters the runtime, so the + /// closure can still use tokio timers, sockets, and spawn. pub async fn run(&self, f: F) -> Result where - R: 'static, - F: FnOnce(Guard) -> Fut + 'static, - Fut: Future> + 'static, + F: FnOnce(Guard) -> Fut, + Fut: Future>, { - Self::drive(self.cancel.subscribe(), self.state.clone(), f).await + let drive = Self::drive(self.cancel.subscribe(), self.state.clone(), f); + let mut run = std::pin::pin!(async { + tokio::select! { + biased; + _ = stopped() => Err(MoqError::Cancelled), + result = drive => result, + } + }); + std::future::poll_fn(|cx| { + let Some(_polling) = Polling::start() else { + return std::task::Poll::Ready(Err(MoqError::Cancelled)); + }; + let _runtime = enter(); + run.as_mut().poll(cx) + }) + .await } /// Wait for the lock, then run `f`, with [Self::cancel] able to interrupt either. @@ -284,8 +352,9 @@ impl Task { /// /// Terminal: there is no way back from here, and the state is gone rather than idle. /// The drop is not synchronous with this call, because an in-flight [Self::run] holds the - /// state until it observes the flag and unwinds. It also lands on the runtime thread, which - /// is where the state was built and the only place with a reactor for what it unregisters. + /// state until it observes the flag and unwinds, or its caller drops it. It also lands on the + /// runtime thread, which is where the state was built and the only place with a reactor for + /// what it unregisters. pub fn cancel(&self) { // send_replace, not send: `send` refuses to store the value while no // receiver exists, so a cancel BEFORE the first `run` would silently @@ -300,42 +369,6 @@ impl Task { state.lock().await.take(); }); } - - /// [Self::cancel], then block until `shutdown` has run on the state. - /// - /// A synchronous caller uses this to make the release of what the state owns - /// observable: the listening socket is gone, not merely scheduled to close. - /// `shutdown` runs on the runtime thread, after any in-flight [Self::run] has - /// unwound, and the lock is held across it so a second cancel waits too. - /// - /// It waits on a channel rather than [tokio::sync::Mutex::blocking_lock] so it - /// works from inside another runtime, as the tests do; it must not run on the - /// runtime thread itself, which would deadlock. - #[cfg(not(target_arch = "wasm32"))] - pub fn cancel_and_wait(&self, shutdown: F) - where - F: FnOnce(T) -> Fut + Send + 'static, - Fut: Future + Send + 'static, - { - // Publish the flag before waiting: an in-flight [Self::run] only releases - // the lock once it observes it. - self.cancel.send_replace(true); - - let state = self.state.clone(); - let (done, wait) = std::sync::mpsc::channel(); - spawn(async move { - let mut state = state.lock().await; - if let Some(inner) = state.take() { - shutdown(inner).await; - } - // A dropped receiver just means the caller is gone; the shutdown above - // still ran, which is what releases the state. - let _ = done.send(()); - }); - // A dropped sender means the runtime is gone, so nothing is left holding - // the state to wait for. - let _ = wait.recv(); - } } impl Drop for Task { diff --git a/rs/moq-ffi/src/server.rs b/rs/moq-ffi/src/server.rs index daae44f026d..401f5149f6f 100644 --- a/rs/moq-ffi/src/server.rs +++ b/rs/moq-ffi/src/server.rs @@ -10,39 +10,165 @@ struct ServerState { config: moq_tokio::listen::Config, publish: Option>, consume: Option>, - server: Option, + requests: Option, +} + +struct Requests { + queue: tokio::sync::mpsc::Receiver, + certificates: moq_tokio::tls::Certificates, +} + +/// Stops a listening server's accept loop without the state lock, which a parked +/// `accept` holds until the host frees it. +struct Listening { + /// Dropped to stop the loop. + stop: tokio::sync::oneshot::Sender<()>, + /// Disconnects once the loop has closed the listener. + closed: std::sync::mpsc::Receiver<()>, +} + +impl Listening { + /// Stop the accept loop and block until the listener's sockets are released. + /// + /// Waits on a std channel so it works from inside another runtime, but must not run on + /// the FFI runtime thread, which the loop needs. + fn close(self) { + drop(self.stop); + // Disconnects when the loop finishes, or when the runtime is gone and dropped it. + let _ = self.closed.recv(); + } +} + +/// Start `server`, report its address to `bound`, and move requests into `queue`, then close +/// the listener once `stop` fires or nothing more can arrive. +/// +/// Runs on the FFI runtime so `MoqServer::cancel` can close the listener while an `accept` +/// is parked, and so a cancelled `listen` never drops a half-started server instead of +/// closing it. A request waits in `queue` until an `accept` is polled for it, so one cancelled +/// but not yet freed never takes it. A slot is reserved before accepting, so at most one +/// request waits unclaimed. +struct AcceptLoop { + server: moq_tokio::Server, + bound: tokio::sync::oneshot::Sender>, + queue: tokio::sync::mpsc::Sender, + stop: tokio::sync::oneshot::Receiver<()>, + closed: std::sync::mpsc::Sender<()>, +} + +impl AcceptLoop { + async fn run(self) { + let Self { + server, + bound, + queue, + mut stop, + closed, + } = self; + // Not raced against `stop`: `Listener::close` is the only synchronous release, so a + // cancel waits out the bind rather than dropping it. + let mut listener = match server.listen().await { + Ok(listener) => listener, + Err(err) => { + let _ = bound.send(Err(MoqError::Bind(format!("{err}")))); + return; + } + }; + match listener.local_addr() { + Ok(addr) => { + let _ = bound.send(Ok(addr.to_string())); + } + Err(err) => { + let _ = bound.send(Err(MoqError::Bind(format!("{err}")))); + listener.close().await; + return; + } + } + + loop { + let slot = tokio::select! { + _ = &mut stop => break, + slot = queue.reserve() => match slot { + Ok(slot) => slot, + Err(_) => break, + }, + }; + let request = tokio::select! { + _ = &mut stop => break, + request = listener.accept() => request, + }; + match request { + Some(request) => slot.send(request), + None => break, + } + } + // `Listener::close` releases the sockets before it returns; a drop only schedules that. + listener.close().await; + drop(closed); + } } impl ServerState { - async fn listen(&mut self) -> Result { - if self.server.is_some() { + /// Bind, and start the accept loop that `listening` stops. + async fn listen( + &mut self, + task: &Task, + listening: &std::sync::Mutex>, + ) -> Result { + if self.requests.is_some() { return Err(MoqError::Bind("already listening".into())); } - let server = self - .config - .clone() - .init(Default::default()) - .map_err(|err| MoqError::Bind(format!("{err}")))? - .listen() - .await - .map_err(|err| MoqError::Bind(format!("{err}")))?; - let addr = server - .local_addr() - .map_err(|err| MoqError::Bind(format!("{err}")))? - .to_string(); - self.server = Some(server); + let (bound, addr) = tokio::sync::oneshot::channel(); + let (queue, requests) = tokio::sync::mpsc::channel(1); + let certificates = { + // `cancel` flags the task before it takes `listening`, so checking the flag under + // that lock means either `cancel` finds the loop or this finds the cancel. `init` + // binds the QUIC socket, so it goes after the check and straight to the loop. + let mut slot = listening.lock().unwrap(); + if task.is_cancelled() { + return Err(MoqError::Cancelled); + } + let server = self + .config + .clone() + .init(Default::default()) + .map_err(|err| MoqError::Bind(format!("{err}")))?; + let certificates = server.certificates(); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let (closed, wait) = std::sync::mpsc::channel(); + crate::ffi::spawn( + AcceptLoop { + server, + bound, + queue, + stop: stopped, + closed, + } + .run(), + ); + *slot = Some(Listening { stop, closed: wait }); + certificates + }; + + // Dropped only when the runtime is gone. + let addr = addr.await.map_err(|_| MoqError::Cancelled)??; + self.requests = Some(Requests { + queue: requests, + certificates, + }); Ok(addr) } async fn accept(&mut self) -> Result>, MoqError> { - let server = self - .server + let requests = self + .requests .as_mut() .ok_or_else(|| MoqError::Bind("not listening; call listen() first".into()))?; - let publish = self.publish.clone(); - let consume = self.consume.clone(); - match server.accept().await { - Some(request) => Ok(Some(MoqRequest::new(request, publish, consume)?)), + match requests.queue.recv().await { + Some(request) => Ok(Some(MoqRequest::new( + request, + self.publish.clone(), + self.consume.clone(), + )?)), None => Ok(None), } } @@ -57,6 +183,8 @@ impl ServerState { #[derive(uniffi::Object)] pub struct MoqServer { task: Task, + /// Outside `task`, so cancellation never waits for a parked accept. + listening: std::sync::Mutex>, } impl MoqServer { @@ -66,7 +194,7 @@ impl MoqServer { fn configure_listen(&self, f: impl FnOnce(&mut ServerState) -> R) -> Result { let mut state = self.task.configure()?; - if state.server.is_some() { + if state.requests.is_some() { return Err(MoqError::Bind("already listening".into())); } Ok(f(&mut state)) @@ -84,8 +212,9 @@ impl MoqServer { config: moq_tokio::listen::Config::default(), publish: None, consume: None, - server: None, + requests: None, }), + listening: Default::default(), }) } @@ -151,7 +280,9 @@ impl MoqServer { /// Bind the listening socket. Returns the bound local address as a string, /// which is useful when binding to an ephemeral port (`:0`). pub async fn listen(&self) -> Result { - self.task.run(|mut state| async move { state.listen().await }).await + self.task + .run(|mut state| async move { state.listen(&self.task, &self.listening).await }) + .await } /// Accept the next incoming session. Returns `None` when the server has closed. @@ -169,11 +300,11 @@ impl MoqServer { /// before `listen()`. pub fn cert_fingerprints(&self) -> Result, MoqError> { let state = self.task.configure()?; - let server = state - .server + let requests = state + .requests .as_ref() .ok_or_else(|| MoqError::Bind("not listening; call listen() first".into()))?; - Ok(server.certificates().fingerprints()) + Ok(requests.certificates.fingerprints()) } /// Cancel any in-flight `listen()` or `accept()` call. @@ -182,14 +313,12 @@ impl MoqServer { /// not when the handle is, so the address can be bound again immediately. /// `cert_fingerprints()` returns `Cancelled` afterwards. pub fn cancel(&self) { - // `Listener::close` consumes the listener and releases its sockets before - // it returns; dropping the state alone would only schedule that, because - // the QUIC endpoint driver holds the socket until it observes the close. - self.task.cancel_and_wait(|mut state| async move { - if let Some(server) = state.server.take() { - server.close().await; - } - }); + self.task.cancel(); + // Hold the lock until close finishes so concurrent callers wait for the same release. + let mut listening = self.listening.lock().unwrap(); + if let Some(listening) = listening.take() { + listening.close(); + } } } diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index f174a220fe6..eb25a59d134 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -27,7 +27,7 @@ async fn ffi_caught_up() { rx.await.expect("ffi runtime dropped the catch-up task"); } -/// Spawn `fut` and wait until the FFI runtime has driven its inner `Task::run`. +/// Poll `fut` once, then wait for the FFI runtime to drive what that started. async fn spawn_parked(fut: F) -> tokio::task::JoinHandle where F: Future + Send + 'static, @@ -3088,6 +3088,97 @@ async fn raw_read_frame_skips_empty_then_populated_groups() { assert_eq!(frame.timestamp_us, 2_000); } +/// Observe the operation's wake even after UniFFI stops forwarding it to the host. +struct ForeignWake { + host: std::task::Waker, + ready: Arc, +} + +impl std::task::Wake for ForeignWake { + fn wake(self: Arc) { + self.ready.notify_one(); + self.host.wake_by_ref(); + } +} + +/// Exercise the real UniFFI cancel/free boundary, retaining the cancelled future until delivery. +fn foreign_call( + future: impl Future> + Send + 'static, +) -> (uniffi::Handle, Arc) { + let ready = Arc::new(tokio::sync::Notify::new()); + let notify = ready.clone(); + let future = async move { + let mut future = std::pin::pin!(future); + let result = std::future::poll_fn(|cx| { + let waker = std::task::Waker::from(Arc::new(ForeignWake { + host: cx.waker().clone(), + ready: notify.clone(), + })); + future.as_mut().poll(&mut std::task::Context::from_waker(&waker)) + }) + .await; + Ok(result) + }; + let handle = uniffi::rust_future_new(future, crate::UniFfiTag); + extern "C" fn continuation(_: u64, _: uniffi::RustFuturePoll) {} + // SAFETY: This live handle lowers Result<(), MoqError> to (), and is freed by the test. + unsafe { uniffi::rust_future_poll::<()>(handle.clone(), continuation, 0) }; + (handle, ready) +} + +#[tokio::test] +async fn foreign_cancel_before_free_preserves_frame() { + let (_broadcast, track, consumer) = raw_track(); + let reading = consumer.clone(); + let (cancelled, delivered) = foreign_call(async move { reading.read_frame().await.map(|_| ()) }); + ffi_caught_up().await; + // SAFETY: The handle is live and has the unit FFI return type. + unsafe { uniffi::rust_future_cancel::<()>(cancelled.clone()) }; + track.write_frame(group_frame(b"next")).unwrap(); + delivered.notified().await; + // SAFETY: This is the only free of the cancelled handle. + unsafe { uniffi::rust_future_free::<()>(cancelled) }; + track.finish().unwrap(); + let frame = consumer + .read_frame() + .await + .unwrap() + .expect("cancelled read consumed the frame"); + assert_eq!(frame.payload, b"next"); +} + +#[tokio::test] +async fn foreign_cancel_before_free_preserves_session() { + let server = MoqServer::new(); + server.set_bind("127.0.0.1:0".into()).unwrap(); + server.set_tls_generate(vec!["localhost".into()]).unwrap(); + let addr = server.listen().await.unwrap(); + let accepting = server.clone(); + let (cancelled, delivered) = foreign_call(async move { accepting.accept().await.map(|_| ()) }); + ffi_caught_up().await; + // SAFETY: The handle is live and has the unit FFI return type. + unsafe { uniffi::rust_future_cancel::<()>(cancelled.clone()) }; + let client = MoqClient::new(); + client.set_tls_verify(false).unwrap(); + client.set_reconnect(false).unwrap(); + let connect = tokio::spawn(async move { client.connect(format!("https://{addr}")).await }); + tokio::time::timeout(TIMEOUT, delivered.notified()) + .await + .expect("session never reached the pending operation"); + // SAFETY: This is the only free of the cancelled handle. + unsafe { uniffi::rust_future_free::<()>(cancelled) }; + let request = tokio::time::timeout(TIMEOUT, server.accept()) + .await + .expect("cancelled accept consumed the session") + .unwrap() + .unwrap(); + let session = request.accept().await.unwrap(); + let client_session = tokio::time::timeout(TIMEOUT, connect).await.unwrap().unwrap().unwrap(); + session.cancel(0); + client_session.shutdown(); + server.cancel(); +} + /// Cancelling `read_frame` after it has taken the next group must not drop that /// group: the next read still returns its first frame. #[tokio::test] @@ -4479,18 +4570,27 @@ async fn request_origin_setters_cancelled_after_cancel() { server.cancel(); } -/// Stopping the runtime is process-wide, so the scenario runs in a child test process: this -/// test re-runs its own binary filtered to itself with the marker set, and judges the exit. +/// Stopping the runtime is process-wide, so a shutdown scenario runs in a child test process. +/// +/// Returns true in the child. In the parent, re-runs this binary filtered to `test` with a +/// marker set, judges its exit, and returns false. +fn shutdown_child(test: &str) -> bool { + const MARKER: &str = "MOQ_FFI_TEST_SHUTDOWN_CHILD"; + if std::env::var_os(MARKER).is_some() { + return true; + } + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &format!("test::{test}")]) + .env(MARKER, "1") + .status() + .expect("failed to spawn the child test process"); + assert!(status.success(), "child test process failed: {status}"); + false +} + #[tokio::test] async fn shutdown_cancels_and_drops_cleanly() { - const MARKER: &str = "MOQ_FFI_TEST_SHUTDOWN_CHILD"; - if std::env::var_os(MARKER).is_none() { - let status = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "test::shutdown_cancels_and_drops_cleanly"]) - .env(MARKER, "1") - .status() - .expect("failed to spawn the child test process"); - assert!(status.success(), "child test process failed: {status}"); + if !shutdown_child("shutdown_cancels_and_drops_cleanly") { return; } @@ -4687,3 +4787,76 @@ async fn data_track_names_cannot_collide() { ); first.finish().unwrap(); } + +/// A `Task::run` polled in place on a host thread must finish its poll before shutdown stops +/// the drivers: a tokio timer polled after its driver is gone panics. +#[test] +fn shutdown_waits_for_an_in_place_poll() { + if !shutdown_child("shutdown_waits_for_an_in_place_poll") { + return; + } + + let (entered, entered_rx) = std::sync::mpsc::channel(); + let (release, release_rx) = std::sync::mpsc::channel::<()>(); + let poller = std::thread::spawn(move || { + let task = crate::ffi::Task::new(()); + let run = task.run(|_| async move { + entered.send(()).unwrap(); + // Holds this poll open while shutdown starts on another thread. + release_rx.recv().unwrap(); + // Register a timer without waiting for wall time to pass. A stopped driver panics here. + let mut timer = std::pin::pin!(tokio::time::sleep(Duration::from_secs(60))); + let _ = timer + .as_mut() + .poll(&mut std::task::Context::from_waker(std::task::Waker::noop())); + // Only shutdown may finish this call. + std::future::pending::>().await + }); + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(run) + }); + entered_rx.recv().unwrap(); + + let shutdown = std::thread::spawn(|| crate::moq_ffi_shutdown()); + + // A fresh call resolves `Cancelled` on its first poll once shutdown has begun. + let probe = crate::ffi::Task::new(()); + loop { + let mut call = std::pin::pin!(probe.run(|_| std::future::pending::>())); + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + match call.as_mut().poll(&mut cx) { + std::task::Poll::Ready(result) => { + assert!(matches!(result, Err(MoqError::Cancelled)), "{result:?}"); + break; + } + std::task::Poll::Pending => std::thread::yield_now(), + } + } + + // Shutdown has begun: the held poll now polls its timer. + release.send(()).unwrap(); + let result = poller.join().expect("the in-place poll panicked"); + assert!(matches!(result, Err(MoqError::Cancelled)), "{result:?}"); + shutdown.join().unwrap(); +} + +#[tokio::test] +async fn server_cancel_during_listen_releases_the_port() { + let addr = std::net::UdpSocket::bind("127.0.0.1:0").unwrap().local_addr().unwrap(); + let server = MoqServer::new(); + server.set_bind(addr.to_string()).unwrap(); + server.set_tls_generate(vec!["localhost".into()]).unwrap(); + let mut listen = Box::pin(server.listen()); + let _ = listen + .as_mut() + .poll(&mut std::task::Context::from_waker(std::task::Waker::noop())); + assert!( + std::net::UdpSocket::bind(addr).is_err(), + "listen must bind on its first poll" + ); + server.cancel(); + std::net::UdpSocket::bind(addr).expect("cancel must release the port before it returns"); + drop(listen); +}