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.

//! [`AskGate`]: an asynchronous [`NetGate`] whose questions a front end
//! reads as [`GateRequest`]s (the `gaterequest` event) and answers by
//! ticket with [`AskGate::answer`]. `rtci-ffi`'s gate is one: JavaScript
//! answers each request from `Deno.permissions`.

use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::rc::Rc;
use std::rc::Weak;
use std::time::Duration;

use serde::Serialize;
use tokio::sync::oneshot;

use crate::gate::DEFAULT_ASK_TIMEOUT;
use crate::gate::Host;
use crate::gate::LocalBoxFuture;
use crate::gate::NetGate;
use crate::gate::Reach;
use crate::gate::ReachKey;
use crate::gate::Verdict;

/// The refusal for every question asked before [`AskGate::attach`].
pub const NO_GATE_REGISTERED: &str = "no permission gate registered";

/// One question for the front end: the `gaterequest` event.
///
/// Serializes as
/// `{"type":"gaterequest","ticket":1,"kind":"remoteCandidate","dir":"connect","proto":"udp","host":"192.0.2.1","port":5000,"resolvedFrom":null}`.
/// `kind` is a [`ReachKind`](crate::ReachKind) name, or `"interfaces"` for
/// the interface-list question (whose `dir`, `proto`, `host`, `port` and
/// `resolvedFrom` are `null`). `host` is a name or an IP address (an IPv6
/// one without brackets); `port` is `null` for a bind (any port).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename = "gaterequest", rename_all = "camelCase")]
pub struct GateRequest {
  /// What [`AskGate::answer`] takes.
  pub ticket: u32,
  pub kind: &'static str,
  pub dir: Option<&'static str>,
  pub proto: Option<&'static str>,
  pub host: Option<String>,
  pub port: Option<u16>,
  pub resolved_from: Option<String>,
  /// The question itself (`None` for the interface list).
  #[serde(skip)]
  pub reach: Option<Reach>,
}

impl GateRequest {
  fn new(ticket: u32, reach: Option<Reach>) -> Self {
    match reach {
      Some(r) => Self {
        ticket,
        kind: r.kind.as_str(),
        dir: Some(r.dir.as_str()),
        proto: Some(r.proto.as_str()),
        host: Some(match &r.host {
          Host::Name(name) => name.clone(),
          Host::Ip(ip) => ip.to_string(),
        }),
        port: r.port,
        resolved_from: r.resolved_from.clone(),
        reach: Some(r),
      },
      None => Self {
        ticket,
        kind: "interfaces",
        dir: None,
        proto: None,
        host: None,
        port: None,
        resolved_from: None,
        reach: None,
      },
    }
  }
}

/// What an answer is remembered by.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Key {
  Reach(ReachKey),
  Interfaces,
}

#[derive(Default)]
struct State {
  attached: bool,
  last_ticket: u32,
  /// Unanswered tickets: what they ask and where the answer goes.
  pending: HashMap<u32, (Key, oneshot::Sender<Verdict>)>,
  /// Requests the front end hasn't taken yet.
  queue: VecDeque<GateRequest>,
  /// Answers given, reused by `decide` (for every connection on this gate).
  answers: HashMap<Key, Verdict>,
  timeout: Option<Duration>,
}

#[derive(Default)]
struct Inner {
  state: RefCell<State>,
  notify: RefCell<Option<Rc<dyn Fn()>>>,
}

/// An asynchronous gate answered by ticket. Deny by default: until
/// [`AskGate::attach`] every question is refused at once
/// ([`NO_GATE_REGISTERED`]). Once attached, each question the engine asks
/// queues a [`GateRequest`] ([`AskGate::take_requests`]) and runs the
/// notifier ([`AskGate::set_notify`]); [`AskGate::answer`] delivers the
/// verdict. An answer is remembered and reused for the same question from
/// any connection on this gate ([`NetGate::decide`]).
///
/// A request the engine stops waiting for (its connection closed, or
/// [`NetGate::ask_timeout`] passed, which is a refusal) leaves the queue
/// and its ticket: a later `answer` for it returns `false`. Dropping the
/// last clone, or [`AskGate::detach`], refuses everything pending.
///
/// Single-threaded, like the engine: answer on the engine's thread.
#[derive(Clone, Default)]
pub struct AskGate {
  inner: Rc<Inner>,
}

impl AskGate {
  /// A detached gate (every question refused).
  pub fn new() -> Self {
    Self::default()
  }

  /// Starts asking (a front end registered its handler).
  pub fn attach(&self) {
    self.inner.state.borrow_mut().attached = true;
  }

  /// Stops asking: everything pending is refused, and so is every later
  /// question that wasn't answered before.
  pub fn detach(&self) {
    let pending: Vec<_> = {
      let mut state = self.inner.state.borrow_mut();
      state.attached = false;
      state.queue.clear();
      state.pending.drain().map(|(_, (_, tx))| tx).collect()
    };
    for tx in pending {
      let _ = tx.send(Verdict::Deny(NO_GATE_REGISTERED.to_string()));
    }
  }

