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
2026-09-04 05:07:02 +00:00
committed by copyberry
parent 048a936a23
commit 1b53f6a44e
17 changed files with 1874 additions and 69 deletions
+55 -7
View File
File diff suppressed because one or more lines are too long
+612 -40
View File
@@ -511,13 +511,29 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "asn1-rs"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048"
dependencies = [
"asn1-rs-derive 0.5.1",
"asn1-rs-impl",
"displaydoc",
"nom 7.1.3",
"num-traits",
"rusticata-macros",
"thiserror 1.0.69",
"time",
]
[[package]]
name = "asn1-rs"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60"
dependencies = [
"asn1-rs-derive",
"asn1-rs-derive 0.6.0",
"asn1-rs-impl",
"displaydoc",
"nom 7.1.3",
@@ -527,6 +543,18 @@ dependencies = [
"time",
]
[[package]]
name = "asn1-rs-derive"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
"synstructure",
]
[[package]]
name = "asn1-rs-derive"
version = "0.6.0"
@@ -1375,6 +1403,15 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bit-vec"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
dependencies = [
"serde",
]
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -1509,6 +1546,29 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
[[package]]
name = "bytecheck"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26333eeac754f0ad8a6bcd0eb0ac012156302e4e16b852b72ee399aea4f12c29"
dependencies = [
"bytecheck_derive",
"ptr_meta",
"rancor",
"simdutf8",
]
[[package]]
name = "bytecheck_derive"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46d07918caa9eeaaf06b7873925c53a61daac173539b4f7715090745e44e4e69"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "bytemuck"
version = "1.25.0"
@@ -1543,9 +1603,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.11.1"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "bytes-utils"
@@ -1658,6 +1718,18 @@ dependencies = [
"shlex",
]
[[package]]
name = "ccm"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ae3c82e4355234767756212c570e29833699ab63e6ffd161887314cc5b43847"
dependencies = [
"aead",
"cipher",
"ctr",
"subtle",
]
[[package]]
name = "cexpr"
version = "0.6.0"
@@ -1698,9 +1770,9 @@ dependencies = [
[[package]]
name = "chacha20"
version = "0.10.0"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.0",
@@ -4922,10 +4994,13 @@ dependencies = [
"codex-process-hardening",
"codex-realtime-webrtc",
"codex-utils-cargo-bin",
"futures",
"libloading",
"pretty_assertions",
"rtc",
"tempfile",
"tokio",
"webrtc",
]
[[package]]
@@ -5341,6 +5416,15 @@ version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
[[package]]
name = "crc32c"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
dependencies = [
"rustc_version",
]
[[package]]
name = "crc32fast"
version = "1.5.0"
@@ -5851,13 +5935,27 @@ dependencies = [
"zeroize",
]
[[package]]
name = "der-parser"
version = "9.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553"
dependencies = [
"asn1-rs 0.6.2",
"displaydoc",
"nom 7.1.3",
"num-bigint",
"num-traits",
"rusticata-macros",
]
[[package]]
name = "der-parser"
version = "10.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
dependencies = [
"asn1-rs",
"asn1-rs 0.7.1",
"displaydoc",
"nom 7.1.3",
"num-bigint",
@@ -6261,6 +6359,7 @@ dependencies = [
"ff",
"generic-array",
"group",
"hkdf 0.12.4",
"pem-rfc7468",
"pkcs8",
"rand_core 0.6.4",
@@ -6828,9 +6927,9 @@ dependencies = [
[[package]]
name = "futures"
version = "0.3.31"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"
checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
dependencies = [
"futures-channel",
"futures-core",
@@ -6843,9 +6942,9 @@ dependencies = [
[[package]]
name = "futures-channel"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
dependencies = [
"futures-core",
"futures-sink",
@@ -6853,15 +6952,15 @@ dependencies = [
[[package]]
name = "futures-core"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-executor"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
dependencies = [
"futures-core",
"futures-task",
@@ -6881,9 +6980,9 @@ dependencies = [
[[package]]
name = "futures-io"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-lite"
@@ -6900,32 +6999,32 @@ dependencies = [
[[package]]
name = "futures-macro"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
"syn 3.0.3",
]
[[package]]
name = "futures-sink"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
[[package]]
name = "futures-task"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-channel",
"futures-core",
@@ -9410,9 +9509,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.29"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "logos"
@@ -9580,6 +9679,16 @@ dependencies = [
"wiremock",
]
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest 0.10.7",
]
[[package]]
name = "md-5"
version = "0.11.0"
@@ -9719,6 +9828,26 @@ dependencies = [
"serde",
]
[[package]]
name = "munge"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e17401f259eba956ca16491461b6e8f72913a0a114e39736ce404410f915a0c"
dependencies = [
"munge_macro",
]
[[package]]
name = "munge_macro"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4568f25ccbd45ab5d5603dc34318c1ec56b117531781260002151b8530a9f931"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "mxc_config_contract"
version = "0.8.0"
@@ -9807,6 +9936,19 @@ dependencies = [
"libc",
]
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.1",
"cfg-if",
"cfg_aliases 0.2.1",
"libc",
"memoffset",
]
[[package]]
name = "nom"
version = "7.1.3"
@@ -10209,13 +10351,22 @@ dependencies = [
"memchr",
]
[[package]]
name = "oid-registry"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9"
dependencies = [
"asn1-rs 0.6.2",
]
[[package]]
name = "oid-registry"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
dependencies = [
"asn1-rs",
"asn1-rs 0.7.1",
]
[[package]]
@@ -10500,6 +10651,18 @@ dependencies = [
"sha2 0.10.9",
]
[[package]]
name = "p384"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
dependencies = [
"ecdsa",
"elliptic-curve",
"primeorder",
"sha2 0.10.9",
]
[[package]]
name = "pagable"
version = "0.4.1"
@@ -11231,6 +11394,26 @@ version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"
[[package]]
name = "ptr_meta"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743da816b98c921cdbe8628ef7381b76f25ecf4da599fc80aca90eae7ef70cc0"
dependencies = [
"ptr_meta_derive",
]
[[package]]
name = "ptr_meta_derive"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "publicsuffix"
version = "2.3.0"
@@ -11307,7 +11490,7 @@ dependencies = [
"cfg_aliases 0.2.1",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"quinn-udp 0.5.14",
"rustc-hash 2.1.1",
"rustls",
"socket2 0.6.3",
@@ -11352,6 +11535,19 @@ dependencies = [
"windows-sys 0.60.2",
]
[[package]]
name = "quinn-udp"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76150b617afc75e6e21ac5f39bc196e80b65415ae48d62dbef8e2519d040ce42"
dependencies = [
"cfg_aliases 0.2.1",
"libc",
"log",
"socket2 0.6.3",
"windows-sys 0.61.2",
]
[[package]]
name = "quote"
version = "1.0.45"
@@ -11658,7 +11854,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"webpki-roots",
"x509-parser",
"x509-parser 0.18.1",
]
[[package]]
@@ -11703,6 +11899,15 @@ dependencies = [
"wildcard",
]
[[package]]
name = "rancor"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b534442d0fcdb55d66f373d9cac6d33b6293a2335bc2136dbd06ce0e87d2572"
dependencies = [
"ptr_meta",
]
[[package]]
name = "rand"
version = "0.8.6"
@@ -11730,7 +11935,7 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
dependencies = [
"chacha20 0.10.0",
"chacha20 0.10.2",
"getrandom 0.4.2",
"rand_core 0.10.1",
]
@@ -11922,15 +12127,16 @@ dependencies = [
[[package]]
name = "rcgen"
version = "0.14.7"
version = "0.14.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10b99e0098aa4082912d4c649628623db6aba77335e4f4569ff5083a6448b32e"
checksum = "091e7a8e7d86e6feb87a27ce8e2cba29d49eff9507afeebefab7eeb2ca667fb4"
dependencies = [
"aws-lc-rs",
"pem",
"ring",
"rustls-pki-types",
"time",
"x509-parser",
"x509-parser 0.18.1",
"yasna",
]
@@ -12029,6 +12235,15 @@ version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"
[[package]]
name = "rend"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "663ba70707f96e871406fe10d68128412e619b06d1d47cb91c3a4c6501176240"
dependencies = [
"bytecheck",
]
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -12154,6 +12369,36 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rkyv"
version = "0.8.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9776093b7ca170454ab1406954f7b7d97a57c51dc6c0642957fb2ef25c2d399"
dependencies = [
"bytecheck",
"bytes",
"hashbrown 0.17.1",
"indexmap 2.14.0",
"munge",
"ptr_meta",
"rancor",
"rend",
"rkyv_derive",
"tinyvec",
"uuid",
]
[[package]]
name = "rkyv_derive"
version = "0.8.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c25ef604ac7dd839d44d64648952ea23c97866f124ff671b0ed2cf3ad9bb06e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "rmcp"
version = "3.2.0"
@@ -12203,6 +12448,282 @@ dependencies = [
"syn 3.0.3",
]
[[package]]
name = "rtc"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e55da8e478486106f04db1ccba177ae3260fb12899982cd5cddf2ac0e1cdcfe9"
dependencies = [
"bytes",
"hex",
"log",
"rand 0.10.1",
"rcgen",
"ring",
"rtc-datachannel",
"rtc-dtls",
"rtc-ice",
"rtc-interceptor",
"rtc-mdns",
"rtc-media",
"rtc-rtcp",
"rtc-rtp",
"rtc-sctp",
"rtc-sdp",
"rtc-shared",
"rtc-srtp",
"rtc-stun",
"rtc-turn",
"rustls",
"sansio",
"serde",
"serde_json",
"sha2 0.10.9",
"unicase",
"url",
]
[[package]]
name = "rtc-datachannel"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bef39b017b5cf0a3511eab456505556b320e0aa04d4547b015ecba9f844fe43"
dependencies = [
"bytes",
"log",
"rtc-sctp",
"rtc-shared",
"sansio",
]
[[package]]
name = "rtc-dtls"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03a1be8a58a72a257c233ad9a2f92130c15994e02f7a1981379fdebbe0d8761a"
dependencies = [
"aes",
"bytecheck",
"byteorder",
"bytes",
"cbc",
"ccm",
"chacha20poly1305",
"der-parser 9.0.0",
"hmac 0.12.1",
"log",
"p256",
"p384",
"rand 0.10.1",
"rand_core 0.6.4",
"rcgen",
"ring",
"rkyv",
"rtc-shared",
"rustls",
"sec1",
"sha1 0.10.6",
"sha2 0.10.9",
"subtle",
"x25519-dalek",
"x509-parser 0.16.0",
]
[[package]]
name = "rtc-ice"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "640c7ecb9a09d21c0d4ba27b3ff22adb07cce90d23a7bce7c82bcbe424844e31"
dependencies = [
"bytes",
"crc",
"log",
"rand 0.10.1",
"rtc-mdns",
"rtc-shared",
"rtc-stun",
"sansio",
"serde",
"url",
"uuid",
]
[[package]]
name = "rtc-interceptor"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9436633af4a6beff6fee08c99464012017fcd1e0a4c0559b1f0d733e8812217a"
dependencies = [
"log",
"rand 0.10.1",
"rtc-interceptor-derive",
"rtc-rtcp",
"rtc-rtp",
"rtc-shared",
"sansio",
]
[[package]]
name = "rtc-interceptor-derive"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3563dafffb11e99264cbfa87c45d806c349c701a96ea3cf3c4778ae3c5da63b4"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "rtc-mdns"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4db343dbcd1445783ac9f832e350775e4e655b2c890bead7d13dca1219e0ac5"
dependencies = [
"bytes",
"log",
"rtc-shared",
"sansio",
"socket2 0.6.3",
]
[[package]]
name = "rtc-media"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "709a571ed5d88854f3f8c0b92e4a445d77ee54fd33dd45f9297a3d91e3e96d67"
dependencies = [
"byteorder",
"bytes",
"rand 0.10.1",
"rtc-rtp",
"rtc-shared",
"thiserror 2.0.18",
]
[[package]]
name = "rtc-rtcp"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8817201df4a87008528804073d2dddfefd08eecb44afe6f6d61f7fb1beed72d0"
dependencies = [
"bytes",
"rtc-shared",
]
[[package]]
name = "rtc-rtp"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2aa84012c4a3d855586878e9f891af5062bd5690278b2c54bfcfb0a0ddd9098"
dependencies = [
"bytes",
"memchr",
"rand 0.10.1",
"rtc-shared",
"serde",
]
[[package]]
name = "rtc-sctp"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78317cf685b6cde3dbd1cd8e7c9f373e74f00dce00000a25c14c6ddb3378da86"
dependencies = [
"bytes",
"crc32c",
"log",
"rand 0.10.1",
"rtc-shared",
"rustc-hash 2.1.1",
"slab",
"thiserror 2.0.18",
]
[[package]]
name = "rtc-sdp"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54ab04410496c8ea47350490298fb135f5432f8fa1aa88edf5dadc81c855a324"
dependencies = [
"rand 0.10.1",
"rtc-shared",
"url",
]
[[package]]
name = "rtc-shared"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dae32667b8c9f15223172ce27471e02791e2b401de559b3ea02a6ec93ff280e0"
dependencies = [
"aes",
"aes-gcm",
"bitflags 1.3.2",
"bytes",
"nix 0.31.3",
"p256",
"rand 0.10.1",
"rcgen",
"sec1",
"serde",
"substring",
"thiserror 2.0.18",
"url",
"winapi",
]
[[package]]
name = "rtc-srtp"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413d48daef797c98c12ff91988abac36d44c81974f0a4b0658549174230819cd"
dependencies = [
"aes",
"byteorder",
"bytes",
"ctr",
"hmac 0.12.1",
"ring",
"rtc-rtcp",
"rtc-rtp",
"rtc-shared",
"sha1 0.10.6",
"subtle",
]
[[package]]
name = "rtc-stun"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4b4540b2b8ff7155ef9e95a3b492a7830e974e2fa9ce4b76ec315c4a6b4953d"
dependencies = [
"base64 0.22.1",
"bytes",
"crc",
"lazy_static",
"md-5 0.10.6",
"rand 0.10.1",
"ring",
"rtc-shared",
"sansio",
"subtle",
"url",
]
[[package]]
name = "rtc-turn"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "449365ff0b87488d5f9532409813e76e1f0f5965ef31ce6fcde9aa786c852c6c"
dependencies = [
"bytes",
"log",
"rtc-shared",
"rtc-stun",
"sansio",
]
[[package]]
name = "runfiles"
version = "0.1.0"
@@ -12424,6 +12945,12 @@ dependencies = [
"flatbuffers",
]
[[package]]
name = "sansio"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c62751faa8bc286982334a082fe125184a29fc89d17775766e4f891b7d726980"
[[package]]
name = "scc"
version = "2.4.0"
@@ -13426,7 +13953,7 @@ dependencies = [
"hmac 0.13.0",
"itoa",
"log",
"md-5",
"md-5 0.11.0",
"memchr",
"rand 0.10.1",
"serde",
@@ -13709,6 +14236,15 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "substring"
version = "1.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ee6433ecef213b2e72f587ef64a2f5943e7cd16fbd82dbe8bc07486c534c86"
dependencies = [
"autocfg",
]
[[package]]
name = "subtle"
version = "2.6.1"
@@ -15588,6 +16124,24 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webrtc"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7330857e1e10fcbfa5f358f152cc01f22a05bb523875c0547677db0f24538dcd"
dependencies = [
"async-broadcast",
"async-channel",
"async-trait",
"bytes",
"event-listener",
"futures",
"log",
"quinn-udp 0.6.1",
"rtc",
"tokio",
]
[[package]]
name = "weezl"
version = "0.1.12"
@@ -16412,19 +16966,36 @@ dependencies = [
"zeroize",
]
[[package]]
name = "x509-parser"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69"
dependencies = [
"asn1-rs 0.6.2",
"data-encoding",
"der-parser 9.0.0",
"lazy_static",
"nom 7.1.3",
"oid-registry 0.7.1",
"rusticata-macros",
"thiserror 1.0.69",
"time",
]
[[package]]
name = "x509-parser"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
dependencies = [
"asn1-rs",
"asn1-rs 0.7.1",
"aws-lc-rs",
"data-encoding",
"der-parser",
"der-parser 10.0.0",
"lazy_static",
"nom 7.1.3",
"oid-registry",
"oid-registry 0.8.1",
"ring",
"rusticata-macros",
"thiserror 2.0.18",
@@ -16473,10 +17044,11 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
[[package]]
name = "yasna"
version = "0.5.2"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
dependencies = [
"bit-vec 0.9.1",
"time",
]
+1
View File
@@ -231,6 +231,7 @@ deny = [
"pagable",
"rmcp",
"tonic",
"webrtc",
"zbus",
], reason = "first-party traits must use native async trait methods with explicit Send bounds" },
# Migration ratchet: `codex-http-client` is the intended reqwest owner. Remove each temporary
+35 -3
View File
@@ -28,6 +28,32 @@ pub struct VoiceHost {
}
impl VoiceHost {
/// Gather an offer in the helper. This establishes neither connectivity nor audio readiness.
pub async fn start_transport(mut self) -> Result<(Self, crate::SessionDescription)> {
let response = self
.request(Message::StartTransport {}, Duration::from_secs(/*secs*/ 20))
.await?;
let Message::Offer { sdp } = response else {
anyhow::bail!("unexpected voice helper response");
};
Ok((self, sdp))
}
/// Return only when the peer's ordered event channel has opened.
pub async fn apply_answer(mut self, sdp: crate::SessionDescription) -> Result<Self> {
let response = self
.request(
Message::ApplyAnswer { sdp },
Duration::from_secs(/*secs*/ 20),
)
.await?;
ensure!(
response == Message::TransportReady {},
"unexpected voice helper response"
);
Ok(self)
}
/// Initialize the packaged native runtime without opening devices or starting a session.
pub async fn initialize_runtime(mut self) -> Result<Self> {
self.exchange(
@@ -103,15 +129,21 @@ impl VoiceHost {
expected: Message,
deadline: Duration,
) -> Result<()> {
ensure!(
self.request(request, deadline).await? == expected,
"unexpected voice helper response"
);
Ok(())
}
async fn request(&mut self, request: Message, deadline: Duration) -> Result<Message> {
timeout(deadline, async {
self.process
.writer_sender()
.send(encode_frame(&request)?)
.await
.map_err(|_| anyhow::anyhow!("voice helper input closed"))?;
let response = self.output.next().await?;
ensure!(response == expected, "unexpected voice helper response");
Ok(())
Ok(self.output.next().await?)
})
.await?
}
+1
View File
@@ -6,6 +6,7 @@ pub use client::VoiceHost;
pub use protocol::MAX_FRAME_BYTES;
pub use protocol::Message;
pub use protocol::RUNTIME_ENVIRONMENT;
pub use protocol::SessionDescription;
pub use protocol::decode_frame;
pub use protocol::encode_frame;
pub use protocol::read_message;
+38 -2
View File
@@ -1,4 +1,4 @@
//! Bounded, same-build lifecycle protocol; this stage carries no audio or credentials.
//! Bounded same-build controls and redacted signaling; audio never crosses this pipe.
use std::io;
use std::io::Read;
@@ -6,7 +6,35 @@ use std::io::Read;
use serde::Deserialize;
use serde::Serialize;
pub const MAX_FRAME_BYTES: usize = 256;
pub const MAX_FRAME_BYTES: usize = 128 * 1024;
/// SDP contains ICE credentials. Bound it at construction and never expose it in diagnostics.
#[derive(Deserialize, PartialEq, Serialize)]
#[serde(try_from = "String")]
pub struct SessionDescription(String);
impl TryFrom<String> for SessionDescription {
type Error = &'static str;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.is_empty() || value.len() > 64 * 1024 {
return Err("invalid voice session description length");
}
Ok(Self(value))
}
}
impl std::fmt::Debug for SessionDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("SessionDescription([REDACTED])")
}
}
impl SessionDescription {
pub fn into_sdp(self) -> String {
self.0
}
}
/// Fixed child settings prevent native initialization from scanning system plugins or caches.
pub const RUNTIME_ENVIRONMENT: [(&str, &str); 7] = [
@@ -34,10 +62,18 @@ pub enum Message {
Ready {},
InitializeRuntime {},
RuntimeReady {},
StartTransport {},
Offer { sdp: SessionDescription },
ApplyAnswer { sdp: SessionDescription },
TransportReady {},
Close {},
Closed {},
}
#[cfg(test)]
#[path = "protocol_tests.rs"]
mod tests;
pub fn encode_frame(message: &Message) -> io::Result<Vec<u8>> {
let payload = serde_json::to_vec(message)?;
if payload.len() > MAX_FRAME_BYTES {
@@ -0,0 +1,28 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn signaling_roundtrips_without_diagnostic_secrets() {
let secret = "a=ice-pwd:synthetic-secret";
let message = Message::ApplyAnswer {
sdp: secret.to_owned().try_into().unwrap(),
};
let debug = format!("{message:?}");
assert!(!debug.contains(secret));
assert!(debug.contains("REDACTED"));
assert_eq!(
decode_frame(&encode_frame(&message).unwrap()).unwrap(),
Some(message)
);
}
#[test]
fn signaling_bounds_apply_to_untrusted_wire_input() {
for sdp in [String::new(), "x".repeat(64 * 1024 + 1)] {
let json = serde_json::json!({"type": "applyAnswer", "sdp": sdp}).to_string();
let mut frame = (json.len() as u32).to_be_bytes().to_vec();
frame.extend(json.as_bytes());
let error = decode_frame(&frame).unwrap_err();
assert_eq!(error.to_string(), "invalid voice frame");
}
}
+4
View File
@@ -14,7 +14,11 @@ workspace = true
[dependencies]
codex-process-hardening = { workspace = true }
codex-realtime-webrtc = { workspace = true }
futures = { workspace = true }
libloading = "=0.8.9"
rtc = "=0.20.3"
tokio = { workspace = true, features = ["rt-multi-thread", "sync", "time"] }
webrtc = "=0.20.3"
[dev-dependencies]
anyhow = { workspace = true }
+10 -3
View File
@@ -1,10 +1,11 @@
# Private voice helper foundation
`codex-voice-host` establishes the inherited-pipe lifecycle for the proposed
bundled voice process. It does not open devices, negotiate
WebRTC, or enable voice in the TUI. The existing CLI is unchanged.
bundled voice process and owns WebRTC negotiation. It does not open devices or
enable voice in the TUI. The existing CLI is unchanged.
Frames are a big-endian u32 length followed by at most 256 bytes of JSON. The
Frames are a big-endian u32 length followed by at most 128 KiB of JSON. SDP is
limited to 64 KiB and redacted in diagnostics. The
parent sends `hello` with protocol `1` and the helper's exact `buildCommit` before
receiving `ready`. It then sends `close` and receives `closed` before process exit.
After `ready`, the parent may send `initializeRuntime` once. `runtimeReady` means
@@ -15,6 +16,12 @@ client terminates the helper if initialization fails or exceeds its deadline.
Unknown fields, incompatible builds, invalid order and oversized frames fail
closed without echoing input. EOF exits even when the main worker cannot progress.
After `ready`, `startTransport` gathers an `offer`; `applyAnswer` returns
`transportReady` only when the ordered `oai-events` channel opens. This can run
without native audio initialization and does not establish audio readiness.
Negotiation has a deadline; `close` tears down the peer before acknowledging exit.
UDP and TCP peer tests use real sockets, without a backend or audio devices.
Bazel stamps the binary with `STABLE_GIT_COMMIT`. Cargo builders must provide the
same variable; an unstamped source build reports `dev` via `--build-commit` and is
not a distributable build identity. The client/control crate has no native audio
+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();
}
+238 -11
View File
@@ -1,23 +1,40 @@
//! Exercise the real helper through installed paths and bounded process I/O.
use std::fs;
use std::path::Path;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use codex_install_context::CodexPackageLayout;
use codex_install_context::InstallContext;
use codex_realtime_webrtc::Message;
use codex_realtime_webrtc::SessionDescription;
use codex_realtime_webrtc::VoiceHost;
use codex_realtime_webrtc::decode_frame;
use codex_realtime_webrtc::encode_frame;
use codex_utils_cargo_bin::cargo_bin;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::process::Child;
use tokio::process::Command;
use tokio::sync::Notify;
use tokio::sync::mpsc;
use tokio::time::timeout;
use webrtc::data_channel::DataChannel;
use webrtc::peer_connection::PeerConnection;
use webrtc::peer_connection::PeerConnectionBuilder;
use webrtc::peer_connection::PeerConnectionEventHandler;
use webrtc::peer_connection::RTCIceConnectionState;
use webrtc::peer_connection::RTCIceGatheringState;
use webrtc::peer_connection::RTCPeerConnectionState;
use webrtc::peer_connection::RTCSessionDescription;
use webrtc::peer_connection::SettingEngine;
const DEADLINE: Duration = Duration::from_secs(/*secs*/ 10);
@@ -97,6 +114,22 @@ async fn closes_after_acknowledgement_and_on_parent_pipe_loss() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn exits_after_parent_pipe_loss_following_transport_start_request() -> Result<()> {
// The binary unit test separately forces startup to block and checks watchdog termination.
let mut child = spawn()?;
handshake(&mut child).await?;
child
.stdin
.take()
.unwrap()
.write_all(&encode_frame(&Message::StartTransport {})?)
.await?;
let output = timeout(Duration::from_secs(/*secs*/ 5), child.wait_with_output()).await??;
assert!(output.stderr.is_empty());
Ok(())
}
#[tokio::test]
async fn rejects_invalid_input_without_echoing_it() -> Result<()> {
assert!(decode_frame(b"\0\0\0\x16{\"type\":\"close\",\"x\":0}").is_err());
@@ -124,28 +157,38 @@ async fn rejects_invalid_input_without_echoing_it() -> Result<()> {
}
Ok(())
}
#[tokio::test]
async fn installed_client_rejects_mixed_builds_and_missing_helper() -> Result<()> {
let directory = tempfile::Builder::new()
.prefix("voice package ")
.tempdir()?;
let bin = directory.path().join("bin");
let helper_dir = directory.path().join("codex-resources/voice/bin");
fn install_helper(root: &Path) -> Result<CodexPackageLayout> {
let bin = root.join("bin");
let helper_dir = root.join("codex-resources/voice/bin");
fs::create_dir_all(&bin)?;
fs::create_dir_all(&helper_dir)?;
fs::write(directory.path().join("codex-package.json"), "{}")?;
fs::write(root.join("codex-package.json"), "{}")?;
let app = bin.join(if cfg!(windows) { "codex.exe" } else { "codex" });
fs::write(&app, [])?;
let source = cargo_bin("codex-voice-host")?;
let helper = helper_dir.join(source.file_name().unwrap());
let helper = helper_dir.join(source.file_name().context("helper binary file name")?);
fs::copy(&source, &helper)?;
let package = InstallContext::from_exe(
InstallContext::from_exe(
/*is_macos*/ cfg!(target_os = "macos"),
Some(&app),
/*method_override*/ None,
)
.package_layout
.unwrap();
.context("package layout")
}
#[tokio::test]
async fn installed_client_rejects_mixed_builds_and_missing_helper() -> Result<()> {
let directory = tempfile::Builder::new()
.prefix("voice package ")
.tempdir()?;
let package = install_helper(directory.path())?;
let bin = directory.path().join("bin");
let source = cargo_bin("codex-voice-host")?;
let helper = directory
.path()
.join("codex-resources/voice/bin")
.join(source.file_name().unwrap());
VoiceHost::connect(&package, &build_commit().await?)
.await?
.close()
@@ -173,6 +216,190 @@ async fn installed_client_rejects_mixed_builds_and_missing_helper() -> Result<()
Ok(())
}
enum RemoteState {
Ice(RTCIceConnectionState),
Peer(RTCPeerConnectionState),
Channel,
}
struct RemoteEvents {
channels: mpsc::Sender<Arc<dyn DataChannel>>,
gathered: Arc<Notify>,
diagnostics: mpsc::Sender<(Duration, RemoteState)>,
started: Instant,
}
impl RemoteEvents {
fn record(&self, state: RemoteState) {
// Keep only the first 32 events; diagnostics must never wait on the connection driver.
let _ = self.diagnostics.try_send((self.started.elapsed(), state));
}
}
impl PeerConnectionEventHandler for RemoteEvents {
fn on_ice_connection_state_change<'a, 'async_trait>(
&'a self,
state: RTCIceConnectionState,
) -> BoxFuture<'async_trait, ()>
where
'a: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move { self.record(RemoteState::Ice(state)) })
}
fn on_connection_state_change<'a, 'async_trait>(
&'a self,
state: RTCPeerConnectionState,
) -> BoxFuture<'async_trait, ()>
where
'a: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move { self.record(RemoteState::Peer(state)) })
}
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.record(RemoteState::Channel);
assert!(
self.channels.try_send(channel).is_ok(),
"receiver must accept the event channel"
);
})
}
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.gathered.notify_one();
}
})
}
}
#[tokio::test]
async fn installed_client_negotiates_and_closes_over_udp_and_tcp() -> Result<()> {
let directory = tempfile::Builder::new()
.prefix("voice package ")
.tempdir()?;
let package = install_helper(directory.path())?;
let commit = build_commit().await?;
for tcp in [false, true] {
let started = Instant::now();
let (diagnostics, mut states) = mpsc::channel(/*buffer*/ 32);
let negotiation = timeout(Duration::from_secs(/*secs*/ 30), async {
let (sender, mut channels) = mpsc::channel(/*buffer*/ 1);
let gathered = Arc::new(Notify::new());
let mut settings = SettingEngine::default();
settings.set_lite(/*lite*/ true);
let builder = PeerConnectionBuilder::new()
.with_setting_engine(settings)
.with_handler(Arc::new(RemoteEvents {
channels: sender,
gathered: gathered.clone(),
diagnostics,
started,
}));
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?;
let result: Result<()> = async {
let host = VoiceHost::connect(&package, &commit).await?;
let (host, offer) = host.start_transport().await?;
remote
.set_remote_description(RTCSessionDescription::offer(offer.into_sdp())?)
.await?;
let answer = remote.create_answer(/*options*/ None).await?;
remote.set_local_description(answer).await?;
gathered.notified().await;
let answer = remote.local_description().await.context("local answer")?;
let host = host
.apply_answer(
SessionDescription::try_from(answer.sdp).map_err(anyhow::Error::msg)?,
)
.await
.with_context(|| format!("tcp={tcp}: apply voice answer"))?;
let channel = channels.recv().await.context("event channel")?;
assert_eq!(
(channel.label().await?, channel.ordered().await?),
("oai-events".into(), true)
);
// This checks the Closed acknowledgement and successful child exit as well.
host.close().await
}
.await;
remote.close().await?;
result
});
let mut heartbeat = tokio::time::interval(Duration::from_millis(/*millis*/ 100));
heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut ticks = 0_u32;
let mut last_poll = started;
let mut max_gap = Duration::ZERO;
let mut max_gap_at = Duration::ZERO;
let result = {
tokio::pin!(negotiation);
loop {
let outcome = tokio::select! {
result = &mut negotiation => Some(result),
_ = heartbeat.tick() => {
ticks += 1;
None
}
};
// Include the final polling gap even when negotiation or its timeout wins.
let now = Instant::now();
let gap = now.duration_since(last_poll);
if gap > max_gap {
max_gap = gap;
max_gap_at = now.duration_since(started);
}
last_poll = now;
if let Some(result) = outcome {
break result;
}
}
};
result
.with_context(|| format!("tcp={tcp}: helper negotiation timed out"))
.and_then(std::convert::identity)
.with_context(|| {
let events: Vec<_> = std::iter::from_fn(|| states.try_recv().ok())
.map(|(elapsed, state)| match state {
RemoteState::Ice(state) => format!("{elapsed:?}: ICE {state}"),
RemoteState::Peer(state) => format!("{elapsed:?}: peer {state}"),
RemoteState::Channel => format!("{elapsed:?}: channel arrived"),
})
.collect();
format!(
"tcp={tcp}: remote connection events (first 32): {events:?}; \
test runtime heartbeat: ticks={ticks}, max polling gap={max_gap:?} \
observed at {max_gap_at:?}"
)
})?;
}
Ok(())
}
// Linux permits raw-byte filenames; macOS filesystems reject this name themselves.
#[cfg(target_os = "linux")]
#[tokio::test]