rtci-host 0.3.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 engine's side of the permission gate: [`GateCache`] remembers the
//! answers a connection was given and dedupes the questions in flight, and
//! mints the [`GateToken`]s the socket factory takes.
//!
//! Lookups go: an answer the cache already has, then [`NetGate::decide`]
//! (not remembered, so a synchronous gate is asked every time, as before
//! any of this was asynchronous), then one [`NetGate::ask`] per question,
//! raced against [`NetGate::ask_timeout`] and guarded against panics, whose
//! answer the cache keeps for the connection's life.

use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::rc::Rc;
use std::task::Context;
use std::task::Poll;

use tokio::sync::Notify;

use crate::gate::GateExt;
use crate::gate::GateToken;
use crate::gate::NetGate;
use crate::gate::Reach;
use crate::gate::ReachKey;
use crate::gate::Verdict;
use crate::gate::describe;
use crate::gate::interfaces_pending;
use crate::rt::Cancel;
use crate::rt::OrCancel;

/// One question: an address, or the interface list.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Question {
  Reach(ReachKey),
  Interfaces,
}

/// A connection's (or a transport's, or a network's) view of its gate.
pub(crate) struct GateCache {
  gate: Rc<dyn NetGate>,
  /// Answers to asked questions (never `decide`'s).
  answers: RefCell<HashMap<Question, Verdict>>,
  /// Questions asked and not answered yet.
  asking: RefCell<HashSet<Question>>,
  /// Notified on every answer (the futures of [`GateCache::verdict`]).
  changed: Notify,
  /// Run after every answer (the owner pokes its driver and its pending
  /// operations).
  on_answer: RefCell<Option<Rc<dyn Fn()>>>,
  /// Cancels the asks in flight (the owner closed).
  cancel: Cancel,
}

impl GateCache {
  pub(crate) fn new(gate: Rc<dyn NetGate>) -> Rc<Self> {
    Rc::new(Self {
      gate,
      answers: RefCell::new(HashMap::new()),
      asking: RefCell::new(HashSet::new()),
      changed: Notify::new(),
      on_answer: RefCell::new(None),
      cancel: Cancel::new(),
    })
  }

  /// Sets what runs after each answer arrives.
  pub(crate) fn set_on_answer(&self, f: impl Fn() + 'static) {
    *self.on_answer.borrow_mut() = Some(Rc::new(f));
  }

  /// Drops the asks in flight; later questions still get answers from the
  /// cache and `decide`, and new asks are not made.
  pub(crate) fn close(&self) {
    self.cancel.cancel();
    self.changed.notify_waiters();
  }

  /// The answer to `reach` now: `Some(Ok(token))` allowed, `Some(Err(why))`
  /// refused, `None` asked and not answered yet (the ask is made here, once).
  pub(crate) fn lookup(
    self: &Rc<Self>,
    reach: &Reach,
  ) -> Option<Result<GateToken, String>> {
    let question = Question::Reach(ReachKey::from(reach));
    let verdict = self.answered(&question).or_else(|| {
      catch(|| self.gate.decide(reach)).unwrap_or_else(|| {
        Some(Verdict::Deny(format!(
          "The permission gate failed for \"{}\"",
          describe(reach)
        )))
      })
    });
    match verdict {
      Some(Verdict::Allow) => Some(Ok(GateToken::new(reach.clone()))),
      Some(Verdict::Deny(why)) => Some(Err(why)),
      None => {
        self.start_ask(question, Some(reach.clone()));
        None
      }
    }
  }

  /// The interface-list question, as [`GateCache::lookup`].
  pub(crate) fn lookup_interfaces(
    self: &Rc<Self>,
  ) -> Option<Result<(), String>> {
    let question = Question::Interfaces;
    let verdict = self.answered(&question).or_else(|| {
      catch(|| self.gate.interfaces())
        .unwrap_or_else(|| Some(interfaces_pending()))
    });
    match verdict {
      Some(v) => Some(v.into_result()),
      None => {
        self.start_ask(question, None);
        None
      }
    }
  }

  /// The answer to `reach`, waiting for it if it was asked. Ready at once
  /// for a gate that decides.
  pub(crate) async fn verdict(
    self: &Rc<Self>,
    reach: Reach,
  ) -> Result<GateToken, String> {
    loop {
      let notified = self.changed.notified();
      let mut notified = std::pin::pin!(notified);
      notified.as_mut().enable();
      if let Some(answer) = self.lookup(&reach) {
        return answer;
      }
      if self.cancel.is_cancelled() {
        return Err(closed());
      }
      notified.await;
    }
  }

