rtci-host 0.2.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 arguments and results the front ends pass across their boundary
//! (`serde` types, camelCase as the W3C dictionaries are), with the parsing
//! both front ends share.

use rtci::data_channel::RTCDataChannelInit;
use rtci::peer_connection::configuration::RTCBundlePolicy;
use serde::Deserialize;
use serde::Serialize;

use crate::error::Error;
use crate::error::ErrorKind;
use crate::gate::GateExt;
use crate::gate::NetGate;
use crate::gate::Proto;
use crate::gate::Reach;
use crate::peer::IceServerSpec;
use crate::peer::ServerTransport;

/// One `RTCIceServer`.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IceServerArg {
  pub urls: Vec<String>,
  pub username: Option<String>,
  pub credential: Option<String>,
}

/// `RTCConfiguration`, as the front end's JavaScript passes it.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfigArg {
  pub ice_servers: Vec<IceServerArg>,
  pub ice_transport_policy: String,
  #[serde(default)]
  pub bundle_policy: Option<String>,
  /// `RTCCertificate` ids (the front end's certificate store's).
  #[serde(default)]
  pub certificates: Vec<u32>,
  /// `RTCConfiguration.denoNetwork`: the front end's handle for a
  /// [`Network`](crate::Network).
  #[serde(default)]
  pub network: Option<u32>,
}

impl ConfigArg {
  /// `iceTransportPolicy: "relay"`.
  pub fn relay_only(&self) -> bool {
    self.ice_transport_policy == "relay"
  }

  /// `bundlePolicy` (`balanced` for anything but `max-bundle` and
  /// `max-compat`).
  pub fn bundle_policy(&self) -> RTCBundlePolicy {
    match self.bundle_policy.as_deref() {
      Some("max-bundle") => RTCBundlePolicy::MaxBundle,
      Some("max-compat") => RTCBundlePolicy::MaxCompat,
      _ => RTCBundlePolicy::Balanced,
    }
  }
}

/// Parses every URL of `RTCConfiguration.iceServers` (the W3C
/// `SyntaxError` / `InvalidAccessError` checks); no gate is asked.
pub fn parse_ice_servers(
  servers: &[IceServerArg],
) -> Result<Vec<IceServerSpec>, Error> {
  let mut specs = Vec::new();
  for server in servers {
    for url in &server.urls {
      specs.push(IceServerSpec::parse(
        url,
        server.username.as_deref(),
        server.credential.as_deref(),
      )?);
    }
  }
  Ok(specs)
}

/// Asks `gate` for each server's host and port before DNS
/// ([`ReachKind::IceServer`](crate::ReachKind::IceServer)); the first
/// refusal is a [`ErrorKind::NotCapable`] error.
pub fn check_ice_servers(
  gate: &dyn NetGate,
  specs: &[IceServerSpec],
) -> Result<(), Error> {
  for spec in specs {
    let proto = match spec.transport {
      ServerTransport::Udp => Proto::Udp,
      ServerTransport::Tcp => Proto::Tcp,
      ServerTransport::Tls => Proto::Tls,
    };
    gate
      .check(&Reach::ice_server(proto, &spec.host, spec.port))
      .map_err(Error::not_capable)?;
  }
  Ok(())
}

/// Whether any server needs TLS (`turns:` / `stuns:`): the front end then
/// builds [`PeerOptions::tls`](crate::PeerOptions::tls).
pub fn needs_tls(specs: &[IceServerSpec]) -> bool {
  specs.iter().any(|s| s.transport == ServerTransport::Tls)
}

/// `RTCIceCandidateInit`.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CandidateArg {
  pub candidate: String,
  pub sdp_mid: Option<String>,
  #[serde(rename = "sdpMLineIndex")]
  pub sdp_m_line_index: Option<u16>,
  pub username_fragment: Option<String>,
}

/// `createDataChannel(label, init)`.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataChannelArg {
  pub label: String,
  pub ordered: bool,
  pub max_packet_life_time: Option<u16>,
  pub max_retransmits: Option<u16>,
  pub protocol: String,
  pub negotiated: bool,
  pub id: Option<u16>,
  // wpt100:S2 the DCEP priority (webrtc-priority 4.3), 256 when absent.
  #[serde(default = "default_channel_priority")]
  pub priority: u16,
}

fn default_channel_priority() -> u16 {
  256
}

impl DataChannelArg {
  /// The engine's channel options; a negotiated channel without an id is a
  /// `TypeError`.
  pub fn to_init(&self) -> Result<RTCDataChannelInit, Error> {
    let negotiated = if self.negotiated {
      Some(self.id.ok_or_else(|| {
        Error::new(ErrorKind::Type, "A negotiated RTCDataChannel needs an id")
      })?)
    } else {
      None
    };
    Ok(RTCDataChannelInit {
      ordered: self.ordered,
      max_packet_life_time: self.max_packet_life_time,
      max_retransmits: self.max_retransmits,
      protocol: self.protocol.clone(),
      negotiated,
      priority: self.priority,
    })
  }
}

/// A created data channel: its engine handle and its stream id, when
/// assigned.
#[derive(Clone, Copy, Debug, Serialize)]
pub struct CreatedChannel {
  pub channel: u32,
  pub id: Option<u16>,
}

/// `generateCertificate`'s algorithm (WebCrypto's dictionaries).
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeygenArg {
  pub name: String,
  pub named_curve: Option<String>,
  pub modulus_length: Option<u32>,
  pub public_exponent: Option<Vec<u8>>,
  pub hash: Option<String>,
}

/// An `RTCCertificate` for the front end's JavaScript.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CertificateInfo {
  pub id: u32,
  /// Milliseconds since the epoch.
  pub expires: f64,
  pub fingerprints: Vec<FingerprintInfo>,
}

/// One `RTCDtlsFingerprint`.
#[derive(Clone, Debug, Serialize)]
pub struct FingerprintInfo {
  pub algorithm: String,
  pub value: String,
}