Add WebRTC negotiation to the voice host (#42676)

## What changed

- Add helper protocol requests to create a WebRTC offer, apply an answer, and report readiness once the ordered `oai-events` data channel opens.
- Support UDP and TCP candidates while bounding signaling size, remote candidates, inbound TCP streams, and WebRTC buffers. Redact session descriptions and peer errors from diagnostics.
- Close unexpected remote data channels and tear down the peer during helper shutdown, including when the parent pipe is lost during startup.

## Testing

- Exercise offer/answer negotiation and clean shutdown over real UDP and TCP sockets.
- Cover signaling validation, candidate and connection limits, early packet loss, slow TCP connection setup, and blocked-startup parent loss.

GitOrigin-RevId: 5f5e60a3a4d1d8eaca2e4724e66284f54061b6af
This commit is contained in:
Benjamin Carlsson authored and copyberry committed 2026-09-04 05:07:02 +00:00
1 parent 048a936a23
commit 1b53f6a44e
17 files changed
+1874 -69

No files matched your search

+45 -3
View File
@@ -1,6 +1,8 @@
//! Same-build helper lifecycle and opt-in private runtime initialization. No devices or media yet.
//! Same-build helper lifecycle, private runtime initialization and owned transport. No devices yet.
mod runtime;
mod transport;
mod transport_runtime;
use std::io;
use std::io::Write;
@@ -22,7 +24,13 @@ fn main() {
match (args.next(), args.next()) {
(Some(arg), None) if arg == "--build-commit" => println!("{BUILD_COMMIT}"),
(None, None) => {
if run().is_err() {
if run(|executor| {
executor
.block_on(transport::Transport::new())
.map_err(io::Error::other)
})
.is_err()
{
std::process::exit(/*code*/ 1);
}
}
@@ -30,7 +38,9 @@ fn main() {
}
}
fn run() -> io::Result<()> {
fn run(
start_transport: impl Fn(&tokio::runtime::Runtime) -> io::Result<transport::Transport>,
) -> io::Result<()> {
let (sender, receiver) = mpsc::sync_channel(/*bound*/ 1);
std::thread::Builder::new()
.name("voice-control".into())
@@ -67,8 +77,29 @@ fn run() -> io::Result<()> {
output.write_all(&encode_frame(&Message::Ready {})?)?;
output.flush()?;
let mut runtime = None;
let executor = tokio::runtime::Runtime::new()?;
let mut transport = None;
let mut answered = false;
loop {
let reply = match receiver.recv() {
Ok(Message::StartTransport {}) if transport.is_none() => {
let peer = start_transport(&executor)?;
let sdp = executor.block_on(peer.offer()).map_err(io::Error::other)?;
transport = Some(peer);
Message::Offer {
sdp: sdp.try_into().map_err(io::Error::other)?,
}
}
Ok(Message::ApplyAnswer { sdp }) if !answered => {
let Some(peer) = transport.as_ref() else {
return Err(io::Error::other("voice transport not started"));
};
executor
.block_on(peer.apply_answer(sdp.into_sdp()))
.map_err(io::Error::other)?;
answered = true;
Message::TransportReady {}
}
Ok(Message::InitializeRuntime {}) => {
if runtime.is_some() {
return Err(io::Error::other("runtime already initialized"));
@@ -77,6 +108,9 @@ fn run() -> io::Result<()> {
Message::RuntimeReady {}
}
Ok(Message::Close {}) => {
if let Some(mut peer) = transport.take() {
executor.block_on(peer.close()).map_err(io::Error::other)?;
}
output.write_all(&encode_frame(&Message::Closed {})?)?;
return output.flush();
}
@@ -85,6 +119,10 @@ fn run() -> io::Result<()> {
Message::Hello { .. }
| Message::Ready {}
| Message::RuntimeReady {}
| Message::StartTransport {}
| Message::ApplyAnswer { .. }
| Message::Offer { .. }
| Message::TransportReady {}
| Message::Closed {},
) => return Err(io::Error::other("invalid voice control sequence")),
};
@@ -92,3 +130,7 @@ fn run() -> io::Result<()> {
output.flush()?;
}
}
#[cfg(test)]
#[path = "main_tests.rs"]
mod tests;
+87
View File
@@ -0,0 +1,87 @@
//! Verify the real parent-loss watchdog while the startup worker is deterministically blocked.
use super::*;
use std::process::Stdio;
use pretty_assertions::assert_eq;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio::time::timeout;
const STARTUP_BLOCKED: &[u8] = b"voice startup blocked\n";
const CHILD_ENV: &str = "CODEX_VOICE_WATCHDOG_TEST_CHILD";
#[test]
#[ignore = "subprocess fixture for the parent-loss watchdog test"]
fn blocked_startup_fixture() {
if std::env::var_os(CHILD_ENV).as_deref() != Some(std::ffi::OsStr::new("1")) {
return;
}
run(|_| {
io::stderr().write_all(STARTUP_BLOCKED)?;
io::stderr().flush()?;
loop {
std::thread::park();
}
})
.unwrap();
}
#[tokio::test]
async fn parent_pipe_loss_terminates_helper_with_blocked_transport_startup() {
timeout(Duration::from_secs(/*secs*/ 10), async {
let mut child = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"tests::blocked_startup_fixture",
"--ignored",
"--nocapture",
])
.env(CHILD_ENV, "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.unwrap();
let mut input = child.stdin.take().unwrap();
input
.write_all(
&encode_frame(&Message::Hello {
protocol: 1,
build_commit: BUILD_COMMIT.to_owned(),
})
.unwrap(),
)
.await
.unwrap();
let expected = encode_frame(&Message::Ready {}).unwrap();
let mut prefix = Vec::new();
// libtest writes a short harness prefix before the helper's framed output.
while !prefix.ends_with(&expected) {
assert!(prefix.len() < 512, "missing helper ready frame");
prefix.push(child.stdout.as_mut().unwrap().read_u8().await.unwrap());
}
input
.write_all(&encode_frame(&Message::StartTransport {}).unwrap())
.await
.unwrap();
let mut marker = vec![0; STARTUP_BLOCKED.len()];
child
.stderr
.as_mut()
.unwrap()
.read_exact(&mut marker)
.await
.unwrap();
assert_eq!(marker, STARTUP_BLOCKED);
assert!(child.try_wait().unwrap().is_none());
drop(input);
let output = child.wait_with_output().await.unwrap();
assert_eq!(output.status.code(), Some(1));
assert_eq!((output.stdout, output.stderr), (vec![], vec![]));
})
.await
.unwrap();
}
+226
View File
@@ -0,0 +1,226 @@
//! Owns one WebRTC peer and ordered event channel; the helper runtime bounds their lifetime.
//! Raw upstream errors and data messages are discarded; typed events use the existing sideband.
//! Candidate admission is bounded before an answer can mutate the peer or start ICE work.
//! Remotely opened channels are rejected; only the locally created event channel is used.
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use futures::future::BoxFuture;
use tokio::sync::Notify;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use tokio::time::timeout;
use webrtc::data_channel::DataChannel;
use webrtc::data_channel::DataChannelEvent;
use webrtc::peer_connection::PeerConnection;
use webrtc::peer_connection::PeerConnectionBuilder;
use webrtc::peer_connection::PeerConnectionEventHandler;
use webrtc::peer_connection::RTCIceCandidateInit;
use webrtc::peer_connection::RTCIceGatheringState;
use webrtc::peer_connection::RTCSessionDescription;
const WAIT: Duration = Duration::from_secs(/*secs*/ 15);
const MAX_REMOTE_CANDIDATES: usize = 32;
type Result<T> = std::result::Result<T, &'static str>;
struct Events(Arc<Notify>);
// The upstream trait requires async-trait's boxed-future ABI.
impl PeerConnectionEventHandler for Events {
fn on_data_channel<'a, 'async_trait>(
&'a self,
channel: Arc<dyn DataChannel>,
) -> BoxFuture<'async_trait, ()>
where
'a: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
// Locally created channels do not invoke this callback.
let _ = channel.close().await;
})
}
fn on_ice_gathering_state_change<'a, 'async_trait>(
&'a self,
state: RTCIceGatheringState,
) -> BoxFuture<'async_trait, ()>
where
'a: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
if state == RTCIceGatheringState::Complete {
self.0.notify_one();
}
})
}
}
pub(crate) struct Transport {
connection: Arc<dyn PeerConnection>,
gathered: Arc<Notify>,
observer: JoinHandle<()>,
ready: watch::Receiver<bool>,
}
impl Transport {
pub(crate) async fn new() -> Result<Self> {
Self::with_runtime(Arc::new(crate::transport_runtime::VoiceRuntime::default())).await
}
async fn with_runtime(runtime: Arc<dyn webrtc::runtime::Runtime>) -> Result<Self> {
let gathered = Arc::new(Notify::new());
// Upstream defaults exhaust checks after 1.4s, including checks sent before
// a TCP connection exists. Keep probing throughout our negotiation deadline.
let check_interval = Duration::from_millis(/*millis*/ 200);
let attempts = u16::try_from(WAIT.as_millis() / check_interval.as_millis())
.map_err(|_| "invalid voice ICE attempt budget")?;
let mut settings = webrtc::peer_connection::SettingEngine::default();
settings.set_ice_connection_attempts(Some(check_interval), Some(attempts));
let connection: Arc<dyn PeerConnection> = Arc::new(
PeerConnectionBuilder::new()
.with_runtime(runtime)
.with_setting_engine(settings)
.with_handler(Arc::new(Events(gathered.clone())))
.with_udp_addrs(vec!["0.0.0.0:0", "[::]:0"])
.with_tcp_addrs(vec!["0.0.0.0:0", "[::]:0"])
.with_data_channel_send_buffer_limit(/*bytes*/ 64 * 1024)
.with_sctp_receive_buffer_size(/*size*/ 64 * 1024)
.build()
.await
.map_err(|_| "failed to create voice peer")?,
);
let channel = match connection
.create_data_channel("oai-events", /*options*/ None)
.await
{
Ok(channel) => channel,
Err(_) => {
let _ = timeout(Duration::from_secs(/*secs*/ 2), connection.close()).await;
return Err("failed to create voice event channel");
}
};
let (sender, ready) = watch::channel(false);
let observer = tokio::spawn(async move {
while let Some(event) = channel.poll().await {
match event {
DataChannelEvent::OnOpen => {
sender.send_replace(true);
}
DataChannelEvent::OnError
| DataChannelEvent::OnClosing
| DataChannelEvent::OnClose => break,
DataChannelEvent::OnMessage(_)
| DataChannelEvent::OnBufferedAmountLow
| DataChannelEvent::OnBufferedAmountHigh => {}
}
}
sender.send_replace(false);
});
Ok(Self {
connection,
gathered,
observer,
ready,
})
}
pub(crate) async fn offer(&self) -> Result<String> {
timeout(WAIT, async {
let offer = self
.connection
.create_offer(/*options*/ None)
.await
.map_err(|_| "failed to create voice offer")?;
self.connection
.set_local_description(offer)
.await
.map_err(|_| "failed to set voice offer")?;
self.gathered.notified().await;
self.connection
.local_description()
.await
.map(|offer| offer.sdp)
.ok_or("missing voice offer")
})
.await
.map_err(|_| "timed out gathering voice candidates")?
}
pub(crate) async fn apply_answer(&self, sdp: String) -> Result<()> {
let answer = RTCSessionDescription::answer(sdp).map_err(|_| "invalid voice answer")?;
let parsed = answer.unmarshal().map_err(|_| "invalid voice answer")?;
let mut seen = HashSet::new();
let mut candidates = Vec::new();
// Count all occurrences, including duplicates and other components/media sections.
// set_remote_description itself installs ICE candidates, so validate before that call.
for (index, attribute) in parsed
.media_descriptions
.iter()
.flat_map(|media| &media.attributes)
.filter(|attribute| attribute.key == "candidate")
.enumerate()
{
if index >= MAX_REMOTE_CANDIDATES {
return Err("too many voice candidates");
}
let candidate = attribute
.value
.as_deref()
.ok_or("invalid voice candidate")?;
let parsed = rtc::ice::candidate::unmarshal_candidate(candidate)
.map_err(|_| "invalid voice candidate")?;
if parsed.component() == 1 && seen.insert(candidate) {
candidates.push(RTCIceCandidateInit {
candidate: format!("candidate:{candidate}"),
..Default::default()
});
}
}
timeout(WAIT, async {
self.connection
.set_remote_description(answer)
.await
.map_err(|_| "failed to apply voice answer")?;
// The async driver requires explicit candidates to start TCP dialing,
// even when they were bundled in the non-trickle answer.
for candidate in candidates {
self.connection
.add_ice_candidate(candidate)
.await
.map_err(|_| "failed to apply voice candidate")?;
}
self.ready
.clone()
.wait_for(|ready| *ready)
.await
.map(|_| ())
.map_err(|_| "voice event channel closed")
})
.await
.map_err(|_| "timed out connecting voice peer")?
}
pub(crate) async fn close(&mut self) -> Result<()> {
self.observer.abort();
let _ = (&mut self.observer).await;
timeout(Duration::from_secs(/*secs*/ 2), self.connection.close())
.await
.map_err(|_| "timed out closing voice peer")?
.map_err(|_| "failed to close voice peer")
}
}
impl Drop for Transport {
fn drop(&mut self) {
self.observer.abort();
// The helper owns the runtime: destroying it cancels all remaining peer tasks.
}
}
#[cfg(test)]
#[path = "transport_tests.rs"]
mod tests;
@@ -0,0 +1,134 @@
//! Exercises real ICE recovery after initial packet loss and slow TCP connection setup.
//! All other runtime behavior, including inbound TCP limits, remains unchanged.
use std::future::Future;
use std::io;
use std::io::IoSliceMut;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::OnceLock;
use std::task::Context;
use std::task::Poll;
use std::time::Duration;
use std::time::Instant;
use futures::future::BoxFuture;
use webrtc::runtime::AsyncInterval;
use webrtc::runtime::AsyncTcpListener;
use webrtc::runtime::AsyncTcpStream;
use webrtc::runtime::AsyncUdpSocket;
use webrtc::runtime::JoinHandle;
use webrtc::runtime::RecvMeta;
use webrtc::runtime::Runtime;
use webrtc::runtime::Transmit;
use crate::transport_runtime::VoiceRuntime;
const INITIAL_OUTAGE: Duration = Duration::from_secs(/*secs*/ 3);
#[derive(Debug, Default)]
pub(super) struct DelayedNetwork {
inner: VoiceRuntime,
first_send: Arc<OnceLock<Instant>>,
}
impl Runtime for DelayedNetwork {
fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle> {
self.inner.spawn(future)
}
fn spawn_reactor(
&self,
reactor_pool_size: usize,
future: BoxFuture<'static, ()>,
) -> Box<dyn JoinHandle> {
self.inner.spawn_reactor(reactor_pool_size, future)
}
fn wrap_udp_socket(&self, socket: std::net::UdpSocket) -> io::Result<Arc<dyn AsyncUdpSocket>> {
Ok(Arc::new(LossyUdp {
inner: self.inner.wrap_udp_socket(socket)?,
first_send: self.first_send.clone(),
}))
}
fn wrap_tcp_listener(
&self,
listener: std::net::TcpListener,
) -> io::Result<Arc<dyn AsyncTcpListener>> {
self.inner.wrap_tcp_listener(listener)
}
fn connect_tcp(
&self,
remote_addr: SocketAddr,
) -> BoxFuture<'_, io::Result<Arc<dyn AsyncTcpStream>>> {
Box::pin(async move {
self.inner.sleep(INITIAL_OUTAGE).await;
self.inner.connect_tcp(remote_addr).await
})
}
fn resolve_host<'a>(&'a self, host: &'a str) -> BoxFuture<'a, io::Result<Vec<SocketAddr>>> {
self.inner.resolve_host(host)
}
fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
self.inner.sleep(duration)
}
fn interval(&self, period: Duration) -> Box<dyn AsyncInterval> {
self.inner.interval(period)
}
fn block_on(&self, future: Pin<Box<dyn Future<Output = ()> + '_>>) {
self.inner.block_on(future);
}
fn yield_now(&self) -> BoxFuture<'static, ()> {
self.inner.yield_now()
}
fn name(&self) -> &'static str {
self.inner.name()
}
}
#[derive(Debug)]
struct LossyUdp {
inner: Arc<dyn AsyncUdpSocket>,
first_send: Arc<OnceLock<Instant>>,
}
impl AsyncUdpSocket for LossyUdp {
fn local_addr(&self) -> io::Result<SocketAddr> {
self.inner.local_addr()
}
fn max_gso_segments(&self) -> usize {
self.inner.max_gso_segments()
}
fn max_gro_segments(&self) -> usize {
self.inner.max_gro_segments()
}
fn poll_send(&self, cx: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>> {
if self.first_send.get_or_init(Instant::now).elapsed() < INITIAL_OUTAGE {
// Report success but discard the datagram, like loss after leaving the socket.
Poll::Ready(Ok(transmit.contents.len()))
} else {
self.inner.poll_send(cx, transmit)
}
}
fn poll_recv(
&self,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
meta: &mut [RecvMeta],
) -> Poll<io::Result<usize>> {
self.inner.poll_recv(cx, bufs, meta)
}
}
@@ -0,0 +1,119 @@
//! Bounds retained inbound TCP streams across one peer's listeners before authentication.
//! Weak references reuse slots after stream ownership ends; other Tokio I/O stays unchanged.
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Weak;
use std::time::Duration;
use futures::future::BoxFuture;
use webrtc::runtime::AsyncInterval;
use webrtc::runtime::AsyncTcpListener;
use webrtc::runtime::AsyncTcpStream;
use webrtc::runtime::AsyncUdpSocket;
use webrtc::runtime::JoinHandle;
use webrtc::runtime::Runtime;
use webrtc::runtime::TokioRuntime;
const MAX_INBOUND_STREAMS: usize = 32;
type AcceptedStreams = Arc<Mutex<Vec<Weak<dyn AsyncTcpStream>>>>;
#[derive(Debug, Default)]
pub(crate) struct VoiceRuntime {
accepted: AcceptedStreams,
}
impl Runtime for VoiceRuntime {
fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle> {
TokioRuntime.spawn(future)
}
fn spawn_reactor(
&self,
reactor_pool_size: usize,
future: BoxFuture<'static, ()>,
) -> Box<dyn JoinHandle> {
TokioRuntime.spawn_reactor(reactor_pool_size, future)
}
fn wrap_udp_socket(&self, socket: std::net::UdpSocket) -> io::Result<Arc<dyn AsyncUdpSocket>> {
TokioRuntime.wrap_udp_socket(socket)
}
fn wrap_tcp_listener(
&self,
listener: std::net::TcpListener,
) -> io::Result<Arc<dyn AsyncTcpListener>> {
Ok(Arc::new(LimitedListener {
inner: TokioRuntime.wrap_tcp_listener(listener)?,
accepted: self.accepted.clone(),
}))
}
fn connect_tcp(
&self,
remote_addr: SocketAddr,
) -> BoxFuture<'_, io::Result<Arc<dyn AsyncTcpStream>>> {
TokioRuntime.connect_tcp(remote_addr)
}
fn resolve_host<'a>(&'a self, host: &'a str) -> BoxFuture<'a, io::Result<Vec<SocketAddr>>> {
TokioRuntime.resolve_host(host)
}
fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
TokioRuntime.sleep(duration)
}
fn interval(&self, period: Duration) -> Box<dyn AsyncInterval> {
TokioRuntime.interval(period)
}
fn block_on(&self, future: Pin<Box<dyn Future<Output = ()> + '_>>) {
TokioRuntime.block_on(future);
}
fn yield_now(&self) -> BoxFuture<'static, ()> {
TokioRuntime.yield_now()
}
fn name(&self) -> &'static str {
TokioRuntime.name()
}
}
#[derive(Debug)]
struct LimitedListener {
inner: Arc<dyn AsyncTcpListener>,
accepted: AcceptedStreams,
}
impl AsyncTcpListener for LimitedListener {
fn accept(&self) -> BoxFuture<'_, io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)>> {
Box::pin(async move {
let (stream, address) = self.inner.accept().await?;
let mut accepted = self
.accepted
.lock()
.map_err(|_| io::Error::other("voice TCP admission unavailable"))?;
accepted.retain(|stream| stream.strong_count() > 0);
if accepted.len() >= MAX_INBOUND_STREAMS {
return Err(io::Error::other("voice TCP connection limit reached"));
}
accepted.push(Arc::downgrade(&stream));
Ok((stream, address))
})
}
fn local_addr(&self) -> io::Result<SocketAddr> {
self.inner.local_addr()
}
}
#[cfg(test)]
#[path = "transport_runtime_tests.rs"]
mod tests;
@@ -0,0 +1,55 @@
//! Exercise admission and slot reuse with real TCP sockets across multiple listeners.
use super::*;
use pretty_assertions::assert_eq;
use tokio::time::timeout;
#[tokio::test]
async fn caps_inbound_streams_and_reuses_slots_across_listeners() {
timeout(Duration::from_secs(/*secs*/ 10), async {
let runtime = VoiceRuntime::default();
let first = runtime
.wrap_tcp_listener(std::net::TcpListener::bind("127.0.0.1:0").unwrap())
.unwrap();
let second = runtime
.wrap_tcp_listener(std::net::TcpListener::bind("127.0.0.1:0").unwrap())
.unwrap();
let mut clients = Vec::new();
let mut streams = Vec::new();
for _ in 0..MAX_INBOUND_STREAMS {
clients.push(
runtime
.connect_tcp(first.local_addr().unwrap())
.await
.unwrap(),
);
streams.push(first.accept().await.unwrap().0);
}
// A second listener shares the budget; rejecting a connection closes its socket.
let rejected = runtime
.connect_tcp(second.local_addr().unwrap())
.await
.unwrap();
assert_eq!(
second.accept().await.unwrap_err().to_string(),
"voice TCP connection limit reached"
);
assert_eq!(rejected.read(&mut [0]).await.unwrap(), 0);
assert_eq!(runtime.accepted.lock().unwrap().len(), MAX_INBOUND_STREAMS);
drop(streams.pop());
let replacement = runtime
.connect_tcp(second.local_addr().unwrap())
.await
.unwrap();
let (accepted, _) = second.accept().await.unwrap();
replacement.write_all(b"x").await.unwrap();
let mut byte = [0];
assert_eq!(accepted.read(&mut byte).await.unwrap(), 1);
assert_eq!(byte, *b"x");
assert_eq!(runtime.accepted.lock().unwrap().len(), MAX_INBOUND_STREAMS);
drop((clients, streams, accepted, replacement));
})
.await
.unwrap();
}
+186
View File
@@ -0,0 +1,186 @@
#[path = "transport_network_tests.rs"]
mod network;
use super::*;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use webrtc::data_channel::RTCDataChannelState;
struct RemoteEvents(mpsc::Sender<Arc<dyn DataChannel>>, Arc<Notify>);
impl PeerConnectionEventHandler for RemoteEvents {
fn on_data_channel<'a, 'async_trait>(
&'a self,
channel: Arc<dyn DataChannel>,
) -> BoxFuture<'async_trait, ()>
where
'a: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
self.0.try_send(channel).unwrap();
})
}
fn on_ice_gathering_state_change<'a, 'async_trait>(
&'a self,
state: RTCIceGatheringState,
) -> BoxFuture<'async_trait, ()>
where
'a: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
if state == RTCIceGatheringState::Complete {
self.1.notify_one();
}
})
}
}
#[tokio::test]
async fn negotiates_real_ordered_channel_over_udp_and_tcp() {
check_negotiation(Arc::new(crate::transport_runtime::VoiceRuntime::default())).await;
}
#[tokio::test]
async fn negotiates_after_early_packet_loss_and_slow_tcp_connect() {
check_negotiation(Arc::new(network::DelayedNetwork::default())).await;
}
async fn check_negotiation(runtime: Arc<dyn webrtc::runtime::Runtime>) {
for tcp in [false, true] {
timeout(Duration::from_secs(/*secs*/ 30), async {
let (sender, mut channels) = mpsc::channel(/*buffer*/ 1);
let gathered = Arc::new(Notify::new());
let mut settings = webrtc::peer_connection::SettingEngine::default();
settings.set_lite(/*lite*/ true);
let builder = PeerConnectionBuilder::new()
.with_setting_engine(settings)
.with_handler(Arc::new(RemoteEvents(sender, gathered.clone())));
let remote = if tcp {
builder.with_tcp_addrs(vec!["0.0.0.0:0"])
} else {
builder.with_udp_addrs(vec!["0.0.0.0:0"])
}
.build()
.await
.unwrap();
let mut local = Transport::with_runtime(runtime.clone()).await.unwrap();
let offer = RTCSessionDescription::offer(local.offer().await.unwrap()).unwrap();
remote.set_remote_description(offer).await.unwrap();
let answer = remote.create_answer(/*options*/ None).await.unwrap();
remote.set_local_description(answer).await.unwrap();
gathered.notified().await;
let mut answer = remote.local_description().await.unwrap().sdp;
let candidates: Vec<_> = answer
.lines()
.filter(|line| line.starts_with("a=candidate:"))
.map(str::to_owned)
.collect();
// Normal generated UDP/TCP answers still connect at the admission boundary.
assert!(!candidates.is_empty() && candidates.len() <= MAX_REMOTE_CANDIDATES);
for _ in candidates.len()..MAX_REMOTE_CANDIDATES {
answer.push_str(&format!("{}\r\n", candidates[0]));
}
local
.apply_answer(answer)
.await
.unwrap_or_else(|error| panic!("tcp={tcp}: {error}"));
let channel = channels.recv().await.unwrap();
assert_eq!(
(
channel.label().await.unwrap(),
channel.ordered().await.unwrap()
),
("oai-events".into(), true)
);
let unexpected = remote
.create_data_channel("unexpected", /*options*/ None)
.await
.unwrap();
loop {
match unexpected.poll().await {
Some(DataChannelEvent::OnClose) => break,
Some(
DataChannelEvent::OnOpen
| DataChannelEvent::OnClosing
| DataChannelEvent::OnBufferedAmountLow
| DataChannelEvent::OnBufferedAmountHigh,
) => {}
event => panic!("unexpected channel did not close: {event:?}"),
}
}
assert_eq!(
(channel.ready_state().await.unwrap(), *local.ready.borrow()),
(RTCDataChannelState::Open, true)
);
channel.send_text("synthetic sideband event").await.unwrap();
local.close().await.unwrap();
assert!(local.ready.has_changed().is_err());
remote.close().await.unwrap();
})
.await
.unwrap();
}
}
#[tokio::test]
async fn rejects_excess_or_invalid_candidates_before_mutating_peer() {
let mut peer = Transport::new().await.unwrap();
let offer = peer.offer().await.unwrap();
let header = offer
.lines()
.filter(|line| !line.starts_with("a=candidate:"))
.map(|line| format!("{line}\r\n"))
.collect::<String>();
for transport in ["udp", "tcp"] {
let mut answer = header.clone();
for index in 0..=MAX_REMOTE_CANDIDATES {
let suffix = if transport == "tcp" {
" tcptype passive"
} else {
""
};
answer.push_str(&format!(
"a=candidate:{index} 1 {transport} 1 192.0.2.1 9 typ host{suffix}\r\n"
));
}
assert_eq!(
peer.apply_answer(answer).await,
Err("too many voice candidates")
);
assert!(peer.connection.remote_description().await.is_none());
}
// The budget is global, before duplicate/component/inactive-media filtering.
let candidate = "a=candidate:duplicate 2 udp 1 192.0.2.1 9 typ host\r\n";
let answer = format!(
"{header}{}m=application 0 UDP/DTLS/SCTP webrtc-datachannel\r\na=inactive\r\n{}",
candidate.repeat(16),
candidate.repeat(17),
);
assert_eq!(
peer.apply_answer(answer).await,
Err("too many voice candidates")
);
assert!(peer.connection.remote_description().await.is_none());
let answer = format!("{header}{candidate}a=candidate:synthetic-secret-invalid\r\n");
assert_eq!(
peer.apply_answer(answer).await,
Err("invalid voice candidate")
);
assert!(peer.connection.remote_description().await.is_none());
peer.close().await.unwrap();
}
#[tokio::test]
async fn invalid_answer_is_redacted_and_peer_can_close() {
let mut peer = Transport::new().await.unwrap();
peer.offer().await.unwrap();
assert_eq!(
peer.apply_answer("synthetic-secret-invalid-sdp".into())
.await,
Err("invalid voice answer")
);
peer.close().await.unwrap();
}