rtci-host 0.1.0

The host I/O around the sans-I/O rtci WebRTC engine: sockets, timers, STUN/TURN clients, ICE-TCP, mDNS and media, behind a permission gate and a socket factory
Documentation
// Copyright 2026 Brainwires. MIT OR Apache-2.0.

//! The single-threaded task glue the engine runs on: spawning `!Send`
//! tasks and cancelling them together.

use std::future::Future;

use tokio::runtime::Handle;
use tokio::runtime::RuntimeFlavor;
use tokio_util::sync::CancellationToken;

/// Spawns a `!Send` task on the current thread.
///
/// On a current-thread runtime (Deno's, or an engine thread of its own) the
/// task is spawned on the runtime itself, as `deno_core::unsync::spawn`
/// does, so no `LocalSet` is needed. On any other runtime the caller must
/// be inside a [`tokio::task::LocalSet`] (else `spawn_local` panics).
pub(crate) fn spawn<F>(future: F)
where
  F: Future + 'static,
  F::Output: 'static,
{
  if Handle::current().runtime_flavor() == RuntimeFlavor::CurrentThread {
    // A current-thread runtime never moves a task to another thread, which
    // is what makes `deno_unsync`'s `Send` mask sound (checked here, not
    // only in debug builds).
    drop(deno_unsync::spawn(future));
  } else {
    drop(tokio::task::spawn_local(future));
  }
}

/// The engine's cancellation handle (`deno_core::CancelHandle` before).
pub(crate) type Cancel = CancellationToken;

/// The future was cancelled before it finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Cancelled;

/// `fut.or_cancel(token)`: the future's output, or [`Cancelled`] once the
/// token is cancelled (at once when it already is), like
/// `deno_core::CancelFuture`.
pub(crate) trait OrCancel: Future + Sized {
  fn or_cancel(
    self,
    token: Cancel,
  ) -> impl Future<Output = Result<Self::Output, Cancelled>> {
    async move { token.run_until_cancelled_owned(self).await.ok_or(Cancelled) }
  }
}

impl<F: Future> OrCancel for F {}

/// Polls `future` once, here, with a waker that does nothing: its output if
/// it is ready (a two-phase operation whose gate decided everything), else
/// the future back, for the caller to spawn or queue (its next poll, with a
/// real waker, registers that one).
pub(crate) fn poll_now<'a, T>(
  mut future: crate::gate::LocalBoxFuture<'a, T>,
) -> Result<T, crate::gate::LocalBoxFuture<'a, T>> {
  let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
  match future.as_mut().poll(&mut cx) {
    std::task::Poll::Ready(value) => Ok(value),
    std::task::Poll::Pending => Err(future),
  }
}