  pub fn is_attached(&self) -> bool {
    self.inner.state.borrow().attached
  }

  /// Runs after each request is queued (a front end wakes its event loop
  /// here). It must not call back into the engine.
  pub fn set_notify(&self, f: impl Fn() + 'static) {
    *self.inner.notify.borrow_mut() = Some(Rc::new(f));
  }

  /// How long the engine waits for an answer (default
  /// [`DEFAULT_ASK_TIMEOUT`]).
  pub fn set_timeout(&self, timeout: Duration) {
    self.inner.state.borrow_mut().timeout = Some(timeout);
  }

  /// The requests queued since the last call, oldest first.
  pub fn take_requests(&self) -> Vec<GateRequest> {
    self.inner.state.borrow_mut().queue.drain(..).collect()
  }

  /// Tickets waiting for an answer.
  pub fn pending(&self) -> usize {
    self.inner.state.borrow().pending.len()
  }

  /// Answers `ticket`. `false` when no one waits for it any more (an
  /// unknown ticket, answered already, timed out, or its connection
  /// closed). The verdict is remembered either way for a known question.
  pub fn answer(&self, ticket: u32, verdict: Verdict) -> bool {
    let entry = {
      let mut state = self.inner.state.borrow_mut();
      let entry = state.pending.remove(&ticket);
      if let Some((key, _)) = &entry {
        state.answers.insert(key.clone(), verdict.clone());
      }
      state.queue.retain(|r| r.ticket != ticket);
      entry
    };
    match entry {
      Some((_, tx)) => tx.send(verdict).is_ok(),
      None => false,
    }
  }

  fn ask_key(
    &self,
    key: Key,
    reach: Option<Reach>,
  ) -> LocalBoxFuture<'static, Verdict> {
    let (ticket, rx) = {
      let mut state = self.inner.state.borrow_mut();
      if !state.attached {
        return Box::pin(std::future::ready(Verdict::Deny(
          NO_GATE_REGISTERED.to_string(),
        )));
      }
      if let Some(verdict) = state.answers.get(&key) {
        return Box::pin(std::future::ready(verdict.clone()));
      }
      let mut ticket = state.last_ticket.wrapping_add(1).max(1);
      while state.pending.contains_key(&ticket) {
        ticket = ticket.wrapping_add(1).max(1);
      }
      state.last_ticket = ticket;
      let (tx, rx) = oneshot::channel();
      state.pending.insert(ticket, (key, tx));
      state.queue.push_back(GateRequest::new(ticket, reach));
      (ticket, rx)
    };
    let notify = self.inner.notify.borrow().clone();
    if let Some(f) = notify {
      f();
    }
    let guard = TicketGuard {
      inner: Rc::downgrade(&self.inner),
      ticket,
    };
    Box::pin(async move {
      let _guard = guard;
      rx.await.unwrap_or_else(|_| {
        Verdict::Deny("The permission request was dropped".to_string())
      })
    })
  }
}

/// Withdraws a ticket whose future was dropped unanswered.
struct TicketGuard {
  inner: Weak<Inner>,
  ticket: u32,
}

impl Drop for TicketGuard {
  fn drop(&mut self) {
    if let Some(inner) = self.inner.upgrade()
      && let Ok(mut state) = inner.state.try_borrow_mut()
    {
      state.pending.remove(&self.ticket);
      state.queue.retain(|r| r.ticket != self.ticket);
    }
  }
}

impl NetGate for AskGate {
  fn decide(&self, reach: &Reach) -> Option<Verdict> {
    let state = self.inner.state.borrow();
    if !state.attached {
      return Some(Verdict::Deny(NO_GATE_REGISTERED.to_string()));
    }
    state
      .answers
      .get(&Key::Reach(ReachKey::from(reach)))
      .cloned()
  }

  fn ask(&self, reach: Reach) -> LocalBoxFuture<'static, Verdict> {
    self.ask_key(Key::Reach(ReachKey::from(&reach)), Some(reach))
  }

  fn interfaces(&self) -> Option<Verdict> {
    let state = self.inner.state.borrow();
    if !state.attached {
      return Some(Verdict::Deny(NO_GATE_REGISTERED.to_string()));
    }
    state.answers.get(&Key::Interfaces).cloned()
  }

  fn ask_interfaces(&self) -> LocalBoxFuture<'static, Verdict> {
    self.ask_key(Key::Interfaces, None)
  }

  fn ask_timeout(&self) -> Duration {
    self
      .inner
      .state
      .borrow()
      .timeout
      .unwrap_or(DEFAULT_ASK_TIMEOUT)
  }
}