  /// The interface-list answer, waiting for it if it was asked.
  pub(crate) async fn interfaces(self: &Rc<Self>) -> Result<(), String> {
    loop {
      let notified = self.changed.notified();
      let mut notified = std::pin::pin!(notified);
      notified.as_mut().enable();
      if let Some(answer) = self.lookup_interfaces() {
        return answer;
      }
      if self.cancel.is_cancelled() {
        return Err(closed());
      }
      notified.await;
    }
  }

  fn answered(&self, question: &Question) -> Option<Verdict> {
    self.answers.borrow().get(question).cloned()
  }

  /// One ask per question in flight; the answer (a refusal on a timeout or
  /// a failure) is remembered and announced.
  fn start_ask(self: &Rc<Self>, question: Question, reach: Option<Reach>) {
    if self.cancel.is_cancelled()
      || !self.asking.borrow_mut().insert(question.clone())
    {
      return;
    }
    let this = self.clone();
    let cancel = self.cancel.clone();
    crate::rt::spawn(
      async move {
        let timeout = this.gate.ask_timeout();
        let what = match &reach {
          Some(r) => format!("net access to \"{}\"", describe(r)),
          None => "the network interfaces".to_string(),
        };
        let future = catch(|| match reach {
          Some(r) => this.gate.ask(r),
          None => this.gate.ask_interfaces(),
        });
        let verdict = match future {
          None => Verdict::Deny(format!("The permission gate failed for {what}")),
          Some(future) => {
            match tokio::time::timeout(timeout, CatchUnwind(future)).await {
              Ok(Some(verdict)) => verdict,
              Ok(None) => {
                Verdict::Deny(format!("The permission gate failed for {what}"))
              }
              Err(_) => Verdict::Deny(format!(
                "The permission request for {what} was not answered within {} ms",
                timeout.as_millis()
              )),
            }
          }
        };
        this.asking.borrow_mut().remove(&question);
        this.answers.borrow_mut().insert(question, verdict);
        this.changed.notify_waiters();
        let on_answer = this.on_answer.borrow().clone();
        if let Some(f) = on_answer {
          f();
        }
      }
      .or_cancel(cancel),
    );
  }
}

fn closed() -> String {
  "The connection closed before the permission was answered".to_string()
}

/// `f()`, or `None` if it panicked (a gate's panic is a refusal).
fn catch<T>(f: impl FnOnce() -> T) -> Option<T> {
  std::panic::catch_unwind(AssertUnwindSafe(f)).ok()
}

/// A future's output, or `None` if polling it panicked.
struct CatchUnwind<F>(F);

impl<F: Future + Unpin> Future for CatchUnwind<F> {
  type Output = Option<F::Output>;

  fn poll(
    mut self: Pin<&mut Self>,
    cx: &mut Context<'_>,
  ) -> Poll<Self::Output> {
    let inner = &mut self.0;
    match std::panic::catch_unwind(AssertUnwindSafe(|| {
      Pin::new(&mut *inner).poll(cx)
    })) {
      Ok(Poll::Ready(v)) => Poll::Ready(Some(v)),
      Ok(Poll::Pending) => Poll::Pending,
      Err(_) => Poll::Ready(None),
    }
  }
}

/// Where a two-phase operation gets its answers: a connection's cache
/// (asks, waits), or a gate asked synchronously only (`None` is a refusal;
/// [`crate::Network::new`]).
pub(crate) enum Verdicts<'a> {
  Cache(Rc<GateCache>),
  Sync(&'a dyn NetGate),
}

impl Verdicts<'_> {
  pub(crate) async fn reach(&self, reach: Reach) -> Result<GateToken, String> {
    match self {
      Verdicts::Cache(cache) => cache.verdict(reach).await,
      Verdicts::Sync(gate) => {
        gate.check(&reach).map(|()| GateToken::new(reach))
      }
    }
  }

  pub(crate) async fn interfaces(&self) -> Result<(), String> {
    match self {
      Verdicts::Cache(cache) => cache.interfaces().await,
      Verdicts::Sync(gate) => gate.check_interfaces(),
    }
  }
}