diff --git a/README.md b/README.md index ba2b808..744984f 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ tag is placed. | wasi | [genesis](libraries/wasi/openspec/changes/archive/2026-10-08-genesis) | wasi: the HTTP handler a WebAssembly component exports, for C++ on wasip2 and wasip3 | own | implemented | 0.1.0 | 2026-10-08 | [code](https://github.com/webcpporg/wasi/tree/6e3c529) | | wasi | [redesign](libraries/wasi/openspec/changes/redesign) | wasi: one namespace per WASI version, one entry point, target features and run scripts | own | accepted | | 2026-10-09 | | | wasi | [wasm-bindgen](libraries/wasi/openspec/changes/wasm-bindgen) | wasm: evolve wasi into WebAssembly integration and generate C++ bindings | own | accepted | | 2026-11-03 | [code](https://github.com/webcpporg/wasi) | -| webrtc | [genesis](libraries/webrtc/openspec/changes/genesis) | webrtc: the W3C WebRTC API in Asio's model, native and in the browser | own | draft | | | | +| webrtc | [genesis](libraries/webrtc/openspec/changes/genesis) | webrtc: the W3C WebRTC API in Asio's model, native and in the browser | own | proposed | | | | | xactor | [genesis](libraries/xactor/openspec/changes/archive/2026-10-07-genesis) | xactor: a deterministic actor system for C++20 | own | implemented | 0.1.0 | 2026-10-07 | [code](https://github.com/webcpporg/xactor/tree/62f3e77) | | xstate | [genesis](libraries/xstate/openspec/changes/archive/2026-10-07-genesis) | xstate: XState's state machines and actors for C++20 | port of XState 5.33.2 (TypeScript, MIT) | implemented | 0.1.0 | 2026-10-07 | [code](https://github.com/webcpporg/xstate/tree/5299db2) | diff --git a/libraries/webrtc/openspec/changes/genesis/.openspec.yaml b/libraries/webrtc/openspec/changes/genesis/.openspec.yaml index ef71366..164d07b 100644 --- a/libraries/webrtc/openspec/changes/genesis/.openspec.yaml +++ b/libraries/webrtc/openspec/changes/genesis/.openspec.yaml @@ -5,7 +5,7 @@ webcpp: title: "webrtc: the W3C WebRTC API in Asio's model, native and in the browser" kind: own port_of: null - status: draft + status: proposed release: null implementation: null decided: null diff --git a/libraries/webrtc/openspec/changes/genesis/design.md b/libraries/webrtc/openspec/changes/genesis/design.md index 11a9e46..aa219f8 100644 --- a/libraries/webrtc/openspec/changes/genesis/design.md +++ b/libraries/webrtc/openspec/changes/genesis/design.md @@ -1,27 +1,55 @@ ## Context webcpp::webrtc is a header-only C++20 library for peer connections and data channels, shaped as -the W3C WebRTC API and written in Asio's model. Its design is in `reference/spec.md`, a draft -dated 2026-10-10 with the owner's decisions of that day (section 2.1) and the controller's -rulings on a review (section 2.2). There is no plan and no reference code yet. The nearest -existing code is trystero's `backend` interface and its native and browser implementations (in -trystero's own reference): a virtual interface with handler callbacks, one implementation per -target, which this library replaces with value types and asynchronous operations. - -Constraints every decision works within, from the superproject's rulebook (its `AGENTS.md`): +the W3C WebRTC API and written in Asio's model. The original specification, dated 2026-10-10 with +the owner's decisions of that day and the controller's rulings on a review, is preserved in +`reference/spec.md`. This revision, of 2026-11-14, checks it against what was built since and +supersedes it where they differ; "What changed since the specification" below lists every +difference, and where this document and `reference/spec.md` disagree, this document and the +requirements rule. + +What the library stands on, as built on 2026-11-14: + +- **webcpp::asio** (`libraries/asio`, status `implementing`, repository `webcpporg/asio`, the + superproject's `libs/asio` at `6c4e2c8`): Boost.Asio itself natively, the shipped backend on + Emscripten and WASIp2/P3, with the portable names `webcpp::asio::any_io_executor`, + `webcpp::asio::post` and `webcpp::asio::error`. Its browser bridge exists: + ``, a service of the io_context whose JavaScript functions + deliver to a `registration` or an `intrusive_registration` by a key that is never reused, and + only post (asio's D7, D12). +- **webcpp::beast** (`libraries/beast`, the superproject's `libs/beast` at `6c53f85`): its + browser WebSocket (`include/webcpp/beast/browser/websocket.hpp`, `detail/imports.hpp`, + `detail/support.hpp`) is the first browser object built on that bridge, and the patterns it + proved (beast's D3, D7, D9 to D12) are the ones this library follows in the browser. +- **libdatachannel 0.24.6**, pinned and built from its sources by the superproject: + `third_party/libs/libdatachannel` at `6b1e2e6`, with libjuice, libsrtp, usrsctp and plog at the + gitlinks `tools/libdatachannel/pin.json` lists, built as static archives by upstream CMake + through B2 (`/webcpp/third_party//libdatachannel`) against the same source-built OpenSSL as + Asio and Beast (`CODING-GUIDELINES.md` chapter 10, "Third-party code"). trystero's native + backend already ships it. +- **trystero's `backend`** at trystero `e9326e9` (`include/webcpp/trystero/backend.hpp`, + `native/peer_connection.hpp`, `native/data_channel.hpp`, `browser/backend.hpp`): the nearest + existing code, a virtual interface with handler callbacks and one implementation per target, + which this library replaces with value types and asynchronous operations. Since the + specification was written it gained the shared connection (one peer connection per remote peer + per app, adopted by the app when its data channel opens and multiplexed among the app's rooms) + and the preservation of native frames that arrive before a handler is installed (a FIFO of 64 + frames for 10 seconds). + +Constraints every decision works within, from the superproject's `CODING-GUIDELINES.md`: - header-only C++20, namespace `webcpp::webrtc`, headers under ``, internals - in `detail`, macros `WEBCPP_WEBRTC_*`; -- targets native and Emscripten only (D3); every test on each target unless its Jamfile says why - not; -- errors as values; exceptions optional through `WEBCPP_WEBRTC_NO_EXCEPTIONS`, with the native - backend unavailable without them (D4); -- no global or static mutable state, so process-wide platform state is held by an object the - program owns (D6); -- allocation through the allocator the program gives, on the executor (D9); -- Boost and std before custom code; third-party code only as a pinned dependency by the - owner's decision; BSL-1.0, "Copyright (c) 2026 WebCpp.org" on every source file; English; no - em dash. + in `detail`, macros `WEBCPP_WEBRTC_*`, the b2 target `/webcpp/webrtc//webrtc`, the error + category `webcpp.webrtc` (chapter 3); +- errors as values; no global or static mutable state; run-time objects allocate through the + allocator their user gives; asynchronous code runs on the executor its user supplies, without + driving the run family; an outside library is wrapped so that the user never names it + (chapter 4); +- every library works with exceptions on and off, and its `config.hpp` defines + `WEBCPP_WEBRTC_NO_EXCEPTIONS` (chapter 6); +- third-party code only as a pinned submodule, by the owner's decision (chapter 10); +- every test on each target its Jamfile declares (chapter 8); BSL-1.0, "Copyright (c) 2026 + WebCpp.org" on every source file; English; no em dash (chapter 2). ## Goals / Non-Goals @@ -29,72 +57,124 @@ Constraints every decision works within, from the superproject's rulebook (its ` - One interface for peer connections and data channels that a program writes once and runs natively and in a browser, with the W3C API's names and shapes. -- Operations in Asio's model: completion tokens, handlers on the object's executor, terminal - cancellation, outstanding work, the execution context outliving the object. +- Operations in Asio's model: completion tokens, handlers on the object's executor, the + cancellation Asio defines, outstanding work, the execution context outliving the object. - Events as pending operations with stated policies, so that no event is lost silently and every lifetime stays in the caller's hands. - Every limit webcpp imposes is a named option and fails as a value; every platform limit is stated in a table of differences. +- The library works with exceptions on and off on both targets. - A native peer and a browser peer connect to each other in the tests. -- trystero can be rewritten on it without loss (spec section 3 maps every part of trystero's - `backend`). +- trystero can be rewritten on it without loss (the table "trystero's backend, part by part" + below). **Non-Goals** - Media: tracks, codecs, transceivers. Media will get an interface of its own. -- wasip2 and wasip3 targets (no WebRTC stack exists for WASI). A later WASI target is a change - of its own. -- `createOffer`, `createAnswer` and the `negotiationneeded` event (D12). -- A native handle (`rtc::` or `emscripten::val`) in any public header. -- Zero-copy receive, for now (D8). -- Policies of trystero's: dropping text messages, dropping frames larger than a room frame, the - per-minute window of connection attempts. -- An integration with xactor inside the library (D11). +- wasip2 and wasip3 targets (D3). A later WASI target is a change of its own. +- `createOffer`, `createAnswer` and the `negotiationneeded` event (D15). +- A native handle (`rtc` ids, `rtc::` or `emscripten::val`) in any public header. +- Zero-copy receive, for now (D9). +- A byte stream over a data channel (an `AsyncReadStream` and `AsyncWriteStream` adapter), which + webcpp::beast's D6 names as an opt-in next layer for its WebSocket: a later change of this + library, which beast would then use (D1). +- Policies of trystero's: the shared connection and its adoption, dropping text messages, + dropping frames larger than a room frame, the bound of 64 frames and 10 seconds on frames no + room has read, the per-minute window of connection attempts. +- An integration with xactor inside the library (D17). ## Decisions -### D1. Kind: own, not wrapper +### D1. A library of its own, of kind own, on webcpp::asio + +**The owner's decision of 2026-11-14:** webcpp::webrtc stays a library of its own, not a part of +webcpp::beast, on webcpp::asio, following the browser patterns webcpp::beast proved. The +reasons: + +- webcpp::beast is a source-compatible facade of Boost.Beast, whose types and control flow it + keeps; WebRTC has no Boost counterpart to be faithful to, so its interface is webcpp's own. +- libdatachannel (MPL-2.0, with libjuice, libsrtp, usrsctp and plog) and its threads would be a + burden on every user of webcpp::beast, most of whom want HTTP or a WebSocket. +- webcpp::beast targets WASIp2 and WASIp3, where no WebRTC stack exists (D3). +- webcpp::beast's D6 already foresees a WebRTC channel's byte stream as an opt-in next layer of + its WebSocket, so the useful relation is beast over webrtc, later, never webrtc inside beast. -The metadata says `kind: own`. On the native target the library does wrap libdatachannel, and -the owner's decision 2.1.3 says so, but a wrapper in webcpp's sense is "webcpp's interface over -another library", whose design is that library's with a thinner face. Here the interface, the -semantics and the bounds are webcpp's: the event policies, the `runtime`, the error category, the -back-pressure rules and the table of differences are specified independently of libdatachannel, -and the second implementation is not a library at all but the browser's objects. The owner's -decision 2.1.1 is "a library of its own, on webcpp::asio". There is no upstream whose tests prove -the library (so not `port`). libdatachannel is justified in the documentation as a dependency of -one backend (D14). +This confirms the owner's decision 2.1.1 of 2026-10-10 ("a library of its own, on +webcpp::asio"). The metadata says `kind: own`: on the native target the library wraps +libdatachannel, but the interface, the semantics and the bounds are webcpp's (the event +policies, the `runtime`, the error category, the back-pressure rules, the table of differences), +specified independently of libdatachannel, and its second implementation is not a library at +all but the browser's objects. There is no upstream whose tests prove the library (so not +`port`), and no upstream interface it keeps (so not `wrapper`). libdatachannel is justified in +the documentation as a dependency of one backend (D16). + +Rejected: WebRTC inside webcpp::beast, for the four reasons above. ### D2. The W3C API's shape and names, in Asio's model Types and operations carry the W3C names (`peer_connection`, `data_channel`, `session_description`, `ice_candidate`, the `RTC*` enumerations in snake case, `ready_state()`, -`buffered_amount()`, `close()`). Operations are `async_*` members taking any completion token; -the executor and the allocator are template parameters defaulting to -`boost::asio::any_io_executor` and `std::allocator`, as Asio's own I/O objects do. -Inputs are views read during the call; outputs are owned, with their text in -the object's allocator. +`buffered_amount()`, `close()`). Operations are `async_*` members taking any completion token. + +The executor is a template parameter defaulting to `webcpp::asio::any_io_executor`, the portable +name webcpp::asio gives: natively Boost.Asio's own type, on Emscripten the shipped backend's, +so that the browser implementation shares the io_context the rest of the program runs on. Asio's +codes are named through `webcpp::asio::error` for the same reason. The allocator is a second +template parameter, defaulting to `std::allocator`, that the object's own state and +its outputs use (D12). Inputs are views read during the call; outputs are owned, with their text +in the object's allocator. + +The specification named `boost::asio::any_io_executor` and said the allocator parameter is "as +Asio's own I/O objects do". Both are corrected: Boost.Asio's type is not the browser's, and +Asio's I/O objects take an executor parameter only, their operations allocating through the +handler's associated allocator, which this library does too (D12). ### D3. Targets: native and Emscripten -wasip2 and wasip3 are not targets. libdatachannel needs threads, which neither WASI target -gives, and a UDP socket layer and a DTLS stack that it has no WASI port of; Boost.Asio itself -does not build for those targets with the pinned wasi-sdk. The build declares native and -emscripten only, and the convenience header stops with `#error` under `__wasi__`, naming this -reason. Rejected: a stub for WASI (it would let a program compile and fail at run time). - -### D4. Exceptions: the native backend needs them - -libdatachannel reports errors by throwing. The native backend calls it only where exceptions are -on. Without them (`WEBCPP_WEBRTC_NO_EXCEPTIONS`) the native backend is not available, and a -program learns it at compile time by the superproject's rule for a header that wraps a throwing -dependency: what follows the native headers' `config.hpp` sits inside -`#ifndef WEBCPP_WEBRTC_NO_EXCEPTIONS`, with a comment naming libdatachannel, so naming -`webcpp::webrtc::peer_connection` fails on that name and merely including the header compiles. -The emscripten backend works with exceptions on and off. Inside the native backend, every call -into libdatachannel that may throw is caught and becomes a value. Rejected for now: a declared -stub whose use fails a `static_assert` with a clearer message, which departs from the rule's -"declares nothing" (Open Questions). +wasip2 and wasip3 are not targets, because there is no WebRTC stack for WASI, neither in the +guest nor from the host: libdatachannel has no WASI port (its thread pool, and libjuice's and +usrsctp's threads, need preemptive threads that wasip2 does not give and that wasip3's +cooperative profile, experimental in wasi-sdk 34, does not give either; its ICE and SCTP layers +were never ported to WASI's sockets), and no WASI host interface offers WebRTC as the browser +offers `RTCPeerConnection`. The build declares native and emscripten only, and the convenience +header stops with `#error` under `__wasi__`, naming this reason. Rejected: a stub for WASI (it +would let a program compile and fail at run time). + +The specification's reason also said that Boost.Asio does not build for WASI with the pinned +wasi-sdk. That is no longer true: webcpp::asio runs on WASIp2 and WASIp3 since 2026-11-03, and +webcpp::beast's guest sockets with it. The reason above is the one that still holds. + +### D4. Exceptions: on and off on both targets, through libdatachannel's C API + +libdatachannel reports errors by throwing, and has no option to build without exceptions: its +sources throw in about three hundred places, and the superproject's build compiles its archives +with `-fexceptions` whatever the consumer asks (`tools/libdatachannel/build.py`). Its C++ API +(`rtc::PeerConnection`, `rtc::DataChannel`) lets those exceptions reach the caller, which is why +trystero's native backend, written on it, needs exceptions. Its C API (`rtc/rtc.h`) does not: +every function of `src/capi.cpp` runs inside `wrap()`, which catches `std::invalid_argument` as +`RTC_ERR_INVALID` and any other `std::exception` as `RTC_ERR_FAILURE`, so no exception crosses +it. + +**The owner's decision of 2026-11-14:** the native backend calls libdatachannel's C API only, so +webcpp::webrtc works with exceptions on and off on both targets, as chapter 6 asks of every +library. Measured on 2026-11-14 (`reference/STATUS.md`): a program compiled with +`-fno-exceptions` against the pinned libdatachannel connected two peers over the loopback through +the C API, exchanged a message, and received `RTC_ERR_INVALID` for a malformed ICE server URL, +with no exception. Each negative code becomes a value of `webcpp.webrtc` (D10); nothing of the C +API appears in a public header. + +What it costs: the C API names objects by `int` ids in a map of libdatachannel's own, behind its +mutex, and passes each callback a `void*` user pointer instead of a closure; and +`rtcReceiveMessage` copies a message out of libdatachannel's queue (`Channel::peek`) before it +copies it into the caller's buffer, one copy and one allocation more per received message than the +C++ API's `receive()`, both inside libdatachannel and in its allocator. Increment 1 measures that +cost (tasks.md 1.11). + +Rejected: the C++ API with exceptions required natively (the specification's ruling 2.2.2), whose +native headers declare nothing without exceptions; it leaves a program built without exceptions +without the native backend, when the C API gives it at a small cost. Rejected with it: a declared +stub whose use fails a `static_assert`, which departs from chapter 6. The specification's open +question on the compile-time message is closed: there is no such message. ### D5. Events are pending operations the caller re-arms @@ -109,172 +189,378 @@ past the bound is closed at once, as a connection past a listen backlog is refus kind at a time (a second completes with `already_started`); a cancelled wait consumes no event. Rejected: one wait returning a variant of events (the review's answer), and callbacks. +webcpp::beast has one read and keeps arrivals in a queue whatever is pending, which is this +library's `async_receive`; it has no other event kinds. Its rule that a queued arrival does not +keep `run` alive holds here too: only a pending operation is outstanding work (D11). + ### D6. A `runtime` owns the platform's process-wide state -libdatachannel keeps process-wide state (`Preload`, `Cleanup`, `SetThreadPoolSize`, -`InitLogger`), and its threads must be stopped through `Cleanup()` before static destruction. -webcpp keeps no global or static mutable state, so the program owns that state through a -`runtime`: made before any peer connection and destroyed after the last; `make` takes it by -reference, so no connection can exist without one. At most one exists at a time in a process -natively. Its other duty is the cap of peer connections on both targets -(`max_peer_connections`, default 256, half of Chromium's 500 per page, counted from -construction until garbage collection): natively it counts live connections made with it; in the -browser it reads the page's census, which lives in JavaScript. Rejected: a hidden singleton -(static state), and a per-connection cap (it cannot see the page). - -### D7. Native handlers are posted, and destruction is safe against libdatachannel's threads - -libdatachannel's events arrive on its own threads. Each is posted to the executor, never run -there, and nothing of the user's allocator is touched on those threads: the posts carry Asio's -default allocator and the queues are filled on the executor. Destruction calls `resetCallbacks()` -on the `rtc::PeerConnection` and on every `rtc::DataChannel` before releasing them; that call -synchronises with a callback in flight because each callback runs under its own recursive -mutex, so once it returns nothing more is posted, and what was posted before finds nothing, -through a weak registration. In the browser the object's registration with webcpp::asio's -bridge is removed and the JavaScript handlers are set to null. The execution context outlives -the object, as for Asio's I/O objects, which is what keeps a libdatachannel thread from posting -to a destroyed `io_context`. - -### D8. Receiving and sending - -`async_receive` appends one whole message to the caller's dynamic buffer, copied once, and -reports whether it was text. No zero-copy receive for now: in the browser the bytes must leave -the JavaScript heap anyway, and natively `rtc::binary` is a `std::vector` in libdatachannel's -allocator, so the one copy is the copy that puts the bytes under the user's allocator. Messages -are kept from the channel's creation. Natively the queue is libdatachannel's own, in its pull -mode (1,024 messages), and past it libdatachannel's thread waits and the peer is slowed: real -flow control, never a failure. In the browser, which has no flow control on receipt, a queue -bounded in bytes (`max_received_bytes`) is the only protection, and past it the channel closes -with `receive_overflow`. `send` and `send_text` queue and return, and `async_send` forms exist -because both of trystero's backends send synchronously, fire and forget, as Asio's sockets offer -`send` beside `async_send`; each fails as a value (`invalid_state`, `buffered_amount_exceeded`, -`message_too_large`). The caller paces itself with `async_wait_buffered_amount_low`. - -### D9. Errors, allocation and cancellation +libdatachannel keeps process-wide state (`rtcPreload`, `rtcCleanup`, `rtcSetThreadPoolSize`, +`rtcInitLogger`), and its threads must be stopped through `rtcCleanup()` before static +destruction. webcpp keeps no global or static mutable state, so the program owns that state +through a `runtime`: made before any peer connection and destroyed after the last; `make` takes +it by reference, so no connection can exist without one. Its other duty is the cap of peer +connections on both targets (`max_peer_connections`, default 256, half of Chromium's 500 per +page, counted from construction until garbage collection): natively it counts, in a member, the +live connections made with it; in the browser it reads the page's census, which lives in +JavaScript. + +At most one `runtime` exists at a time in a native process, because libdatachannel's state is the +process's: a second one's destructor would clean up the first's connections. This is a +precondition the documentation states, not a check: a check would need a flag of the process, +which is the static mutable state chapter 4 forbids. The specification required that the library +refuse a second `runtime`; that requirement is corrected to the precondition. + +Rejected: a hidden singleton (static state), a per-connection cap (it cannot see the page), and a +check through an unused id of libdatachannel's user-pointer map (it relies on what libdatachannel +does not document). + +### D7. Native events are posted, and destruction is synchronous with libdatachannel's threads + +libdatachannel's callbacks run on its own threads. Each callback the backend installs reads its +user pointer, a small control block the object owns, copies what the event carries into storage +of the standard allocator, and posts to the executor through a `std::weak_ptr` to the object's +state; it never runs a handler there, and touches nothing of the user's allocator: the queues of +D5 are filled on the executor. Destroying a channel calls `rtcDeleteDataChannel`, destroying a +connection `rtcDeletePeerConnection`, which libdatachannel documents to block "until all scheduled +callbacks of `pc` return" and to call no callback for it afterwards (`DOC.md`, +`rtcDeletePeerConnection` and `rtcDelete`); only then is the inbox freed, and what was posted +before finds nothing through the weak pointer. Destruction runs on the executor, never on +a libdatachannel thread, so it never waits for itself. + +The specification relied on `resetCallbacks()` of the C++ API, which synchronises with a +callback in flight through each callback's recursive mutex; `rtcDelete*` does the same, and says +so in libdatachannel's documentation rather than in its internals. + +The execution context outlives the object, as for Asio's I/O objects, which is what keeps a +libdatachannel thread from posting to a destroyed `io_context`. + +### D8. Browser events enter through webcpp::asio's bridge, as webcpp::beast's do + +The browser implementation follows webcpp::beast's browser WebSocket as built: + +- **One registration per object.** The connection's state and each channel's state is an + `intrusive_registration` of the io_context's bridge (``), so + the bridge indexes it without allocating, and one bridge function per object receives all its + events, which `deliver()` sorts by the event's `type`. +- **Arrivals are staged, and one notification is posted.** `deliver()` never runs a handler and + never touches a caller's buffer: it records the arrival in the object's state (charging a + message to the receive budget at once, D9) and posts at most one notification to the executor + for all arrivals not yet drained, which completes the pending waits there. A generation number + makes a notification posted for an earlier state find nothing. +- **JavaScript stays in JavaScript.** The browser calls are `EM_ASM` functions in inline + functions of `detail/imports.hpp`, which catch every JavaScript exception in JavaScript, before + it can reach a WebAssembly frame, and report it as a value (the DOMException's `name`); a + promise is followed by the same bridge function, whose event says how it settled. So the + emscripten backend raises nothing of its own and works with exceptions on and off. +- **Destruction and shutdown.** The destructor completes every pending operation with + `operation_aborted` (posted), sets the JavaScript handlers to null, and removes the + registration. The io_context's shutdown calls the registration's `shutdown()`, which destroys + the pending handlers without calling them, as Asio's own operations are destroyed. + +Where it differs from beast: a peer connection has several event kinds and the waits of D5, +where a WebSocket has one read; and a promise of `setLocalDescription` or +`setRemoteDescription` cannot be cancelled, so its operation supports terminal cancellation only +(D11). + +### D9. Receiving and sending + +`async_receive` appends one whole message to the caller's dynamic buffer and reports whether it +was text. No zero-copy receive for now: in the browser the bytes must leave the JavaScript heap +anyway, and natively they leave libdatachannel's queue through `rtcReceiveMessage`, which copies +into the caller's buffer directly. Messages are kept from the channel's creation, so a channel +accepted later, or handed from one owner to another, loses nothing it received before its first +`async_receive`: trystero's adoption of a shared connection relies on it (the table below). + +- **Natively** the queue is libdatachannel's own, in its pull mode (no message callback; + `rtcReceiveMessage`, `rtcGetAvailableAmount` and the available callback), bounded at 1,024 + messages (`RECV_QUEUE_LIMIT`, `src/impl/internals.hpp:46` at `6b1e2e6`). Past it libdatachannel's + thread waits for room (`src/impl/queue.hpp:93`), SCTP stops reading and the peer is slowed: + real flow control, never a failure. That thread delivers the connection's other channels too: + measured on 2026-11-14 (`test/stall_test.cpp`), a channel flooded past 1,024 unread messages + stalls every other channel of its connection until it is read or destroyed. So a program reads + every channel it holds, or closes it, and the documentation says so. Closing a channel does not + stop libdatachannel's queue (`DataChannel::close()`, `src/impl/datachannel.cpp:97-113`, closes + the stream and resets the callbacks only), so the backend drains it when the channel's owner + closes it, when its connection closes and when it is destroyed, which releases the waiting + thread; increment 1 tests it (3,000 messages never read, then the channel destroyed in under + two seconds). Draining discards what is unread, as the W3C discards a message received once the + channel left "open"; messages that arrived before the peer closed the channel are still + delivered, then `async_receive` completes with `error::closed`. +- **In the browser**, which has no flow control on receipt, a queue bounded in bytes + (`max_received_bytes`) is the only protection. As webcpp::beast's `queue_limits::receive` + does, the budget counts each message's payload and the bookkeeping of its record, and is + charged when the browser delivers the message, before the executor drains it, so that a + stopped or busy io_context does not let the page's memory grow. Past it the channel closes with + `receive_overflow`. + +`send` and `send_text` queue and return; the `async_send` forms complete once the message is +queued (at once, posted), because both of trystero's backends send synchronously, fire and +forget, as Asio's sockets offer `send` beside `async_send`. Each fails as a value: +`invalid_state` when the channel is not open, `message_too_large` past the smaller of +`max_message_size` and the peer's limit, `buffered_amount_exceeded` when the message would pass +`max_buffered_amount`. The caller paces itself with `async_wait_buffered_amount_low`. + +Where it differs from webcpp::beast's D7: beast closes the WebSocket with +`browser_errc::send_limit` when a write passes its bound, because a fragmented message already +partly given to the browser cannot be taken back; a data channel's message is sent whole by one +call and refused before the browser sees it, so the channel stays open and the caller can wait +and retry. The defaults differ too: beast's two bounds are 4 MiB each; this library keeps the +specification's 16 MiB for both, since data channels carry files where a WebSocket carries +signalling. + +### D10. Errors: the category `webcpp.webrtc`, the browser's names and the C API's codes Errors are values: `webcpp::webrtc::error`, category `webcpp.webrtc`, ten enumerators with fixed values that are never reused (`invalid_state` 1 to `too_many_peer_connections` 10). Asio's codes -keep their meaning: `operation_aborted`, `already_started`, `operation_not_supported`. Every -run-time object (the connection, its channels, their queues, the text of descriptions, -candidates and labels) is allocated through the object's `Allocator`, on the executor; what -libdatachannel and the browser hold is theirs, and none of the types is shareable. Every -operation supports terminal cancellation; a cancelled description operation cannot cancel the -promise (browser) or the libdatachannel thread (native) behind it, so its effect may happen -after the handler ran with `operation_aborted`, and the documentation says so. - -### D10. `close()` fires no state change +keep their meaning: `operation_aborted`, `already_started`, `operation_not_supported`, through +`webcpp::asio::error`. + +- **In the browser** a rejected promise or a thrown exception arrives as its DOMException's + `name`, read in JavaScript as beast's `webcpp_beast_open` reads `SyntaxError` and + `SecurityError`: `InvalidStateError`, `OperationError`, `InvalidAccessError`, `TypeError` and + `SyntaxError` become the enumerator of the same name, any other name `operation_error`. + webcpp::asio's `promise_rejected` never reaches the caller. +- **Natively** a negative code of the C API becomes, per call, the code the browser gives for the + same call (`RTC_ERR_INVALID` on `rtcCreatePeerConnection` is a malformed ICE server URL, + `syntax_error`; on `rtcSetRemoteDescription` a description that cannot be parsed, + `operation_error`, as Chromium reports it), and `operation_error` where nothing more precise + applies. The table is in the plan (Task 1.4) and the documentation. + +Like webcpp::beast's D10, the category holds only what has no Asio counterpart; unlike beast, +whose `browser_errc` covers the browser alone, its values cover both targets, because the W3C +errors are the interface's own. + +### D11. Cancellation, per operation and per type + +Every operation installs a cancellation handler on its associated cancellation slot, as +webcpp::beast's operations do (beast's D11), and states the types it supports: + +| Operation | Supports | Effect of a cancellation | +| --- | --- | --- | +| the waits of D5 and `async_receive` | terminal, partial, total | completes with `operation_aborted`; consumes no event and no message | +| `async_set_local_description`, `async_set_remote_description` | terminal | completes with `operation_aborted`; the description may still be applied, after the handler ran | +| `async_add_ice_candidate`, `async_send`, `async_send_text` | terminal, partial, total | none in practice: each completes at once, posted | + +A pending operation is outstanding work on the object's executor and on its handler's associated +executor (two work guards, as beast's `operation` holds), so natively `run()` does not return while +a candidate or a state change is awaited; a program that re-arms its waits keeps `run()` alive +until it closes the connection, and that is the way to end it. + +### D12. Allocation + +- **The object's state** (the connection, its channels, the queues of D5, the browser's receive + queue, the text of descriptions, candidates and labels) is allocated through the object's + `Allocator`, on the executor. +- **An operation's state** is allocated through its handler's associated allocator, as Asio's + and webcpp::beast's operations are (beast's D12). +- **What runs on libdatachannel's threads** allocates through the standard allocator only (the + copies an event carries, Asio's posts with no associated allocator), never through the user's, + which may be a resource used only on the executor. **What libdatachannel and the browser hold + is theirs:** the C API's maps and the messages in libdatachannel's queues, or what + `emscripten::val` holds in the JavaScript heap. + +None of the types is shareable in chapter 4's sense: they are run-time objects. The allocator +outlives the io_context's pending handlers, as trystero's resource does, since a posted +notification may hold the state until it runs. + +Where it differs from webcpp::beast's D12: beast takes the allocator through a constructor +`stream(std::allocator_arg_t, const Allocator&, Args&&...)` and erases it into a memory resource, +because its stream type must stay Boost.Beast's `websocket::stream`; this library has +no upstream type to keep, so the allocator is a template parameter, as a standard container's, +given to `make`, and its outputs carry it by value. + +### D13. `close()` fires no state change As the W3C's `close()`: every pending operation of the connection completes with -`operation_aborted`, `state()` reads `closed`, no state-change event is delivered, and the -connection's channels then close with `error::closed` on their pending operations. A data -channel's `close()` completes its pending operations with `operation_aborted`, except -`async_wait_close`, which completes once the channel is closed. When a channel closes by other -causes (the peer, the connection, its transport) its pending operations complete with -`error::closed` and `async_wait_close` completes successfully; trystero ends a link on that. +`operation_aborted`, `state()` reads `closed`, no state-change event is delivered (natively the +backend drops the `Closed` states libdatachannel reports while closing), and the connection's +channels then close with `error::closed` on their pending operations. A data channel's `close()` +completes its pending operations with `operation_aborted`, except `async_wait_close`, which +completes once the channel is closed. When a channel closes by other causes (the peer, the +connection, its transport) its pending operations complete with `error::closed` and +`async_wait_close` completes successfully; trystero ends a link on that. -### D11. How it meets xactor - -It does not: webcpp::webrtc knows nothing of xactor. They meet at the executor. An xactor actor -that needs a peer holds a `peer_connection` made on the executor its driver runs on, starts -operations from its turns, and turns each completion into a message to itself. +### D14. What a target cannot honour follows webcpp::beast's rule, and its mechanism -### D12. Left out of the W3C API: `createOffer`, `createAnswer`, `negotiationneeded` +`operation_not_supported` under `WEBCPP_WEBRTC_UNSUPPORTED_ERROR` (the default), ignored under +`WEBCPP_WEBRTC_UNSUPPORTED_IGNORE`, as beast's D3; a setting is ignored by default only where the +platform does an equivalent thing of its own, with the reason. As beast's D9: both macros defined +is an `#error`; the b2 feature `webcpp-webrtc-unsupported=error|ignore`, propagated, sets one; and +the browser classes live in an inline namespace named after the policy (`unsupported_error`, +`unsupported_ignore`), so that translation units that disagree name different types and fail to +link. The native classes, which honour every setting, are outside it. + +Natively a remote candidate's `username_fragment` is ignored whatever the policy, which is such +an equivalent: libdatachannel creates one ICE transport per connection and never restarts it (no +path of `src/impl/peerconnection.cpp` at `6b1e2e6` does), so every candidate it is given belongs +to that transport's session, and a candidate's own `ufrag` attribute, when its text has one, still +reaches it. A browser peer's candidates carry the field, so refusing it would +break the interop that D18 tests. + +Natively a text message holding a zero cannot be sent: the C API takes a text as a +zero-terminated string. The send fails with `operation_not_supported` whatever the policy, since +ignoring it would truncate the message silently, which beast's rule forbids. + +The documentation keeps the table of differences (`bind_address`, local `sdp_m_line_index` and +`username_fragment`, a remote candidate's `username_fragment` natively, a text holding a zero +natively, a received message past `max_message_size`, unread messages and the stall of D9, the +omitted operations, no native handle). + +### D15. Left out of the W3C API: `createOffer`, `createAnswer`, `negotiationneeded` libdatachannel marks `createOffer` and `createAnswer` "for specific use cases only", and its `setLocalDescription` takes a type, not a description, so a description created that way cannot be applied as the W3C allows; the implicit `setLocalDescription`, the one trystero uses, does -both. libdatachannel has no `negotiationneeded` event, only a query. Natively automatic -negotiation is off, so on both targets a description exists only when -`async_set_local_description` asks for one, and the program negotiates when it adds a channel. A -later version may add the event, synthesised natively. Both omissions are in the table of -differences. - -### D13. What a target cannot honour follows webcpp::beast's rule - -`operation_not_supported` under `WEBCPP_WEBRTC_UNSUPPORTED_ERROR` (the default), ignored under -`WEBCPP_WEBRTC_UNSUPPORTED_IGNORE`. The documentation keeps the table of differences -(`bind_address`, local `sdp_m_line_index` and `username_fragment`, a received message past -`max_message_size`, unread messages, the omitted operations, no native handle). - -### D14. libdatachannel, wrapped and justified +both. libdatachannel has no `negotiationneeded` event, only a query (`rtcIsNegotiationNeeded`). +Natively automatic negotiation is off (`rtcConfiguration::disableAutoNegotiation`), so on both +targets a description exists only when `async_set_local_description` asks for one, and the +program negotiates when it adds a channel. A later version may add the event, synthesised +natively. Both omissions are in the table of differences. + +### D16. libdatachannel, pinned, wrapped and justified + +The native implementation wraps libdatachannel behind the interface, through its C API (D4); +nothing of it appears in a public header. The documentation justifies it as chapter 4 asks: no +WebRTC exists in webcpp, Boost, the C++ Alliance or the standard library, and libdatachannel is +the smallest complete implementation (data channels without a media engine), with its DTLS on +the same source-built OpenSSL as Asio and Beast. webcpp uses it unmodified, as a dependency, and +copies none of its files. + +It is pinned, as the superproject builds it today: libdatachannel 0.24.6 at `6b1e2e6` in +`third_party/libs/libdatachannel`, its nested sources at the gitlinks of +`tools/libdatachannel/pin.json`, through `/webcpp/third_party//libdatachannel`, whose usage +requirements give the include directory, `RTC_STATIC` and the archives; a native consumer builds +with `threading=multi`. The specification's `-sLIBDATACHANNEL_ROOT` and +`.local/libdatachannel` no longer exist: neither selects an installed copy now. A constant this +library quotes from libdatachannel (`RECV_QUEUE_LIMIT` 1,024, `DEFAULT_LOCAL_MAX_MESSAGE_SIZE` +256 KiB, `DEFAULT_REMOTE_MAX_MESSAGE_SIZE` 64 KiB) is checked again when the pin moves. + +**The owner's decision of 2026-11-14 on the licence:** MPL-2.0 is accepted for libdatachannel as +a dependency of webcpp::webrtc, used unmodified, as trystero already distributes it; its nested +dependencies keep their own licences (the superproject's third-party table). MPL's file-level +copyleft reaches none of webcpp's files while the dependency is unmodified. + +### D17. How it meets xactor -The native implementation wraps libdatachannel behind the interface; nothing of `rtc::` appears -in a public header. The documentation justifies it as the superproject's rule asks: no WebRTC -exists in webcpp, Boost, the C++ Alliance or the standard library, and libdatachannel is the -smallest complete implementation (data channels without the media stack), MPL-2.0, with its own -OpenSSL or mbedTLS for DTLS. webcpp uses it unmodified, as a dependency, and copies none of its -files. It is not pinned by webcpp today: like trystero, the library finds libdatachannel 0.24.6 -where `-sLIBDATACHANNEL_ROOT=` or the superproject's `.local/libdatachannel` says, and it -is pinned when webcpp builds it from `third_party/`. +It does not: webcpp::webrtc knows nothing of xactor. They meet at the executor. An xactor actor +that needs a peer holds a `peer_connection` made on the executor its driver runs on, starts +operations from its turns, and turns each completion into a message to itself. -### D15. Tests: every lane on both targets, interop with a real browser +### D18. Tests: every lane on both targets, interop with a real browser Every lane runs on native and on emscripten, both suspension variants, at the owner's three CI levels. Each target alone: two peers in one process or one page, every case the semantics name. Native lifetime: destruction while libdatachannel's threads deliver events, repeated, under -ThreadSanitizer. Interop: a native peer and a headless-Chrome peer, signalled through a local +ThreadSanitizer (100 rounds clean on 2026-11-14; libdatachannel's archives are not instrumented, so +what it checks is this library's side of each hand-off). Interop: a native peer and a headless-Chrome peer, signalled through a local relay, with Chrome started with `--allow-loopback-in-peer-connection` and `--disable-features=WebRtcHideLocalIpsWithMdns`, and the native peer binding to `127.0.0.1`. -Allocation: a counting resource. Exceptions: emscripten suites with exceptions on and off; -natively, a headers-alone translation unit and a `webcpp.compile-diagnostic` test. No network -beyond loopback: host candidates only, no STUN. +Allocation: a counting resource. Exceptions: every suite, native and emscripten, once as the build +asks and once with `off`. No network beyond loopback: host candidates only, +no STUN. -### D16. Increments +### D19. Increments -1. The interface, the `runtime` and the native implementation, with their tests. +1. The interface, the `runtime` and the native implementation, with their tests (reference code + in `reference/source/`, `reference/plan.md` increment 1). 2. The browser implementation, its tests and the interop lane. -3. trystero on webcpp::webrtc (with webcpp::asio and webcpp::crypto), its `backend` gone. +3. trystero on webcpp::webrtc (with webcpp::asio, webcpp::beast for its relays and + webcpp::crypto), its `backend` gone: a change of trystero's. + +## trystero's backend, part by part + +Every part of trystero's `backend` at `e9326e9` that touches WebRTC has a home here; this replaces +the specification's section 3, whose line numbers were trystero's of 2026-10-10. + +| trystero at `e9326e9` | webcpp::webrtc | +| --- | --- | +| `factory::make_peer_connection`, null on refusal (`backend.hpp:353`) | `basic_peer_connection::make`, a `result` | +| `peer_connection::set_local_description`, completing with the type and SDP (`backend.hpp:251`) | `async_set_local_description`, completing with a `session_description`; `local_description()` | +| `set_remote_description`, `add_ice_candidate` (the candidate as JSON), `has_remote_description` | the same operations; the candidate as a value, its JSON trystero's | +| `peer_connection::handlers::ice_candidate`, `data_channel`, `state` | `async_wait_ice_candidate`, `async_accept_data_channel`, `async_wait_state_change` and `async_wait_ice_connection_state_change` | +| the browser's merge of `connectionState` and `iceConnectionState` (`browser/backend.hpp:650`) | both states, separately; trystero merges them itself | +| `create_data_channel`, null on refusal (`backend.hpp:242`) | `create_data_channel`, a `result` | +| `data_channel::is_open` (`backend.hpp:171`) | `ready_state()` | +| `data_channel::handlers::open`, `message`, `close`, `buffered_amount_low`, and `set_handlers`, which a handler may call during its own call | `async_wait_open`, `async_receive`, `async_wait_close`, `async_wait_buffered_amount_low`, each re-armed by its owner | +| native frames that arrive before a message handler is installed, kept in a FIFO of 64 frames for 10 seconds (`native/data_channel.hpp:47`, `:224-245`) | messages are kept from the channel's creation until `async_receive` (D9); the bound of 64 frames and 10 seconds, Trystero's pending-data bound, stays trystero's, over `async_receive` | +| the shared connection: one peer connection per remote peer per app, adopted when its channel opens and routed among the app's rooms (`doc/protocol.adoc`, "The data channel") | trystero's policy over this library: a `peer_connection` and its `data_channel` are movable values the app owns, one reader at a time per channel, and nothing is lost while one owner hands them to another | +| `data_channel::send`, synchronous, dropped when not open (`backend.hpp:178`) | `send`, synchronous, and `async_send`; both fail as values when not open | +| `buffered_amount`, `low_threshold` (65,535 bytes) | `buffered_amount()`, `set_buffered_amount_low_threshold` | +| `backend_config::bind_address` (`native/backend.hpp:59`) | `configuration::bind_address`, native only (D14) | +| the page's cap of 256 `RTCPeerConnection`s (`browser/backend.hpp:919-927`) | `runtime_options::max_peer_connections` (D6) | +| `native_handle()` (`native/peer_connection.hpp:256`, `browser/backend.hpp:642`) | none; media, which the handle was kept for, will get an interface of its own | +| `backend_config::max_peer_connections_per_minute` (`native/backend.hpp:68`) | stays trystero's: a policy of its rooms against floods, not a limit of a platform | +| dropping text messages and binaries larger than a room frame, on libdatachannel's thread (`native/data_channel.hpp:189-192`) or in the page (`browser/backend.hpp:402-404`) | stays trystero's, on the executor: this library delivers text with `is_text` true and fails a message past `max_message_size` | +| the TURN URL rewritten as `turn:user:credential@host` (`native/peer_connection.hpp:261`) | `ice_server`'s `username` and `credential`, which the native backend writes in that form, the one the C API parses | + +The sealer, `random`, the timers, the clocks and the WebSockets go to webcpp::crypto, +webcpp::asio and webcpp::beast. + +## What changed since the specification + +- D1: the owner's decision of 2026-11-14, a library of its own, not inside webcpp::beast. +- D2: the executor defaults to `webcpp::asio::any_io_executor`; Asio's codes through + `webcpp::asio::error`; the claim that Asio's I/O objects take an allocator parameter removed. +- D3: the WASI reason corrected (Boost.Asio runs on WASIp2 and WASIp3 now). +- D4: the native backend uses libdatachannel's C API and works without exceptions; ruling 2.2.2 + and section 6 of the specification, the headers that declare nothing and the + `webcpp.compile-diagnostic` test are withdrawn; the owner's open question on the message is + closed. +- D6: one native `runtime` at a time is a precondition, not a refusal. +- D7: destruction through `rtcDelete*`, documented by libdatachannel, instead of + `resetCallbacks()`. +- D9: measured, a native channel never read stalls its connection's others; channels drain their + queue when closed by their owner or connection, and when destroyed. +- D8, D9, D11, D12, D14: aligned with webcpp::beast as built (one intrusive registration, staged + arrivals, the receive budget charged on arrival with each record's bookkeeping, cancellation + per type, operation state in the handler's allocator, the inline namespace and the b2 feature of + the unsupported policy), with the differences each states. +- D10: the browser's DOMException names and the C API's codes mapped to the category. +- D16: libdatachannel pinned and built from `third_party/`; MPL-2.0 accepted by the owner. +- The table of trystero's backend at `e9326e9`, with the shared connection and the preservation of + early native frames. ## Risks / Trade-offs -- [No plan and no reference code] -> the proposal cannot be accepted as it is: writing the plan - and the reference code is group 0 of the tasks. -- [A native channel that is never read holds one of libdatachannel's threads while its queue is - full] -> increment 1 measures whether that stalls the connection's other channels, and the - documentation says what it finds. +- [The C API costs a copy and an allocation per received message inside libdatachannel] -> + to be measured against the C++ API's `receive()` before increment 1 closes (tasks.md 1.11); the + cost is libdatachannel's, not the user's allocator's. +- [A native channel that is never read stalls its connection's other channels once 1,024 + messages wait] -> measured in increment 1 and pinned by a test; the documentation tells a + program to read every channel it holds or close it; closing or destroying the channel drains its + queue and releases the others (D9). A per-channel byte bound natively, as the browser's, would + trade the flow control for independence (O3). - [A cancelled description operation still takes effect] -> stated on every such operation's - page; the W3C promise cannot be cancelled. + page; the W3C promise cannot be cancelled, and the operation supports terminal cancellation + only. - [The browser has no flow control on receipt] -> `max_received_bytes` closes the channel with `receive_overflow`; documented as a difference. -- [Without exceptions the native backend is unavailable] -> by design (D4); a native program - needing no exceptions cannot use it; the compile-time message is the compiler's own. -- [The compile-time message is unclear] -> accepted; the documentation names it on the library's - page and in `config.hpp`'s Doc Comment. -- [libdatachannel is unpinned today] -> found through a variable or `.local`; pinned when built - from `third_party/`; its version (0.24.6) is stated, and constants quoted from it - (`RECV_QUEUE_LIMIT` 1,024, `DEFAULT_LOCAL_MAX_MESSAGE_SIZE`) must be re-checked when it moves. -- [MPL-2.0] -> file-level copyleft reaches none of webcpp's files while the dependency is used - unmodified; the owner decides (Open Questions). +- [A second native `runtime`] -> a precondition, documented on the class and on the library's + page; the library cannot detect it without static state. +- [Constants quoted from libdatachannel] -> checked again when the pin moves (D16). +- [The superproject's libdatachannel target speaks of trystero] -> its threading message names + "Trystero's native backend"; increment 1's superproject change words it for every consumer. - [Interop depends on Chrome's flags] -> the flags are named in the tests' documentation; a change in Chrome's switches fails the lane loudly. - [Chromium's limit of peer connections] -> the page's census and the default cap of 256. -- [Depends on webcpp::asio's bridge and JSPI/Asyncify variants] -> increment 2 waits for the - asio proposal; increment 1 needs only the executors. ## Migration Plan There is nothing to migrate: no program depends on webcpp::webrtc. trystero's `backend` goes in increment 3, a later change of trystero's; until then trystero keeps its own. -To start the implementation: write `reference/plan.md` and the reference code (tasks group 0), -get the owner's decisions of the Open Questions, then implement the increments in order. The -library is created as a repository `webcpporg/webrtc` by the owner, checked out as `libs/webrtc`. +To start the implementation: the proposal is decided, the owner creates the repository +`webcpporg/webrtc`, it starts from one import commit of `reference/source/`, is checked out as the +superproject's submodule `libs/webrtc`, and `reference/plan.md` is followed from increment 1. -Rollback: the proposal is a draft; withdrawing it deletes `openspec/changes/genesis/`. +Rollback: a proposal withdrawn or rejected is archived with that status, so that its reasons stay +readable (`CONTRIBUTING.md`); nothing outside this directory exists yet to undo. ## Open Questions -- libdatachannel's licence. MPL-2.0 is decided case by case by the owner, and no entry records - that decision for libdatachannel. webcpp uses it unmodified, so MPL's file-level copyleft - reaches none of webcpp's files; the decision to record is that MPL-2.0 is accepted for this - dependency. -- The compile-time message without exceptions: the spec follows the rule's "declares nothing" - (the compiler's "no member named 'peer_connection'"); a declared stub with a `static_assert` - naming libdatachannel and exceptions would be clearer but departs from the rule. Does the - owner want the stub? -- Whether a later version synthesises `negotiationneeded` natively. -- The exact names of the headers, the Jamfile targets and the library's repository layout, - which the plan fixes. -- The precise form of webcpp::asio's browser bridge that increment 2 uses (its proposal is a - draft). -- Whether libdatachannel is built from `third_party/` before or after the first release. +- O1. Whether a later version synthesises `negotiationneeded` natively. +- O2. Whether a later change adds a byte stream over a data channel, for webcpp::beast's D6. +- O3. Whether natively a channel should keep its own queue bounded in bytes, read from + libdatachannel at once as the browser's is, so that a channel never read cannot stall its + connection's others, at the price of the flow control that slows the peer (D9). diff --git a/libraries/webrtc/openspec/changes/genesis/proposal.md b/libraries/webrtc/openspec/changes/genesis/proposal.md index ee4a244..6a4a4eb 100644 --- a/libraries/webrtc/openspec/changes/genesis/proposal.md +++ b/libraries/webrtc/openspec/changes/genesis/proposal.md @@ -6,42 +6,49 @@ against the browser's JavaScript objects, or hide both behind a virtual interfac trystero, webcpp's serverless WebRTC rooms, took the second road: its `backend` interface, with `native/peer_connection.hpp`, `native/data_channel.hpp` and `browser/backend.hpp`, is a callback interface with one implementation per target, null on refusal, and it keeps WebRTC details -(the browser's cap of peer connections, the merge of two state machines) inside trystero where no -other program can use them. +(the browser's cap of peer connections, the merge of two state machines, the frames that arrive +before a handler is installed) inside trystero where no other program can use them. webcpp::webrtc is that interface done as a library: the W3C WebRTC API's shape and names (`RTCPeerConnection`, `RTCDataChannel`), whose operations follow Asio's model (completion tokens, handlers on webcpp::asio's executors, errors as values), so that a program is written once and runs natively (libdatachannel) and in a browser (Emscripten, driving the browser's own -objects). Media (tracks, codecs) is out of scope: data channels only, what trystero needs. +objects through webcpp::asio's bridge, as webcpp::beast's browser WebSocket does). Media (tracks, +codecs) is out of scope: data channels only, what trystero needs. It is the precondition of +trystero's move onto webcpp::webrtc, webcpp::beast (its relays), webcpp::asio and webcpp::crypto. ## What Changes -- **New library `webcpp::webrtc`**, webcpp's own design, header-only C++20, namespace +- **New library `webcpp::webrtc`**, webcpp's own design, a library of its own on webcpp::asio and + not a part of webcpp::beast (the owner's decision of 2026-11-14), header-only C++20, namespace `webcpp::webrtc`, for two targets: native and Emscripten (both suspension variants, JSPI and Asyncify). wasip2 and wasip3 are not targets: there is no WebRTC stack for WASI, and the - library's convenience header stops with `#error` under `__wasi__`, naming the reason. -- The interface of the specification's section 4: `basic_peer_connection` and - `basic_data_channel` templated on an executor and an allocator, value types for inputs + library's configuration stops with `#error` under WASI, naming the reason. +- The interface: `basic_peer_connection` and `basic_data_channel` templated on an executor + (default `webcpp::asio::any_io_executor`) and an allocator, value types for inputs (`configuration`, `ice_server`, `session_description_view`, `ice_candidate_view`, `data_channel_init`) and owned outputs (`basic_session_description`, `basic_ice_candidate`), the five state and policy enumerations, `options` (webcpp's own bounds), and a `runtime` that owns what the platform holds for the whole process. -- Operations are `async_*` members with any completion token and terminal cancellation; events - (candidates, state changes, incoming channels, open, close, buffered amount low) are pending - operations the caller re-arms, as Asio's `async_accept`, with a stated policy for an event - that arrives while no wait is pending. +- Operations are `async_*` members with any completion token, their state in the handler's + allocator, with the cancellation types each honours; events (candidates, state changes, + incoming channels, open, close, buffered amount low) are pending operations the caller re-arms, + as Asio's `async_accept`, with a stated policy for an event that arrives while no wait is pending. - Errors are values: `webcpp::webrtc::error`, an `error_category` named `webcpp.webrtc`, ten - enumerators with fixed values, plus Asio's own codes with their usual meaning. + enumerators with fixed values, the browser's DOMException names and libdatachannel's codes + mapped onto them, plus Asio's own codes with their usual meaning. - Back-pressure and bounds: `max_message_size`, `max_buffered_amount`, `max_received_bytes`, `max_queued_candidates`, `max_queued_channels` and `max_peer_connections`, each failing as a value. -- The native backend wraps libdatachannel (unmodified, a dependency, justified in the library's - documentation) and is available only where exceptions are on; the emscripten backend works - with exceptions on and off. +- The native backend calls libdatachannel 0.24.6, the superproject's pinned and source-built + copy, through its C API only, so the library works with exceptions on and off on both targets + (the owner's decision of 2026-11-14); libdatachannel's MPL-2.0 licence is accepted for it. +- The browser backend follows webcpp::beast's proven patterns: one intrusive registration of the + bridge per object, arrivals staged and charged on arrival, one notification per batch, + JavaScript's exceptions caught in JavaScript, the unsupported policy in an inline namespace. - A native peer and a headless-Chrome peer connect to each other in the tests. -- Increment 3 moves trystero onto this library and removes trystero's `backend`; that is a - change of trystero's, not of this proposal. +- Increment 3 moves trystero onto this library and removes the WebRTC of trystero's `backend`; + that is a change of trystero's, not of this proposal. ## Capabilities @@ -61,23 +68,26 @@ None. webcpp's design; libdatachannel and the browser are implementations behind it (design.md, D1). Repository `webcpporg/webrtc`, to be created by the owner, checked out as the submodule `libs/webrtc`, BSL-1.0, "Copyright (c) 2026 WebCpp.org". -- **Implementation:** not started. There is no plan and no reference code: `reference/` holds - the draft specification (`spec.md`) and `reference/STATUS.md` ("reference code: none yet; - required before the proposal is accepted"). The first tasks are to write the plan and the - reference code (tasks.md, group 0). trystero's `backend` and its two implementations are the - nearest existing code and the precursor of the interface, but they live in trystero's - reference, not here, and they are not this library's reference code. -- **Dependencies:** webcpp::asio (the executors, and on Emscripten its bridge, which only posts - to the io_context); Boost.Asio, Boost.System (`result`, `error_code`) and Boost's other - headers; webcpp::config (``); libdatachannel 0.24.6 on native, unmodified, - MPL-2.0 (the licence awaits the owner, design.md Open Questions), found today through - `-sLIBDATACHANNEL_ROOT` or the superproject's `.local/libdatachannel`, pinned later when built - from `third_party/`; the browser's `RTCPeerConnection` and `RTCDataChannel` on Emscripten. - It knows nothing of xactor. -- **Status:** draft; no release; no implementation; not decided. -- **Other proposals:** depends on webcpp::asio's genesis (`libraries/asio`) for the executors - and the browser bridge. trystero (`libraries/trystero`) is its first user: increment 3 is a - later change of trystero, which replaces its `backend`, keeps its own policies (dropping text - messages and oversized frames, its per-minute window of connections) and merges the two - states itself. Native encryption and randomness stay in webcpp::crypto, WebSockets in +- **Implementation:** increment 1 is written as reference code: `reference/source/` holds the + interface and the native implementation over libdatachannel's C API with their tests, built and + passed on 2026-11-14 against the superproject's pinned libdatachannel, as the build asks, without + exceptions and under ThreadSanitizer, clean of clang-format and clang-tidy (`reference/STATUS.md`). + `reference/plan.md` holds the three increments. Increment 1's measurement of the C API's cost, + its documentation and its repository remain (tasks.md 1.11 to 1.13), then increments 2 and 3. +- **Dependencies:** webcpp::asio (the executors and the portable names; on Emscripten its + bridge); Boost.Asio through webcpp::asio, Boost.System (`result`, `error_code`) and Boost's + other headers; webcpp::config (``); natively libdatachannel 0.24.6 at + `6b1e2e6` with libjuice, libsrtp, usrsctp and plog, unmodified, MPL-2.0 and their own licences, + built by the superproject from `third_party/` through `/webcpp/third_party//libdatachannel` + against the same OpenSSL as Asio and Beast, with `threading=multi`; the browser's + `RTCPeerConnection` and `RTCDataChannel` on Emscripten. It knows nothing of xactor or of webcpp::beast. +- **Status:** proposed, for its public discussion on the pull request; no release; not decided. +- **Other proposals:** depends on webcpp::asio's genesis (`libraries/asio`, implementing) for the + executors and the browser bridge, and follows webcpp::beast's genesis (`libraries/beast`) in its + browser patterns; webcpp::beast may later use a byte stream of this library (beast's D6). + trystero (`libraries/trystero`) is its first user: increment 3 is a later change of trystero, + which replaces its `backend`'s WebRTC, keeps its own policies (the shared connection, dropping + text messages and oversized frames, its bound on unread frames, its per-minute window of + connections) and merges the two states itself. Native encryption and randomness stay in + webcpp::crypto, WebSockets in webcpp::beast. diff --git a/libraries/webrtc/openspec/changes/genesis/reference/STATUS.md b/libraries/webrtc/openspec/changes/genesis/reference/STATUS.md index b8b3bdc..b6fc850 100644 --- a/libraries/webrtc/openspec/changes/genesis/reference/STATUS.md +++ b/libraries/webrtc/openspec/changes/genesis/reference/STATUS.md @@ -1,59 +1,90 @@ # webcpp::webrtc: where the proposal stands, and how to resume -Written 2026-10-13, when this proposal was drafted from the specification. - -**Reference code: none yet; required before the proposal is accepted.** -**Plan: none yet; required before the proposal is accepted.** +Written 2026-11-14, when the draft of 2026-10-13 was brought up to date and given its plan and +its reference code, and proposed the same day (tasks.md 0.8): its status is `proposed`, for its +public discussion on webcpporg/proposals#12 and the maintainers' decision. ## What exists -- `spec.md`: the draft specification, dated 2026-10-10 (status `draft`): the owner's decisions of - that day, the controller's rulings on the review, the interface (section 4), the semantics - (section 5), exceptions, what a target cannot honour, testing, libdatachannel, the three - increments and the questions open for the owner. It is the only file the proposal's - requirements and tasks rest on. -- No repository, no branch, no header, no test, no commit. Nothing was built, run or measured - for this library. - -## Measured +- `spec.md`: the original specification of 2026-10-10, kept as written. `../design.md` (revised + 2026-11-14) supersedes it where they differ, and lists every difference in "What changed since + the specification". +- `plan.md`: the implementation plan, in three increments, one task per step. +- `source/`: the reference code of increment 1, the library's tree as its repository will start: + `build.jam`, `meta/libraries.json`, `README.md`, `AGENTS.md`, `LICENSE_1_0.txt`, the public + headers (`webrtc.hpp`, `config.hpp`, `error.hpp`, `types.hpp`, `options.hpp`, `runtime.hpp`, + `data_channel.hpp`, `peer_connection.hpp`), the platform-free machinery (`detail/operation.hpp`, + `detail/events.hpp`), the native backend over libdatachannel's C API + (`detail/native/capi.hpp`, `channel.hpp`, `connection.hpp`), and the tests (`test/`). +- The owner's decisions of 2026-11-14: a library of its own, not inside webcpp::beast + (design.md, D1); libdatachannel's MPL-2.0 accepted (D16); the native backend on libdatachannel's + C API, so that the library works with exceptions on and off (D4). -Nothing. The draft quotes facts about libdatachannel 0.24.6 (`RECV_QUEUE_LIMIT` of 1,024, -`DEFAULT_LOCAL_MAX_MESSAGE_SIZE`, the callbacks' recursive mutex, `resetCallbacks()`), about -Chromium's limit of 500 peer connections per page and about two Chrome switches, each with the -file and line it read them from. None was re-verified when this proposal was written. Two -measurements are left to increment 1: whether a never-read native channel stalls the -connection's other channels, and the allocation behaviour on the executor. +## Built, run and measured, 2026-11-14 -## The nearest existing code +On macOS 27.0 (arm64), Apple clang 21.0.0, Boost 1.92.0, b2 5.5.3, in a worktree of the +superproject at `eb08198` (`origin/main`: asio `6c4e2c8`, beast `6c53f85`, cobalt `5d51c4a`, +trystero `e9326e9`, libdatachannel `6b1e2e6`, OpenSSL `45e844f`), with `source/` linked as +`libs/webrtc`: -trystero's `backend` interface with `native/peer_connection.hpp`, `native/data_channel.hpp` and -`browser/backend.hpp` is this library's first draft, section 3 of the specification maps every -part of it. It lives in trystero's own proposal (`libraries/trystero`, its `reference/source/`), -and it is not this library's reference code: it is a virtual interface with callbacks and no -runtime, bounds or error category. +- **The provider.** `b2 ... threading=multi /webcpp/third_party//libdatachannel` built OpenSSL and + libdatachannel's static archives (libdatachannel itself in 13.8 s). +- **The suite, from scratch.** `b2 --user-config=.local/user-config.jam -a -j10 threading=multi + libs/webrtc/test`: 25 targets, all `**passed**`: `config`, `config_all_off`, + `config_developer_defined`, `error`, `types`, `events`, `events_no_exceptions`, `native`, + `native_no_exceptions`, `allocation`, `lifetime`, `stall`, and the 13 headers-alone units, in + about 70 s. +- **Without exceptions.** `native_no_exceptions` compiles its translation unit with + `-fno-exceptions` and links the archives the superproject builds with `-fexceptions`; it passes + whole. Before the reference code, a probe of 60 lines built with `-fno-exceptions` against the + same pinned libdatachannel connected two peers over the loopback through the C API, received + "hello", and got `RTC_ERR_INVALID` (-1) for the ICE server URL `stun:`, with no exception + (design.md, D4). +- **ThreadSanitizer.** `b2 ... threading=multi thread-sanitizer=on + define=WEBCPP_TEST_WEBRTC_REPEAT=100 libs/webrtc/test//lifetime libs/webrtc/test//native`: both + passed, no report, 100 rounds of destruction while the peer floods. libdatachannel's archives + are not instrumented: what it checks is this library's side of each hand-off. +- **A never-read channel stalls the others** (tasks.md 1.10): 3,000 messages on a channel never + read, then one on a second channel of the same connection: it did not arrive in 3 s; destroying + the first channel's far end released it, and that destruction returned in under 2 s + (`test/stall_test.cpp`, `test/lifetime_test.cpp`). +- **The lint, as far as one library goes.** wasi-sdk 34's `clang-format` (23.1) with the + superproject's `.clang-format`: every file formatted. Its `clang-tidy` with the superproject's + `.clang-tidy` and `test/.clang-tidy` (asio's), over a compilation database of the suite's 25 + translation units from b2's dry run (the native commands with `--target=arm64-apple-macosx15.0`, + the SDK's sysroot and libc++), and once more over the aggregate unit with `-fno-exceptions`: no + finding. The whole `tools/lint/lint.sh` was not run: it lints the whole tree. +- **Re-verified in libdatachannel at `6b1e2e6`:** `RECV_QUEUE_LIMIT` 1,024 and + `DEFAULT_LOCAL_MAX_MESSAGE_SIZE` 256 KiB (`src/impl/internals.hpp:41-46`); the queue's push + waits for room (`src/impl/queue.hpp:93`); `DataChannel::close()` does not stop the queue + (`src/impl/datachannel.cpp:97-113`) and a closed channel queues nothing new (`incoming`); the C + API's `wrap()` (`src/capi.cpp:217-228`); `rtcDeletePeerConnection` and `rtcDelete` block until + the callbacks in flight return (`DOC.md`); `setLocalDescription` sets the description before it + returns (`src/peerconnection.cpp:83-160`); a new channel inherits its connection's user pointer + (`rtcCreateDataChannelEx`, `rtcSetDataChannelCallback`), which the backend replaces at once. -## Open +## What remains -- The plan (`reference/plan.md`) and the reference code (tasks.md, group 0). -- The owner's two decisions: libdatachannel's MPL-2.0 licence, and whether a native program - built without exceptions gets the compiler's message or a stub's (design.md, Open Questions). -- The names of headers, Jamfile targets and the repository layout, which the plan fixes. -- webcpp::asio's browser bridge and suspension variants, which increment 2 consumes; that - proposal is a draft too. +- tasks.md 1.11: the C API's cost on receipt, measured against the C++ API's `receive()`. +- tasks.md 1.12: the documentation (the library's page, Doc Comments checked by MrDocs). +- tasks.md 1.13: the repository `webcpporg/webrtc` from one import commit of `source/`, the + superproject's change (submodule, CI lanes, the libdatachannel target's threading message, which + names trystero, worded for every consumer; webrtc moved from chapter 18 to chapter 15 of + `CODING-GUIDELINES.md`), the whole lint, the review. +- Increments 2 and 3 (tasks.md groups 2 and 3). +- The superproject's `CODING-GUIDELINES.md` chapter 18 still summarizes the draft of 2026-10-13 + (the stale WASI reason, libdatachannel found through `-sLIBDATACHANNEL_ROOT`, the open + questions on the licence and on the message without exceptions): it is updated with this + revision, in the superproject. +- Open questions O1 to O3 (design.md). ## How to resume -1. Read `spec.md` whole, then `../design.md` and `../tasks.md`; read webcpp::asio's genesis - (`libraries/asio`: executors, the bridge, JSPI and Asyncify) and trystero's genesis - (`libraries/trystero`: the `backend` this library replaces). -2. Do tasks 0.1 and 0.2: write `reference/plan.md` in the three increments of section 10, and - the reference code for the interface and the native implementation, with the tests of - section 8 that apply natively. Update this file with the repository, the commit and what was - measured, and when. -3. Ask the owner for the decisions of section 11, then propose the change to `proposed`. -4. Implement increment 1, then 2, then trystero's change (increment 3), in that order. - -Prerequisites are the superproject's: Boost 1.92 with its sources, b2, a C++20 compiler, -Emscripten from emsdk for increment 2, libdatachannel 0.24.6 found through -`-sLIBDATACHANNEL_ROOT=` or the superproject's `.local/libdatachannel`, and a headless -Chrome for the interop lane. +1. Read `../design.md` whole, then `plan.md` and `../tasks.md`; `spec.md` only for history. +2. Make a worktree of the superproject from `origin/main`; initialize `libs/config`, `libs/asio` + and, recursively, `third_party/libs/libdatachannel` and `third_party/libs/openssl`; set up + `.local/` as the superproject's `AGENTS.md` chapter 1 says; link this `source/` as + `libs/webrtc`. +3. Run the commands above; expect the same 25 passes. +4. Go on with tasks.md 1.11, then 1.12 and 1.13 once the owner accepts the proposal and creates + the repository; then increment 2, then trystero's change. diff --git a/libraries/webrtc/openspec/changes/genesis/reference/plan.md b/libraries/webrtc/openspec/changes/genesis/reference/plan.md new file mode 100644 index 0000000..8fad677 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/plan.md @@ -0,0 +1,451 @@ +--- +title: "webcpp::webrtc: implementation plan" +tags: [webcpp, webrtc, asio, emscripten, plan] +status: active +created: 2026-11-14 +--- + +# webcpp::webrtc Implementation Plan + +**Goal.** Build webcpp::webrtc as `../design.md` decides it, in three increments: (1) the +interface, the `runtime` and the native implementation over libdatachannel's C API; (2) the +browser implementation over webcpp::asio's bridge, with the interop lane; (3) trystero on it, a +change of trystero's. + +**Where it stands.** Increment 1 is written: `source/` is its tree, built and tested on +2026-11-14 against the superproject's pinned libdatachannel (`STATUS.md`). Its tasks below say +what each file is and how it was proved, and point to the file instead of repeating it. Increments +2 and 3 are to do; their tasks carry the interfaces, the files, the tests and the expected output. + +**Architecture.** + +- One public interface, ``, whose class templates `basic_peer_connection` and + `basic_data_channel` hold a `std::shared_ptr` to a backend state: `detail::native::*` natively, + `detail::browser::*` on emscripten (increment 2). The facade owns the state; posted events hold + it weakly. +- What waits is a `detail::pending`, made by `detail::make_operation` in the handler's + associated allocator, with two work guards and the handler's cancellation slot + (`detail/operation.hpp`). What an event becomes while nothing waits is `detail::state_watch` and + `detail::event_queue` (`detail/events.hpp`). Both are the same on both targets. +- Natively, libdatachannel's C API: an object is an `int` id with a user pointer to an inbox + (`std::weak_ptr` to the state, the executor); every callback copies and posts; destruction calls + `rtcDelete*`, which waits for the callbacks in flight. +- In the browser, one `intrusive_registration` of the io_context's bridge per object, `EM_ASM` + imports that catch JavaScript's exceptions in JavaScript, arrivals staged and charged on + arrival, one notification posted per batch (webcpp::beast's browser WebSocket, design.md D8). + +**Tech stack.** C++20; b2 5.5.3; Boost 1.92 (System, Asio through webcpp::asio, Core +lightweight_test); webcpp::config, webcpp::asio; libdatachannel 0.24.6 at `6b1e2e6` with libjuice, +libsrtp, usrsctp and plog, and OpenSSL 3.5.9, all built by the superproject from +`third_party/`; Emscripten 6.0.11 and Node for increment 2, headless Chrome for its interop lane; +wasi-sdk 34's clang-format and clang-tidy for the lint. + +## Global constraints + +- **Where the code lives.** The repository `webcpporg/webrtc`, created by the owner once the + proposal is accepted, starts from one import commit of `source/` (`CODING-GUIDELINES.md` + chapter 2) and is checked out as the superproject's submodule `libs/webrtc`. Until then + `source/` is built by linking it as `libs/webrtc` in a worktree of the superproject, never + committed there (Task 1.1). +- **Rules.** `CODING-GUIDELINES.md` chapters 1 to 13, and the library's `source/AGENTS.md`. Every + test is seen failing before the code that makes it pass, and only a build from scratch, + `b2 -a`, counts as evidence. +- **Commits.** Under the committer's own identity, with explicit paths and no trailer: + `git -c user.name= -c user.email=
commit -- `; the subject is prefixed + `webrtc:`. +- **Text.** English; no em dash; the licence notice of chapter 2 on every source file. +- **Commands.** From the superproject's root, with `.local/user-config.jam` as `AGENTS.md` + chapter 1 sets it up and `CPATH`, `CPLUS_INCLUDE_PATH` and `C_INCLUDE_PATH` unset: + + ``` + b2 --user-config=.local/user-config.jam -a -j10 threading=multi libs/webrtc/test + ``` + +## File structure + +| Path | What it holds | +| --- | --- | +| `build.jam` | `/webcpp/webrtc//headers`, `/webcpp/webrtc//webrtc` (natively with `/webcpp/third_party//libdatachannel`), the feature `webcpp-webrtc-unsupported` | +| `meta/libraries.json` | the library's entry | +| `include/webcpp/webrtc.hpp` | the convenience header | +| `include/webcpp/webrtc/config.hpp` | `WEBCPP_WEBRTC_NO_EXCEPTIONS`, the unsupported policy, the `#error` under WASI | +| `include/webcpp/webrtc/error.hpp` | `error`, the category `webcpp.webrtc` | +| `include/webcpp/webrtc/types.hpp` | the enumerations, the input views, the owned outputs | +| `include/webcpp/webrtc/options.hpp` | `options`, `runtime_options` | +| `include/webcpp/webrtc/runtime.hpp` | `runtime`, `detail::runtime_slot` | +| `include/webcpp/webrtc/data_channel.hpp` | `basic_data_channel` | +| `include/webcpp/webrtc/peer_connection.hpp` | `basic_peer_connection` | +| `include/webcpp/webrtc/detail/operation.hpp` | `pending`, `operation`, `make_operation` | +| `include/webcpp/webrtc/detail/events.hpp` | `state_watch`, `event_queue` | +| `include/webcpp/webrtc/detail/native/capi.hpp` | the C API's include, codes, states, texts | +| `include/webcpp/webrtc/detail/native/channel.hpp` | `channel_state`, `read_message` | +| `include/webcpp/webrtc/detail/native/connection.hpp` | `connection_state` | +| `include/webcpp/webrtc/detail/browser/*.hpp` | increment 2: `imports.hpp`, `channel.hpp`, `connection.hpp`, `census.hpp` | +| `test/Jamfile`, `test/.clang-tidy` | the tests; the tests' clang-tidy options, asio's | +| `test/require.hpp`, `test/pair.hpp` | `require`; two peers over the loopback, signalled in memory | +| `test/*_test.cpp` | config, error, types, events, native, allocation, lifetime, stall | +| `doc/`, `bench/` | increment 1, Tasks 1.12 and 1.11: the library's page, the receive benchmark | + +## Increment 1: the interface, the runtime and the native implementation + +### Task 1.1: The repository and its build (tasks.md 1.1) + +**Files:** `build.jam`, `meta/libraries.json`, `include/webcpp/webrtc/config.hpp`, +`test/Jamfile`, `test/config_test.cpp`, `README.md`, `AGENTS.md`, `LICENSE_1_0.txt`. + +**Interfaces.** `/webcpp/webrtc//headers` (include directory, webcpp::config, webcpp::asio's +headers, the unsupported policy's define); `/webcpp/webrtc//webrtc` (adds webcpp::asio and, +natively, `/webcpp/third_party//libdatachannel`, whose usage requirements bring `RTC_STATIC`, the +include directory and the archives, and which refuses `threading=single`). + +**Steps.** + +1. Make a worktree of the superproject from `origin/main`, initialize `libs/config`, `libs/asio` + and, recursively, `third_party/libs/libdatachannel` and `third_party/libs/openssl`, and link + `source/` as `libs/webrtc` (the Jamroot finds a library by its `build.jam`). +2. Write `config_test.cpp` (three builds: as the build asks, `WEBCPP_NO_EXCEPTIONS`, the macro + itself), see it fail without `config.hpp`, then write `config.hpp`. +3. Build the provider once: `b2 ... threading=multi /webcpp/third_party//libdatachannel` + (OpenSSL then libdatachannel's static archives; 13.8 s for libdatachannel on 2026-11-14). + +**Expected output.** `**passed**` for `config`, `config_all_off`, `config_developer_defined`. + +### Task 1.2: The value types (tasks.md 1.2) + +**Files:** `include/webcpp/webrtc/types.hpp`, `test/types_test.cpp`. + +**Interfaces.** `sdp_type`, `peer_connection_state`, `ice_connection_state`, +`data_channel_state`, `ice_transport_policy`; `ice_server`, `configuration`, +`session_description_view`, `ice_candidate_view`, `data_channel_init` (every member with a `{}` +default member initializer, so that a designated initializer leaving one out never warns); +`basic_session_description` and `basic_ice_candidate` with `view()`; +`session_description`, `ice_candidate`. + +**Tests.** Defaults; the enumerations' first value; a description's view round trip; a +candidate's view, an empty mid as no mid; a candidate's strings under a polymorphic allocator. + +**Expected output.** `**passed** ... types.test`. + +### Task 1.3: Options and errors (tasks.md 1.3) + +**Files:** `include/webcpp/webrtc/options.hpp`, `include/webcpp/webrtc/error.hpp`, +`test/error_test.cpp`. + +**Interfaces.** `options` (64, 16, 256 KiB, 16 MiB, 16 MiB), `runtime_options` (256, 0); +`enum class error` 1 to 10, `webrtc_category()` named `webcpp.webrtc`, `make_error_code`, +`boost::system::is_error_code_enum`. + +**Expected output.** `**passed** ... error.test`. + +### Task 1.4: The event machinery, without a platform (tasks.md 1.4) + +**Files:** `include/webcpp/webrtc/detail/operation.hpp`, `include/webcpp/webrtc/detail/events.hpp`, +`test/events_test.cpp`; the Jamfile builds it as the build asks and with +`off`. + +**Interfaces.** + +```cpp +template class pending { // completes once, then frees itself +public: + void complete(error_code, Values...); // posts the handler + void fail(error_code); // posts it with the fallback values + void discard() noexcept; // frees it without calling the handler + void link(pending*& slot) noexcept; // the slot it clears when it ends +}; +template +pending& make_operation(Handler&&, const IoExecutor&, std::tuple fallback, + webcpp::asio::cancellation_type supported); +template class state_watch; // coalesces; one wait; close +template class event_queue; // bounded; exempt entries; close +``` + +**Tests.** States coalesce; no change keeps a wait pending; a second wait of a kind completes with +`already_started`; a cancelled wait consumes nothing; the bound keeps a place for the end of +gathering; a satisfied wait is posted, not run inside the call; `close` aborts the wait and refuses +the next with `error::closed`; an operation is allocated through its handler's allocator. + +**Expected output.** `**passed**` for `events` and `events_no_exceptions`. + +**The C API's codes**, per call, which Tasks 1.6 and 1.7 apply (design.md, D10): + +| Call | `RTC_ERR_INVALID` | `RTC_ERR_FAILURE` | +| --- | --- | --- | +| `rtcCreatePeerConnection` | `syntax_error` (an ICE server URL) | `operation_error` | +| `rtcSetLocalDescription` | `operation_error` | `operation_error` (no channel to negotiate) | +| `rtcSetRemoteDescription` | `operation_error` (cannot be parsed, as Chromium) | `invalid_state` (the signaling state refuses it) | +| `rtcAddRemoteCandidate` | `operation_error` | `operation_error` | +| `rtcCreateDataChannelEx` | `operation_error` | `operation_error` | +| `rtcSendMessage` | `operation_error` | `invalid_state` (closed meanwhile) | +| `rtcReceiveMessage` | `operation_error` | `operation_error` | + +Checked before the call, as the W3C checks them: a closed connection (`invalid_state`); a +candidate before a remote description (`invalid_state`); both reliability limits, `negotiated` +without an id, id 65535, a label or protocol past 65,535 bytes (`type_error`); a send on a channel +not open (`invalid_state`), past the message limit (`message_too_large`) or the buffered bound +(`buffered_amount_exceeded`); natively, a text holding a zero (`operation_not_supported`). + +### Task 1.5: The native runtime (tasks.md 1.5) + +**Files:** `include/webcpp/webrtc/runtime.hpp`. + +**Interfaces.** `runtime(const runtime_options& = {})` calls `rtcSetThreadPoolSize` when the size +is not 0, then `rtcPreload`; `~runtime()` calls `rtcCleanup`, which waits for libdatachannel's +threads. `get_options()`, `peer_connections()`. `detail::runtime_slot` takes a place in the count +(`std::atomic`, a member), or none past `max_peer_connections`, and gives it back when the +connection's state goes. One runtime at a time natively is a precondition (design.md, D6). + +**Tests.** In `native_test.cpp`, `errors_as_values`: a cap of 1 refuses a second connection +with `too_many_peer_connections`, and the count returns to 0 once the first goes; +`destruction_and_moves`: the count follows a move and a destruction. + +### Task 1.6: The native peer connection (tasks.md 1.6) + +**Files:** `include/webcpp/webrtc/detail/native/capi.hpp`, +`include/webcpp/webrtc/detail/native/connection.hpp`, +`include/webcpp/webrtc/peer_connection.hpp`. + +**Interfaces.** `basic_peer_connection>`: `make(runtime&, const Executor&, const configuration&, const +options& = options(), const Allocator& = Allocator())` returning +`boost::system::result`; move only; `async_set_local_description` +(terminal cancellation), `async_set_remote_description` and `async_add_ice_candidate` (their +inputs copied during the call, in the object's allocator, so that a deferred token reads nothing +of the caller's afterwards), `async_wait_ice_candidate`, `async_wait_state_change`, +`async_wait_ice_connection_state_change`, `async_accept_data_channel`, `create_data_channel`, +`local_description`, `has_remote_description`, `state`, `ice_state`, `close`. + +**What the native state does.** `open` builds `rtcConfiguration` (URLs in libdatachannel's +`turn:user:credential@host` form, `bindAddress`, `iceTransportPolicy`, `disableAutoNegotiation`, +`maxMessageSize`), makes the connection, sets the user pointer to its inbox and the callbacks of +the local candidate, the state, the ICE state, the gathering state (`RTC_GATHERING_COMPLETE` is the +end of candidates, exempt from the bound) and the incoming channel. `rtcSetLocalDescription` is +synchronous in libdatachannel, so the description is read back at once. `close` closes the state +watches with `operation_aborted`, drops the queued candidates and channels, closes every live +channel with `error::closed` (each draining its queue before the connection's transports close), +then `rtcClosePeerConnection`; the destructor then calls `rtcDeletePeerConnection`. + +**Tests.** `native_test.cpp`: `a_full_exchange` (offer, answer, candidates to their end both ways +with none refused, the state reaching `connected`, the local description holding `a=candidate`), +`close_fires_no_state_change`, `destruction_and_moves`, `run_returns_once_closed`, +`errors_as_values` (a malformed URL is `syntax_error`; a candidate before a description is +`invalid_state`; adding a channel produces no description). + +### Task 1.7: The native data channel (tasks.md 1.7) + +**Files:** `include/webcpp/webrtc/detail/native/channel.hpp`, +`include/webcpp/webrtc/data_channel.hpp`. + +**Interfaces.** `basic_data_channel`: `async_wait_open`, `async_wait_close`, +`async_receive(DynamicBuffer&, token)` (Asio's first-version dynamic buffers), +`async_send(ConstBufferSequence, token)`, `async_send_text`, `async_wait_buffered_amount_low`, +`send`, `send_text`, `set_buffered_amount_low_threshold`, `buffered_amount`, `ready_state`, +`label`, `id`, `close`. + +**What the native state does.** `attach` sets the user pointer and the callbacks (open, closed, +buffered amount low, available), reads the label, and takes the state the channel already has. +No message callback is set, so libdatachannel keeps messages in its own queue (pull mode). +`read_message` peeks the size, refuses a message larger than the room left in the caller's buffer +with `no_buffer_space` (it stays queued), and copies into one contiguous region when the buffer +offers one, through storage of the channel's allocator otherwise. The peer closing the channel +still delivers what arrived before; the owner's `close()` and the connection's close discard what +is unread, as the W3C discards a message received once the channel left "open", by draining the +queue, which also releases a libdatachannel thread waiting for room. + +**Tests.** `native_test.cpp`: binary and text both ways with `is_text`, the label on both sides, +`received_before_the_first_receive`, `a_negotiated_channel` (id 7 on both, nothing accepted), +`bounds` (`message_too_large`, `buffered_amount_exceeded`, the channel staying open, +`no_buffer_space` then the message read into a larger buffer), `a_channel_closed_by_its_owner`. + +### Task 1.8: Exceptions (tasks.md 1.8) + +**Files:** `test/Jamfile` (`native_no_exceptions`, `events_no_exceptions`, the headers-alone +calls without `on`). + +**What proves it.** The whole native suite, built with `exception-handling=off` (`-fno-exceptions` +on its translation units), passes against the archives the superproject builds with +`-fexceptions` (`tools/libdatachannel/build.py`); the C API's `wrap()` keeps libdatachannel's +exceptions inside. No header of the library throws, tries or catches. + +**Expected output.** `**passed** ... native_no_exceptions.test`. + +### Task 1.9: Allocation and lifetime (tasks.md 1.9) + +**Files:** `test/allocation_test.cpp`, `test/lifetime_test.cpp`. + +**Tests.** A connection pair over a polymorphic allocator on a counting resource: the state, the +queues and the outputs allocate there (a description's text has that resource), and no allocation +of it happens on another thread than the io_context's. `destroyed_while_messages_arrive`: the +answering peer and its channel are destroyed while the offering peer floods them, repeated +(`WEBCPP_TEST_WEBRTC_REPEAT`, 10 by default, 100 under ThreadSanitizer); +`a_flooded_channel_is_destroyed_promptly`: 3,000 messages on a channel never read, then its +destruction under two seconds. + +**ThreadSanitizer.** + +``` +b2 --user-config=.local/user-config.jam -j10 threading=multi thread-sanitizer=on \ + define=WEBCPP_TEST_WEBRTC_REPEAT=100 libs/webrtc/test//lifetime libs/webrtc/test//native +``` + +Expected: both `**passed**`, no `WARNING: ThreadSanitizer` in their output. libdatachannel's +archives are not instrumented: what TSan sees is this library's side of every hand-off. + +### Task 1.10: A never-read channel and the others (tasks.md 1.10) + +**Files:** `test/stall_test.cpp`. + +Measured on 2026-11-14: with 3,000 messages on a channel never read, a message sent on a second +channel of the same connection does not arrive in three seconds; destroying the first channel's +far end releases it. The test asserts that finding, so that a change in libdatachannel fails it +and the documentation is changed with it. Documentation: a program reads every channel it holds, +or closes it. + +**Expected output.** `**passed** ... stall.test`. + +### Task 1.11: The C API's cost on receipt (tasks.md 1.11) + +**Files:** `bench/Jamfile`, `bench/receive_bench.cpp`. + +A benchmark program receives 100,000 messages of 1 KiB and of 64 KiB through `rtcReceiveMessage` +and, for comparison only, through the C++ API's `receive()`, in a release build, and reports +messages per second and allocations per message (a replaced global `operator new` counting). +Expected: one more allocation and copy per message through the C API (`Channel::peek` returns a +copy); the documentation states the measured ratio, and the comparison program is not shipped. + +### Task 1.12: Documentation (tasks.md 1.12) + +**Files:** `doc/` (AsciiDoc, Diataxis: a tutorial with two peers, how-to pages for signalling and +pacing, the reference by MrDocs, explanations), the Doc Comments of every public symbol. + +**Content the proposal fixes.** libdatachannel's justification and licence (design.md, D16); the +table of differences (design.md, D14, with the native text holding a zero and the stalled +connection added); the per-operation cancellation table (D11); the error table of Task 1.4; the +runtime's precondition (D6); exceptions (D4); allocation and what is outside the allocator (D12). + +**Expected output.** `b2 -a doc` and the doc check clean; MrDocs strict reports nothing. + +### Task 1.13: Lint, lanes and review (tasks.md 1.13) + +1. `clang-format` and `clang-tidy` of wasi-sdk 34 with the superproject's configuration and + `test/.clang-tidy`: clean on 2026-11-14 for every translation unit of the test suite and the + headers-alone units, with and without exceptions (`STATUS.md` says how it was run); the whole + lint, `tools/lint/lint.sh`, runs once the library is a submodule. +2. The superproject's change: register `libs/webrtc` (`.gitmodules`, `meta`, the CI's lanes), + word `third_party`'s libdatachannel refusal of `threading=single` for every consumer, not for + trystero alone, and move webrtc from chapter 18 to chapter 15 of `CODING-GUIDELINES.md`. +3. The review of the increment, then the owner's merge. + +## Increment 2: the browser implementation and the interop lane + +### Task 2.1: The browser imports (tasks.md 2.1) + +**Files:** `include/webcpp/webrtc/detail/browser/imports.hpp`. + +**Interfaces.** `EM_ASM` functions in inline functions, as webcpp::beast's +`browser/detail/imports.hpp`: `webcpp_webrtc_make(config, callback)` (an `RTCPeerConnection` +whose `onicecandidate`, `onconnectionstatechange`, `oniceconnectionstatechange`, `ondatachannel` +call the bridge function with `{type, ...}`; a thrown exception returned as its `name`), +`webcpp_webrtc_set_local(pc, callback)`, `webcpp_webrtc_set_remote(pc, type, sdp, callback)`, +`webcpp_webrtc_add_candidate(pc, init, callback)` (each promise's settlement delivered as an event, +its rejection as the DOMException's `name`), `webcpp_webrtc_channel(pc, label, init)`, +`webcpp_webrtc_send(dc, data, size, text)`, `webcpp_webrtc_close(object)`, +`webcpp_webrtc_message_size`, `webcpp_webrtc_copy` (beast's two, for `ArrayBuffer` and text). +Every handler set to null by `detach`. + +**Tests.** `browser_imports_test.cpp`, both suspension variants: an exception thrown in each +import arrives as its name, and C++ is never re-entered. + +### Task 2.2: The page's census (tasks.md 2.2) + +**Files:** `include/webcpp/webrtc/detail/browser/census.hpp`, the emscripten `runtime`. + +**Interfaces.** The census lives in JavaScript, on the page, under +`Symbol.for("webcpp.webrtc.census")`: a count of every `RTCPeerConnection` from its construction +until a `FinalizationRegistry` sees it collected, as trystero's is today (`browser/src.hpp:67`, +`browser/backend.hpp:951-960`). `make` past `max_peer_connections` fails with +`too_many_peer_connections`. + +**Tests.** `browser_runtime_test.cpp`: the cap, and a freed slot once the census counts the +object collected (a forced collection under node's `--expose-gc`). + +### Task 2.3: The browser peer connection (tasks.md 2.3) + +**Files:** `include/webcpp/webrtc/detail/browser/connection.hpp`; the facade selects it under +`WEBCPP_TARGET_EMSCRIPTEN`. + +**What it does.** The state is an `intrusive_registration` of the bridge (one key per object); its +`deliver` stages each event and posts at most one notification, with a generation number; the +notification feeds `state_watch` and `event_queue` on the executor. `close()` sets the handlers to +null, closes the object, fails the watches with `operation_aborted`; the bridge's `shutdown` +discards what waits. Errors by name (design.md, D10). `bind_address` follows the unsupported +policy (Task 2.5). + +**Tests.** `browser_test.cpp`, two peers in one page, every case of increment 1's native suite +that applies, in both suspension variants and with exceptions on and off. + +### Task 2.4: The browser data channel (tasks.md 2.4) + +**Files:** `include/webcpp/webrtc/detail/browser/channel.hpp`. + +**What it does.** Messages are staged in `deliver` into a queue in the object's allocator, charged +at once to `max_received_bytes` with each message's record (beast's `message_record_bytes`); past +it the channel closes and `async_receive` completes with `receive_overflow`; a received message past +`max_message_size` closes it with `message_too_large`. A send checks `readyState`, the size and +`bufferedAmount` before `send`, so the channel stays open on a refusal. + +**Tests.** `browser_channel_test.cpp`: overflow, an oversized receipt, the refusals, the +buffered-amount wait, the close paths, a channel accepted after its messages arrived. + +### Task 2.5: What the browser cannot honour (tasks.md 2.5) + +**Files:** `build.jam` (the feature), `config.hpp`, the browser classes inside +`inline namespace unsupported_error` or `unsupported_ignore`. + +**Tests.** `bind_address` fails `make` with `operation_not_supported` under the default and is +ignored under `webcpp-webrtc-unsupported=ignore`; two translation units with different policies +that pass a channel between them fail to link (beast's D9 test, copied). + +### Task 2.6: The emscripten lanes (tasks.md 2.6) + +``` +b2 --user-config=.local/user-config.jam -a toolset=emscripten webcpp-suspend=jspi libs/webrtc/test +b2 --user-config=.local/user-config.jam -a toolset=emscripten webcpp-suspend=asyncify libs/webrtc/test +``` + +Expected: every browser test `**passed**` in both, and in their `exception-handling=off` twins. + +### Task 2.7: The interop lane (tasks.md 2.7) + +**Files:** `test/interop/` (a native peer, a page, a local relay over webcpp::beast's WebSocket), +an own lane in `test/Jamfile`. + +**What it does.** Chrome headless with `--allow-loopback-in-peer-connection` and +`--disable-features=WebRtcHideLocalIpsWithMdns`; the native peer binds to 127.0.0.1; the relay +carries the descriptions and candidates as JSON. The native peer sends "ping", the page answers +"pong", in both suspension variants. + +**Expected output.** The lane's two runs `**passed**`. + +### Task 2.8: Lint, lanes, review (tasks.md 2.8) + +The whole lint with the emscripten toolset; every lane at the owner's CI levels; the review; the +documentation's table of differences checked against the browser's behaviour. + +## Increment 3: trystero on webcpp::webrtc + +A change of trystero's own (`libraries/trystero/openspec/changes/`), proposed when +increment 2 is merged. Its tasks: + +1. **Replace the backend's WebRTC.** `backend::peer_connection`, `backend::data_channel`, + `native/peer_connection.hpp`, `native/data_channel.hpp` and the WebRTC part of + `browser/backend.hpp` go; the room's code holds `webrtc::basic_peer_connection` and + `webrtc::basic_data_channel` over a polymorphic allocator on the app's resource, as + design.md's table "trystero's backend, part by part" maps them. +2. **Keep trystero's policies.** Dropping text messages and binaries larger than a room frame + (on the executor, after `async_receive`); the bound of 64 frames and 10 seconds on frames no + room has read; the per-minute window of connections; the merge of the two states; the shared + connection and its adoption, with one reader per channel. +3. **Prove it.** trystero's native and browser suites pass unchanged, its allocation test counts + the same resource, and `webcpp::webrtc` is recorded as its dependency in `build.jam`, + `meta/libraries.json` and its documentation. diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/AGENTS.md b/libraries/webrtc/openspec/changes/genesis/reference/source/AGENTS.md new file mode 100644 index 0000000..dff4ceb --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/AGENTS.md @@ -0,0 +1,27 @@ +# Working on webrtc + +Read the superproject's [AGENTS.md](../../AGENTS.md) and +[CODING-GUIDELINES.md](../../CODING-GUIDELINES.md) first. The library's proposal, its design +and its plan are in `proposals/libraries/webrtc/openspec/changes/genesis`. + +- **Natively, libdatachannel's C API only** (`rtc/rtc.h`), never its C++ API: the C API catches + every exception libdatachannel throws and returns a negative code, which is what lets this + library work with exceptions on and off (design.md, D4). A new call maps its codes to + `webcpp.webrtc` as the browser reports the same call (design.md, D10; plan, Task 1.4). +- **libdatachannel's callbacks run on its threads.** Each copies what it carries into the + standard allocator and posts to the executor through the object's weak pointer; none runs a + handler, none touches the user's allocator (design.md, D7). Destruction runs on the executor + and calls `rtcDelete*`, which waits for the callbacks in flight; never call it from a callback. +- **A channel's queue is libdatachannel's.** Past 1,024 unread messages its thread waits for + room, and the connection's other channels stall (measured, `test/stall_test.cpp`). Closing or + destroying a channel drains its queue; keep that, or a thread waits on (design.md, D9). +- **The runtime is the process's.** One at a time natively, made before any connection and + destroyed after the last connection and channel; tests make one per case. +- **Tests use real peers over the loopback,** bound to 127.0.0.1, with no STUN, and every run of + the io_context says why after `lint-run:`. Each suite runs as the build asks and, where it + matters, with `off`. The lifetime test runs under ThreadSanitizer with + `thread-sanitizer=on define=WEBCPP_TEST_WEBRTC_REPEAT=100`. +- **Increment 2** adds the browser implementation on webcpp::asio's bridge, following + webcpp::beast's browser WebSocket (design.md, D8); until then the headers that need a backend + (`runtime.hpp`, `data_channel.hpp`, `peer_connection.hpp`) stop with an `#error` on emscripten, + and the Jamfile declares native only. diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/LICENSE_1_0.txt b/libraries/webrtc/openspec/changes/genesis/reference/source/LICENSE_1_0.txt new file mode 100644 index 0000000..36b7cd9 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/LICENSE_1_0.txt @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/README.md b/libraries/webrtc/openspec/changes/genesis/reference/source/README.md new file mode 100644 index 0000000..7ee49f6 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/README.md @@ -0,0 +1,35 @@ +# webcpp::webrtc + +The W3C WebRTC data-channel API in Asio's model: peer connections and data channels whose +operations take completion tokens and run on the user's executor, written once and run natively +(over libdatachannel's C API) and, from increment 2, in the browser (over its own +`RTCPeerConnection` and `RTCDataChannel`). Media is out of scope. + +```cpp +#include + +namespace webrtc = webcpp::webrtc; + +webcpp::asio::io_context io; +webrtc::runtime rt; // libdatachannel's threads, and the cap of connections +auto pc = webrtc::peer_connection::make(rt, io.get_executor(), webrtc::configuration{}); +auto channel = pc->create_data_channel("chat"); +pc->async_set_local_description([&](boost::system::error_code ec, + webrtc::session_description offer) { + // send offer.view() to the peer through your signalling +}); +pc->async_wait_ice_candidate([&](boost::system::error_code ec, webrtc::ice_candidate c) { + // trickle c.view() to the peer; an empty candidate ends gathering +}); +``` + +A program uses `/webcpp/webrtc//webrtc`. Natively it brings the superproject's pinned +libdatachannel 0.24.6 (`/webcpp/third_party//libdatachannel`) with its OpenSSL, and needs +`threading=multi`; it works with exceptions on and off. + +This tree is the reference code of the proposal `libraries/webrtc/openspec/changes/genesis` in +`webcpporg/proposals`: increment 1, the interface and the native implementation, with its tests. +Its design, its plan and where it stands are there. + +Distributed under the Boost Software License, Version 1.0. libdatachannel is used unmodified +under the MPL-2.0, with its nested dependencies under their own licences. diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/build.jam b/libraries/webrtc/openspec/changes/genesis/reference/source/build.jam new file mode 100644 index 0000000..5e4daa6 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/build.jam @@ -0,0 +1,31 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) +# +# webrtc, the W3C WebRTC data-channel API in Asio's model. A program uses +# /webcpp/webrtc//webrtc: natively it brings the pinned libdatachannel and its +# OpenSSL, which need threading=multi; in the browser (increment 2) it brings +# nothing but webcpp::asio's browser runtime. + +project /webcpp/webrtc ; + +import feature ; + +# What a target cannot honour: an error by default, ignored where the platform +# does an equivalent thing of its own (design.md, D14). Propagated, so that a +# whole program agrees. +feature.feature webcpp-webrtc-unsupported : error ignore : propagated ; + +# The headers, without a backend: what the platform-free tests use. +alias headers : : : : include /webcpp/config//config + /webcpp/asio//headers + error:WEBCPP_WEBRTC_UNSUPPORTED_ERROR + ignore:WEBCPP_WEBRTC_UNSUPPORTED_IGNORE ; + +# Natively, libdatachannel through its C API, which works with exceptions on +# and off (design.md, D4): no is required of a consumer. +alias webrtc : : emscripten : : headers /webcpp/asio//asio ; +alias webrtc : : : : headers /webcpp/asio//asio + /webcpp/third_party//libdatachannel ; diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc.hpp new file mode 100644 index 0000000..28744c6 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc.hpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + webcpp::webrtc, the W3C WebRTC data-channel API in Asio's model: peer connections and data + channels whose operations take completion tokens and run on the user's executor, natively over + libdatachannel and, from increment 2, in the browser over its own objects. + + Its targets are native and emscripten; under WASI its configuration stops with an `#error` that + names the reason. + + @see The library's page. +*/ +#ifndef WEBCPP_WEBRTC_HPP +#define WEBCPP_WEBRTC_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#endif // WEBCPP_WEBRTC_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/config.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/config.hpp new file mode 100644 index 0000000..074d53c --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/config.hpp @@ -0,0 +1,57 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The configuration of webrtc, which each of its headers includes first: whether webrtc is built + without exceptions, and the policy for what a target cannot honour. + + webcpp::webrtc works with exceptions on and off on every target it builds for: natively it calls + libdatachannel's C API, which catches libdatachannel's exceptions and returns codes, and in the + browser its JavaScript catches the browser's. It raises no exception of its own; the macro + exists so that a program sets `WEBCPP_NO_EXCEPTIONS` for every library alike. + + @see "Exceptions", in the guide. +*/ +#ifndef WEBCPP_WEBRTC_CONFIG_HPP +#define WEBCPP_WEBRTC_CONFIG_HPP + +#include + +#ifdef __MRDOCS__ +/** + Defined when webrtc is built without exceptions: when webcpp has none, or when the developer + defines it. + + webrtc raises no exception of its own, so the macro changes nothing in its behaviour. +*/ +#define WEBCPP_WEBRTC_NO_EXCEPTIONS +#undef WEBCPP_WEBRTC_NO_EXCEPTIONS +/** Makes what a target cannot honour fail with `operation_not_supported`, the default. */ +#define WEBCPP_WEBRTC_UNSUPPORTED_ERROR +#undef WEBCPP_WEBRTC_UNSUPPORTED_ERROR +/** Makes what a target cannot honour, and where it may be ignored, ignored. */ +#define WEBCPP_WEBRTC_UNSUPPORTED_IGNORE +#undef WEBCPP_WEBRTC_UNSUPPORTED_IGNORE +#endif + +#if !defined(WEBCPP_HAS_EXCEPTIONS) && !defined(WEBCPP_WEBRTC_NO_EXCEPTIONS) +#define WEBCPP_WEBRTC_NO_EXCEPTIONS +#endif + +#if defined(WEBCPP_WEBRTC_UNSUPPORTED_ERROR) && defined(WEBCPP_WEBRTC_UNSUPPORTED_IGNORE) +#error \ + "webcpp::webrtc: define one of WEBCPP_WEBRTC_UNSUPPORTED_ERROR and WEBCPP_WEBRTC_UNSUPPORTED_IGNORE, not both" +#elif !defined(WEBCPP_WEBRTC_UNSUPPORTED_ERROR) && !defined(WEBCPP_WEBRTC_UNSUPPORTED_IGNORE) +/** Makes what a target cannot honour fail with `operation_not_supported`, the default. */ +#define WEBCPP_WEBRTC_UNSUPPORTED_ERROR +#endif + +#if defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(__wasi__) +#error \ + "webcpp::webrtc has no WASI target: there is no WebRTC stack for WASI. libdatachannel has no WASI port (its threads, and libjuice's and usrsctp's, need preemptive threads, and its ICE and SCTP were never ported to WASI sockets), and no WASI host interface offers WebRTC as a browser offers RTCPeerConnection. Build for native or emscripten." +#endif + +#endif // WEBCPP_WEBRTC_CONFIG_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/data_channel.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/data_channel.hpp new file mode 100644 index 0000000..33940f3 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/data_channel.hpp @@ -0,0 +1,349 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_DATA_CHANNEL_HPP +#define WEBCPP_WEBRTC_DATA_CHANNEL_HPP + +#include + +#include +#include +#include + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#error "webcpp::webrtc: the browser implementation is increment 2 of reference/plan.md" +#endif + +#include +#include + +#include // lint-world: the default executor +#include // lint-world: completion tokens +#include // lint-world: a send's buffer sequence + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::webrtc { + +template +class basic_peer_connection; + +namespace detail { +struct channel_access; +} // namespace detail + +/** + A data channel, the W3C's `RTCDataChannel`, whose events are operations the caller re-arms. + + Messages are kept from the channel's creation until `async_receive` reads them: natively in + libdatachannel's own bounded queue, which slows the peer when it is full. A channel is made by + its connection's `create_data_channel` or `async_accept_data_channel`; it is movable, not + copyable, and its executor's context outlives it. + + @tparam Executor The executor its handlers run on. + @tparam Allocator The allocator of its state, its queues and its label. +*/ +template > +class basic_data_channel { + using state_type = detail::native::channel_state; + +public: + /** The executor its handlers run on. */ + using executor_type = Executor; + /** The allocator of its state. */ + using allocator_type = Allocator; + + /** Moves the channel, its pending operations included; the source holds none. */ + basic_data_channel(basic_data_channel&& other) noexcept = default; + + /** + Moves the channel, closing the one this held. + + @param other The channel moved from. + @return This channel. + */ + basic_data_channel& operator=(basic_data_channel&& other) noexcept { + if (this != &other) { + reset(); + state_ = std::move(other.state_); + } + return *this; + } + + basic_data_channel(const basic_data_channel&) = delete; + basic_data_channel& operator=(const basic_data_channel&) = delete; + + /** Closes the channel and completes every pending operation with `operation_aborted`. */ + // Posting the aborted completions allocates, and a failure to allocate there ends the + // program, as in any noexcept destructor that must complete operations. + // NOLINTNEXTLINE(bugprone-exception-escape) + ~basic_data_channel() { reset(); } + + /** + The executor its handlers run on. + + @return The executor. + */ + [[nodiscard]] executor_type get_executor() const noexcept { return state_->get_executor(); } + + /** + The allocator of its state. + + @return The allocator. + */ + [[nodiscard]] allocator_type get_allocator() const noexcept { return state_->get_allocator(); } + + /** + Waits for the channel to open; completes at once, posted, when it is open. + + @param token The completion token, of signature `void(error_code)`; `error::closed` when the + channel closed first. + @return What the token makes of the operation. + */ + template + auto async_wait_open(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple<>{}, detail::wait_cancellation); + state->wait_open(op); + }, + token, state_); + } + + /** + Waits for the channel to close; completes at once, posted, when it is closed. + + @param token The completion token, of signature `void(error_code)`. + @return What the token makes of the operation. + */ + template + auto async_wait_close(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple<>{}, detail::wait_cancellation); + state->wait_close(op); + }, + token, state_); + } + + /** + Appends the next message, whole, to `buffer`. + + A message larger than the room left in `buffer` stays queued, and the operation completes + with `no_buffer_space`. Once the peer closed the channel, the messages it sent before are + still delivered, then the operation completes with `error::closed`. + + @param buffer A dynamic buffer (Asio's first version, as `beast::flat_buffer`), which + outlives the operation. + @param token The completion token, of signature `void(error_code, std::size_t, bool)`: the + message's size and whether it was text. + @return What the token makes of the operation. + */ + template + auto async_receive(DynamicBuffer& buffer, CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state, DynamicBuffer* target) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple{0, false}, + detail::wait_cancellation); + state->receive(*target, op); + }, + token, state_, &buffer); + } + + /** + Sends a binary message, completing once it is queued, at once, posted. + + @param buffers The message, read during the call. + @param token The completion token, of signature `void(error_code)`. + @return What the token makes of the operation. + */ + template + auto async_send(const ConstBufferSequence& buffers, CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state, + const ConstBufferSequence& data) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple<>{}, detail::wait_cancellation); + op.fail(send_buffers(*state, data)); + }, + token, state_, buffers); + } + + /** + Sends a text message, completing once it is queued, at once, posted. + + @param text The message, UTF-8, read during the call. + @param token The completion token, of signature `void(error_code)`. + @return What the token makes of the operation. + */ + template + auto async_send_text(std::string_view text, CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state, std::string_view data) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple<>{}, detail::wait_cancellation); + op.fail(state->send(data.data(), data.size(), true)); + }, + token, state_, text); + } + + /** + Waits for `buffered_amount()` to be at or below the threshold; at once, posted, when it is. + + @param token The completion token, of signature `void(error_code)`. + @return What the token makes of the operation. + */ + template + auto async_wait_buffered_amount_low(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple<>{}, detail::wait_cancellation); + state->wait_buffered_amount_low(op); + }, + token, state_); + } + + /** + Sends a binary message: queues it, or fails. + + @param buffers The message, read during the call. + @return `error::invalid_state` when the channel is not open, `error::message_too_large` past + the smaller of `options::max_message_size` and the peer's limit, + `error::buffered_amount_exceeded` past `options::max_buffered_amount`; nothing once queued. + */ + template + boost::system::error_code send(const ConstBufferSequence& buffers) { + return send_buffers(*state_, buffers); + } + + /** + Sends a text message: queues it, or fails as `send` does. + + @param text The message, UTF-8, read during the call. Natively a text holding a zero fails + with `operation_not_supported` (the table of differences). + @return The failure, or nothing once queued. + */ + boost::system::error_code send_text(std::string_view text) { + return state_->send(text.data(), text.size(), true); + } + + /** + Sets the threshold `async_wait_buffered_amount_low` waits for. + + @param threshold The threshold, in bytes; 0 at first. + */ + void set_buffered_amount_low_threshold(std::size_t threshold) { + state_->set_buffered_amount_low_threshold(threshold); + } + + /** + The bytes queued to send, the W3C's `bufferedAmount`. + + @return The bytes. + */ + [[nodiscard]] std::size_t buffered_amount() const { return state_->buffered_amount(); } + + /** + The channel's state, the W3C's `readyState`. + + @return The state. + */ + [[nodiscard]] data_channel_state ready_state() const noexcept { return state_->ready_state(); } + + /** + The channel's label. + + @return A view of the label, in the object's allocator, valid while the channel lives. + */ + [[nodiscard]] std::string_view label() const noexcept { return state_->label(); } + + /** + The channel's SCTP stream id, the W3C's `id`. + + @return The id, or nothing before the transport gave it one. + */ + [[nodiscard]] std::optional id() const { return state_->id(); } + + /** + Closes the channel: its pending operations complete with `operation_aborted`, but + `async_wait_close`, which completes once it is closed; unread messages are discarded. + */ + void close() { state_->close(); } + +private: + template + friend class basic_peer_connection; + friend struct detail::channel_access; + + explicit basic_data_channel(std::shared_ptr state) noexcept + : state_(std::move(state)) {} + + // Sends the message `buffers` holds, gathered once in the channel's allocator when it is in + // several buffers. + template + static boost::system::error_code send_buffers(state_type& state, + const ConstBufferSequence& buffers) { + const auto begin = webcpp::asio::buffer_sequence_begin(buffers); + const auto end = webcpp::asio::buffer_sequence_end(buffers); + if (begin == end) { + return state.send(nullptr, 0, false); + } + if (std::next(begin) == end) { + const webcpp::asio::const_buffer one(*begin); + return state.send(static_cast(one.data()), one.size(), false); + } + using storage_allocator = std::allocator_traits::template rebind_alloc; + std::vector storage(webcpp::asio::buffer_size(buffers), + storage_allocator(state.get_allocator())); + webcpp::asio::buffer_copy(webcpp::asio::buffer(storage), buffers); + return state.send(storage.data(), storage.size(), false); + } + + void reset() { + if (state_) { + state_->destroy(); + state_.reset(); + } + } + + std::shared_ptr state_; +}; + +namespace detail { + +/** The library's access to a channel's construction. */ +struct channel_access { + /** A channel over `state`, null for the value a failed accept completes with. */ + template + static Channel make(std::shared_ptr state) noexcept { + return Channel(std::move(state)); + } +}; + +} // namespace detail + +/** A data channel on Asio's type-erased executor, in the standard allocator. */ +using data_channel = basic_data_channel<>; + +} // namespace webcpp::webrtc + +#endif // WEBCPP_WEBRTC_DATA_CHANNEL_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/events.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/events.hpp new file mode 100644 index 0000000..5bca435 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/events.hpp @@ -0,0 +1,174 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_DETAIL_EVENTS_HPP +#define WEBCPP_WEBRTC_DETAIL_EVENTS_HPP + +#include + +#include +#include + +#include // lint-world: Asio's codes + +#include +#include +#include +#include +#include + +// What an event becomes while no wait of its kind is pending (design.md, D5), common to both +// backends and testable without a platform: each class holds at most one wait, completes it from +// what it keeps, and runs on the object's executor only. + +namespace webcpp::webrtc::detail { + +/** + A state whose changes coalesce while no wait is pending: a wait completes with the current state + once it differs from the one the previous wait completed with, or from the first enumerator. +*/ +template +class state_watch { +public: + /** The current state. */ + [[nodiscard]] State current() const noexcept { return current_; } + + /** Starts a wait, which completes once the state differs from the one last delivered. */ + void wait(pending& op) { + if (waiter_ != nullptr) { + op.fail(webcpp::asio::error::already_started); + return; + } + if (closed_) { + op.fail(make_error_code(error::closed)); + return; + } + op.link(waiter_); + deliver(); + } + + /** Records a change, which completes the pending wait if it is one. */ + void update(State state) { + if (closed_) { + return; + } + current_ = state; + deliver(); + } + + /** + Ends the watch: the state reads `state`, nothing more is delivered, the wait fails with `ec`. + */ + void close(State state, error_code ec) { + current_ = state; + closed_ = true; + if (waiter_ != nullptr) { + waiter_->fail(ec); + } + } + +private: + void deliver() { + if (waiter_ != nullptr && current_ != delivered_) { + delivered_ = current_; + waiter_->complete({}, current_); + } + } + + State current_{}; + State delivered_{}; + pending* waiter_ = nullptr; + bool closed_ = false; +}; + +/** + Events kept in order while no wait is pending, in the object's allocator, up to a bound; an + exempt event, as the end of gathering, has a place of its own past it. +*/ +template +class event_queue { +public: + /** Makes an empty queue of at most `bound` events that are not exempt. */ + event_queue(std::size_t bound, const Allocator& allocator) + : queue_(allocator_type(allocator)), bound_(bound) {} + + /** Starts a wait, which completes with the oldest event kept, or with the next one. */ + void wait(pending& op) { + if (waiter_ != nullptr) { + op.fail(webcpp::asio::error::already_started); + return; + } + if (!queue_.empty()) { + T value = std::move(queue_.front().value); + if (!queue_.front().exempt) { + --counted_; + } + queue_.pop_front(); + op.complete({}, std::move(value)); + return; + } + if (closed_) { + op.fail(make_error_code(error::closed)); + return; + } + op.link(waiter_); + } + + /** + Hands `value` to the pending wait, or keeps it. + + @return Empty when it was delivered or kept; the value itself when the bound refused it, for + the caller to dispose of (a channel past the backlog is closed). + */ + std::optional push(T value, bool exempt = false) { + if (closed_) { + return std::optional(std::move(value)); + } + if (waiter_ != nullptr) { + waiter_->complete({}, std::move(value)); + return std::nullopt; + } + if (!exempt && counted_ >= bound_) { + return std::optional(std::move(value)); + } + if (!exempt) { + ++counted_; + } + queue_.push_back(entry{std::move(value), exempt}); + return std::nullopt; + } + + /** The number of events kept. */ + [[nodiscard]] std::size_t size() const noexcept { return queue_.size(); } + + /** Ends the queue: what it keeps is dropped, and the wait fails with `ec`. */ + void close(error_code ec) { + closed_ = true; + counted_ = 0; + queue_.clear(); + if (waiter_ != nullptr) { + waiter_->fail(ec); + } + } + +private: + struct entry { + T value; + bool exempt = false; + }; + + using allocator_type = std::allocator_traits::template rebind_alloc; + + std::deque queue_; + std::size_t bound_ = 0; + std::size_t counted_ = 0; + pending* waiter_ = nullptr; + bool closed_ = false; +}; + +} // namespace webcpp::webrtc::detail + +#endif // WEBCPP_WEBRTC_DETAIL_EVENTS_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/capi.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/capi.hpp new file mode 100644 index 0000000..12f8b6e --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/capi.hpp @@ -0,0 +1,140 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_DETAIL_NATIVE_CAPI_HPP +#define WEBCPP_WEBRTC_DETAIL_NATIVE_CAPI_HPP + +#include + +#include +#include + +// libdatachannel's C API, which catches every exception libdatachannel throws and returns a +// negative code instead, so that this backend works with exceptions on and off (design.md, D4). +#include // lint-world: libdatachannel's WebRTC, the library's purpose + +#include + +#include +#include +#include +#include + +namespace webcpp::webrtc::detail::native { + +/** The error type of every completion. */ +using boost::system::error_code; + +/** + The code of a negative result of the C API, for one call. + + @param rc The result, negative. + @param invalid What `RTC_ERR_INVALID` (a `std::invalid_argument` inside) means for this call. + @param failure What `RTC_ERR_FAILURE` (any other exception inside) means for this call. +*/ +inline error_code code_of(int rc, error invalid, error failure) { + switch (rc) { + case RTC_ERR_INVALID: return make_error_code(invalid); + case RTC_ERR_FAILURE: return make_error_code(failure); + default: return make_error_code(error::operation_error); + } +} + +/** The state libdatachannel reports, as the W3C names it. */ +inline peer_connection_state state_of(rtcState state) { + switch (state) { + case RTC_NEW: return peer_connection_state::new_; + case RTC_CONNECTING: return peer_connection_state::connecting; + case RTC_CONNECTED: return peer_connection_state::connected; + case RTC_DISCONNECTED: return peer_connection_state::disconnected; + case RTC_FAILED: return peer_connection_state::failed; + case RTC_CLOSED: return peer_connection_state::closed; + } + return peer_connection_state::failed; +} + +/** The ICE state libdatachannel reports, as the W3C names it. */ +inline ice_connection_state ice_state_of(rtcIceState state) { + switch (state) { + case RTC_ICE_NEW: return ice_connection_state::new_; + case RTC_ICE_CHECKING: return ice_connection_state::checking; + case RTC_ICE_CONNECTED: return ice_connection_state::connected; + case RTC_ICE_COMPLETED: return ice_connection_state::completed; + case RTC_ICE_FAILED: return ice_connection_state::failed; + case RTC_ICE_DISCONNECTED: return ice_connection_state::disconnected; + case RTC_ICE_CLOSED: return ice_connection_state::closed; + } + return ice_connection_state::failed; +} + +/** The type libdatachannel names a description by. */ +inline const char* type_name(sdp_type type) { + switch (type) { + case sdp_type::offer: return "offer"; + case sdp_type::answer: return "answer"; + case sdp_type::pranswer: return "pranswer"; + case sdp_type::rollback: return "rollback"; + } + return "offer"; +} + +/** The type a description's name says, or nothing for a name that is none. */ +inline std::optional type_of(std::string_view name) { + if (name == "offer") { + return sdp_type::offer; + } + if (name == "answer") { + return sdp_type::answer; + } + if (name == "pranswer") { + return sdp_type::pranswer; + } + if (name == "rollback") { + return sdp_type::rollback; + } + return std::nullopt; +} + +/** Whether `size` fits the C API's `int`. */ +inline bool fits_int(std::size_t size) noexcept { + return size <= static_cast(INT_MAX); +} + +/** + Reads a text of the C API, whose getter writes it with its terminating zero, into `out`. + + The getter is called once for the length, then until the text fits: a local description grows as + candidates are gathered between the two calls. + + @param get The getter, `rtcGetLocalDescription` or another of its form. + @param id The object it reads. + @param out The string it writes, in the caller's allocator. + @return The C API's code: 0, or negative. +*/ +template +int read_text(int (*get)(int, char*, int), int id, String& out) { + for (;;) { + const int length = get(id, nullptr, 0); + if (length < 0) { + return length; + } + out.resize(static_cast(length)); + const int written = get(id, out.data(), length); + if (written == RTC_ERR_TOO_SMALL) { + continue; + } + if (written < 0) { + return written; + } + // Without its terminating zero. + out.resize(written > 0 ? static_cast(written) - 1 : 0); + return 0; + } +} + +} // namespace webcpp::webrtc::detail::native + +#endif // WEBCPP_WEBRTC_DETAIL_NATIVE_CAPI_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/channel.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/channel.hpp new file mode 100644 index 0000000..c3ae5c7 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/channel.hpp @@ -0,0 +1,521 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_DETAIL_NATIVE_CHANNEL_HPP +#define WEBCPP_WEBRTC_DETAIL_NATIVE_CHANNEL_HPP + +#include + +#include +#include +#include +#include +#include + +#include // lint-world: copies a message into the caller's buffer +#include // lint-world: Asio's codes +#include // lint-world: libdatachannel's events are posted + +#include +#include +#include +#include +#include +#include + +namespace webcpp::webrtc::detail::native { + +/** What one attempt to read a message found. */ +enum class read_status { + /** No message is queued. */ + empty, + /** One message was appended to the caller's buffer. */ + message, + /** The message could not be read; it stays queued. */ + failed, +}; + +/** The outcome of one attempt to read a message. */ +struct read_result { + /** What the attempt found. */ + read_status status = read_status::empty; + /** The message's size in bytes, without a text's terminating zero. */ + std::size_t size = 0; + /** Whether the message was text. */ + bool text = false; + /** Why it could not be read. */ + error_code ec; +}; + +/** + Appends the next message of the channel `dc` to the dynamic buffer `opaque` points to. + + The message is copied once into the buffer when the buffer offers one contiguous region for it, + and through storage of the channel's allocator otherwise. A message larger than the room left in + the buffer stays queued, and the attempt fails with `no_buffer_space`, as webcpp::beast's does. +*/ +template +read_result read_message(void* opaque, int dc, const Allocator& allocator) { + auto& buffer = *static_cast(opaque); + int size = 0; + int rc = rtcReceiveMessage(dc, nullptr, &size); + if (rc == RTC_ERR_NOT_AVAIL) { + return {}; + } + if (rc < 0) { + return { + .status = read_status::failed, + .size = 0, + .text = false, + .ec = make_error_code(error::operation_error), + }; + } + // A binary message has a positive size; a text one a negative size that counts its zero. + const bool text = size < 0; + const std::size_t length = + text ? static_cast(-(size + 1)) : static_cast(size); + const std::size_t needed = text ? length + 1 : length; + const std::size_t room = buffer.max_size() - buffer.size(); + if (length > room) { + return { + .status = read_status::failed, + .size = 0, + .text = false, + .ec = error_code(webcpp::asio::error::no_buffer_space), + }; + } + if (needed == 0) { + // An empty binary message: the C API discards a message only into a buffer. + char sink = 0; + int capacity = 1; + rc = rtcReceiveMessage(dc, &sink, &capacity); + if (rc < 0) { + return { + .status = read_status::failed, + .size = 0, + .text = false, + .ec = make_error_code(error::operation_error), + }; + } + return {.status = read_status::message, .size = 0, .text = false, .ec = {}}; + } + if (needed <= room) { + const auto prepared = buffer.prepare(needed); + const auto first = *webcpp::asio::buffer_sequence_begin(prepared); + if (first.size() >= needed) { + int capacity = static_cast(needed); + rc = rtcReceiveMessage(dc, static_cast(first.data()), &capacity); + if (rc < 0) { + return { + .status = read_status::failed, + .size = 0, + .text = false, + .ec = make_error_code(error::operation_error), + }; + } + buffer.commit(length); + return {.status = read_status::message, .size = length, .text = text, .ec = {}}; + } + } + using storage_allocator = std::allocator_traits::template rebind_alloc; + std::vector storage(needed, storage_allocator(allocator)); + int capacity = static_cast(needed); + rc = rtcReceiveMessage(dc, storage.data(), &capacity); + if (rc < 0) { + return { + .status = read_status::failed, + .size = 0, + .text = false, + .ec = make_error_code(error::operation_error), + }; + } + buffer.commit(webcpp::asio::buffer_copy(buffer.prepare(length), + webcpp::asio::buffer(storage.data(), length))); + return {.status = read_status::message, .size = length, .text = text, .ec = {}}; +} + +/** + The state of a native data channel: libdatachannel's channel, by its id in the C API, and what + waits on it, on the object's executor. + + libdatachannel's callbacks run on its threads; each posts to the executor through a weak pointer, + so that one posted before the channel went finds nothing (design.md, D7). +*/ +template +class channel_state : public std::enable_shared_from_this> { +public: + /** The channel's text type. */ + using string_type = detail::string; + + /** Makes the state of a channel not yet attached to libdatachannel. */ + channel_state(const Executor& executor, const Allocator& allocator, const options& opts) + : executor_(executor), + allocator_(allocator), + label_(typename string_type::allocator_type(allocator)), + inbox_{{}, executor}, + max_message_size_(opts.max_message_size), + max_buffered_amount_(opts.max_buffered_amount) {} + + channel_state(const channel_state&) = delete; + channel_state& operator=(const channel_state&) = delete; + channel_state(channel_state&&) = delete; + channel_state& operator=(channel_state&&) = delete; + + /** Deletes libdatachannel's channel, aborting what waits. */ + // Posting the aborted completions allocates, and a failure to allocate there ends the + // program, as in any noexcept destructor that must complete operations. + // NOLINTNEXTLINE(bugprone-exception-escape) + ~channel_state() { destroy(); } + + /** + Takes over libdatachannel's channel `dc`: its user pointer, its callbacks, its label and the + state it is in already, since it may have opened, or closed, before. + */ + void attach(int dc) { + dc_ = dc; + inbox_.self = this->weak_from_this(); + rtcSetUserPointer(dc_, &inbox_); + rtcSetOpenCallback(dc_, &on_open); + rtcSetClosedCallback(dc_, &on_closed); + rtcSetBufferedAmountLowCallback(dc_, &on_buffered_amount_low); + rtcSetAvailableCallback(dc_, &on_available); + static_cast(read_text(&rtcGetDataChannelLabel, dc_, label_)); + if (rtcIsClosed(dc_)) { + ready_ = data_channel_state::closed; + } else if (rtcIsOpen(dc_)) { + ready_ = data_channel_state::open; + } + } + + /** The object's executor. */ + [[nodiscard]] const Executor& get_executor() const noexcept { return executor_; } + + /** The object's allocator. */ + [[nodiscard]] const Allocator& get_allocator() const noexcept { return allocator_; } + + /** Waits for the channel to open; at once when it is. */ + void wait_open(pending<>& op) { + if (open_ != nullptr) { + op.fail(webcpp::asio::error::already_started); + return; + } + if (ready_ == data_channel_state::open) { + op.complete({}); + return; + } + if (ready_ != data_channel_state::connecting) { + op.fail(make_error_code(error::closed)); + return; + } + op.link(open_); + } + + /** Waits for the channel to close; at once when it is. */ + void wait_close(pending<>& op) { + if (close_ != nullptr) { + op.fail(webcpp::asio::error::already_started); + return; + } + if (ready_ == data_channel_state::closed) { + op.complete({}); + return; + } + op.link(close_); + } + + /** Waits for the buffered amount to fall to the threshold; at once when it is there. */ + void wait_buffered_amount_low(pending<>& op) { + if (low_ != nullptr) { + op.fail(webcpp::asio::error::already_started); + return; + } + if (ready_ == data_channel_state::closing || ready_ == data_channel_state::closed) { + op.fail(make_error_code(error::closed)); + return; + } + if (buffered_amount() <= threshold_) { + op.complete({}); + return; + } + op.link(low_); + } + + /** Waits for the next message, appended to `buffer`, which outlives the wait. */ + template + void receive(DynamicBuffer& buffer, pending& op) { + if (receive_ != nullptr) { + op.fail(webcpp::asio::error::already_started); + return; + } + if (dc_ < 0 || ready_ == data_channel_state::closing) { + op.fail(make_error_code(error::closed)); + return; + } + target_ = &buffer; + read_ = &read_message; + op.link(receive_); + attempt(); + if (receive_ != nullptr && ready_ == data_channel_state::closed) { + receive_->fail(make_error_code(error::closed)); + } + } + + /** + Sends one message, binary or text, at once or not at all. + + @return The failure, or nothing once libdatachannel queued it. + */ + error_code send(const char* data, std::size_t size, bool text) { + if (dc_ < 0 || ready_ != data_channel_state::open) { + return make_error_code(error::invalid_state); + } + const int peer = rtcMaxMessageSize(dc_); + const std::size_t limit = peer > 0 + ? std::min(max_message_size_, static_cast(peer)) + : max_message_size_; + if (size > limit || !fits_int(size)) { + return make_error_code(error::message_too_large); + } + const std::size_t queued = buffered_amount(); + if (size > max_buffered_amount_ || queued > max_buffered_amount_ - size) { + return make_error_code(error::buffered_amount_exceeded); + } + int rc = 0; + if (text) { + // The C API takes a text as a zero-terminated string, which cannot hold a zero. + const std::string_view view(data, size); + if (view.find('\0') != std::string_view::npos) { + return {webcpp::asio::error::operation_not_supported}; + } + const string_type terminated(view, typename string_type::allocator_type(allocator_)); + rc = rtcSendMessage(dc_, terminated.c_str(), -1); + } else { + rc = rtcSendMessage(dc_, data, static_cast(size)); + } + if (rc < 0) { + // It closed meanwhile, on libdatachannel's thread, or refused the message. + return code_of(rc, error::operation_error, error::invalid_state); + } + return {}; + } + + /** Sets the threshold of `async_wait_buffered_amount_low`. */ + void set_buffered_amount_low_threshold(std::size_t threshold) { + threshold_ = threshold; + if (dc_ >= 0) { + rtcSetBufferedAmountLowThreshold( + dc_, static_cast(std::min(threshold, INT_MAX))); + } + buffered_amount_low(); + } + + /** The bytes queued to send. */ + [[nodiscard]] std::size_t buffered_amount() const { + const int amount = dc_ >= 0 ? rtcGetBufferedAmount(dc_) : 0; + return amount > 0 ? static_cast(amount) : 0; + } + + /** The channel's state. */ + [[nodiscard]] data_channel_state ready_state() const noexcept { return ready_; } + + /** The channel's label. */ + [[nodiscard]] std::string_view label() const noexcept { return label_; } + + /** The channel's SCTP stream id, once it has one. */ + [[nodiscard]] std::optional id() const { + const int stream = dc_ >= 0 ? rtcGetDataChannelStream(dc_) : -1; + if (stream < 0 || stream > 65535) { + return std::nullopt; + } + return static_cast(stream); + } + + /** + Closes the channel by its owner: what waits ends with `operation_aborted`, but + `async_wait_close`, and unread messages are discarded, as the W3C discards a message + received once the channel left "open". + */ + void close() { + if (dc_ < 0 || ready_ == data_channel_state::closing || + ready_ == data_channel_state::closed) { + return; + } + ready_ = data_channel_state::closing; + abort(webcpp::asio::error::operation_aborted); + rtcClose(dc_); + drain(); + } + + /** Closes the channel because its connection closed: what waits ends with `error::closed`. */ + void connection_closed() { + if (dc_ < 0 || ready_ == data_channel_state::closed) { + return; + } + ready_ = data_channel_state::closed; + abort(make_error_code(error::closed)); + rtcClose(dc_); + drain(); + if (close_ != nullptr) { + close_->complete({}); + } + } + + /** Deletes libdatachannel's channel, after which none of its callbacks runs. */ + void destroy() { + if (dc_ < 0) { + return; + } + ready_ = data_channel_state::closed; + abort(webcpp::asio::error::operation_aborted); + if (close_ != nullptr) { + close_->fail(webcpp::asio::error::operation_aborted); + } + rtcClose(dc_); + drain(); + // Blocks until every callback of the channel in flight returned; none runs afterwards. + rtcDeleteDataChannel(dc_); + dc_ = -1; + } + +private: + struct inbox { + std::weak_ptr self; + Executor executor; + }; + + using event = void (channel_state::*)(); + + // Runs on libdatachannel's threads: posts, through the weak pointer, and touches nothing of + // the user's allocator; the post carries Asio's default allocator. + static void post_event(void* pointer, event what) { + const auto& box = *static_cast(pointer); + webcpp::asio::post(box.executor, [self = box.self, what] { + if (const auto state = self.lock()) { + ((*state).*what)(); + } + }); + } + + static void RTC_API on_open(int /*id*/, void* pointer) { + post_event(pointer, &channel_state::opened); + } + + static void RTC_API on_closed(int /*id*/, void* pointer) { + post_event(pointer, &channel_state::closed); + } + + static void RTC_API on_buffered_amount_low(int /*id*/, void* pointer) { + post_event(pointer, &channel_state::buffered_amount_low); + } + + static void RTC_API on_available(int /*id*/, void* pointer) { + post_event(pointer, &channel_state::attempt); + } + + void opened() { + if (dc_ < 0 || ready_ != data_channel_state::connecting) { + return; + } + ready_ = data_channel_state::open; + if (open_ != nullptr) { + open_->complete({}); + } + } + + // The channel closed: by the peer, by its transport, or as its owner asked. Messages that + // arrived before the peer closed it are still delivered, then receives fail with `closed`. + void closed() { + if (dc_ < 0) { + return; + } + ready_ = data_channel_state::closed; + if (open_ != nullptr) { + open_->fail(make_error_code(error::closed)); + } + if (low_ != nullptr) { + low_->fail(make_error_code(error::closed)); + } + attempt(); + if (receive_ != nullptr) { + receive_->fail(make_error_code(error::closed)); + } + if (close_ != nullptr) { + close_->complete({}); + } + } + + void buffered_amount_low() { + if (low_ != nullptr && buffered_amount() <= threshold_) { + low_->complete({}); + } + } + + // Reads one message for the pending receive, if one is queued. + void attempt() { + if (receive_ == nullptr || dc_ < 0) { + return; + } + const read_result result = read_(target_, dc_, allocator_); + switch (result.status) { + case read_status::message: receive_->complete({}, result.size, result.text); break; + case read_status::failed: receive_->fail(result.ec); break; + case read_status::empty: break; + } + } + + void abort(error_code ec) { + if (open_ != nullptr) { + open_->fail(ec); + } + if (receive_ != nullptr) { + receive_->fail(ec); + } + if (low_ != nullptr) { + low_->fail(ec); + } + } + + // Discards what is queued in libdatachannel, which also releases a libdatachannel thread + // waiting for room in a full queue. A closed channel queues nothing new, so this ends. + void drain() { + using storage_allocator = std::allocator_traits::template rebind_alloc; + std::vector sink{storage_allocator(allocator_)}; + for (;;) { + int size = 0; + if (rtcReceiveMessage(dc_, nullptr, &size) != RTC_ERR_SUCCESS) { + return; + } + const auto needed = static_cast(size < 0 ? -size : size) + 1; + if (sink.size() < needed) { + sink.resize(needed); + } + int capacity = static_cast(sink.size()); + if (rtcReceiveMessage(dc_, sink.data(), &capacity) != RTC_ERR_SUCCESS) { + return; + } + } + } + + Executor executor_; + Allocator allocator_; + string_type label_; + inbox inbox_; + int dc_ = -1; + data_channel_state ready_ = data_channel_state::connecting; + std::size_t max_message_size_ = 0; + std::size_t max_buffered_amount_ = 0; + std::size_t threshold_ = 0; + pending<>* open_ = nullptr; + pending<>* close_ = nullptr; + pending<>* low_ = nullptr; + pending* receive_ = nullptr; + void* target_ = nullptr; + read_result (*read_)(void*, int, const Allocator&) = nullptr; +}; + +} // namespace webcpp::webrtc::detail::native + +#endif // WEBCPP_WEBRTC_DETAIL_NATIVE_CHANNEL_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/connection.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/connection.hpp new file mode 100644 index 0000000..810441e --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/native/connection.hpp @@ -0,0 +1,463 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_DETAIL_NATIVE_CONNECTION_HPP +#define WEBCPP_WEBRTC_DETAIL_NATIVE_CONNECTION_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include // lint-world: Asio's codes +#include // lint-world: libdatachannel's events are posted + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::webrtc::detail::native { + +/** + The state of a native peer connection: libdatachannel's connection, by its id in the C API, its + channels, and what waits on it, on the object's executor. + + libdatachannel's callbacks run on its threads; each copies what it carries into the standard + allocator and posts to the executor through a weak pointer (design.md, D7). +*/ +template +class connection_state + : public std::enable_shared_from_this> { +public: + /** A channel's state. */ + using channel_type = channel_state; + /** A channel. */ + using data_channel = basic_data_channel; + /** A description, owned. */ + using session_description = basic_session_description; + /** A candidate, owned. */ + using ice_candidate = basic_ice_candidate; + /** The connection's text type. */ + using string_type = detail::string; + + /** Makes the state of a connection not yet made in libdatachannel. */ + connection_state(runtime_slot slot, const Executor& executor, const options& opts, + const Allocator& allocator) + : slot_(std::move(slot)), + executor_(executor), + allocator_(allocator), + options_(opts), + inbox_{{}, executor}, + candidates_(opts.max_queued_candidates, allocator), + channels_(opts.max_queued_channels, allocator), + registry_(registry_allocator(allocator)) {} + + connection_state(const connection_state&) = delete; + connection_state& operator=(const connection_state&) = delete; + connection_state(connection_state&&) = delete; + connection_state& operator=(connection_state&&) = delete; + + /** Deletes libdatachannel's connection, aborting what waits. */ + // Posting the aborted completions allocates, and a failure to allocate there ends the + // program, as in any noexcept destructor that must complete operations. + // NOLINTNEXTLINE(bugprone-exception-escape) + ~connection_state() { destroy(); } + + /** + Makes libdatachannel's connection, with automatic negotiation off. + + @return `error::syntax_error` for an ICE server URL libdatachannel cannot parse, + `error::type_error` for a bound out of the C API's range, `error::operation_error` for any + other refusal; nothing once made. + */ + error_code open(const configuration& config) { + if (!fits_int(options_.max_message_size)) { + return make_error_code(error::type_error); + } + using strings_allocator = + std::allocator_traits::template rebind_alloc; + using pointers_allocator = + std::allocator_traits::template rebind_alloc; + std::vector urls{strings_allocator(allocator_)}; + for (const ice_server& server : config.ice_servers) { + for (const std::string_view url : server.urls) { + urls.push_back(ice_url(url, server.username, server.credential)); + } + } + if (!fits_int(urls.size())) { + return make_error_code(error::type_error); + } + std::vector pointers{pointers_allocator(allocator_)}; + for (const string_type& url : urls) { + pointers.push_back(url.c_str()); + } + const string_type bind(config.bind_address, text_allocator()); + + rtcConfiguration native{}; + native.iceServers = pointers.empty() ? nullptr : pointers.data(); + native.iceServersCount = static_cast(pointers.size()); + native.bindAddress = bind.empty() ? nullptr : bind.c_str(); + native.iceTransportPolicy = config.policy == ice_transport_policy::relay + ? RTC_TRANSPORT_POLICY_RELAY + : RTC_TRANSPORT_POLICY_ALL; + // A description exists only when async_set_local_description asks for one, as in the + // browser (design.md, D15). + native.disableAutoNegotiation = true; + native.maxMessageSize = static_cast(options_.max_message_size); + const int pc = rtcCreatePeerConnection(&native); + if (pc < 0) { + return code_of(pc, error::syntax_error, error::operation_error); + } + pc_ = pc; + inbox_.self = this->weak_from_this(); + rtcSetUserPointer(pc_, &inbox_); + rtcSetLocalCandidateCallback(pc_, &on_candidate); + rtcSetStateChangeCallback(pc_, &on_state); + rtcSetIceStateChangeCallback(pc_, &on_ice_state); + rtcSetGatheringStateChangeCallback(pc_, &on_gathering_state); + rtcSetDataChannelCallback(pc_, &on_data_channel); + return {}; + } + + /** The object's executor. */ + [[nodiscard]] const Executor& get_executor() const noexcept { return executor_; } + + /** The object's allocator. */ + [[nodiscard]] const Allocator& get_allocator() const noexcept { return allocator_; } + + /** Creates and applies the implicit local description, an offer or an answer. */ + void set_local_description(pending& op) { + if (closed_) { + op.fail(make_error_code(error::invalid_state)); + return; + } + // Synchronous in libdatachannel: the description is set when the call returns. + const int rc = rtcSetLocalDescription(pc_, nullptr); + if (rc < 0) { + op.fail(code_of(rc, error::operation_error, error::operation_error)); + return; + } + auto description = local_description(); + if (!description) { + op.fail(make_error_code(error::operation_error)); + return; + } + op.complete({}, std::move(*description)); + } + + /** Applies the remote description `sdp` of type `type`. */ + void set_remote_description(sdp_type type, const string_type& sdp, pending<>& op) { + if (closed_) { + op.fail(make_error_code(error::invalid_state)); + return; + } + const int rc = rtcSetRemoteDescription(pc_, sdp.c_str(), type_name(type)); + if (rc < 0) { + // invalid_argument: a description it cannot parse; another exception: a description + // the signaling state does not admit. + op.fail(code_of(rc, error::operation_error, error::invalid_state)); + return; + } + op.complete({}); + } + + /** Adds the remote candidate `candidate`; an empty one adds none. */ + void add_ice_candidate(const string_type& candidate, const std::optional& mid, + pending<>& op) { + if (closed_ || !has_remote_description()) { + op.fail(make_error_code(error::invalid_state)); + return; + } + if (candidate.empty()) { + op.complete({}); + return; + } + const int rc = rtcAddRemoteCandidate(pc_, candidate.c_str(), mid ? mid->c_str() : nullptr); + if (rc < 0) { + op.fail(code_of(rc, error::operation_error, error::operation_error)); + return; + } + op.complete({}); + } + + /** Waits for the next local candidate, or for the end of gathering. */ + void wait_ice_candidate(pending& op) { candidates_.wait(op); } + + /** Waits for the connection's state to change. */ + void wait_state_change(pending& op) { state_.wait(op); } + + /** Waits for the ICE state to change. */ + void wait_ice_state_change(pending& op) { ice_.wait(op); } + + /** Waits for the next channel the peer opened. */ + void accept_data_channel(pending& op) { channels_.wait(op); } + + /** Creates a channel, the W3C's `createDataChannel`. */ + boost::system::result create_data_channel(std::string_view label, + const data_channel_init& init) { + if (init.max_packet_life_time && init.max_retransmits) { + return make_error_code(error::type_error); + } + if ((init.negotiated && !init.id) || (init.id && *init.id == 65535)) { + return make_error_code(error::type_error); + } + if (label.size() > 65535 || init.protocol.size() > 65535) { + return make_error_code(error::type_error); + } + if (closed_) { + return make_error_code(error::invalid_state); + } + const string_type label_text(label, text_allocator()); + const string_type protocol(init.protocol, text_allocator()); + rtcDataChannelInit native{}; + native.reliability.unordered = !init.ordered; + if (init.max_packet_life_time) { + native.reliability.unreliable = true; + native.reliability.maxPacketLifeTime = *init.max_packet_life_time; + } else if (init.max_retransmits) { + native.reliability.unreliable = true; + native.reliability.maxRetransmits = *init.max_retransmits; + } + native.protocol = protocol.c_str(); + native.negotiated = init.negotiated; + if (init.id) { + native.manualStream = true; + native.stream = *init.id; + } + const int dc = rtcCreateDataChannelEx(pc_, label_text.c_str(), &native); + if (dc < 0) { + return code_of(dc, error::operation_error, error::operation_error); + } + return channel_access::make(adopt(dc)); + } + + /** The local description, once one was set. */ + [[nodiscard]] std::optional local_description() const { + if (pc_ < 0) { + return std::nullopt; + } + string_type name(text_allocator()); + if (read_text(&rtcGetLocalDescriptionType, pc_, name) != 0) { + return std::nullopt; + } + const auto type = type_of(name); + if (!type) { + return std::nullopt; + } + session_description description{*type, string_type(text_allocator())}; + if (read_text(&rtcGetLocalDescription, pc_, description.sdp) != 0) { + return std::nullopt; + } + return description; + } + + /** Whether a remote description was applied. */ + [[nodiscard]] bool has_remote_description() const { + return pc_ >= 0 && rtcGetRemoteDescription(pc_, nullptr, 0) > 0; + } + + /** The connection's state. */ + [[nodiscard]] peer_connection_state state() const noexcept { return state_.current(); } + + /** The ICE state. */ + [[nodiscard]] ice_connection_state ice_state() const noexcept { return ice_.current(); } + + /** + Closes the connection, as the W3C's `close()`: no state change is delivered, what waits on + the connection ends with `operation_aborted`, and its channels close with `error::closed`. + */ + void close() { + if (closed_) { + return; + } + closed_ = true; + const error_code aborted(webcpp::asio::error::operation_aborted); + state_.close(peer_connection_state::closed, aborted); + ice_.close(ice_connection_state::closed, aborted); + candidates_.close(aborted); + // Channels not yet accepted go with the queue, and close. + channels_.close(aborted); + // The channels drain their queues before the connection closes its transports, so that + // no libdatachannel thread waits for room in one meanwhile. + for (const auto& weak : registry_) { + if (const auto channel = weak.lock()) { + channel->connection_closed(); + } + } + registry_.clear(); + if (pc_ >= 0) { + rtcClosePeerConnection(pc_); + } + } + + /** Deletes libdatachannel's connection, after which none of its callbacks runs. */ + void destroy() { + close(); + if (pc_ >= 0) { + // Blocks until every callback of the connection in flight returned. + rtcDeletePeerConnection(pc_); + pc_ = -1; + } + slot_.reset(); + } + +private: + struct inbox { + std::weak_ptr self; + Executor executor; + }; + + using registry_allocator = + std::allocator_traits::template rebind_alloc>; + using text_allocator_type = string_type::allocator_type; + + [[nodiscard]] text_allocator_type text_allocator() const { + return text_allocator_type(allocator_); + } + + // Runs on libdatachannel's threads: posts `f`, which runs on the state if it still exists. + template + static void post_event(void* pointer, F f) { + const auto& box = *static_cast(pointer); + webcpp::asio::post(box.executor, [self = box.self, f = std::move(f)]() mutable { + if (const auto state = self.lock()) { + f(*state); + } + }); + } + + static void RTC_API on_candidate(int /*pc*/, const char* candidate, const char* mid, + void* pointer) { + // Copied in the standard allocator: the user's is not touched on this thread. + post_event(pointer, [text = std::string(candidate != nullptr ? candidate : ""), + media = std::string(mid != nullptr ? mid : "")]( + connection_state& state) { state.gathered(text, media); }); + } + + static void RTC_API on_state(int /*pc*/, rtcState state, void* pointer) { + post_event(pointer, [state](connection_state& self) { + if (!self.closed_) { + self.state_.update(state_of(state)); + } + }); + } + + static void RTC_API on_ice_state(int /*pc*/, rtcIceState state, void* pointer) { + post_event(pointer, [state](connection_state& self) { + if (!self.closed_) { + self.ice_.update(ice_state_of(state)); + } + }); + } + + static void RTC_API on_gathering_state(int /*pc*/, rtcGatheringState state, void* pointer) { + if (state == RTC_GATHERING_COMPLETE) { + post_event(pointer, [](connection_state& self) { self.gathered({}, {}); }); + } + } + + static void RTC_API on_data_channel(int /*pc*/, int dc, void* pointer) { + const auto& box = *static_cast(pointer); + webcpp::asio::post(box.executor, [self = box.self, dc] { + if (const auto state = self.lock()) { + state->arrived(dc); + } else { + // The connection went: the channel goes too. + rtcDeleteDataChannel(dc); + } + }); + } + + // A local candidate, or with an empty text the end of gathering, which the bound keeps a + // place for (design.md, D5). + void gathered(const std::string& text, const std::string& mid) { + if (closed_) { + return; + } + const bool end = text.empty(); + ice_candidate candidate{ + string_type(text, text_allocator()), + string_type(mid, text_allocator()), + end ? std::nullopt : std::optional(0), + string_type(text_allocator()), + }; + // A candidate past the bound is dropped here; it is still in local_description(). + static_cast(candidates_.push(std::move(candidate), end)); + } + + // A channel the peer opened. + void arrived(int dc) { + if (closed_) { + rtcDeleteDataChannel(dc); + return; + } + // Past the backlog, the refused channel is destroyed here, which closes it. + static_cast(channels_.push(channel_access::make(adopt(dc)))); + } + + std::shared_ptr adopt(int dc) { + auto channel = + std::allocate_shared(allocator_, executor_, allocator_, options_); + channel->attach(dc); + std::erase_if(registry_, [](const auto& weak) { return weak.expired(); }); + registry_.push_back(channel); + return channel; + } + + static string_type ice_url(std::string_view url, std::string_view username, + std::string_view credential, const text_allocator_type& allocator) { + string_type out(url, allocator); + // "turn:host" with a user name becomes "turn:user:credential@host", the form + // libdatachannel parses, as trystero writes it. + const bool turn = url.starts_with("turn:") || url.starts_with("turns:"); + if (!turn || username.empty()) { + return out; + } + const auto colon = url.find(':'); + out.assign(url.substr(0, colon + 1)); + out.append(username); + out.push_back(':'); + out.append(credential); + out.push_back('@'); + out.append(url.substr(colon + 1)); + return out; + } + + string_type ice_url(std::string_view url, std::string_view username, + std::string_view credential) const { + return ice_url(url, username, credential, text_allocator()); + } + + runtime_slot slot_; + Executor executor_; + Allocator allocator_; + options options_; + inbox inbox_; + int pc_ = -1; + bool closed_ = false; + state_watch state_; + state_watch ice_; + event_queue candidates_; + event_queue channels_; + std::vector, registry_allocator> registry_; +}; + +} // namespace webcpp::webrtc::detail::native + +#endif // WEBCPP_WEBRTC_DETAIL_NATIVE_CONNECTION_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/operation.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/operation.hpp new file mode 100644 index 0000000..b42e7e4 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/detail/operation.hpp @@ -0,0 +1,211 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_DETAIL_OPERATION_HPP +#define WEBCPP_WEBRTC_DETAIL_OPERATION_HPP + +#include + +#include // lint-world: completions are posted +#include // lint-world: an operation's storage +#include // lint-world: per-operation cancellation +#include // lint-world: the handler's executor +#include // lint-world: per-operation cancellation +#include // lint-world: Asio's codes +#include // lint-world: pending work keeps run alive +#include // lint-world: completions are posted + +#include + +#include +#include +#include + +namespace webcpp::webrtc::detail { + +/** The error type of every completion. */ +using boost::system::error_code; + +/** + A pending operation that completes once, posting its handler with an error and `Values`. + + Its owner, an object's state, keeps it in a slot (a pointer) while it waits; the operation clears + that slot when it ends, whoever ends it: the state, a cancellation, or the io_context's shutdown. +*/ +template +class pending { +public: + pending(const pending&) = delete; + pending& operator=(const pending&) = delete; + pending(pending&&) = delete; + pending& operator=(pending&&) = delete; + + /** Posts the handler with `ec` and `values`, and frees the operation. */ + void complete(error_code ec, Values... values) { + unlink(); + do_complete(ec, std::move(values)...); + } + + /** Posts the handler with `ec` and the values the operation was made with, and frees it. */ + void fail(error_code ec) { + unlink(); + do_fail(ec); + } + + /** Frees the operation without calling its handler, as Asio's shutdown destroys operations. */ + void discard() noexcept { + unlink(); + do_discard(); + } + + /** Puts the operation in `slot`, which it clears when it ends. */ + void link(pending*& slot) noexcept { + slot_ = &slot; + slot = this; + } + +protected: + pending() = default; + ~pending() = default; + +private: + /** Posts the handler with `ec` and `values`, and frees the operation. */ + virtual void do_complete(error_code ec, Values... values) = 0; + /** Posts the handler with `ec` and the values the operation was made with, and frees it. */ + virtual void do_fail(error_code ec) = 0; + /** Frees the operation without calling its handler. */ + virtual void do_discard() noexcept = 0; + + void unlink() noexcept { + if (slot_ != nullptr && *slot_ == this) { + *slot_ = nullptr; + } + slot_ = nullptr; + } + + pending** slot_ = nullptr; +}; + +/** + The operation of a handler: its storage in the handler's associated allocator, outstanding work + on the object's executor and on the handler's, and the handler's cancellation slot. +*/ +template +class operation final : public pending { + using handler_executor = webcpp::asio::associated_executor_t; + using allocator_type = std::allocator_traits< + webcpp::asio::associated_allocator_t>::template rebind_alloc; + +public: + /** + Makes the operation of `handler`, in its associated allocator. + + @param handler The completion handler. + @param executor The object's executor, which the completion is posted to. + @param fallback The values a failure completes with. + @param supported The cancellation types the operation honours; none installs no handler. + @return The operation, which frees itself when it ends. + */ + static operation& make(Handler handler, const IoExecutor& executor, + std::tuple fallback, + webcpp::asio::cancellation_type supported) { + allocator_type allocator(webcpp::asio::get_associated_allocator(handler)); + operation* storage = std::allocator_traits::allocate(allocator, 1); + std::allocator_traits::construct(allocator, storage, std::move(handler), + executor, std::move(fallback)); + storage->start(supported); + return *storage; + } + + /** Constructs the operation; `make` is the way to make one. */ + operation(Handler handler, IoExecutor executor, std::tuple fallback) + : handler_(std::move(handler)), + executor_(std::move(executor)), + work_(executor_), + handler_work_(webcpp::asio::get_associated_executor(handler_, executor_)), + fallback_(std::move(fallback)) {} + + operation(const operation&) = delete; + operation& operator=(const operation&) = delete; + operation(operation&&) = delete; + operation& operator=(operation&&) = delete; + ~operation() = default; + +private: + void start(webcpp::asio::cancellation_type supported) { + auto slot = webcpp::asio::get_associated_cancellation_slot(handler_); + if (slot.is_connected() && supported != webcpp::asio::cancellation_type::none) { + // The handler runs where the cancellation is emitted, on the object's executor as + // Asio requires of an I/O object; it ends the operation, which clears the slot, and + // touches nothing of itself afterwards. + slot.assign([this, supported](webcpp::asio::cancellation_type type) { + if ((type & supported) != webcpp::asio::cancellation_type::none) { + this->fail(webcpp::asio::error::operation_aborted); + } + }); + } + } + + void do_complete(error_code ec, Values... values) override { finish(ec, std::move(values)...); } + + void do_fail(error_code ec) override { + std::apply([this, ec](Values&... values) { finish(ec, std::move(values)...); }, fallback_); + } + + void do_discard() noexcept override { + webcpp::asio::get_associated_cancellation_slot(handler_).clear(); + destroy(allocator_type(webcpp::asio::get_associated_allocator(handler_))); + } + + template + void finish(error_code ec, Args&&... values) { + webcpp::asio::get_associated_cancellation_slot(handler_).clear(); + // The allocator is taken before the handler moves out, which may leave it without one. + const allocator_type allocator(webcpp::asio::get_associated_allocator(handler_)); + // Post before the work guards go with the operation: the queued completion keeps run + // alive from then on. + webcpp::asio::post(executor_, webcpp::asio::append(std::move(handler_), ec, + std::forward(values)...)); + destroy(allocator); + } + + void destroy(allocator_type allocator) noexcept { + std::allocator_traits::destroy(allocator, this); + std::allocator_traits::deallocate(allocator, this, 1); + } + + Handler handler_; + IoExecutor executor_; + webcpp::asio::executor_work_guard work_; + webcpp::asio::executor_work_guard handler_work_; + std::tuple fallback_; +}; + +/** The cancellation types a wait honours: it consumes nothing when cancelled. */ +inline constexpr webcpp::asio::cancellation_type wait_cancellation = + webcpp::asio::cancellation_type::terminal | webcpp::asio::cancellation_type::partial | + webcpp::asio::cancellation_type::total; + +/** + Makes the operation of `handler` and returns it as the pending operation of its signature. + + @param handler The completion handler. + @param executor The object's executor. + @param fallback The values a failure completes with. + @param supported The cancellation types the operation honours. + @return The operation. +*/ +template +pending& make_operation(Handler&& handler, const IoExecutor& executor, + std::tuple fallback, + webcpp::asio::cancellation_type supported) { + using type = operation, IoExecutor, Values...>; + return type::make(std::forward(handler), executor, std::move(fallback), supported); +} + +} // namespace webcpp::webrtc::detail + +#endif // WEBCPP_WEBRTC_DETAIL_OPERATION_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/error.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/error.hpp new file mode 100644 index 0000000..1d4c018 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/error.hpp @@ -0,0 +1,118 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_ERROR_HPP +#define WEBCPP_WEBRTC_ERROR_HPP + +#include + +#include +#include +#include + +#include +#include + +namespace webcpp::webrtc { + +/** + The failures of webcpp::webrtc that have no counterpart among Asio's codes. + + Their values are fixed and never reused. Asio's codes keep their own meaning beside them: + `operation_aborted` for an operation cancelled or ended by `close()` or destruction, + `already_started` for a second wait of one kind, `operation_not_supported` for what a target + cannot honour, `no_buffer_space` for a message larger than the room left in the caller's buffer. +*/ +enum class error { + /** + The W3C's `InvalidStateError`: a candidate before a remote description, a send on a channel + that is not open. + */ + invalid_state = 1, + /** + The W3C's `OperationError`: the platform refused an operation, as a description it cannot + parse. + */ + operation_error = 2, + /** The W3C's `InvalidAccessError`. */ + invalid_access = 3, + /** + The W3C's `TypeError`: an argument out of its range, as both reliability limits of a channel. + */ + type_error = 4, + /** The W3C's `SyntaxError`: an ICE server URL that cannot be parsed. */ + syntax_error = 5, + /** The channel or the connection closed under a pending operation. */ + closed = 6, + /** A message past `options::max_message_size` or the peer's limit, sent or received. */ + message_too_large = 7, + /** A send that would pass `options::max_buffered_amount`. */ + buffered_amount_exceeded = 8, + /** The browser's unread messages past `options::max_received_bytes`. */ + receive_overflow = 9, + /** `make` past `runtime_options::max_peer_connections`. */ + too_many_peer_connections = 10, +}; + +namespace detail { + +/** The category of webcpp::webrtc's errors, named `webcpp.webrtc`. */ +class error_category final : public boost::system::error_category { +public: + /** The category's name. */ + [[nodiscard]] const char* name() const noexcept override { return "webcpp.webrtc"; } + + /** An English description of a value of `error`. */ + [[nodiscard]] std::string message(int value) const override { + switch (static_cast(value)) { + case error::invalid_state: return "Invalid state"; + case error::operation_error: return "Operation refused by the platform"; + case error::invalid_access: return "Invalid access"; + case error::type_error: return "Argument out of its range"; + case error::syntax_error: return "Syntax error"; + case error::closed: return "Closed"; + case error::message_too_large: return "Message too large"; + case error::buffered_amount_exceeded: return "Buffered amount exceeded"; + case error::receive_overflow: return "Receive queue overflow"; + case error::too_many_peer_connections: return "Too many peer connections"; + } + return "Unknown webcpp.webrtc error"; + } +}; + +} // namespace detail + +/** + The category of webcpp::webrtc's errors, named `webcpp.webrtc`. + + @return The category, alive for the whole program. +*/ +inline const boost::system::error_category& webrtc_category() noexcept { + static const detail::error_category category; + return category; +} + +/** + Makes the error code of a value of `error`. + + @param e The error. + @return The code, of the category `webcpp.webrtc`. +*/ +inline boost::system::error_code make_error_code(error e) noexcept { + return {static_cast(e), webrtc_category()}; +} + +} // namespace webcpp::webrtc + +namespace boost::system { + +/** Makes `webcpp::webrtc::error` convert to `boost::system::error_code`. */ +template <> +struct is_error_code_enum : std::true_type {}; + +} // namespace boost::system + +#endif // WEBCPP_WEBRTC_ERROR_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/options.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/options.hpp new file mode 100644 index 0000000..d71bcee --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/options.hpp @@ -0,0 +1,57 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_OPTIONS_HPP +#define WEBCPP_WEBRTC_OPTIONS_HPP + +#include + +#include +#include + +namespace webcpp::webrtc { + +/** + webcpp's own bounds on a peer connection and its channels, past which an object fails as a value. + + None of them throws or blocks: each is a code of `error`. +*/ +struct options { + /** + Local candidates kept while no `async_wait_ice_candidate` is pending; the end of gathering has + a place of its own. + */ + std::size_t max_queued_candidates = 64; + /** + Incoming channels kept while no `async_accept_data_channel` is pending; one past it is closed + at once. + */ + std::size_t max_queued_channels = 16; + /** The largest message sent or received, announced natively in the SDP. */ + std::size_t max_message_size = std::size_t{256} * 1024; + /** + The most bytes a channel may hold to send; a send past it fails with + `buffered_amount_exceeded`. + */ + std::size_t max_buffered_amount = std::size_t{16} * 1024 * 1024; + /** + In the browser, the most bytes of unread messages and their records; past it the channel + closes. + */ + std::size_t max_received_bytes = std::size_t{16} * 1024 * 1024; +}; + +/** What the platform holds for the whole process or page, given to `runtime`. */ +struct runtime_options { + /** The most peer connections alive at once; 256 is half of Chromium's 500 per page. */ + std::size_t max_peer_connections = 256; + /** Natively, libdatachannel's threads; 0 for its own default. */ + std::uint32_t thread_pool_size = 0; +}; + +} // namespace webcpp::webrtc + +#endif // WEBCPP_WEBRTC_OPTIONS_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/peer_connection.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/peer_connection.hpp new file mode 100644 index 0000000..dd0821e --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/peer_connection.hpp @@ -0,0 +1,377 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_PEER_CONNECTION_HPP +#define WEBCPP_WEBRTC_PEER_CONNECTION_HPP + +#include + +#include +#include +#include +#include +#include + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#error "webcpp::webrtc: the browser implementation is increment 2 of reference/plan.md" +#endif + +#include +#include + +#include // lint-world: the default executor +#include // lint-world: completion tokens + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::webrtc { + +/** + A peer connection, the W3C's `RTCPeerConnection`, whose operations follow Asio's model and whose + events are operations the caller re-arms, as an acceptor's `async_accept`. + + Its operations run on its executor, which is not thread safe: a program calls them, and emits + their cancellations, on that executor. Its executor's context, its `runtime` and its allocator + outlive it. + + @tparam Executor The executor its handlers run on. + @tparam Allocator The allocator of its state, its queues and its outputs. +*/ +template > +class basic_peer_connection { + using state_type = detail::native::connection_state; + using string_type = detail::string; + +public: + /** The executor its handlers run on. */ + using executor_type = Executor; + /** The allocator of its state and outputs. */ + using allocator_type = Allocator; + /** A description it produced. */ + using session_description = basic_session_description; + /** A candidate it gathered. */ + using ice_candidate = basic_ice_candidate; + /** One of its channels. */ + using data_channel = basic_data_channel; + + /** + Makes a peer connection. + + @param rt The runtime, which counts it and outlives it. + @param executor The executor its handlers run on. + @param config How it gathers candidates, read during the call. + @param opts Its bounds. + @param allocator The allocator of its state and outputs. + @return The connection; or `error::too_many_peer_connections` past the runtime's cap, + `error::syntax_error` for an ICE server URL that cannot be parsed, `error::type_error` for a + bound out of the platform's range, `error::operation_error` for another refusal. + */ + static boost::system::result make( + runtime& rt, const Executor& executor, const configuration& config, + const options& opts = options(), const Allocator& allocator = Allocator()) { + detail::runtime_slot slot(rt); + if (!slot) { + return make_error_code(error::too_many_peer_connections); + } + auto state = + std::allocate_shared(allocator, std::move(slot), executor, opts, allocator); + if (const auto ec = state->open(config)) { + return ec; + } + return basic_peer_connection(std::move(state)); + } + + /** Moves the connection, its pending operations included; the source holds none. */ + basic_peer_connection(basic_peer_connection&& other) noexcept = default; + + /** + Moves the connection, closing the one this held. + + @param other The connection moved from. + @return This connection. + */ + basic_peer_connection& operator=(basic_peer_connection&& other) noexcept { + if (this != &other) { + reset(); + state_ = std::move(other.state_); + } + return *this; + } + + basic_peer_connection(const basic_peer_connection&) = delete; + basic_peer_connection& operator=(const basic_peer_connection&) = delete; + + /** Closes the connection and completes every pending operation with `operation_aborted`. */ + // Posting the aborted completions allocates, and a failure to allocate there ends the + // program, as in any noexcept destructor that must complete operations. + // NOLINTNEXTLINE(bugprone-exception-escape) + ~basic_peer_connection() { reset(); } + + /** + The executor its handlers run on. + + @return The executor. + */ + [[nodiscard]] executor_type get_executor() const noexcept { return state_->get_executor(); } + + /** + The allocator of its state and outputs. + + @return The allocator. + */ + [[nodiscard]] allocator_type get_allocator() const noexcept { return state_->get_allocator(); } + + /** + Creates and applies the implicit local description: an offer, or an answer to the remote + offer, the W3C's `setLocalDescription()` without an argument. + + A cancellation is terminal only: the description may still be applied after the handler ran + with `operation_aborted`. + + @param token The completion token, of signature `void(error_code, session_description)`. + @return What the token makes of the operation. + */ + template + auto async_set_local_description(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + auto& op = detail::make_operation( + std::move(handler), state->get_executor(), + std::tuple{ + session_description{sdp_type::offer, string_type(text_allocator(*state))}, + }, + webcpp::asio::cancellation_type::terminal); + state->set_local_description(op); + }, + token, state_); + } + + /** + Applies the remote peer's description. + + @param description The description, read during the call. + @param token The completion token, of signature `void(error_code)`. + @return What the token makes of the operation. + */ + template + auto async_set_remote_description(session_description_view description, + CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state, sdp_type type, + const string_type& sdp) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple<>{}, + webcpp::asio::cancellation_type::terminal); + state->set_remote_description(type, sdp, op); + }, + token, state_, description.type, string_type(description.sdp, text_allocator(*state_))); + } + + /** + Adds a remote candidate; an empty `candidate` ends the remote gathering and adds none. + + @param candidate The candidate, read during the call. + @param token The completion token, of signature `void(error_code)`; + `error::invalid_state` before a remote description. + @return What the token makes of the operation. + */ + template + auto async_add_ice_candidate(ice_candidate_view candidate, CompletionToken&& token) { + std::optional mid; + if (candidate.sdp_mid) { + mid.emplace(*candidate.sdp_mid, text_allocator(*state_)); + } + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state, const string_type& text, + const std::optional& media) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple<>{}, detail::wait_cancellation); + state->add_ice_candidate(text, media, op); + }, + token, state_, string_type(candidate.candidate, text_allocator(*state_)), + std::move(mid)); + } + + /** + Waits for the next local candidate; one whose `candidate` is empty is the end of gathering. + + While no wait is pending, candidates are kept up to `options::max_queued_candidates`; one + past it is dropped here and stays in `local_description()`. + + @param token The completion token, of signature `void(error_code, ice_candidate)`. + @return What the token makes of the operation. + */ + template + auto async_wait_ice_candidate(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + const auto text = text_allocator(*state); + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple{ + ice_candidate{ + string_type(text), + string_type(text), + std::nullopt, + string_type(text), + }, + }, + detail::wait_cancellation); + state->wait_ice_candidate(op); + }, + token, state_); + } + + /** + Waits for the connection's state to differ from the one the previous wait completed with. + + @param token The completion token, of signature `void(error_code, peer_connection_state)`. + @return What the token makes of the operation. + */ + template + auto async_wait_state_change(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + auto& op = detail::make_operation(std::move(handler), state->get_executor(), + std::tuple{state->state()}, + detail::wait_cancellation); + state->wait_state_change(op); + }, + token, state_); + } + + /** + Waits for the ICE state to differ from the one the previous wait completed with. + + @param token The completion token, of signature `void(error_code, ice_connection_state)`. + @return What the token makes of the operation. + */ + template + auto async_wait_ice_connection_state_change(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + auto& op = + detail::make_operation(std::move(handler), state->get_executor(), + std::tuple{state->ice_state()}, + detail::wait_cancellation); + state->wait_ice_state_change(op); + }, + token, state_); + } + + /** + Waits for the next channel the peer opened. + + While none is pending, channels are kept up to `options::max_queued_channels`; one past it + is closed at once, as a connection past a listen backlog is refused. + + @param token The completion token, of signature `void(error_code, data_channel)`. + @return What the token makes of the operation. + */ + template + auto async_accept_data_channel(CompletionToken&& token) { + return webcpp::asio::async_initiate( + [](auto handler, const std::shared_ptr& state) { + auto& op = detail::make_operation( + std::move(handler), state->get_executor(), + std::tuple{ + detail::channel_access::make( + std::shared_ptr{}), + }, + detail::wait_cancellation); + state->accept_data_channel(op); + }, + token, state_); + } + + /** + Creates a data channel, the W3C's `createDataChannel`; adding one does not negotiate. + + @param label The channel's label, read during the call. + @param init How it is created. + @return The channel; or `error::type_error` for both reliability limits, `negotiated` + without an `id`, an id of 65535 or a label or protocol past 65,535 bytes; + `error::invalid_state` on a closed connection. + */ + boost::system::result create_data_channel(std::string_view label, + const data_channel_init& init = {}) { + return state_->create_data_channel(label, init); + } + + /** + The local description, the W3C's `localDescription`, with the candidates gathered so far. + + @return The description, or nothing before one was set. + */ + [[nodiscard]] std::optional local_description() const { + return state_->local_description(); + } + + /** + Whether a remote description was applied, which a candidate needs. + + @return Whether there is one. + */ + [[nodiscard]] bool has_remote_description() const { return state_->has_remote_description(); } + + /** + The connection's state, the W3C's `connectionState`. + + @return The state. + */ + [[nodiscard]] peer_connection_state state() const noexcept { return state_->state(); } + + /** + The ICE state, the W3C's `iceConnectionState`. + + @return The state. + */ + [[nodiscard]] ice_connection_state ice_state() const noexcept { return state_->ice_state(); } + + /** + Closes the connection, as the W3C's `close()`: no state change is delivered, its pending + operations complete with `operation_aborted`, its channels close with `error::closed`, and a + wait started afterwards completes with `error::closed`. + */ + void close() { state_->close(); } + +private: + explicit basic_peer_connection(std::shared_ptr state) noexcept + : state_(std::move(state)) {} + + static string_type::allocator_type text_allocator(const state_type& state) { + return typename string_type::allocator_type(state.get_allocator()); + } + + void reset() { + if (state_) { + state_->destroy(); + state_.reset(); + } + } + + std::shared_ptr state_; +}; + +/** A peer connection on Asio's type-erased executor, in the standard allocator. */ +using peer_connection = basic_peer_connection<>; + +} // namespace webcpp::webrtc + +#endif // WEBCPP_WEBRTC_PEER_CONNECTION_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/runtime.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/runtime.hpp new file mode 100644 index 0000000..3807de3 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/runtime.hpp @@ -0,0 +1,155 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_RUNTIME_HPP +#define WEBCPP_WEBRTC_RUNTIME_HPP + +#include + +#include + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#error "webcpp::webrtc: the browser implementation is increment 2 of reference/plan.md" +#endif + +#include + +#include +#include +#include + +namespace webcpp::webrtc { + +namespace detail { +struct runtime_access; +} // namespace detail + +/** + What the platform holds for the whole process, which the program owns: natively libdatachannel's + threads and global state, and on both targets the cap of peer connections. + + A program makes one before any peer connection and destroys it after the last, and after the + last data channel; `make` takes it by reference, so no connection exists without one. Natively at + most one exists at a time in a process, because libdatachannel's state is the process's: a + second one's destructor would end the first one's connections. That is a precondition: webrtc + keeps no static state to check it with. + + @see "The runtime", in the guide. +*/ +class runtime { +public: + /** + Loads libdatachannel's global resources, with its thread pool sized as `opts` says. + + @param opts The cap of peer connections and the thread pool's size. + */ + explicit runtime(const runtime_options& opts = {}) : options_(opts) { + if (opts.thread_pool_size != 0) { + rtcSetThreadPoolSize(static_cast(opts.thread_pool_size)); + } + rtcPreload(); + } + + /** Unloads libdatachannel's global resources, waiting until its threads have stopped. */ + ~runtime() { rtcCleanup(); } + + runtime(const runtime&) = delete; + runtime& operator=(const runtime&) = delete; + runtime(runtime&&) = delete; + runtime& operator=(runtime&&) = delete; + + /** + The options it was made with. + + @return The options. + */ + [[nodiscard]] const runtime_options& get_options() const noexcept { return options_; } + + /** + The peer connections made with it that are alive. + + @return Their number. + */ + [[nodiscard]] std::size_t peer_connections() const noexcept { return live_.load(); } + +private: + friend struct detail::runtime_access; + + bool acquire() noexcept { + std::size_t live = live_.load(); + do { + if (live >= options_.max_peer_connections) { + return false; + } + } while (!live_.compare_exchange_weak(live, live + 1)); + return true; + } + + void release() noexcept { live_.fetch_sub(1); } + + runtime_options options_; + // Connections may live on several executors and threads, so the count is atomic. + std::atomic live_{0}; +}; + +namespace detail { + +/** The library's access to a runtime's count. */ +struct runtime_access { + /** Counts one more connection, unless the cap is reached. */ + static bool acquire(runtime& rt) noexcept { return rt.acquire(); } + + /** Counts one connection less. */ + static void release(runtime& rt) noexcept { rt.release(); } +}; + +/** One connection's place in a runtime's count, given back when it goes. */ +class runtime_slot { +public: + /** No place. */ + runtime_slot() = default; + + /** Takes a place in `rt`, or none past its cap. */ + explicit runtime_slot(runtime& rt) noexcept + : runtime_(runtime_access::acquire(rt) ? &rt : nullptr) {} + + runtime_slot(const runtime_slot&) = delete; + runtime_slot& operator=(const runtime_slot&) = delete; + + /** Moves the place. */ + runtime_slot(runtime_slot&& other) noexcept + : runtime_(std::exchange(other.runtime_, nullptr)) {} + + /** Moves the place, giving this one's back. */ + runtime_slot& operator=(runtime_slot&& other) noexcept { + if (this != &other) { + reset(); + runtime_ = std::exchange(other.runtime_, nullptr); + } + return *this; + } + + ~runtime_slot() { reset(); } + + /** Whether it holds a place. */ + explicit operator bool() const noexcept { return runtime_ != nullptr; } + + /** Gives the place back. */ + void reset() noexcept { + if (runtime_ != nullptr) { + runtime_access::release(*std::exchange(runtime_, nullptr)); + } + } + +private: + runtime* runtime_ = nullptr; +}; + +} // namespace detail + +} // namespace webcpp::webrtc + +#endif // WEBCPP_WEBRTC_RUNTIME_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/types.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/types.hpp new file mode 100644 index 0000000..3e345f4 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/include/webcpp/webrtc/types.hpp @@ -0,0 +1,228 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WEBRTC_TYPES_HPP +#define WEBCPP_WEBRTC_TYPES_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::webrtc { + +/** The type of a session description, the W3C's `RTCSdpType`. */ +enum class sdp_type { + /** "offer". */ + offer, + /** "answer". */ + answer, + /** "pranswer". */ + pranswer, + /** "rollback". */ + rollback, +}; + +/** The state of a peer connection, the W3C's `RTCPeerConnectionState`. */ +enum class peer_connection_state { + /** "new". */ + new_, + /** "connecting". */ + connecting, + /** "connected". */ + connected, + /** "disconnected". */ + disconnected, + /** "failed". */ + failed, + /** "closed". */ + closed, +}; + +/** The state of a peer connection's ICE agent, the W3C's `RTCIceConnectionState`. */ +enum class ice_connection_state { + /** "new". */ + new_, + /** "checking". */ + checking, + /** "connected". */ + connected, + /** "completed". */ + completed, + /** "disconnected". */ + disconnected, + /** "failed". */ + failed, + /** "closed". */ + closed, +}; + +/** The state of a data channel, the W3C's `RTCDataChannelState`. */ +enum class data_channel_state { + /** "connecting". */ + connecting, + /** "open". */ + open, + /** "closing". */ + closing, + /** "closed". */ + closed, +}; + +/** Which candidates ICE may use, the W3C's `RTCIceTransportPolicy`. */ +enum class ice_transport_policy { + /** "all". */ + all, + /** "relay": TURN only. */ + relay, +}; + +/** A STUN or TURN server, the W3C's `RTCIceServer`, read during the call that takes it. */ +struct ice_server { + /** Its URLs, `stun:host:port` or `turn:host:port?transport=udp`. */ + std::span urls{}; + /** The TURN user name, empty for STUN. */ + std::string_view username{}; + /** The TURN credential, empty for STUN. */ + std::string_view credential{}; +}; + +/** How a peer connection gathers candidates, the W3C's `RTCConfiguration`, read during `make`. */ +struct configuration { + /** The servers ICE gathers through; empty for host candidates only. */ + std::span ice_servers{}; + /** Which candidates ICE may use. */ + ice_transport_policy policy = ice_transport_policy::all; + /** + The local address ICE binds to, natively; empty for every interface but the loopback. + + A loopback candidate needs "127.0.0.1". The browser cannot honour it (the table of + differences). + */ + std::string_view bind_address{}; +}; + +/** A session description given to a call, the W3C's `RTCSessionDescriptionInit`. */ +struct session_description_view { + /** Its type. */ + sdp_type type = sdp_type::offer; + /** Its SDP. */ + std::string_view sdp{}; +}; + +/** + An ICE candidate given to a call, the W3C's `RTCIceCandidateInit`. + + An empty `candidate` ends the remote peer's candidates, and adds none. +*/ +struct ice_candidate_view { + /** The candidate's attribute line, `candidate:...`, or empty. */ + std::string_view candidate{}; + /** The media stream identification it belongs to, when known. */ + std::optional sdp_mid{}; + /** The index of the m-line it belongs to, when known. */ + std::optional sdp_m_line_index{}; + /** Its ICE user name fragment; natively ignored (the table of differences). */ + std::string_view username_fragment{}; +}; + +/** How a data channel is created, the W3C's `RTCDataChannelInit`. */ +struct data_channel_init { + /** Whether messages arrive in order. */ + bool ordered = true; + /** + How long a message may be retransmitted, in milliseconds; exclusive with `max_retransmits`. + */ + std::optional max_packet_life_time{}; + /** How many times a message may be retransmitted; exclusive with `max_packet_life_time`. */ + std::optional max_retransmits{}; + /** The subprotocol name. */ + std::string_view protocol{}; + /** + Whether both peers create the channel themselves, with the same `id`, without announcing it. + */ + bool negotiated = false; + /** The SCTP stream id, required when `negotiated`; chosen by the platform otherwise. */ + std::optional id{}; +}; + +namespace detail { + +/** The string type of an output, in the allocator rebound to `char`. */ +template +using string = + std::basic_string, + typename std::allocator_traits::template rebind_alloc>; + +} // namespace detail + +/** + A session description a peer connection produced, owned, its text in the connection's allocator. + + @tparam Allocator The allocator of its text. +*/ +template +struct basic_session_description { + /** Its type. */ + sdp_type type = sdp_type::offer; + /** Its SDP. */ + detail::string sdp{}; + + /** + The view of this description, to give to the other peer's `async_set_remote_description`. + + @return A view valid while this description is unchanged. + */ + [[nodiscard]] session_description_view view() const noexcept { return {type, sdp}; } +}; + +/** + An ICE candidate a peer connection gathered, owned, its text in the connection's allocator. + + An empty `candidate` is the end of gathering, the W3C's own form of it. + + @tparam Allocator The allocator of its text. +*/ +template +struct basic_ice_candidate { + /** The candidate's attribute line, `candidate:...`, or empty at the end of gathering. */ + detail::string candidate{}; + /** The media stream identification it belongs to; empty when unknown. */ + detail::string sdp_mid{}; + /** The index of the m-line it belongs to; natively always 0 (the table of differences). */ + std::optional sdp_m_line_index{}; + /** Its ICE user name fragment; natively empty (the table of differences). */ + detail::string username_fragment{}; + + /** + The view of this candidate, to give to the other peer's `async_add_ice_candidate`. + + @return A view valid while this candidate is unchanged; an empty `sdp_mid` is no mid. + */ + [[nodiscard]] ice_candidate_view view() const noexcept { + return { + candidate, + sdp_mid.empty() ? std::nullopt : std::optional(sdp_mid), + sdp_m_line_index, + username_fragment, + }; + } +}; + +/** A session description in the standard allocator. */ +using session_description = basic_session_description>; + +/** An ICE candidate in the standard allocator. */ +using ice_candidate = basic_ice_candidate>; + +} // namespace webcpp::webrtc + +#endif // WEBCPP_WEBRTC_TYPES_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/meta/libraries.json b/libraries/webrtc/openspec/changes/genesis/reference/source/meta/libraries.json new file mode 100644 index 0000000..728678e --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/meta/libraries.json @@ -0,0 +1,17 @@ +{ + "key": "webrtc", + "name": "webrtc", + "authors": [ + "R" + ], + "description": "The W3C WebRTC data-channel API in Asio's model, natively over libdatachannel and in the browser.", + "category": [ + "Concurrent", + "IO" + ], + "maintainers": [ + "R " + ], + "cxxstd": "20", + "port-of": null +} diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/.clang-tidy b/libraries/webrtc/openspec/changes/genesis/reference/source/test/.clang-tidy new file mode 100644 index 0000000..6cca041 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/.clang-tidy @@ -0,0 +1,26 @@ +# The tests inherit the superproject's configuration and switch off one check +# and one option. +# +# bugprone-unchecked-optional-access reports an optional that a test reads +# where its value must be there. Either the test has asserted it first, with +# `if (!BOOST_TEST(x.has_value())) { return; }`, and BOOST_TEST is a call +# returning whether its condition held, which the checker does not look into; +# or the test calls value(), whose failure on an empty optional ends the +# program, with std::bad_optional_access or, built without exceptions, an +# abort, and so fails the test. The library's headers are still analysed with +# it, through the aggregate translation unit tools/lint/compile_commands.py +# writes. +# +# bugprone-exception-escape.CheckMain treats every test's main as a function +# that should not throw. A test's main lets what a failing case throws, a +# boost::system::system_error from value() on a failed result or a +# std::bad_alloc, end the process uncaught, which fails the test as it should; +# example/.clang-tidy says the same of the examples. The check stays on for +# everything else: a noexcept function, a destructor, a move or a swap. +--- +InheritParentConfig: true +Checks: > + -bugprone-unchecked-optional-access +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/Jamfile b/libraries/webrtc/openspec/changes/genesis/reference/source/test/Jamfile new file mode 100644 index 0000000..5f3bd3b --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/Jamfile @@ -0,0 +1,53 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/webrtc//headers ; + +import webcpp ; + +# Increment 1 builds natively only; increment 2 adds emscripten, both +# suspension variants (reference/plan.md). +webcpp.targets native ; + +# Every public header alone, against libdatachannel. It works without +# exceptions: libdatachannel is called through its C API (design.md, D4). +webcpp.headers-alone webrtc : ../include + : : /webcpp/webrtc//webrtc multi : native ; + +# config.hpp defines WEBCPP_WEBRTC_NO_EXCEPTIONS exactly when webcpp has no +# exceptions, and keeps it when a developer defines it in a build that has +# them. +webcpp.compile config : config_test.cpp ; +webcpp.compile config_developer_defined : config_test.cpp + : WEBCPP_WEBRTC_NO_EXCEPTIONS WEBCPP_TEST_WEBRTC_DEVELOPER_DEFINED ; +webcpp.compile config_all_off : config_test.cpp + : WEBCPP_NO_EXCEPTIONS WEBCPP_TEST_WEBRTC_ALL_OFF ; + +# The platform-free parts: errors, value types, the event machinery. +webcpp.run error : error_test.cpp ; +webcpp.run types : types_test.cpp ; +webcpp.run events : events_test.cpp ; +webcpp.run events_no_exceptions : events_test.cpp : off ; + +# Two native peers over the loopback, as the build asks and without +# exceptions; libdatachannel's threads need threading=multi. +webcpp.run native : native_test.cpp : /webcpp/webrtc//webrtc multi : native ; +webcpp.run native_no_exceptions : native_test.cpp + : /webcpp/webrtc//webrtc multi off : native ; + +# Allocation: the object's state, queues and outputs in its allocator, and +# nothing of it on libdatachannel's threads. +webcpp.run allocation : allocation_test.cpp + : /webcpp/webrtc//webrtc multi : native ; + +# Destruction while libdatachannel's threads deliver events, and a flooded +# channel never read, then destroyed. +webcpp.run lifetime : lifetime_test.cpp + : /webcpp/webrtc//webrtc multi : native ; + +# The measurement of tasks.md 1.10: a never-read channel past 1,024 messages +# and the connection's other channels. +webcpp.run stall : stall_test.cpp : /webcpp/webrtc//webrtc multi : native ; diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/allocation_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/allocation_test.cpp new file mode 100644 index 0000000..21cb79f --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/allocation_test.cpp @@ -0,0 +1,121 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Allocation (design.md, D12): a connection made with a polymorphic allocator over a counting +// resource keeps its state, its queues and its outputs there, and nothing of that resource is +// touched on libdatachannel's threads (spec: "Allocation: run-time objects use the object's +// allocator", "Semantics: native threads post to the executor"). + +#include + +#include "pair.hpp" +#include "require.hpp" + +#include // lint-world: messages +#include // lint-world: the tests' event loop + +#include + +#include +#include +#include +#include +#include +#include + +namespace webrtc = webcpp::webrtc; +namespace asio = webcpp::asio; +using webrtc::detail::error_code; + +namespace { + +// Counts what it gives, and what it gives on a thread other than the one that made it, which is +// the thread that runs the io_context. +class counting_resource final : public std::pmr::memory_resource { +public: + std::atomic allocations{0}; + std::atomic foreign{0}; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations; + if (std::this_thread::get_id() != owner_) { // lint-world: which thread allocates + ++foreign; + } + return std::pmr::new_delete_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + std::pmr::new_delete_resource()->deallocate(p, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } + + std::thread::id owner_ = std::this_thread::get_id(); // lint-world: which thread allocates +}; + +using allocator = std::pmr::polymorphic_allocator; +using connection = webrtc::basic_peer_connection; +using channel = connection::data_channel; + +void state_queues_and_outputs_in_the_allocator() { + counting_resource resource; + asio::io_context io; + webrtc::runtime rt; + const allocator a(&resource); + auto first = connection::make(rt, io.get_executor(), webcpp::test::loopback_configuration(), + webrtc::options(), a); + auto second = connection::make(rt, io.get_executor(), webcpp::test::loopback_configuration(), + webrtc::options(), a); + webcpp::test::require(BOOST_TEST(first.has_value())); + webcpp::test::require(BOOST_TEST(second.has_value())); + const std::size_t made = resource.allocations.load(); + BOOST_TEST_GT(made, 0u); + + webcpp::test::trickle ab(*first, *second); + webcpp::test::trickle ba(*second, *first); + auto created = first->create_data_channel("allocated"); + webcpp::test::require(BOOST_TEST(created.has_value())); + std::optional remote; + std::string text; + auto buffer = asio::dynamic_buffer(text); + std::optional received; + created->async_wait_open([&](error_code ec) { + BOOST_TEST(!ec); + BOOST_TEST(!created->send_text("counted")); + }); + second->async_accept_data_channel([&](error_code ec, channel c) { + if (!BOOST_TEST(!ec)) { + return; + } + remote.emplace(std::move(c)); + BOOST_TEST(remote->label() == "allocated"); + remote->async_receive(buffer, [&](error_code ec, std::size_t n, bool) { + BOOST_TEST(!ec); + received = n; + first->close(); + second->close(); + }); + }); + webcpp::test::negotiate(*first, *second, ab, ba, [](error_code ec) { BOOST_TEST(!ec); }); + io.run_for( + webcpp::test::exchange_limit); // lint-run: the peers' events come from libdatachannel + BOOST_TEST(received == std::optional(7)); + const auto description = first->local_description(); + webcpp::test::require(BOOST_TEST(description.has_value())); + BOOST_TEST(description->sdp.get_allocator().resource() == &resource); + BOOST_TEST_GT(resource.allocations.load(), made); + BOOST_TEST_EQ(resource.foreign.load(), 0u); +} + +} // namespace + +int main() { + state_queues_and_outputs_in_the_allocator(); + return boost::report_errors(); +} diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/config_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/config_test.cpp new file mode 100644 index 0000000..d647ea8 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/config_test.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// defines WEBCPP_WEBRTC_NO_EXCEPTIONS exactly when webcpp has no +// exceptions, and keeps the developer's own definition in a build that has them; it selects the +// unsupported policy, error by default. test/Jamfile builds this file three times: as the build +// asks; with WEBCPP_NO_EXCEPTIONS, which WEBCPP_TEST_WEBRTC_ALL_OFF tells this file; and with the +// macro itself defined, which WEBCPP_TEST_WEBRTC_DEVELOPER_DEFINED tells this file. + +#include + +#ifndef WEBCPP_CONFIG_HPP +#error "config.hpp does not include " +#endif + +#ifdef WEBCPP_TEST_WEBRTC_ALL_OFF +#ifndef WEBCPP_WEBRTC_NO_EXCEPTIONS +#error "WEBCPP_NO_EXCEPTIONS does not define WEBCPP_WEBRTC_NO_EXCEPTIONS" +#endif +#elif defined(WEBCPP_TEST_WEBRTC_DEVELOPER_DEFINED) +#ifndef WEBCPP_WEBRTC_NO_EXCEPTIONS +#error "config.hpp drops WEBCPP_WEBRTC_NO_EXCEPTIONS, which the developer defined" +#endif +#elif defined(WEBCPP_HAS_EXCEPTIONS) == defined(WEBCPP_WEBRTC_NO_EXCEPTIONS) +#error "WEBCPP_WEBRTC_NO_EXCEPTIONS is not defined exactly when webcpp has no exceptions" +#endif + +#if !defined(WEBCPP_WEBRTC_UNSUPPORTED_ERROR) == !defined(WEBCPP_WEBRTC_UNSUPPORTED_IGNORE) +#error "config.hpp selects exactly one unsupported policy" +#endif diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/error_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/error_test.cpp new file mode 100644 index 0000000..0aa95af --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/error_test.cpp @@ -0,0 +1,56 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The category webcpp.webrtc and its ten values, fixed and never reused (spec: "Errors: the error +// category and its ten values"). + +#include + +#include +#include + +#include + +namespace webrtc = webcpp::webrtc; + +namespace { + +void the_category() { + const boost::system::error_code ec = webrtc::error::closed; + BOOST_TEST(std::strcmp(ec.category().name(), "webcpp.webrtc") == 0); + BOOST_TEST_EQ(ec.value(), 6); + BOOST_TEST(ec == webrtc::error::closed); + BOOST_TEST(!ec.message().empty()); +} + +void the_values() { + BOOST_TEST_EQ(static_cast(webrtc::error::invalid_state), 1); + BOOST_TEST_EQ(static_cast(webrtc::error::operation_error), 2); + BOOST_TEST_EQ(static_cast(webrtc::error::invalid_access), 3); + BOOST_TEST_EQ(static_cast(webrtc::error::type_error), 4); + BOOST_TEST_EQ(static_cast(webrtc::error::syntax_error), 5); + BOOST_TEST_EQ(static_cast(webrtc::error::closed), 6); + BOOST_TEST_EQ(static_cast(webrtc::error::message_too_large), 7); + BOOST_TEST_EQ(static_cast(webrtc::error::buffered_amount_exceeded), 8); + BOOST_TEST_EQ(static_cast(webrtc::error::receive_overflow), 9); + BOOST_TEST_EQ(static_cast(webrtc::error::too_many_peer_connections), 10); +} + +void every_value_has_a_message() { + for (int value = 1; value <= 10; ++value) { + BOOST_TEST(webrtc::webrtc_category().message(value) != + webrtc::webrtc_category().message(0)); + } +} + +} // namespace + +int main() { + the_category(); + the_values(); + every_value_has_a_message(); + return boost::report_errors(); +} diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/events_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/events_test.cpp new file mode 100644 index 0000000..cd91b19 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/events_test.cpp @@ -0,0 +1,233 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// What an event becomes while no wait is pending (design.md, D5), without a platform: states +// coalesce, events queue up to a bound with a place kept for the end of gathering, one wait of a +// kind at a time, a cancelled wait consumes nothing, a satisfied wait is posted, and an +// operation's storage is its handler's (spec: "Events: ...", "Semantics: handlers run on the +// executor, never inside the call"). + +#include +#include +#include + +#include // lint-world: a handler's own allocator +#include // lint-world: a handler's cancellation +#include // lint-world: a handler's cancellation +#include // lint-world: the tests' event loop + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webrtc = webcpp::webrtc; +namespace asio = webcpp::asio; +using webrtc::detail::error_code; + +namespace { + +using state = webrtc::peer_connection_state; + +// Starts a wait on `watch` whose result lands in `out`. +template +webrtc::detail::pending& wait_op(asio::io_context& io, Handler handler) { + return webrtc::detail::make_operation(std::move(handler), io.get_executor(), + std::tuple{state::new_}, + webrtc::detail::wait_cancellation); +} + +void states_coalesce() { + asio::io_context io; + webrtc::detail::state_watch watch; + watch.update(state::connecting); + watch.update(state::connected); + std::optional got; + watch.wait(wait_op(io, [&](error_code ec, state s) { + BOOST_TEST(!ec); + got = s; + })); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(got == state::connected); +} + +void no_change_keeps_waiting() { + asio::io_context io; + webrtc::detail::state_watch watch; + watch.update(state::connected); + int completions = 0; + watch.wait(wait_op(io, [&](error_code, state) { ++completions; })); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST_EQ(completions, 1); + std::optional next; + watch.wait(wait_op(io, [&](error_code ec, state s) { + BOOST_TEST(!ec); + next = s; + })); + io.restart(); + io.poll(); + BOOST_TEST(!next); + watch.update(state::connected); + io.poll(); + BOOST_TEST(!next); + watch.update(state::disconnected); + io.restart(); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(next == state::disconnected); +} + +void one_wait_of_a_kind() { + asio::io_context io; + webrtc::detail::state_watch watch; + std::optional first; + std::optional second; + watch.wait(wait_op(io, [&](error_code ec, state) { first = ec; })); + watch.wait(wait_op(io, [&](error_code ec, state) { second = ec; })); + io.poll(); + BOOST_TEST(second && *second == asio::error::already_started); + BOOST_TEST(!first); + watch.update(state::connecting); + io.restart(); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(first && !*first); +} + +void a_cancelled_wait_consumes_nothing() { + asio::io_context io; + using candidate = webrtc::ice_candidate; + webrtc::detail::event_queue> queue(4, {}); + asio::cancellation_signal signal; + std::optional cancelled; + queue.wait(webrtc::detail::make_operation( + asio::bind_cancellation_slot(signal.slot(), + [&](error_code ec, const candidate&) { cancelled = ec; }), + io.get_executor(), std::tuple{}, webrtc::detail::wait_cancellation)); + signal.emit(asio::cancellation_type::terminal); + BOOST_TEST(!queue.push(candidate{"candidate:1", "0", 0, ""})); + std::optional next; + queue.wait(webrtc::detail::make_operation( + [&](error_code ec, candidate c) { + BOOST_TEST(!ec); + next = std::move(c); + }, + io.get_executor(), std::tuple{}, webrtc::detail::wait_cancellation)); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(cancelled && *cancelled == asio::error::operation_aborted); + BOOST_TEST(next && next->candidate == "candidate:1"); +} + +void the_bound_keeps_a_place_for_the_end() { + asio::io_context io; + using candidate = webrtc::ice_candidate; + webrtc::detail::event_queue> queue(2, {}); + BOOST_TEST(!queue.push(candidate{"candidate:1", "0", 0, ""})); + BOOST_TEST(!queue.push(candidate{"candidate:2", "0", 0, ""})); + BOOST_TEST(queue.push(candidate{"candidate:3", "0", 0, ""}).has_value()); + BOOST_TEST(!queue.push(candidate{}, true)); + BOOST_TEST_EQ(queue.size(), 3u); + std::vector got; + std::function next; + next = [&] { + queue.wait(webrtc::detail::make_operation( + [&](error_code ec, candidate c) { + if (ec) { + return; + } + got.emplace_back(c.candidate); + if (!c.candidate.empty()) { + next(); + } + }, + io.get_executor(), std::tuple{}, webrtc::detail::wait_cancellation)); + }; + next(); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST((got == std::vector{"candidate:1", "candidate:2", ""})); +} + +void a_satisfied_wait_is_posted() { + asio::io_context io; + webrtc::detail::state_watch watch; + watch.update(state::connected); + bool ran = false; + watch.wait(wait_op(io, [&](error_code, state) { ran = true; })); + BOOST_TEST(!ran); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(ran); +} + +void close_aborts_and_then_refuses() { + asio::io_context io; + webrtc::detail::state_watch watch; + std::optional pending; + watch.wait(wait_op(io, [&](error_code ec, state) { pending = ec; })); + watch.close(state::closed, asio::error::operation_aborted); + watch.update(state::failed); + std::optional later; + watch.wait(wait_op(io, [&](error_code ec, state) { later = ec; })); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(pending && *pending == asio::error::operation_aborted); + BOOST_TEST(later && *later == webrtc::error::closed); + BOOST_TEST(watch.current() == state::closed); +} + +// An allocator that counts what it gives, as a handler's associated allocator. +template +struct counting_allocator { + using value_type = T; + std::size_t* count; + + explicit counting_allocator(std::size_t* c) : count(c) {} + + template + explicit counting_allocator(const counting_allocator& other) : count(other.count) {} + + T* allocate(std::size_t n) { + ++*count; + return std::allocator().allocate(n); + } + + void deallocate(T* p, std::size_t n) { std::allocator().deallocate(p, n); } + + template + bool operator==(const counting_allocator& other) const { + return count == other.count; + } +}; + +void an_operation_is_in_its_handlers_allocator() { + asio::io_context io; + std::size_t count = 0; + webrtc::detail::state_watch watch; + bool ran = false; + watch.wait(webrtc::detail::make_operation( + asio::bind_allocator(counting_allocator(&count), + [&](error_code, state) { ran = true; }), + io.get_executor(), std::tuple{state::new_}, webrtc::detail::wait_cancellation)); + BOOST_TEST_GE(count, 1u); + watch.update(state::connecting); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(ran); +} + +} // namespace + +int main() { + states_coalesce(); + no_change_keeps_waiting(); + one_wait_of_a_kind(); + a_cancelled_wait_consumes_nothing(); + the_bound_keeps_a_place_for_the_end(); + a_satisfied_wait_is_posted(); + close_aborts_and_then_refuses(); + an_operation_is_in_its_handlers_allocator(); + return boost::report_errors(); +} diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/lifetime_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/lifetime_test.cpp new file mode 100644 index 0000000..39d362f --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/lifetime_test.cpp @@ -0,0 +1,143 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Lifetime against libdatachannel's threads (design.md, D7 and D9): a connection destroyed while +// its peer floods it, again and again; and a channel flooded past libdatachannel's queue of 1,024 +// messages, never read, whose destruction releases the thread that waits for room (spec: +// "Lifetime: native destruction is safe against foreign threads", "Testing: native lifetime"). + +#include + +#include "pair.hpp" +#include "require.hpp" + +#include // lint-world: messages +#include // lint-world: lets a flood fill the queue + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webrtc = webcpp::webrtc; +namespace asio = webcpp::asio; +using webrtc::detail::error_code; + +#ifndef WEBCPP_TEST_WEBRTC_REPEAT +#define WEBCPP_TEST_WEBRTC_REPEAT 10 +#endif + +namespace { + +// Sends small messages until the channel refuses one, then waits for room and goes on, until it +// fails otherwise. +void flood(webrtc::data_channel& channel, std::size_t& sent) { + static constexpr std::array message{}; + for (;;) { + const auto ec = channel.send(asio::buffer(message)); + if (ec == webrtc::error::buffered_amount_exceeded) { + channel.async_wait_buffered_amount_low([&channel, &sent](error_code ec) { + if (!ec) { + flood(channel, sent); + } + }); + return; + } + if (ec) { + return; + } + ++sent; + } +} + +// The answering peer and its channel are destroyed while the offering peer floods them; then the +// offering peer closes. Repeated, under ThreadSanitizer in its lane. +void destroyed_while_messages_arrive() { + for (int round = 0; round < WEBCPP_TEST_WEBRTC_REPEAT; ++round) { + webrtc::options opts; + opts.max_buffered_amount = std::size_t{64} * 1024; + webcpp::test::pair p(opts); + std::optional ca; + std::optional cb; + std::size_t sent = 0; + std::size_t read = 0; + std::string text; + auto buffer = asio::dynamic_buffer(text); + std::function receive = [&] { + cb->async_receive(buffer, [&](error_code ec, std::size_t n, bool) { + if (ec) { + return; + } + buffer.consume(n); + if (++read == 50) { + // Mid-flood: the answering side goes, its channel first. + cb.reset(); + p.b.reset(); + asio::post(p.io, [&] { p.a->close(); }); + return; + } + receive(); + }); + }; + webcpp::test::open_channel(p, "flood", [&](webrtc::data_channel a, webrtc::data_channel b) { + ca.emplace(std::move(a)); + cb.emplace(std::move(b)); + ca->set_buffered_amount_low_threshold(std::size_t{16} * 1024); + flood(*ca, sent); + receive(); + }); + p.run(); + BOOST_TEST_GE(read, 50u); + BOOST_TEST_GT(sent, 50u); + } +} + +// A channel flooded past libdatachannel's 1,024 unread messages is destroyed promptly: draining +// its queue releases the thread that waits for room. +void a_flooded_channel_is_destroyed_promptly() { + webcpp::test::pair p; + std::optional ca; + std::optional cb; + asio::steady_timer filled(p.io); // lint-world: lets the flood fill the queue + std::size_t sent = 0; + std::chrono::steady_clock::duration took{}; // lint-world: measures the destruction + webcpp::test::open_channel( + p, "never-read", [&](webrtc::data_channel a, webrtc::data_channel b) { + ca.emplace(std::move(a)); + cb.emplace(std::move(b)); + static constexpr std::array message{}; + for (int i = 0; i < 3000; ++i) { + if (ca->send(asio::buffer(message))) { + break; + } + ++sent; + } + filled.expires_after(std::chrono::seconds(1)); + filled.async_wait([&](error_code) { + const auto start = std::chrono::steady_clock::now(); // lint-world: measures it + cb.reset(); + took = std::chrono::steady_clock::now() - start; // lint-world: measures it + p.a->close(); + p.b->close(); + }); + }); + p.run(); + BOOST_TEST_EQ(sent, 3000u); + BOOST_TEST(took < std::chrono::seconds(2)); +} + +} // namespace + +int main() { + destroyed_while_messages_arrive(); + a_flooded_channel_is_destroyed_promptly(); + return boost::report_errors(); +} diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/native_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/native_test.cpp new file mode 100644 index 0000000..63e19b5 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/native_test.cpp @@ -0,0 +1,476 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Two native peers in one process over the loopback, through libdatachannel's C API: the +// exchange, the channel's messages both ways, the cases the semantics name, and the errors. The +// Jamfile builds it as the build asks and without exceptions. + +#include + +#include "pair.hpp" +#include "require.hpp" + +#include // lint-world: a handler's cancellation +#include // lint-world: messages +#include // lint-world: a handler's cancellation +#include // lint-world: lets messages arrive unread + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webrtc = webcpp::webrtc; +namespace asio = webcpp::asio; +using webcpp::test::pair; +using webrtc::detail::error_code; + +namespace { + +// Waits for state changes until `until`, recording each. +void watch_states(webrtc::peer_connection& pc, std::vector& seen, + webrtc::peer_connection_state until) { + pc.async_wait_state_change([&pc, &seen, until](error_code ec, webrtc::peer_connection_state s) { + if (ec) { + return; + } + seen.push_back(s); + if (s != until) { + watch_states(pc, seen, until); + } + }); +} + +// The whole exchange: offer, answer, candidates to their end, a channel, binary and text both +// ways, the label, the states, and both sides closing. +class full_exchange { +public: + using received = std::vector>; + + void run() { + watch_states(*p_.a, states_a_, webrtc::peer_connection_state::connected); + webcpp::test::open_channel(p_, "chat", + [this](webrtc::data_channel a, webrtc::data_channel b) { + opened(std::move(a), std::move(b)); + }); + p_.run(); + } + + void check() const { + BOOST_TEST(p_.ab->ended); + BOOST_TEST(p_.ba->ended); + BOOST_TEST_GT(p_.ab->gathered, 0); + BOOST_TEST_EQ(p_.ab->refused, 0); + BOOST_TEST_EQ(p_.ba->refused, 0); + BOOST_TEST(!states_a_.empty() && + states_a_.back() == webrtc::peer_connection_state::connected); + BOOST_TEST((received_b_ == received{{4, false}, {2, true}})); + BOOST_TEST((received_a_ == received{{4, true}})); + BOOST_TEST_EQ(at_b_.size(), 6u); + BOOST_TEST(at_b_.substr(4) == "ab"); + BOOST_TEST(at_a_ == "pong"); + BOOST_TEST(closed_a_); + BOOST_TEST(closed_b_); + BOOST_TEST(cb_.value().ready_state() == webrtc::data_channel_state::closed); + const auto local = p_.a->local_description(); + BOOST_TEST(local && local->type == webrtc::sdp_type::offer); + BOOST_TEST(local && local->sdp.find("a=candidate") != std::string::npos); + BOOST_TEST(p_.a->has_remote_description()); + } + +private: + void opened(webrtc::data_channel a, webrtc::data_channel b) { + auto& ca = ca_.emplace(std::move(a)); + auto& cb = cb_.emplace(std::move(b)); + BOOST_TEST(ca.label() == "chat"); + BOOST_TEST(cb.label() == "chat"); + BOOST_TEST(ca.ready_state() == webrtc::data_channel_state::open); + const std::array bytes{ + std::byte{1}, + std::byte{2}, + std::byte{3}, + std::byte{4}, + }; + BOOST_TEST(!ca.send(asio::buffer(bytes))); + BOOST_TEST(!ca.send_text("ab")); + BOOST_TEST(!cb.send_text("pong")); + // Two receives at b, then it waits for the close a makes after its one receive. + receive_at_b(); + ca.async_receive(buffer_a_, [this](error_code ec, std::size_t n, bool text) { + BOOST_TEST(!ec); + received_a_.emplace_back(n, text); + ca_.value().async_wait_close([this](error_code ec) { + BOOST_TEST(!ec); + closed_a_ = true; + }); + ca_.value().close(); + }); + } + + void receive_at_b() { + cb_.value().async_receive(buffer_b_, [this](error_code ec, std::size_t n, bool text) { + BOOST_TEST(!ec); + received_b_.emplace_back(n, text); + if (received_b_.size() < 2) { + receive_at_b(); + return; + } + cb_.value().async_wait_close([this](error_code ec) { + BOOST_TEST(!ec); + closed_b_ = true; + }); + }); + } + + pair p_; + std::vector states_a_; + std::string at_a_; + std::string at_b_; + received received_a_; + received received_b_; + decltype(asio::dynamic_buffer(at_a_)) buffer_a_ = asio::dynamic_buffer(at_a_); + decltype(asio::dynamic_buffer(at_b_)) buffer_b_ = asio::dynamic_buffer(at_b_); + std::optional ca_; + std::optional cb_; + bool closed_a_ = false; + bool closed_b_ = false; +}; + +void a_full_exchange() { + full_exchange exchange; + exchange.run(); + exchange.check(); +} + +// Messages are kept from the channel's creation: three sent before the first receive arrive in +// order. +void received_before_the_first_receive() { + pair p; + std::optional cb; + std::optional ca; + std::string text; + auto buffer = asio::dynamic_buffer(text); + asio::steady_timer later(p.io); // lint-world: lets the messages arrive unread + std::vector got; + webcpp::test::open_channel(p, "early", [&](webrtc::data_channel a, webrtc::data_channel b) { + ca.emplace(std::move(a)); + cb.emplace(std::move(b)); + BOOST_TEST(!ca->send_text("one")); + BOOST_TEST(!ca->send_text("two")); + BOOST_TEST(!ca->send_text("three")); + later.expires_after(std::chrono::milliseconds(300)); + later.async_wait([&](error_code) { + const auto next = std::make_shared>(); + *next = [&, next] { + cb->async_receive(buffer, [&, next](error_code ec, std::size_t n, bool) { + if (!BOOST_TEST(!ec)) { + return; + } + got.emplace_back(text.substr(0, n)); + buffer.consume(n); + if (got.size() < 3) { + (*next)(); + } else { + p.a->close(); + p.b->close(); + } + }); + }; + (*next)(); + }); + }); + p.run(); + BOOST_TEST((got == std::vector{"one", "two", "three"})); +} + +// A negotiated channel: both peers make it with one id, and neither accepts it. +void a_negotiated_channel() { + pair p; + webrtc::data_channel_init init; + init.negotiated = true; + init.id = 7; + auto ca = p.a->create_data_channel("x", init); + auto cb = p.b->create_data_channel("x", init); + webcpp::test::require(BOOST_TEST(ca.has_value())); + webcpp::test::require(BOOST_TEST(cb.has_value())); + asio::cancellation_signal stop_accepting; + std::optional accepted; + p.b->async_accept_data_channel(asio::bind_cancellation_slot( + stop_accepting.slot(), [&](error_code ec, webrtc::data_channel) { accepted = ec; })); + int open = 0; + auto opened = [&](error_code ec) { + BOOST_TEST(!ec); + if (++open == 2) { + BOOST_TEST(ca->id() == std::optional(7)); + BOOST_TEST(cb->id() == std::optional(7)); + stop_accepting.emit(asio::cancellation_type::terminal); + p.a->close(); + p.b->close(); + } + }; + ca->async_wait_open(opened); + cb->async_wait_open(opened); + p.negotiate([](error_code ec) { BOOST_TEST(!ec); }); + p.run(); + BOOST_TEST_EQ(open, 2); + BOOST_TEST(accepted && *accepted == asio::error::operation_aborted); +} + +// The errors that fail as values, before and after negotiation. +void errors_as_values() { + asio::io_context io; + webrtc::runtime_options rt_opts; + rt_opts.max_peer_connections = 1; + webrtc::runtime rt(rt_opts); + const auto config = webcpp::test::loopback_configuration(); + auto first = webrtc::peer_connection::make(rt, io.get_executor(), config); + webcpp::test::require(BOOST_TEST(first.has_value())); + const auto second = webrtc::peer_connection::make(rt, io.get_executor(), config); + BOOST_TEST(second.has_error() && second.error() == webrtc::error::too_many_peer_connections); + BOOST_TEST_EQ(rt.peer_connections(), 1u); + { + const auto gone = std::move(*first); + } + BOOST_TEST_EQ(rt.peer_connections(), 0u); + + const std::array bad_urls{"stun:"}; + webrtc::ice_server bad_server; + bad_server.urls = bad_urls; + const std::array bad_servers{bad_server}; + webrtc::configuration bad = config; + bad.ice_servers = bad_servers; + const auto refused = webrtc::peer_connection::make(rt, io.get_executor(), bad); + BOOST_TEST(refused.has_error() && refused.error() == webrtc::error::syntax_error); + BOOST_TEST_EQ(rt.peer_connections(), 0u); + + auto made = webrtc::peer_connection::make(rt, io.get_executor(), config); + webcpp::test::require(BOOST_TEST(made.has_value())); + webrtc::peer_connection& pc = *made; + BOOST_TEST(pc.state() == webrtc::peer_connection_state::new_); + BOOST_TEST(pc.ice_state() == webrtc::ice_connection_state::new_); + BOOST_TEST(!pc.local_description()); + BOOST_TEST(!pc.has_remote_description()); + + webrtc::data_channel_init both; + both.max_packet_life_time = 100; + both.max_retransmits = 3; + const auto two_limits = pc.create_data_channel("x", both); + BOOST_TEST(two_limits.has_error() && two_limits.error() == webrtc::error::type_error); + webrtc::data_channel_init no_id; + no_id.negotiated = true; + const auto without_id = pc.create_data_channel("x", no_id); + BOOST_TEST(without_id.has_error() && without_id.error() == webrtc::error::type_error); + + auto channel = pc.create_data_channel("chat"); + webcpp::test::require(BOOST_TEST(channel.has_value())); + BOOST_TEST(channel->ready_state() == webrtc::data_channel_state::connecting); + BOOST_TEST(channel->send_text("early") == webrtc::error::invalid_state); + + std::optional before_description; + pc.async_add_ice_candidate( + webrtc::ice_candidate_view{ + .candidate = "candidate:1 1 UDP 1 127.0.0.1 9 typ host", + .sdp_mid = std::string_view("0"), + .sdp_m_line_index = 0, + .username_fragment = {}, + }, + [&](error_code ec) { before_description = ec; }); + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST(before_description && *before_description == webrtc::error::invalid_state); + // Adding a channel does not negotiate: no description exists yet. + BOOST_TEST(!pc.local_description()); +} + +// Sends past the bounds fail and leave the channel open; a message larger than the caller's +// buffer stays queued. +void bounds() { + webrtc::options opts; + opts.max_message_size = 1024; + opts.max_buffered_amount = 512; + pair p(opts); + std::string small_text; + auto small = asio::dynamic_buffer(small_text, 8); + std::string large_text; + auto large = asio::dynamic_buffer(large_text); + std::optional ca; + std::optional cb; + std::optional too_small; + std::optional later; + webcpp::test::open_channel(p, "bounds", [&](webrtc::data_channel a, webrtc::data_channel b) { + ca.emplace(std::move(a)); + cb.emplace(std::move(b)); + const std::vector big(1025, 'x'); + BOOST_TEST(ca->send(asio::buffer(big)) == webrtc::error::message_too_large); + const std::vector over(600, 'x'); + BOOST_TEST(ca->send(asio::buffer(over)) == webrtc::error::buffered_amount_exceeded); + BOOST_TEST(ca->ready_state() == webrtc::data_channel_state::open); + const std::vector fits(16, 'y'); + BOOST_TEST(!ca->send(asio::buffer(fits))); + cb->async_receive(small, [&](error_code ec, std::size_t, bool) { + too_small = ec; + cb->async_receive(large, [&](error_code ec, std::size_t n, bool) { + BOOST_TEST(!ec); + later = n; + p.a->close(); + p.b->close(); + }); + }); + }); + p.run(); + BOOST_TEST(too_small && *too_small == asio::error::no_buffer_space); + BOOST_TEST(later == std::optional(16)); +} + +// close() fires no state change: the pending wait ends with operation_aborted, the state reads +// closed, the channels close with error::closed, the peer's channel sees its close, and a wait +// started afterwards completes with error::closed. +void close_fires_no_state_change() { + pair p; + std::optional ca; + std::optional cb; + std::string unused_a; + std::string unused_b; + auto ba = asio::dynamic_buffer(unused_a); + auto bb = asio::dynamic_buffer(unused_b); + std::optional state_wait; + std::optional local_receive; + std::optional remote_receive; + std::optional after_close; + bool remote_closed = false; + webcpp::test::open_channel(p, "c", [&](webrtc::data_channel a, webrtc::data_channel b) { + ca.emplace(std::move(a)); + cb.emplace(std::move(b)); + // The first wait completes with the current state, connected; the second is pending + // when the connection closes. + p.a->async_wait_state_change([&](error_code ec, webrtc::peer_connection_state s) { + BOOST_TEST(!ec); + BOOST_TEST(s == webrtc::peer_connection_state::connected); + p.a->async_wait_state_change( + [&](error_code ec, webrtc::peer_connection_state) { state_wait = ec; }); + ca->async_receive(ba, [&](error_code ec, std::size_t, bool) { local_receive = ec; }); + cb->async_receive(bb, [&](error_code ec, std::size_t, bool) { + remote_receive = ec; + cb->async_wait_close([&](error_code ec) { + BOOST_TEST(!ec); + remote_closed = true; + p.b->close(); + }); + }); + p.a->close(); + BOOST_TEST(p.a->state() == webrtc::peer_connection_state::closed); + p.a->async_wait_state_change( + [&](error_code ec, webrtc::peer_connection_state) { after_close = ec; }); + }); + }); + p.run(); + BOOST_TEST(state_wait && *state_wait == asio::error::operation_aborted); + BOOST_TEST(local_receive && *local_receive == webrtc::error::closed); + BOOST_TEST(remote_receive && *remote_receive == webrtc::error::closed); + BOOST_TEST(after_close && *after_close == webrtc::error::closed); + BOOST_TEST(remote_closed); +} + +// A channel's close() ends its receive with operation_aborted and its close wait once closed. +void a_channel_closed_by_its_owner() { + pair p; + std::optional ca; + std::optional cb; + std::string text; + auto buffer = asio::dynamic_buffer(text); + std::optional receive; + std::optional close_wait; + webcpp::test::open_channel(p, "c", [&](webrtc::data_channel a, webrtc::data_channel b) { + ca.emplace(std::move(a)); + cb.emplace(std::move(b)); + ca->async_receive(buffer, [&](error_code ec, std::size_t, bool) { receive = ec; }); + ca->async_wait_close([&](error_code ec) { + close_wait = ec; + p.a->close(); + p.b->close(); + }); + ca->close(); + BOOST_TEST(ca->ready_state() == webrtc::data_channel_state::closing); + }); + p.run(); + BOOST_TEST(receive && *receive == asio::error::operation_aborted); + BOOST_TEST(close_wait && !*close_wait); + BOOST_TEST(ca->ready_state() == webrtc::data_channel_state::closed); +} + +// Destruction with a wait pending runs its handler once, with operation_aborted; a move carries +// the pending wait. +void destruction_and_moves() { + asio::io_context io; + webrtc::runtime rt; + int aborted = 0; + { + auto made = webrtc::peer_connection::make(rt, io.get_executor(), + webcpp::test::loopback_configuration()); + webcpp::test::require(BOOST_TEST(made.has_value())); + made->async_wait_state_change([&](error_code ec, webrtc::peer_connection_state) { + BOOST_TEST(ec == asio::error::operation_aborted); + ++aborted; + }); + const webrtc::peer_connection moved(std::move(*made)); + BOOST_TEST_EQ(rt.peer_connections(), 1u); + } + io.run(); // lint-run: drains the posted completions of this test + BOOST_TEST_EQ(aborted, 1); + BOOST_TEST_EQ(rt.peer_connections(), 0u); +} + +// A program that re-arms its waits keeps run() alive until it closes the connection, and no +// longer: run() returns well before the exchange's limit. +void run_returns_once_closed() { + pair p; + std::optional ca; + std::optional cb; + std::vector seen; + std::function rearm = [&] { + p.b->async_wait_state_change([&](error_code ec, webrtc::peer_connection_state s) { + if (ec) { + return; + } + seen.push_back(s); + rearm(); + }); + }; + rearm(); + webcpp::test::open_channel(p, "c", [&](webrtc::data_channel a, webrtc::data_channel b) { + ca.emplace(std::move(a)); + cb.emplace(std::move(b)); + p.b->close(); + p.a->close(); + }); + const auto start = std::chrono::steady_clock::now(); // lint-world: measures run's return + p.run(); + const auto took = + std::chrono::steady_clock::now() - start; // lint-world: measures run's return + BOOST_TEST(took < webcpp::test::exchange_limit); + BOOST_TEST(!seen.empty()); +} + +} // namespace + +int main() { + a_full_exchange(); + received_before_the_first_receive(); + a_negotiated_channel(); + errors_as_values(); + bounds(); + close_fires_no_state_change(); + a_channel_closed_by_its_owner(); + destruction_and_moves(); + run_returns_once_closed(); + return boost::report_errors(); +} diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/pair.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/pair.hpp new file mode 100644 index 0000000..3d4d4db --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/pair.hpp @@ -0,0 +1,244 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Two native peers in one process, bound to the loopback and signalled in memory: the first +// offers, the second answers, and each trickles its candidates to the other until its gathering +// ends. Every wait it starts stops re-arming once its work is done, so that io_context::run +// returns when a test's exchange is over. + +#ifndef WEBCPP_TEST_WEBRTC_PAIR_HPP +#define WEBCPP_TEST_WEBRTC_PAIR_HPP + +#include + +#include "require.hpp" + +#include // lint-world: the tests' event loop + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +namespace webrtc = webcpp::webrtc; + +/** The loopback, without which libdatachannel offers no candidate two local peers can use. */ +inline constexpr std::string_view loopback = "127.0.0.1"; + +/** How long one exchange may take before a test gives up on it. */ +inline constexpr std::chrono::seconds exchange_limit{20}; + +/** A configuration with host candidates on the loopback only, no STUN, as CI allows. */ +inline webrtc::configuration loopback_configuration() { + webrtc::configuration config; + config.bind_address = loopback; + return config; +} + +/** + Sends the candidates one peer gathers to the other, holding them until the other has a remote + description, and stops at the end of gathering. +*/ +template +class trickle { +public: + using candidate_type = PeerConnection::ice_candidate; + + trickle(PeerConnection& from, PeerConnection& to) : from_(from), to_(to) {} + + /** Starts waiting for the first candidate. */ + void start() { + from_.async_wait_ice_candidate([this](webrtc::detail::error_code ec, candidate_type c) { + if (ec) { + return; + } + const bool end = c.candidate.empty(); + if (end) { + ended = true; + } else { + ++gathered; + } + if (ready_) { + add(c); + } else { + waiting_.push_back(std::move(c)); + } + if (!end) { + start(); + } + }); + } + + /** The other peer has a remote description: what was held goes now. */ + void ready() { + ready_ = true; + for (const auto& c : waiting_) { + add(c); + } + waiting_.clear(); + } + + /** Local candidates gathered, without the end. */ + int gathered = 0; + /** Whether the end of gathering arrived. */ + bool ended = false; + /** Candidates the other peer refused. */ + int refused = 0; + +private: + void add(const candidate_type& c) { + to_.async_add_ice_candidate(c.view(), [this](webrtc::detail::error_code ec) { + if (ec) { + ++refused; + } + }); + } + + PeerConnection& from_; + PeerConnection& to_; + std::vector waiting_; + bool ready_ = false; +}; + +/** + Negotiates `a` and `b`: an offer from `a`, the answer from `b`, candidates both ways; calls + `done` with the error of the first step that failed, or none once both descriptions are set. +*/ +template +void negotiate(PeerConnection& a, PeerConnection& b, trickle& ab, + trickle& ba, + const std::function& done) { + using description = PeerConnection::session_description; + ab.start(); + ba.start(); + a.async_set_local_description( + [&a, &b, &ab, &ba, done](webrtc::detail::error_code ec, const description& offer) { + if (ec) { + done(ec); + return; + } + BOOST_TEST(offer.type == webrtc::sdp_type::offer); + b.async_set_remote_description( + offer.view(), [&a, &b, &ab, &ba, done](webrtc::detail::error_code ec) { + if (ec) { + done(ec); + return; + } + ab.ready(); + b.async_set_local_description( + [&a, &ba, done](webrtc::detail::error_code ec, const description& answer) { + if (ec) { + done(ec); + return; + } + BOOST_TEST(answer.type == webrtc::sdp_type::answer); + a.async_set_remote_description( + answer.view(), [&ba, done](webrtc::detail::error_code ec) { + if (!ec) { + ba.ready(); + } + done(ec); + }); + }); + }); + }); +} + +/** An io_context, a runtime, and two peers on the loopback, made with `opts`. */ +struct pair { + explicit pair(const webrtc::options& opts = webrtc::options(), + const webrtc::runtime_options& rt_opts = webrtc::runtime_options()) + : rt(rt_opts) { + auto first = + webrtc::peer_connection::make(rt, io.get_executor(), loopback_configuration(), opts); + auto second = + webrtc::peer_connection::make(rt, io.get_executor(), loopback_configuration(), opts); + require(BOOST_TEST(first.has_value())); + require(BOOST_TEST(second.has_value())); + a.emplace(std::move(*first)); + b.emplace(std::move(*second)); + ab.emplace(*a, *b); + ba.emplace(*b, *a); + } + + /** Negotiates the two peers, trickling candidates both ways. */ + void negotiate(const std::function& done) { + test::negotiate(*a, *b, *ab, *ba, done); + } + + /** Runs the exchange until no work is left, or the limit passes. */ + void run() { + io.run_for(exchange_limit); // lint-run: the peers' events come from libdatachannel + } + + webcpp::asio::io_context io; + webrtc::runtime rt; + std::optional a; + std::optional b; + std::optional> ab; + std::optional> ba; +}; + +/** + Opens one channel labelled `label` from `p.a` to `p.b`, and calls `opened` with both ends once + both are open. +*/ +inline void open_channel(pair& p, std::string_view label, + std::function opened, + const webrtc::data_channel_init& init = {}) { + auto created = p.a->create_data_channel(label, init); + require(BOOST_TEST(created.has_value())); + + struct state { + std::optional local; + std::optional remote; + bool local_open = false; + bool remote_open = false; + std::function opened; + + void check() { + if (local_open && remote_open) { + opened(std::move(*local), std::move(*remote)); + } + } + }; + + const auto s = std::make_shared(state{ + .local = std::move(*created), + .remote = std::nullopt, + .local_open = false, + .remote_open = false, + .opened = std::move(opened), + }); + s->local->async_wait_open([s](webrtc::detail::error_code ec) { + BOOST_TEST(!ec); + s->local_open = !ec; + s->check(); + }); + p.b->async_accept_data_channel([s](webrtc::detail::error_code ec, webrtc::data_channel dc) { + if (!BOOST_TEST(!ec)) { + return; + } + s->remote.emplace(std::move(dc)); + s->remote->async_wait_open([s](webrtc::detail::error_code ec) { + BOOST_TEST(!ec); + s->remote_open = !ec; + s->check(); + }); + }); + p.negotiate([](webrtc::detail::error_code ec) { BOOST_TEST(!ec); }); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_WEBRTC_PAIR_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/require.hpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/require.hpp new file mode 100644 index 0000000..09a32af --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/require.hpp @@ -0,0 +1,31 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// What a test's helper does with a check its caller cannot go on without. A test case that fails +// such a check itself returns (`if (!BOOST_TEST(...)) { return; }`); a helper cannot return from +// its caller, and a lightweight_test program may be built without exceptions, so the helper ends +// the program instead, with the errors counted so far. + +#ifndef WEBCPP_TEST_WEBRTC_REQUIRE_HPP +#define WEBCPP_TEST_WEBRTC_REQUIRE_HPP + +#include + +#include + +namespace webcpp::test { + +// Ends the program as main would end it, with the errors counted so far, unless `held`, which is +// what BOOST_TEST returned: BOOST_TEST has already reported the failure. +inline void require(bool held) { + if (!held) { + std::exit(boost::report_errors()); + } +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_WEBRTC_REQUIRE_HPP diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/stall_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/stall_test.cpp new file mode 100644 index 0000000..b7dc435 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/stall_test.cpp @@ -0,0 +1,123 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The measurement of tasks.md 1.10: a native channel that is never read, flooded past +// libdatachannel's queue of 1,024 messages, stalls the connection's other channels, since the +// thread that waits for room in its queue is the one that delivers the association's messages; +// destroying it drains its queue and releases them (design.md, D9). + +#include + +#include "pair.hpp" +#include "require.hpp" + +#include // lint-world: messages +#include // lint-world: bounds each wait of the measurement + +#include + +#include +#include +#include +#include +#include +#include + +namespace webrtc = webcpp::webrtc; +namespace asio = webcpp::asio; +using webrtc::detail::error_code; + +namespace { + +// Opens "x" and "y", floods "x" without reading it, then sends one message on "y" and waits for +// it, three seconds; if it does not arrive, destroys the far end of "x" and waits again. +class stall { +public: + void run() { + webcpp::test::open_channel(p_, "x", [this](webrtc::data_channel a, webrtc::data_channel b) { + x_local_.emplace(std::move(a)); + x_remote_.emplace(std::move(b)); + open_y(); + }); + p_.run(); + } + + void check() const { + // Measured on 2026-11-14 with libdatachannel 0.24.6: the connection's other channel + // stalls while the never-read one is full, and destroying that one releases it. A change + // of this finding changes the documentation's (design.md, D9). + BOOST_TEST_EQ(sent_, 3000u); + BOOST_TEST(stalled_ == std::optional(true)); + BOOST_TEST(released_ == std::optional(true)); + } + +private: + void open_y() { + auto y = p_.a->create_data_channel("y"); + webcpp::test::require(BOOST_TEST(y.has_value())); + y_local_.emplace(std::move(*y)); + p_.b->async_accept_data_channel([this](error_code ec, webrtc::data_channel c) { + webcpp::test::require(BOOST_TEST(!ec)); + y_remote_.emplace(std::move(c)); + y_local_.value().async_wait_open([this](error_code ec) { + webcpp::test::require(BOOST_TEST(!ec)); + flood_x(); + }); + }); + } + + void flood_x() { + static constexpr std::array message{}; + for (int i = 0; i < 3000 && !x_local_.value().send(asio::buffer(message)); ++i) { + ++sent_; + } + timer_.expires_after(std::chrono::seconds(1)); + timer_.async_wait([this](error_code) { send_on_y(); }); + } + + void send_on_y() { + BOOST_TEST(!y_local_.value().send_text("y")); + y_remote_.value().async_receive(buffer_, [this](error_code ec, std::size_t, bool) { + if (stalled_) { + released_ = !ec; + } else { + stalled_ = false; + timer_.cancel(); + } + p_.a->close(); + p_.b->close(); + }); + timer_.expires_after(std::chrono::seconds(3)); + timer_.async_wait([this](error_code ec) { + if (ec) { + return; + } + stalled_ = true; + x_remote_.reset(); + }); + } + + webcpp::test::pair p_; + std::optional x_local_; + std::optional x_remote_; + std::optional y_local_; + std::optional y_remote_; + asio::steady_timer timer_{p_.io}; // lint-world: bounds each wait of the measurement + std::string text_; + decltype(asio::dynamic_buffer(text_)) buffer_ = asio::dynamic_buffer(text_); + std::optional stalled_; + std::optional released_; + std::size_t sent_ = 0; +}; + +} // namespace + +int main() { + stall measurement; + measurement.run(); + measurement.check(); + return boost::report_errors(); +} diff --git a/libraries/webrtc/openspec/changes/genesis/reference/source/test/types_test.cpp b/libraries/webrtc/openspec/changes/genesis/reference/source/test/types_test.cpp new file mode 100644 index 0000000..5f6dec9 --- /dev/null +++ b/libraries/webrtc/openspec/changes/genesis/reference/source/test/types_test.cpp @@ -0,0 +1,106 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The value types: their defaults, the views of the outputs, and the outputs' allocator (spec: +// "Types: ...", "Options are webcpp's own bounds"). + +#include +#include + +#include + +#include +#include + +namespace webrtc = webcpp::webrtc; + +namespace { + +void defaults() { + const webrtc::data_channel_init init; + BOOST_TEST(init.ordered); + BOOST_TEST(!init.negotiated); + BOOST_TEST(!init.max_packet_life_time); + BOOST_TEST(!init.max_retransmits); + BOOST_TEST(!init.id); + BOOST_TEST(init.protocol.empty()); + const webrtc::configuration config; + BOOST_TEST(config.policy == webrtc::ice_transport_policy::all); + BOOST_TEST(config.bind_address.empty()); + BOOST_TEST(config.ice_servers.empty()); +} + +void option_defaults() { + const webrtc::options opts; + BOOST_TEST_EQ(opts.max_queued_candidates, 64u); + BOOST_TEST_EQ(opts.max_queued_channels, 16u); + BOOST_TEST_EQ(opts.max_message_size, 262144u); + BOOST_TEST_EQ(opts.max_buffered_amount, 16777216u); + BOOST_TEST_EQ(opts.max_received_bytes, 16777216u); + const webrtc::runtime_options rt; + BOOST_TEST_EQ(rt.max_peer_connections, 256u); + BOOST_TEST_EQ(rt.thread_pool_size, 0u); +} + +void enumerations_start_at_new() { + BOOST_TEST(webrtc::peer_connection_state{} == webrtc::peer_connection_state::new_); + BOOST_TEST(webrtc::ice_connection_state{} == webrtc::ice_connection_state::new_); + BOOST_TEST(webrtc::data_channel_state{} == webrtc::data_channel_state::connecting); +} + +void a_description_round_trip() { + webrtc::session_description d{.type = webrtc::sdp_type::answer, .sdp = "v=0\r\n"}; + const webrtc::session_description_view view = d.view(); + BOOST_TEST(view.type == webrtc::sdp_type::answer); + BOOST_TEST(view.sdp == d.sdp); + BOOST_TEST(view.sdp.data() == d.sdp.data()); +} + +void a_candidate_view() { + const webrtc::ice_candidate c{ + .candidate = "candidate:1 1 UDP 1 127.0.0.1 9 typ host", + .sdp_mid = "0", + .sdp_m_line_index = 0, + .username_fragment = "", + }; + const webrtc::ice_candidate_view view = c.view(); + BOOST_TEST(view.candidate == c.candidate); + BOOST_TEST(view.sdp_mid && *view.sdp_mid == "0"); + BOOST_TEST(view.sdp_m_line_index && *view.sdp_m_line_index == 0); + const webrtc::ice_candidate no_mid{ + .candidate = "", + .sdp_mid = "", + .sdp_m_line_index = std::nullopt, + .username_fragment = "", + }; + BOOST_TEST(!no_mid.view().sdp_mid); +} + +void a_candidate_under_a_pmr_allocator() { + std::pmr::monotonic_buffer_resource resource; + using allocator = std::pmr::polymorphic_allocator; + const allocator a(&resource); + const webrtc::basic_ice_candidate c{ + .candidate = webrtc::detail::string(std::string(64, 'c'), a), + .sdp_mid = webrtc::detail::string("0", a), + .sdp_m_line_index = 0, + .username_fragment = webrtc::detail::string(a), + }; + BOOST_TEST(c.candidate.get_allocator().resource() == &resource); + BOOST_TEST(c.sdp_mid.get_allocator().resource() == &resource); +} + +} // namespace + +int main() { + defaults(); + option_defaults(); + enumerations_start_at_new(); + a_description_round_trip(); + a_candidate_view(); + a_candidate_under_a_pmr_allocator(); + return boost::report_errors(); +} diff --git a/libraries/webrtc/openspec/changes/genesis/specs/webrtc/spec.md b/libraries/webrtc/openspec/changes/genesis/specs/webrtc/spec.md index 361fc20..6674a1d 100644 --- a/libraries/webrtc/openspec/changes/genesis/specs/webrtc/spec.md +++ b/libraries/webrtc/openspec/changes/genesis/specs/webrtc/spec.md @@ -3,15 +3,22 @@ webcpp::webrtc is one interface for peer connections and data channels, shaped as the W3C WebRTC API, whose operations follow Asio's model (completion tokens, handlers on webcpp::asio's executors), so that a program, and trystero first, is written once and runs -natively and in a browser. Natively it wraps libdatachannel; compiled with Emscripten it drives -the browser's `RTCPeerConnection` and `RTCDataChannel`. Media (tracks, codecs) is out of scope: -data channels only. The requirements below state what the draft specification -(`reference/spec.md`, 2026-10-10) requires; nothing is built yet. +natively and in a browser. Natively it wraps libdatachannel through its C API; compiled with +Emscripten it drives the browser's `RTCPeerConnection` and `RTCDataChannel`. Media (tracks, +codecs) is out of scope: data channels only. The requirements below state what `design.md` +(revised 2026-11-14) decides; increment 1 is built as reference code (`reference/source/`). ## ADDED Requirements +### Requirement: Library: a library of its own +webcpp::webrtc SHALL be a library of its own on webcpp::asio, not a part of webcpp::beast, as the owner decided on 2026-11-14, and its headers MUST NOT include webcpp::beast; a later byte stream over a data channel, which webcpp::beast's D6 foresees as an opt-in next layer, would make webcpp::beast use this library, never the reverse. + +#### Scenario: Header dependencies on beast +- **WHEN** the library's headers are scanned for includes +- **THEN** none is from `` or `` + ### Requirement: Library: header-only, namespace and conventions -The library SHALL be a header-only C++20 library in the namespace `webcpp::webrtc`, with its headers under ``, its internals in `detail`, its macros prefixed `WEBCPP_WEBRTC_`, licensed BSL-1.0 with "Copyright (c) 2026 WebCpp.org" on every source file, and a convenience header that includes the public interface of the selected target. +The library SHALL be a header-only C++20 library in the namespace `webcpp::webrtc`, with its headers under ``, its internals in `detail`, its macros prefixed `WEBCPP_WEBRTC_`, the b2 target `/webcpp/webrtc//webrtc`, licensed BSL-1.0 with "Copyright (c) 2026 WebCpp.org" on every source file, and a convenience header `` that includes the public interface of the selected target. #### Scenario: A program includes the convenience header natively - **WHEN** a native program includes the library's convenience header and names `webcpp::webrtc::peer_connection` @@ -22,29 +29,29 @@ The library SHALL be a header-only C++20 library in the namespace `webcpp::webrt - **THEN** every public name is in `webcpp::webrtc`, every macro starts with `WEBCPP_WEBRTC_`, and every implementation name is in `webcpp::webrtc::detail` ### Requirement: Library: targets are native and emscripten only -The library's build SHALL declare the targets native and emscripten and no other, and its convenience header MUST stop with `#error` under `__wasi__`, naming the reason: no WebRTC stack exists for WASI, libdatachannel needs threads that neither wasip2 nor wasip3 gives, and a UDP socket layer and a DTLS stack it has no WASI port of, and Boost.Asio itself does not build for those targets. +The library's build SHALL declare the targets native and emscripten and no other, and its configuration header, which every header includes first, MUST stop with `#error` under WASI, naming the reason: there is no WebRTC stack for WASI, because libdatachannel has no WASI port (its threads, and libjuice's and usrsctp's, need preemptive threads that neither wasip2 nor wasip3's cooperative profile gives, and its ICE and SCTP were never ported to WASI sockets) and no WASI host interface offers WebRTC. #### Scenario: Included under WASI -- **WHEN** the convenience header is compiled for wasm32-wasip2 or wasm32-wasip3 -- **THEN** compilation stops with an `#error` whose text names that no WebRTC stack exists for WASI, threads, UDP and DTLS +- **WHEN** any header of the library is compiled for wasm32-wasip2 or wasm32-wasip3 +- **THEN** compilation stops with an `#error` whose text names that there is no WebRTC stack for WASI, libdatachannel's threads and sockets, and the missing host interface #### Scenario: The build lists its targets -- **WHEN** the library's `build.jam` is read +- **WHEN** the library's test Jamfile is read - **THEN** it declares native and emscripten and has no wasip2 or wasip3 lane ### Requirement: Library: data channels only, no media -The library SHALL offer peer connections and data channels and MUST NOT offer tracks, transceivers or codecs, and no public header SHALL expose a native handle: nothing of `rtc::` or `emscripten::val` appears in any public header, and media will get an interface of its own. +The library SHALL offer peer connections and data channels and MUST NOT offer tracks, transceivers or codecs, and no public header SHALL expose a native handle: nothing of libdatachannel (its ids, `rtc::` or `rtc/rtc.h`'s types) or of `emscripten::val` appears in a public member, and media will get an interface of its own. #### Scenario: No native handle -- **WHEN** the public headers are searched for `rtc::`, `emscripten::val` and `native_handle` -- **THEN** nothing is found outside the headers of the backend directories, and no public class has a native handle member +- **WHEN** the public classes are inspected +- **THEN** none has a native handle member and none returns or takes a libdatachannel id or an `emscripten::val` ### Requirement: Library: no global or static mutable state -The library SHALL keep no global or static mutable state, and the platform's process-wide state (libdatachannel's thread pool, logger and cleanup; the browser page's census of peer connections) MUST be held through a `runtime` object the program owns. +The library SHALL keep no global or static mutable state, and the platform's process-wide state (libdatachannel's thread pool, global resources and cleanup; the browser page's census of peer connections) MUST be held through a `runtime` object the program owns. #### Scenario: Two runtimes in one process natively -- **WHEN** a second `runtime` is constructed while one is alive on the native target -- **THEN** the library refuses it, because at most one exists at a time in a process (libdatachannel's state is the process's) +- **WHEN** the documentation of `runtime` is read +- **THEN** it states that at most one exists at a time in a native process, because libdatachannel's state is the process's, as a precondition the library does not check, since a check would need static state ### Requirement: Types: the five enumerations The library SHALL define `sdp_type { offer, answer, pranswer, rollback }`, `peer_connection_state { new_, connecting, connected, disconnected, failed, closed }`, `ice_connection_state { new_, checking, connected, completed, disconnected, failed, closed }`, `data_channel_state { connecting, open, closing, closed }` and `ice_transport_policy { all, relay }`, each an `enum class` whose enumerators carry the W3C names, with a trailing underscore on `new_` only. @@ -58,26 +65,26 @@ The library SHALL define `sdp_type { offer, answer, pranswer, rollback }`, `peer - **THEN** its `ready_state()` is `data_channel_state::connecting` until the transport opens ### Requirement: Types: inputs are views read during the call -The library SHALL take its inputs as views read during the call that takes them: `ice_server { std::span urls; std::string_view username; std::string_view credential; }`, `configuration { std::span ice_servers; ice_transport_policy policy = all; std::string_view bind_address; }`, `session_description_view { sdp_type type; std::string_view sdp; }`, `ice_candidate_view { std::string_view candidate; std::optional sdp_mid; std::optional sdp_m_line_index; std::string_view username_fragment; }` and `data_channel_init { bool ordered = true; std::optional max_packet_life_time; std::optional max_retransmits; std::string_view protocol; bool negotiated = false; std::optional id; }`, and an implementation MUST NOT keep a view after the call returns. +The library SHALL take its inputs as views read during the call that takes them: `ice_server { urls; username; credential; }`, `configuration { ice_servers; policy = all; bind_address; }`, `session_description_view { type; sdp; }`, `ice_candidate_view { candidate; sdp_mid; sdp_m_line_index; username_fragment; }` and `data_channel_init { ordered = true; max_packet_life_time; max_retransmits; protocol; negotiated = false; id; }`, every member with a default member initializer, and an implementation MUST NOT keep a view after the call returns, which an asynchronous operation honours by copying what it needs before it returns, whatever its completion token. #### Scenario: A temporary string as an SDP -- **WHEN** a program passes a `session_description_view` over a `std::string` to `async_set_remote_description` and destroys the string as soon as the call returns -- **THEN** the operation completes correctly, because the library copied what it needed during the call +- **WHEN** a program passes a `session_description_view` over a `std::string` to `async_set_remote_description` with a deferred token and destroys the string before it starts the operation +- **THEN** the operation completes correctly, because the library copied the SDP during the call #### Scenario: Defaults - **WHEN** a `data_channel_init` and a `configuration` are default-constructed - **THEN** `ordered` is true, `negotiated` is false, the optional members are empty, `policy` is `all` and `bind_address` is empty ### Requirement: Types: outputs are owned and use the object's allocator -The library SHALL return `basic_session_description` (`type` and `sdp`) and `basic_ice_candidate` (`candidate`, `sdp_mid`, `sdp_m_line_index`, `username_fragment`) as owned values whose text is a `std::basic_string` over the allocator rebound to `char`, each with a `view()` member returning the matching input view, and the aliases `session_description` and `ice_candidate` SHALL name the instantiations over `std::allocator`. +The library SHALL return `basic_session_description` (`type` and `sdp`) and `basic_ice_candidate` (`candidate`, `sdp_mid`, `sdp_m_line_index`, `username_fragment`) as owned values whose text is a `std::basic_string` over the allocator rebound to `char`, each with a `view()` member returning the matching input view (an empty `sdp_mid` as no mid), and the aliases `session_description` and `ice_candidate` SHALL name the instantiations over `std::allocator`. #### Scenario: A description round trip - **WHEN** a program takes the `session_description` a completed `async_set_local_description` delivered and calls `view()` - **THEN** the view has the same `type` and an `sdp` equal to the owned text, usable as `async_set_remote_description`'s argument on the other peer -#### Scenario: A candidate under a pmr allocator -- **WHEN** a connection is made with a polymorphic allocator over a counting resource and a candidate is delivered -- **THEN** the candidate's strings are allocated from that resource +#### Scenario: A description under a pmr allocator +- **WHEN** a connection is made with a polymorphic allocator over a counting resource and its local description is read +- **THEN** the description's text is allocated from that resource ### Requirement: Types: options are webcpp's own bounds The library SHALL define `options` with the members and defaults `max_queued_candidates = 64`, `max_queued_channels = 16`, `max_message_size = 256 * 1024`, `max_buffered_amount = 16 * 1024 * 1024` and `max_received_bytes = 16 * 1024 * 1024`, the last applying on emscripten only, and an object MUST fail as a value (never throw, never block) when a bound is reached. @@ -87,51 +94,51 @@ The library SHALL define `options` with the members and defaults `max_queued_can - **THEN** `max_queued_candidates` is 64, `max_queued_channels` is 16, `max_message_size` is 262144, `max_buffered_amount` is 16777216 and `max_received_bytes` is 16777216 ### Requirement: Runtime: process-wide platform state -The library SHALL provide `runtime`, constructed from `runtime_options { std::size_t max_peer_connections = 256; unsigned thread_pool_size = 0; }` (explicit, default argument `{}`), neither copyable nor assignable, which MUST be created before any peer connection and destroyed after the last, and `basic_peer_connection::make` SHALL take it by reference so that no connection can exist without one. +The library SHALL provide `runtime`, constructed from `runtime_options { std::size_t max_peer_connections = 256; std::uint32_t thread_pool_size = 0; }` (explicit, default argument), neither copyable nor movable, which MUST be created before any peer connection and destroyed after the last connection and channel, and `basic_peer_connection::make` SHALL take it by reference so that no connection can exist without one. #### Scenario: Native construction and destruction - **WHEN** a native `runtime` is constructed with `thread_pool_size` 4 and later destroyed -- **THEN** its constructor applied libdatachannel's thread pool size 4, its destructor waited for `rtc::Cleanup()`, and no libdatachannel thread outlives it +- **THEN** its constructor called `rtcSetThreadPoolSize(4)` and `rtcPreload()`, its destructor `rtcCleanup()`, which returns once libdatachannel's threads stopped #### Scenario: The default thread pool - **WHEN** `thread_pool_size` is 0 - **THEN** libdatachannel's own default is used ### Requirement: Runtime: the cap of peer connections -The `runtime` SHALL enforce `max_peer_connections` (default 256, half of Chromium's limit of 500 per page) on both targets, counting natively the connections made with it that are alive and in the browser reading the page's census of every `RTCPeerConnection` from its construction until the garbage collector frees it, kept in JavaScript and never in C++, and `make` past the cap MUST fail with `error::too_many_peer_connections`. +The `runtime` SHALL enforce `max_peer_connections` (default 256, half of Chromium's limit of 500 per page) on both targets, counting natively, in a member, the connections made with it that are alive and in the browser reading the page's census of every `RTCPeerConnection` from its construction until the garbage collector frees it, kept in JavaScript and never in C++, and `make` past the cap MUST fail with `error::too_many_peer_connections`. #### Scenario: Past the cap -- **WHEN** a `runtime` with `max_peer_connections` 2 has two live peer connections and `make` is called a third time +- **WHEN** a `runtime` with `max_peer_connections` 1 has one live peer connection and `make` is called again - **THEN** `make` returns a failed `result` whose error is `error::too_many_peer_connections` -#### Scenario: A connection closed frees a slot -- **WHEN** one of two live connections is destroyed and `make` is called again +#### Scenario: A connection gone frees a slot +- **WHEN** the live connection is destroyed and `make` is called again - **THEN** it succeeds, natively; in the browser it succeeds once the census no longer counts the freed object ### Requirement: Peer connection: make -`basic_peer_connection::make(runtime&, Executor, configuration const&, options const& = {}, Allocator = {})` SHALL return a `boost::system::result` that fails as a value: `error::too_many_peer_connections` past the runtime's cap, and the platform's refusal (a bad server URL, a field the target cannot honour) as its code. +`basic_peer_connection::make(runtime&, const Executor&, const configuration&, const options& = options(), const Allocator& = Allocator())` SHALL return a `boost::system::result` that fails as a value: `error::too_many_peer_connections` past the runtime's cap, `error::syntax_error` for an ICE server URL that cannot be parsed, `error::type_error` for a bound out of the platform's range, and `error::operation_error` for another refusal. #### Scenario: A server URL that cannot be parsed -- **WHEN** `make` is called with an ice server whose URL is malformed -- **THEN** the result holds `error::syntax_error` +- **WHEN** `make` is called with an ice server whose URL is `stun:` +- **THEN** the result holds `error::syntax_error` and the runtime's count is unchanged #### Scenario: A valid configuration -- **WHEN** `make` is called with one STUN-less configuration and an `io_context`'s executor +- **WHEN** `make` is called with a configuration with no ice server and an `io_context`'s executor - **THEN** the result holds a connection whose `get_executor()` equals that executor ### Requirement: Peer connection: move-only, executor and allocator -`basic_peer_connection` SHALL be movable and not copyable, with `executor_type`, `allocator_type`, `get_executor()` and `get_allocator()`, template parameters `Executor` (default `boost::asio::any_io_executor`) and `Allocator` (default `std::allocator`), and the aliases `peer_connection`, `data_channel`, `session_description` and `ice_candidate` for the defaults. +`basic_peer_connection` SHALL be movable and not copyable, with `executor_type`, `allocator_type`, `get_executor()` and `get_allocator()`, template parameters `Executor` (default `webcpp::asio::any_io_executor`, natively Boost.Asio's own type, on Emscripten the shipped backend's) and `Allocator` (default `std::allocator`), and the aliases `peer_connection`, `data_channel`, `session_description` and `ice_candidate` for the defaults. #### Scenario: A move -- **WHEN** a connection with a pending `async_wait_state_change` is move-constructed -- **THEN** the new object owns the pending wait and the moved-from object holds no operation +- **WHEN** a connection with a pending `async_wait_state_change` is move-constructed and the new object is destroyed +- **THEN** the handler runs once, with `operation_aborted`, and the moved-from object holds nothing ### Requirement: Peer connection: set the local description -`async_set_local_description(CompletionToken&&)` SHALL create and apply the implicit local description (an offer or an answer as the connection's state requires, the form trystero uses) and complete with `(error_code, session_description)`. +`async_set_local_description(CompletionToken&&)` SHALL create and apply the implicit local description (an offer or an answer as the connection's signaling state requires, the form trystero uses) and complete with `(error_code, session_description)`. #### Scenario: An offer - **WHEN** a connection that has just created a data channel awaits `async_set_local_description` -- **THEN** it completes with no error and a `session_description` of type `offer` whose `sdp` is non-empty, and `local_description()` then returns the same description +- **THEN** it completes with no error and a `session_description` of type `offer` whose `sdp` is non-empty, and `local_description()` then returns it, with the candidates gathered so far #### Scenario: An answer - **WHEN** a connection whose remote description is an offer awaits `async_set_local_description` @@ -156,36 +163,36 @@ The `runtime` SHALL enforce `max_peer_connections` (default 256, half of Chromiu The connection SHALL offer `async_wait_ice_candidate` (completing with `(error_code, ice_candidate)`), `async_wait_state_change` (`(error_code, peer_connection_state)`), `async_wait_ice_connection_state_change` (`(error_code, ice_connection_state)`) and `async_accept_data_channel` (`(error_code, data_channel)`), each a pending operation the caller re-arms, as Asio's `async_accept`. #### Scenario: Re-arming -- **WHEN** a program loops on `async_wait_ice_candidate`, starting a new wait in each handler -- **THEN** it receives every candidate in order, then the end-of-candidates value +- **WHEN** a program loops on `async_wait_ice_candidate`, starting a new wait in each handler, and gives each candidate to the other peer +- **THEN** it receives every candidate in order, then the end-of-candidates value, and the other peer refuses none ### Requirement: Peer connection: channels, queries and close -The connection SHALL provide `create_data_channel(std::string_view label, data_channel_init const& = {})` returning `boost::system::result`, `local_description()` returning `std::optional`, `has_remote_description()`, `state()`, `ice_state()` and `close()`, and `create_data_channel` MUST fail with `error::type_error` when both `max_packet_life_time` and `max_retransmits` are set. +The connection SHALL provide `create_data_channel(std::string_view label, const data_channel_init& = {})` returning `boost::system::result`, `local_description()` returning `std::optional`, `has_remote_description()`, `state()`, `ice_state()` and `close()`, and `create_data_channel` MUST fail with `error::type_error` when both `max_packet_life_time` and `max_retransmits` are set, when `negotiated` is set without an `id`, for an `id` of 65535, and for a label or protocol past 65,535 bytes, and with `error::invalid_state` on a closed connection. #### Scenario: Both reliability limits - **WHEN** `create_data_channel("x", {.max_packet_life_time = 100, .max_retransmits = 3})` is called - **THEN** the result holds `error::type_error` #### Scenario: Negotiated channel -- **WHEN** `create_data_channel("x", {.negotiated = true, .id = 7})` is called on both peers -- **THEN** both channels open with id 7 and neither peer receives the channel through `async_accept_data_channel` +- **WHEN** `create_data_channel("x", {.negotiated = true, .id = 7})` is called on both peers before they negotiate +- **THEN** both channels open with `id()` 7 and neither peer receives the channel through `async_accept_data_channel` #### Scenario: Before any description - **WHEN** `local_description()` is called before `async_set_local_description` completed - **THEN** it returns an empty optional ### Requirement: Peer connection: destruction -The destructor of a connection SHALL close it and complete every pending operation with `boost::asio::error::operation_aborted`. +The destructor of a connection SHALL close it and complete every pending operation with `boost::asio::error::operation_aborted`, posted. #### Scenario: Destroyed with a wait pending - **WHEN** a connection with a pending `async_wait_state_change` is destroyed - **THEN** the handler is invoked once, on the executor, with `operation_aborted` ### Requirement: Data channel: the interface -`basic_data_channel` SHALL be movable and not copyable and SHALL provide `async_wait_open` and `async_wait_close` (both `(error_code)`), `async_receive(DynamicBuffer&, CompletionToken&&)` (`(error_code, std::size_t, bool is_text)`), `async_send(ConstBufferSequence const&, CompletionToken&&)` and `async_send_text(std::string_view, CompletionToken&&)` (both `(error_code)`), `async_wait_buffered_amount_low`, the synchronous `send` and `send_text` returning `boost::system::error_code`, `set_buffered_amount_low_threshold(std::size_t)`, `buffered_amount()`, `ready_state()`, `label()` (a view into the object's allocator) and `close()`, and its destructor MUST close it and complete every pending operation with `operation_aborted`. +`basic_data_channel` SHALL be movable and not copyable and SHALL provide `async_wait_open` and `async_wait_close` (both `(error_code)`), `async_receive(DynamicBuffer&, CompletionToken&&)` (`(error_code, std::size_t, bool is_text)`), `async_send(const ConstBufferSequence&, CompletionToken&&)` and `async_send_text(std::string_view, CompletionToken&&)` (both `(error_code)`), `async_wait_buffered_amount_low`, the synchronous `send` and `send_text` returning `boost::system::error_code`, `set_buffered_amount_low_threshold(std::size_t)`, `buffered_amount()`, `ready_state()`, `label()` (a view into the object's allocator), `id()` (the stream id, once it has one) and `close()`, and its destructor MUST close it and complete every pending operation with `operation_aborted`. #### Scenario: Open and send -- **WHEN** a channel is created, `async_wait_open` completes, and `send_text("hi")` is called +- **WHEN** a channel is created, `async_wait_open` completes, and `send_text("ab")` is called - **THEN** `send_text` returns a default `error_code` and the remote `async_receive` completes with 2 bytes and `is_text` true #### Scenario: Label @@ -196,22 +203,22 @@ The destructor of a connection SHALL close it and complete every pending operati Every completion handler SHALL be invoked on the object's executor through its associated executor and allocator, as Asio's I/O objects invoke theirs, and MUST NOT be invoked inside the call that started the operation: a completion known at once is posted. #### Scenario: Immediate completion is posted -- **WHEN** `async_wait_open` is called on an open channel +- **WHEN** a wait is started whose event is already there - **THEN** the call returns first and the handler runs later from the executor, with no error ### Requirement: Semantics: native threads post to the executor -On the native target, an event arriving on a libdatachannel thread SHALL be posted to the executor and MUST NOT run there, and nothing of the user's allocator SHALL be touched on those threads: the posts carry Asio's default allocator and the library's queues are filled on the executor. +On the native target, an event arriving on a libdatachannel thread SHALL be copied into the standard allocator and posted to the executor through a weak pointer to the object's state, and MUST NOT run a handler there, and nothing of the user's allocator SHALL be touched on those threads: the library's queues are filled on the executor. #### Scenario: An event from a foreign thread -- **WHEN** libdatachannel delivers a message on its own thread while a program runs `io_context::run` on another -- **THEN** the handler runs on the `run` thread and the counting resource of the object's allocator recorded no allocation made on libdatachannel's thread +- **WHEN** libdatachannel delivers candidates, states and messages on its threads while a program runs the io_context on its own thread, with a connection over a counting resource +- **THEN** every handler runs on the io_context's thread and the resource recorded no allocation made on another thread ### Requirement: Semantics: browser events enter through the bridge -On the emscripten target, browser events SHALL enter through webcpp::asio's bridge, which only posts to the `io_context`, and nothing of the library MUST call `poll`, `run` or `dispatch` from a JavaScript event. +On the emscripten target, each object SHALL be one `intrusive_registration` of webcpp::asio's bridge, whose `deliver` stages the event in the object's state and posts at most one notification to the executor for what is staged, as webcpp::beast's browser WebSocket does, and nothing of the library MUST call `poll`, `run` or `dispatch` from a JavaScript event or run a handler inside `deliver`. -#### Scenario: A message event -- **WHEN** the browser fires `onmessage` on a channel -- **THEN** the library posts to the `io_context` through the bridge and the handler runs in a later turn of the run family +#### Scenario: A burst of messages +- **WHEN** the browser fires `onmessage` three times on a channel before the executor runs +- **THEN** the three messages are staged, one notification is posted, and the pending receive completes in a later turn of the run family ### Requirement: Errors: the error category and its ten values The library SHALL define `webcpp::webrtc::error`, an enumeration registered with a `boost::system::error_category` named `webcpp.webrtc`, with these enumerators whose values are fixed and never reused: 1 `invalid_state`, 2 `operation_error`, 3 `invalid_access`, 4 `type_error`, 5 `syntax_error`, 6 `closed`, 7 `message_too_large`, 8 `buffered_amount_exceeded`, 9 `receive_overflow`, 10 `too_many_peer_connections`. @@ -225,27 +232,31 @@ The library SHALL define `webcpp::webrtc::error`, an enumeration registered with - **THEN** they are 1 to 10 in the order above ### Requirement: Errors: meanings of the codes -The codes SHALL mean: `invalid_state` the W3C's `InvalidStateError` (a candidate before a remote description, a send on a channel that is not open); `operation_error` the W3C's `OperationError`, and natively any exception libdatachannel throws on an operation; `invalid_access` the W3C's `InvalidAccessError`; `type_error` the W3C's `TypeError` (both `max_packet_life_time` and `max_retransmits`); `syntax_error` the W3C's `SyntaxError` (an ICE server URL that cannot be parsed); `closed` the channel or the connection closed under a pending operation; `message_too_large` a message past `max_message_size`, sent or received; `buffered_amount_exceeded` a send that would pass `max_buffered_amount`; `receive_overflow` the browser's received bytes past `max_received_bytes`; `too_many_peer_connections` `make` past `max_peer_connections`. +The codes SHALL mean: `invalid_state` the W3C's `InvalidStateError` (a candidate before a remote description, a send on a channel that is not open, an operation on a closed connection); `operation_error` the W3C's `OperationError`, and natively a refusal of libdatachannel's C API with no more precise meaning; `invalid_access` the W3C's `InvalidAccessError`; `type_error` the W3C's `TypeError` (an argument out of its range); `syntax_error` the W3C's `SyntaxError` (an ICE server URL that cannot be parsed); `closed` the channel or the connection closed under a pending operation, or before a wait started; `message_too_large` a message past the size limit, sent or received; `buffered_amount_exceeded` a send that would pass `max_buffered_amount`; `receive_overflow` the browser's received bytes past `max_received_bytes`; `too_many_peer_connections` `make` past `max_peer_connections`; and in the browser a DOMException's `name` SHALL become the enumerator of that name, any other name `operation_error`, natively each negative code of the C API the code the browser gives for the same call. -#### Scenario: A send on a closed channel +#### Scenario: A send on a channel not open - **WHEN** `send` is called on a channel whose `ready_state()` is not `open` - **THEN** it returns `error::invalid_state` -#### Scenario: A libdatachannel exception -- **WHEN** libdatachannel throws during an operation on the native backend -- **THEN** the handler receives `error::operation_error` and no exception reaches the caller +#### Scenario: A refusal of libdatachannel +- **WHEN** libdatachannel's C API returns `RTC_ERR_INVALID` for a remote description it cannot parse +- **THEN** the handler receives `error::operation_error` and the program sees no exception ### Requirement: Errors: Asio's codes keep their meaning -The library SHALL use `boost::asio::error::operation_aborted` for an operation cancelled by `close()`, by destruction or by a cancellation slot, `boost::asio::error::already_started` for a second pending wait of one kind, and `boost::asio::error::operation_not_supported` for what a target cannot honour. +The library SHALL use, through `webcpp::asio::error`, `operation_aborted` for an operation cancelled by `close()`, by destruction or by a cancellation slot, `already_started` for a second pending wait of one kind, `operation_not_supported` for what a target cannot honour, and `no_buffer_space` for a message larger than the room left in the caller's dynamic buffer, which then stays queued. #### Scenario: Cancelled by a slot - **WHEN** an `async_receive` is cancelled through its cancellation slot -- **THEN** its handler runs with `operation_aborted` +- **THEN** its handler runs with `operation_aborted` and the next receive gets the next message + +#### Scenario: A buffer too small +- **WHEN** `async_receive` is given a buffer whose `max_size()` leaves 8 bytes for a 16-byte message +- **THEN** it completes with `no_buffer_space`, and a receive into a larger buffer then gets the 16 bytes -### Requirement: Semantics: terminal cancellation and the description operations -Every operation SHALL support terminal cancellation, and a cancelled `async_set_local_description` or `async_set_remote_description` in the browser, and a cancelled `async_set_local_description` natively, MUST be documented to leave its effect in place: the description is still applied, and that effect may happen after the handler ran with `operation_aborted`. +### Requirement: Semantics: cancellation per operation +Every operation SHALL install a handler on its associated cancellation slot, and SHALL honour terminal, partial and total cancellation for the waits, `async_receive`, `async_add_ice_candidate` and the sends, completing with `operation_aborted` and consuming nothing, and terminal cancellation only for `async_set_local_description` and `async_set_remote_description`, whose description MUST be documented to stay applied: the browser's promise cannot be cancelled, and its effect may happen after the handler ran. -#### Scenario: Cancel a description +#### Scenario: Cancel a description in the browser - **WHEN** `async_set_local_description` is cancelled before the browser's promise settles - **THEN** the handler runs with `operation_aborted` and `local_description()` may later return the description @@ -264,8 +275,8 @@ While no `async_wait_state_change` or `async_wait_ice_connection_state_change` i While no `async_wait_ice_candidate` is pending, the library SHALL queue candidates in the object's allocator up to `max_queued_candidates`; a candidate past the bound MUST NOT be queued, it is still in `local_description()`, and the end of gathering SHALL always be queued, in a place the bound keeps for it. #### Scenario: Past the bound -- **WHEN** 65 candidates arrive with `max_queued_candidates` 64 and no wait pending -- **THEN** 64 are queued, the 65th is not queued but appears in `local_description()`'s SDP, and the end of gathering is still delivered +- **WHEN** three candidates arrive with `max_queued_candidates` 2 and no wait pending, then the end of gathering +- **THEN** two are queued, the third is not, and the end of gathering is still delivered after them ### Requirement: Events: incoming channels queue, bounded While no `async_accept_data_channel` is pending, the library SHALL queue incoming channels in the object's allocator up to `max_queued_channels`, and a channel arriving past the bound MUST be closed at once, as a connection past a listen backlog is refused. @@ -275,18 +286,18 @@ While no `async_accept_data_channel` is pending, the library SHALL queue incomin - **THEN** 16 are queued and the 17th is closed at once ### Requirement: Events: the end of candidates -`async_wait_ice_candidate` SHALL complete successfully with an `ice_candidate` whose `candidate` is empty, the W3C's end-of-candidates form, when gathering ends (natively from `onGatheringStateChange` reaching `Complete`; in the browser from an `icecandidate` event whose candidate is null or empty), and this value MUST NOT be terminal: an ICE restart gathers again and the next wait completes with the next candidate. +`async_wait_ice_candidate` SHALL complete successfully with an `ice_candidate` whose `candidate` is empty, the W3C's end-of-candidates form, when gathering ends (natively when libdatachannel's gathering state reaches `RTC_GATHERING_COMPLETE`; in the browser from an `icecandidate` event whose candidate is null or empty), and this value MUST NOT be terminal: in the browser an ICE restart gathers again and the next wait completes with the next candidate. #### Scenario: Gathering completes - **WHEN** gathering finishes after three candidates - **THEN** the fourth wait completes with no error and an empty `candidate` ### Requirement: Events: one wait of a kind at a time -A second pending wait of the same kind on one object SHALL complete at once with `boost::asio::error::already_started`, and the first MUST be unaffected. +A second pending wait of the same kind on one object SHALL complete at once, posted, with `already_started`, and the first MUST be unaffected. -#### Scenario: Two candidate waits -- **WHEN** `async_wait_ice_candidate` is called twice without a candidate in between -- **THEN** the second completes with `already_started` and the first completes with the next candidate +#### Scenario: Two state waits +- **WHEN** `async_wait_state_change` is called twice without a change in between +- **THEN** the second completes with `already_started` and the first completes with the next change ### Requirement: Events: a cancelled wait consumes no event A cancelled wait SHALL consume no event: the next wait of its kind MUST get the event the cancelled one would have had. @@ -304,59 +315,59 @@ Waits that are already satisfied SHALL complete at once, posted: `async_wait_ope #### Scenario: Below the threshold - **WHEN** `buffered_amount()` is 0 and `async_wait_buffered_amount_low` is called -- **THEN** it completes at once with no error +- **THEN** it completes at once, posted, with no error ### Requirement: Events: a channel closing -When a data channel closes (the peer closed it, its connection closed, or its transport failed), its pending `async_wait_open`, `async_receive`, `async_send` and `async_wait_buffered_amount_low` SHALL complete with `error::closed`, `async_wait_close` SHALL complete successfully, and `ready_state()` MUST read `closed`. +When the peer closes a data channel, or its transport fails, the messages that arrived before SHALL still be delivered, then `async_receive` SHALL complete with `error::closed`; its pending `async_wait_open` and `async_wait_buffered_amount_low` SHALL complete with `error::closed`, `async_wait_close` SHALL complete successfully, and `ready_state()` MUST read `closed`. #### Scenario: The peer closes - **WHEN** the remote side closes a channel while a local `async_receive` is pending - **THEN** the receive completes with `error::closed`, a pending `async_wait_close` completes with no error, and `ready_state()` is `closed` ### Requirement: Events: close fires no state change -`basic_peer_connection::close()` SHALL close the connection and its channels, as the W3C's `close()` fire no state change, complete every pending operation of the connection with `operation_aborted` and leave `state()` reading `closed`, and the connection's channels SHALL then close with `error::closed` on their pending operations; `basic_data_channel::close()` SHALL complete the channel's pending operations with `operation_aborted` except `async_wait_close`, which completes once the channel is closed. +`basic_peer_connection::close()` SHALL close the connection and its channels, as the W3C's `close()` fire no state change, complete every pending operation of the connection with `operation_aborted`, leave `state()` reading `closed`, and complete a wait started afterwards with `error::closed`; the connection's channels SHALL then close with `error::closed` on their pending operations; `basic_data_channel::close()` SHALL complete the channel's pending operations with `operation_aborted` except `async_wait_close`, which completes once the channel is closed, and both MUST discard what is unread, as the W3C discards a message received once the channel left "open". #### Scenario: Connection close with a state wait pending - **WHEN** `close()` is called while `async_wait_state_change` is pending -- **THEN** the wait completes with `operation_aborted` and not with a `closed` state, and `state()` is `closed` +- **THEN** the wait completes with `operation_aborted` and not with a `closed` state, `state()` is `closed`, and a wait started afterwards completes with `error::closed` #### Scenario: Channel close with a receive pending - **WHEN** `close()` is called on a channel with a pending `async_receive` and a pending `async_wait_close` -- **THEN** the receive completes with `operation_aborted` and the close wait completes with no error once the channel is closed +- **THEN** the receive completes with `operation_aborted`, `ready_state()` reads `closing`, and the close wait completes with no error once the channel is closed ### Requirement: Lifetime: the execution context outlives the object -The execution context SHALL outlive every object made on its executor, as for Asio's I/O objects, which is what keeps a libdatachannel thread from posting to a destroyed `io_context`. +The execution context, the `runtime` and the object's allocator SHALL outlive every object made with them, as for Asio's I/O objects, which is what keeps a libdatachannel thread from posting to a destroyed `io_context`. #### Scenario: Documented order -- **WHEN** a program declares an `io_context`, a `runtime` and a `peer_connection` in that order -- **THEN** destruction runs in reverse (connection, runtime, context) and no handler touches freed state +- **WHEN** a program declares a memory resource, an `io_context`, a `runtime` and a `peer_connection` in that order +- **THEN** destruction runs in reverse and no handler touches freed state -### Requirement: Lifetime: native destruction is safe against foreign threads -On the native target, destroying a connection or channel SHALL call `resetCallbacks()` on the `rtc::PeerConnection` and on every `rtc::DataChannel` before releasing them, which synchronises with a callback in flight because each callback runs under its own recursive mutex, so that once it returns nothing more is posted, and what was posted before MUST find nothing, through a weak registration. +### Requirement: Lifetime: native destruction is synchronous with libdatachannel's threads +On the native target, destroying a channel SHALL call `rtcDeleteDataChannel` and destroying a connection `rtcDeletePeerConnection`, on the executor, which libdatachannel documents to block until every callback in flight returned and to call none afterwards, so that once it returns nothing more is posted, and what was posted before MUST find nothing, through a weak pointer. #### Scenario: Destroyed while messages arrive -- **WHEN** a connection is destroyed repeatedly while a peer floods a channel, under ThreadSanitizer +- **WHEN** a connection and its channel are destroyed while a peer floods the channel, repeatedly, under ThreadSanitizer - **THEN** no data race, use after free or handler call on a destroyed object is reported ### Requirement: Lifetime: browser destruction removes the registration -In the browser, destroying an object SHALL remove its registration with the bridge and set the JavaScript handlers to null. +In the browser, destroying an object SHALL remove its registration from the bridge and set the JavaScript handlers to null, and the io_context's shutdown SHALL destroy what waits on the object without calling it. #### Scenario: Event after destruction - **WHEN** the browser fires an event on an RTCDataChannel whose C++ object was destroyed - **THEN** no C++ handler runs and no error is raised ### Requirement: Lifetime: pending operations are outstanding work -A pending operation SHALL count as outstanding work on its handler's executor, as Asio's operations do, so that `run()` does not return while a candidate or a state change is awaited, and a program that re-arms its waits keeps `run()` alive until it closes the connection. +A pending operation SHALL count as outstanding work on the object's executor and on its handler's associated executor, as Asio's operations do, so that `run()` does not return while a candidate or a state change is awaited, and a program that re-arms its waits keeps `run()` alive until it closes the connection. #### Scenario: run() until close - **WHEN** a program waits for state changes in a loop and calls `close()` on the connection - **THEN** `run()` returns once the aborted wait's handler has run and does not re-arm ### Requirement: Messages: receive appends one whole message -`async_receive` SHALL append one whole message to the caller's dynamic buffer, copied once, and complete with the message's size and whether it was text, and messages MUST be kept from the channel's creation, so a channel accepted through `async_accept_data_channel` loses nothing it received before its first `async_receive`. +`async_receive` SHALL append one whole message to the caller's dynamic buffer and complete with the message's size and whether it was text, and messages MUST be kept from the channel's creation, so a channel accepted through `async_accept_data_channel`, or handed from one owner to another, loses nothing it received before its first `async_receive`. #### Scenario: Received before the first receive -- **WHEN** a channel is accepted and the peer's three messages arrive before `async_receive` is first called +- **WHEN** a channel opens and the peer's three messages arrive before `async_receive` is first called - **THEN** three successive receives return the three messages in order #### Scenario: Binary and text @@ -364,24 +375,28 @@ A pending operation SHALL count as outstanding work on its handler's executor, a - **THEN** the receives complete with (no error, 4, false) and (no error, 2, true) ### Requirement: Messages: native receive uses libdatachannel's queue -On the native target the library SHALL use libdatachannel's own queue in its pull mode (no `onMessage` callback; `receive()`, `availableAmount()` and `onAvailable`), bounded by 1,024 messages (libdatachannel's `RECV_QUEUE_LIMIT` at v0.24.6) each at most `max_message_size`, and past the bound libdatachannel's thread MUST wait for room, SCTP stops reading and the peer is slowed: flow control, never a failure. +On the native target the library SHALL use libdatachannel's own queue in its pull mode (no message callback; `rtcReceiveMessage`, `rtcGetAvailableAmount` and the available callback), bounded by 1,024 messages (libdatachannel's `RECV_QUEUE_LIMIT` at 0.24.6) each at most `max_message_size`, past which libdatachannel's thread waits for room and the peer is slowed, never a failure; the documentation MUST state the measured consequence that a channel never read stalls its connection's other channels, and the library MUST drain a channel's queue when its owner or its connection closes it and when it is destroyed, which releases the waiting thread. #### Scenario: A slow reader - **WHEN** a peer sends faster than the program calls `async_receive` for more than 1,024 messages - **THEN** no message is lost, no error is delivered, and the peer's sends slow down +#### Scenario: A channel never read +- **WHEN** 3,000 messages are sent on a channel that is never read, and a message is then sent on another channel of the same connection +- **THEN** the other message does not arrive until the first channel is destroyed, and its destruction returns in under two seconds + ### Requirement: Messages: emscripten receive is bounded in bytes -On the emscripten target the library SHALL keep unread messages in a queue of the channel in the object's allocator, filled from `onmessage` and bounded by `max_received_bytes`, and past the bound the channel MUST close and the pending or next `async_receive` complete with `error::receive_overflow`, because the browser has no flow control on receipt. +On the emscripten target the library SHALL keep unread messages in a queue of the channel in the object's allocator, staged by the bridge's `deliver` and charged at once, with each message's record, to `max_received_bytes`, as webcpp::beast's `queue_limits::receive` is, and past the bound the channel MUST close and the pending or next `async_receive` complete with `error::receive_overflow`, because the browser has no flow control on receipt. #### Scenario: Overflow -- **WHEN** unread messages in a browser channel exceed `max_received_bytes` +- **WHEN** unread messages and their records in a browser channel exceed `max_received_bytes`, the io_context being stopped meanwhile - **THEN** the channel closes and the next `async_receive` completes with `receive_overflow` ### Requirement: Messages: size limit -A message larger than `max_message_size` (default 256 KiB) SHALL fail as a value with `error::message_too_large`: on a send without closing the channel (the limit being the smaller of `max_message_size` and the peer's announced limit); natively on a receive it is refused by libdatachannel, which is told the limit as its local `Configuration::maxMessageSize` and announces it in the SDP; in the browser, which cannot announce it, a received message past it MUST close the channel and the pending or next `async_receive` complete with `message_too_large`. +A message larger than `max_message_size` (default 256 KiB) SHALL fail as a value with `error::message_too_large`: on a send without closing the channel (the limit being the smaller of `max_message_size` and the peer's announced limit); natively on a receive it is refused by libdatachannel, which is given the limit as its local `maxMessageSize` and announces it in the SDP; in the browser, which cannot announce it, a received message past it MUST close the channel and the pending or next `async_receive` complete with `message_too_large`. #### Scenario: Oversized send -- **WHEN** `send` is called with 262145 bytes and the default options +- **WHEN** `send` is called with 1025 bytes and `max_message_size` 1024 - **THEN** it returns `error::message_too_large` and the channel stays open #### Scenario: Oversized receive in the browser @@ -389,7 +404,7 @@ A message larger than `max_message_size` (default 256 KiB) SHALL fail as a value - **THEN** the channel closes and `async_receive` completes with `message_too_large` ### Requirement: Messages: send queues and returns -`send` and `send_text` SHALL queue the message and return an `error_code`, and `async_send` and `async_send_text` SHALL complete once it is queued, which on both targets is at once, posted; each MUST fail as a value with `invalid_state` when the channel is not open and with `buffered_amount_exceeded` when the message would pass `max_buffered_amount` (default 16 MiB). +`send` and `send_text` SHALL queue the message and return an `error_code`, and `async_send` and `async_send_text` SHALL complete once it is queued, which on both targets is at once, posted; each MUST fail as a value with `invalid_state` when the channel is not open and with `buffered_amount_exceeded` when the message would pass `max_buffered_amount` (default 16 MiB), leaving the channel open, unlike webcpp::beast's WebSocket, whose fragmented write cannot be taken back. #### Scenario: Not open - **WHEN** `send` is called on a channel in the `connecting` state @@ -397,109 +412,95 @@ A message larger than `max_message_size` (default 256 KiB) SHALL fail as a value #### Scenario: Buffer full - **WHEN** queued bytes plus the message would exceed `max_buffered_amount` -- **THEN** `send` returns `error::buffered_amount_exceeded` and the caller waits with `async_wait_buffered_amount_low` before sending again +- **THEN** `send` returns `error::buffered_amount_exceeded`, the channel stays open, and the caller waits with `async_wait_buffered_amount_low` before sending again ### Requirement: Messages: buffered amount and threshold `buffered_amount()` SHALL report the bytes queued and not yet sent, `set_buffered_amount_low_threshold(std::size_t)` SHALL set the threshold, and `async_wait_buffered_amount_low` SHALL complete when `buffered_amount()` is at or below it. #### Scenario: Pacing -- **WHEN** the threshold is 0, 1 MiB is queued and then drained -- **THEN** a pending `async_wait_buffered_amount_low` completes with no error once `buffered_amount()` is 0 +- **WHEN** a sender floods a channel until `send` returns `buffered_amount_exceeded` and then waits with a threshold of 16 KiB +- **THEN** the wait completes with no error once `buffered_amount()` falls to 16 KiB or below, and sending resumes ### Requirement: Allocation: run-time objects use the object's allocator -Every run-time object (the connection, its channels, their queues, and the text of `session_description`, `ice_candidate` and `label()`) SHALL be allocated through the object's `Allocator`, on the executor, while what libdatachannel and the browser hold (the `rtc::` objects, their strings and the messages in their queue, or `emscripten::val` in the JavaScript heap) remains theirs, and none of the types MUST be treated as shareable between processes. +The object's state, its queues and the text of `session_description`, `ice_candidate` and `label()` SHALL be allocated through the object's `Allocator`, on the executor, an operation's state through its handler's associated allocator, and what libdatachannel and the browser hold (the C API's maps and the messages in libdatachannel's queues, or `emscripten::val` in the JavaScript heap) remains theirs; none of the types is shareable between processes. #### Scenario: Counting resource -- **WHEN** a connection and a channel are made with a polymorphic allocator over a counting resource and a message cycle runs -- **THEN** the queues, descriptions, candidates and label are allocated from that resource, counting only what runs on the executor - -### Requirement: Exceptions: the native backend needs them -The native backend SHALL call libdatachannel only where exceptions are on: under `WEBCPP_WEBRTC_NO_EXCEPTIONS` the native headers MUST declare nothing after their `config.hpp` include (what follows sits inside `#ifndef WEBCPP_WEBRTC_NO_EXCEPTIONS`, with a comment naming libdatachannel), so that a native program built without exceptions that names `webcpp::webrtc::peer_connection` fails on that name and one that only includes the header compiles. - -#### Scenario: Include without exceptions -- **WHEN** a native translation unit built with `WEBCPP_WEBRTC_NO_EXCEPTIONS` only includes the library's headers -- **THEN** it compiles +- **WHEN** a connection pair and a channel are made with a polymorphic allocator over a counting resource and a message cycle runs +- **THEN** the resource counted allocations during the exchange, the description's text uses it, and none happened on another thread than the io_context's -#### Scenario: Naming the type without exceptions -- **WHEN** such a unit names `webcpp::webrtc::peer_connection` -- **THEN** the `webcpp.compile-diagnostic` test sees the compiler stop on that name +### Requirement: Exceptions: on and off on both targets +The library SHALL work with exceptions on and off on both targets, with `WEBCPP_WEBRTC_NO_EXCEPTIONS` in `config.hpp` as chapter 6 asks: natively it MUST call libdatachannel only through its C API, whose functions catch libdatachannel's exceptions and return negative codes, and in the browser its JavaScript imports MUST catch the browser's exceptions in JavaScript, before they reach a WebAssembly frame; no header of the library throws, tries or catches. -### Requirement: Exceptions: every libdatachannel call is caught -Inside the native backend, every call into libdatachannel that may throw SHALL be caught and become a value (`operation_error`, or the code the semantics name), and nothing MUST escape to the caller. +#### Scenario: The native suite without exceptions +- **WHEN** the native suite is built with `exception-handling=off` against the archives the superproject builds +- **THEN** it compiles with `-fno-exceptions` and passes whole -#### Scenario: A throwing call -- **WHEN** libdatachannel throws `std::invalid_argument` from an operation -- **THEN** the handler receives an error code and the program sees no exception - -### Requirement: Exceptions: the emscripten backend works with exceptions on and off -The emscripten backend SHALL raise no exception of its own, catch the browser's at the bridge, and be built and tested with exceptions both on and off. - -#### Scenario: Both builds -- **WHEN** the emscripten suites run in the exceptions-on and exceptions-off variants -- **THEN** both pass whole - -### Requirement: Exceptions: the documentation names the limit -The library's page and `config.hpp`'s Doc Comment SHALL name that the native backend needs exceptions and why (libdatachannel throws), and each headers-alone call, test and program of the native backend MUST declare `on`, with the reason in a comment, since b2 lets no usage requirement override a build's `exception-handling=off`. - -#### Scenario: Doc Comment -- **WHEN** `config.hpp` is read -- **THEN** its Doc Comment states that the native backend is unavailable under `WEBCPP_WEBRTC_NO_EXCEPTIONS` and names libdatachannel +#### Scenario: A malformed URL without exceptions +- **WHEN** a program built without exceptions makes a connection with the URL `stun:` +- **THEN** `make` returns `error::syntax_error` and the program goes on ### Requirement: Targets: what a target cannot honour -What one target cannot honour SHALL follow webcpp::beast's rule: with `WEBCPP_WEBRTC_UNSUPPORTED_ERROR` (the default) the operation fails with `boost::asio::error::operation_not_supported`, and with `WEBCPP_WEBRTC_UNSUPPORTED_IGNORE` the setting is ignored. +What one target cannot honour SHALL follow webcpp::beast's rule: with `WEBCPP_WEBRTC_UNSUPPORTED_ERROR` (the default) the operation fails with `operation_not_supported`, and with `WEBCPP_WEBRTC_UNSUPPORTED_IGNORE` the setting is ignored where the platform does an equivalent thing of its own; both macros defined MUST be an `#error`, the propagated b2 feature `webcpp-webrtc-unsupported=error|ignore` SHALL set one, and the browser classes SHALL live in an inline namespace named after the policy, so that translation units that disagree fail to link. #### Scenario: bind_address in the browser - **WHEN** `make` is called on emscripten with a non-empty `configuration::bind_address` -- **THEN** it fails with `operation_not_supported` under the default, and ignores the field under `WEBCPP_WEBRTC_UNSUPPORTED_IGNORE` +- **THEN** it fails with `operation_not_supported` under the default, and ignores the field under the ignore policy + +### Requirement: Targets: native limits +Natively a remote candidate's `username_fragment` SHALL be ignored, since libdatachannel keeps one ICE transport per connection and never restarts it, and a text message holding a zero MUST fail with `operation_not_supported` whatever the policy, since the C API takes a text as a zero-terminated string and ignoring it would truncate the message. + +#### Scenario: A text holding a zero +- **WHEN** `send_text` is called natively with a text that holds a zero byte +- **THEN** it returns `operation_not_supported` and sends nothing ### Requirement: Targets: bind_address natively `configuration::bind_address` SHALL make the native backend bind ICE to that address (libjuice only), an empty value meaning every interface but the loopback, and it is needed for loopback candidates. #### Scenario: Loopback -- **WHEN** a native peer is made with `bind_address` "127.0.0.1" -- **THEN** it offers a loopback host candidate, which libdatachannel does not offer otherwise +- **WHEN** two native peers are made with `bind_address` "127.0.0.1" and no ice server +- **THEN** they gather loopback host candidates and connect ### Requirement: Targets: candidate fields of a local candidate -A local candidate's `sdp_m_line_index` SHALL be `0` natively (`rtc::Candidate` has only a mid, and the connection's only m-line is the data channels') and the browser's own on emscripten, and its `username_fragment` SHALL be empty natively (`rtc::Candidate` does not expose it) and the browser's own on emscripten. +A local candidate's `sdp_m_line_index` SHALL be `0` natively (libdatachannel gives only a mid, and the connection's only m-line is the data channels') and the browser's own on emscripten, and its `username_fragment` SHALL be empty natively and the browser's own on emscripten. #### Scenario: Native local candidate - **WHEN** a native peer delivers a local candidate - **THEN** `sdp_m_line_index` is 0 and `username_fragment` is empty ### Requirement: Targets: negotiated and id are honoured on both -`data_channel_init::negotiated` and `id` SHALL be honoured on both targets (libdatachannel 0.24.6 and the browser both have them). +`data_channel_init::negotiated` and `id` SHALL be honoured on both targets (libdatachannel 0.24.6's C API, `manualStream` and `stream`, and the browser both have them). #### Scenario: Id on both -- **WHEN** a channel is created with `negotiated` true and `id` 5 natively and in the browser +- **WHEN** a channel is created with `negotiated` true and `id` 5 on both peers - **THEN** both channels use stream id 5 and open without a channel announcement ### Requirement: Interface: createOffer, createAnswer and negotiationneeded are not offered -The library MUST NOT offer `createOffer`, `createAnswer` or the `negotiationneeded` event on either target: libdatachannel marks the first two "for specific use cases only" and its `setLocalDescription` takes a type, not a description, so a description so created cannot be applied as the W3C allows, and it has no such event, only the query; automatic negotiation SHALL be off natively (`disableAutoNegotiation`), so on both targets a description exists only when `async_set_local_description` asks for one and the program negotiates when it adds a channel. +The library MUST NOT offer `createOffer`, `createAnswer` or the `negotiationneeded` event on either target: libdatachannel marks the first two "for specific use cases only" and its `setLocalDescription` takes a type, not a description, and it has no such event, only a query; automatic negotiation SHALL be off natively (`disableAutoNegotiation`), so on both targets a description exists only when `async_set_local_description` asks for one and the program negotiates when it adds a channel. #### Scenario: Adding a channel does not negotiate - **WHEN** a program calls `create_data_channel` on a fresh connection and does nothing else -- **THEN** no description is produced and no event is delivered until `async_set_local_description` is awaited +- **THEN** `local_description()` is empty until `async_set_local_description` is awaited ### Requirement: Documentation: the table of differences -The library's documentation SHALL keep the table of differences between the targets: `bind_address`, local `sdp_m_line_index`, local `username_fragment`, a received message past `max_message_size`, unread received messages, `createOffer`/`createAnswer`/`negotiationneeded`, and a native handle, each with what native and emscripten do. +The library's documentation SHALL keep the table of differences between the targets: `bind_address`, local `sdp_m_line_index`, local `username_fragment`, a remote `username_fragment` natively, a text holding a zero natively, a received message past `max_message_size`, unread received messages and the stall of a channel never read natively, `createOffer`/`createAnswer`/`negotiationneeded`, and a native handle, each with what native and emscripten do. #### Scenario: The table exists - **WHEN** the documentation page is built -- **THEN** it contains the table with those seven rows +- **THEN** it contains the table with those rows ### Requirement: Documentation: libdatachannel is justified -The documentation SHALL justify libdatachannel as the superproject's rule for a third-party dependency asks: no WebRTC exists in webcpp, Boost, the C++ Alliance or the standard library, libdatachannel is the smallest complete implementation (data channels without the media stack), licensed MPL-2.0, with its own OpenSSL or mbedTLS for DTLS, and webcpp uses it unmodified, as a dependency, and copies none of its files. +The documentation SHALL justify libdatachannel as the superproject's rule for a library from outside asks: no WebRTC exists in webcpp, Boost, the C++ Alliance or the standard library, libdatachannel is the smallest complete implementation (data channels without a media engine), its DTLS runs on the same source-built OpenSSL as Asio and Beast, it is licensed MPL-2.0, accepted by the owner on 2026-11-14 for this use, with its nested dependencies under their own licences, and webcpp uses it unmodified, as a dependency, and copies none of its files. #### Scenario: The justification - **WHEN** the library's page is read -- **THEN** it states the licence, the version 0.24.6, that the library is unmodified and not copied, and why nothing else qualifies +- **THEN** it states the licence and its acceptance, the version 0.24.6 and its pin, that the library is unmodified and not copied, and why nothing else qualifies -### Requirement: Dependencies: libdatachannel is found, not pinned, today -The native build SHALL find libdatachannel 0.24.6 where `-sLIBDATACHANNEL_ROOT=` or the superproject's `.local/libdatachannel` says, as trystero's does, and webcpp MUST pin it when it builds it from `third_party/`; its MPL-2.0 licence is for the owner to accept before the library is published. +### Requirement: Dependencies: libdatachannel is pinned and built from its sources +The native build SHALL link the superproject's pinned libdatachannel, 0.24.6 at `6b1e2e6` in `third_party/libs/libdatachannel` with its nested sources at the gitlinks of `tools/libdatachannel/pin.json`, through `/webcpp/third_party//libdatachannel`, built as static archives by upstream CMake through B2 against the same source-built OpenSSL as Asio and Beast, and a native consumer MUST build with `threading=multi`; no installed copy is looked for. -#### Scenario: The variable -- **WHEN** b2 is run with `-sLIBDATACHANNEL_ROOT=` for a native lane -- **THEN** the lane links the libdatachannel found in that directory +#### Scenario: A native lane +- **WHEN** b2 builds a native test of the library with `threading=multi` +- **THEN** it links the archives B2 built from `third_party/libs/libdatachannel`, and no `LIBDATACHANNEL_ROOT` or `.local/libdatachannel` is read ### Requirement: Integration: it knows nothing of xactor The library MUST NOT depend on xactor; an xactor actor that needs a peer SHALL hold a `peer_connection` made on the executor its driver runs on, start operations from its turns, and turn each completion into a message to itself. @@ -509,7 +510,7 @@ The library MUST NOT depend on xactor; an xactor actor that needs a peer SHALL h - **THEN** none is from `` ### Requirement: Integration: every part of trystero's backend has a home -The interface SHALL cover every part of trystero's `backend` that touches WebRTC: `make` as a `result` instead of a null factory; descriptions as values; candidates as values, not JSON; `async_wait_ice_candidate`, `async_accept_data_channel`, `async_wait_state_change` and `async_wait_ice_connection_state_change` instead of handlers, with both states separate and trystero merging them; `create_data_channel` as a `result`; `ready_state()` for `is_open`; the channel waits for open, message, close and buffered-amount-low; synchronous and asynchronous sends failing as values when not open; `buffered_amount()` and the threshold; `configuration::bind_address`; the cap through `runtime_options::max_peer_connections`; and no native handle; while trystero's per-minute window of connections and its dropping of text messages and oversized binaries SHALL stay trystero's. +The interface SHALL cover every part of trystero's `backend` at trystero `e9326e9` that touches WebRTC, as `design.md`'s table maps it: `make` as a `result` instead of a null factory; descriptions as values; candidates as values, not JSON; the waits instead of handlers, with both states separate and trystero merging them; `create_data_channel` as a `result`; `ready_state()` for `is_open`; the channel waits for open, message, close and buffered-amount-low; synchronous and asynchronous sends failing as values when not open; `buffered_amount()` and the threshold; `configuration::bind_address`; the cap through `runtime_options::max_peer_connections`; messages kept from a channel's creation, which trystero's adoption of a shared connection and its native frames before a handler need; and no native handle; while trystero's shared connection, its bound of 64 frames and 10 seconds, its per-minute window of connections and its dropping of text messages and oversized binaries SHALL stay trystero's. #### Scenario: The merge of states - **WHEN** trystero needs one state out of `connectionState` and `iceConnectionState` @@ -524,20 +525,20 @@ Every test lane SHALL run on native and on emscripten, both suspension variants #### Scenario: A full exchange - **WHEN** the lane runs two peers in one process -- **THEN** an offer and an answer are exchanged, candidates are trickled to the end, a channel opens, a binary and a text message cross in both directions, and both sides close +- **THEN** an offer and an answer are exchanged, candidates are trickled to the end, a channel opens, binary and text messages cross in both directions, and both sides close ### Requirement: Testing: every case the semantics names has a test -The test suites SHALL contain a test for each case the semantics name: two waits of one kind, a cancelled wait consuming nothing, `async_wait_open` on a channel already open, a pending receive completing with `closed`, `close()` firing no state change, the coalescing of states, the candidate and channel bounds, a message past `max_message_size`, the browser's `max_received_bytes`, `make` past the runtime's cap, and a channel accepted that received before its first `async_receive`. +The test suites SHALL contain a test for each case the semantics name: two waits of one kind, a cancelled wait consuming nothing, `async_wait_open` on a channel already open, a pending receive completing with `closed`, `close()` firing no state change, the coalescing of states, the candidate and channel bounds, a message past `max_message_size`, a message past the room of the caller's buffer, the browser's `max_received_bytes`, `make` past the runtime's cap, a channel accepted that received before its first `async_receive`, and a native channel never read stalling the others. #### Scenario: The list is covered -- **WHEN** the suites' test names are compared with the eleven cases above +- **WHEN** the suites' test names are compared with the cases above - **THEN** each has a test on the targets where it applies ### Requirement: Testing: native lifetime -The native lane SHALL test destruction while libdatachannel's threads are delivering events, repeated, under ThreadSanitizer; that `run()` returns only once the connection is closed; and that the `runtime` stops libdatachannel's threads before `main` returns. +The native lane SHALL test destruction while libdatachannel's threads are delivering events, repeated, under ThreadSanitizer; that `run()` returns only once the connection is closed; that a flooded channel's destruction returns promptly; and that the `runtime` stops libdatachannel's threads before `main` returns. #### Scenario: Repeated destruction -- **WHEN** a loop creates a connection pair, floods a channel and destroys one side, 1,000 times, under ThreadSanitizer +- **WHEN** a loop creates a connection pair, floods a channel and destroys one side, 100 times, under ThreadSanitizer - **THEN** ThreadSanitizer reports nothing ### Requirement: Testing: native and browser peers interoperate @@ -548,11 +549,11 @@ An interop lane SHALL connect a native peer and a headless-Chrome peer through a - **THEN** both are received, in both the `jspi` and the `asyncify` page ### Requirement: Testing: allocation and exceptions lanes -The allocation lane SHALL prove with a counting resource that the queues, descriptions, candidates and labels use the object's allocator (natively counting only what runs on the executor), and the exceptions lane SHALL run the emscripten suites whole with exceptions on and off, and natively a headers-alone translation unit proving the native headers compile without exceptions and a `webcpp.compile-diagnostic` test proving that naming `webcpp::webrtc::peer_connection` stops at that name. +The allocation lane SHALL prove with a counting resource that the queues, descriptions, candidates and labels use the object's allocator (natively none of it on libdatachannel's threads), and the exceptions lane SHALL run the native and emscripten suites whole with exceptions on and with `exception-handling=off`. -#### Scenario: Compile diagnostic -- **WHEN** the diagnostic test compiles a unit naming `peer_connection` under `WEBCPP_WEBRTC_NO_EXCEPTIONS` -- **THEN** compilation fails and the test passes +#### Scenario: Both builds natively +- **WHEN** the native suite runs as the build asks and with `exception-handling=off` +- **THEN** both pass ### Requirement: Testing: no network beyond loopback CI SHALL gather ICE with host candidates only and use no STUN or TURN server. @@ -562,15 +563,15 @@ CI SHALL gather ICE with host candidates only and use no STUN or TURN server. - **THEN** every test configuration has an empty `ice_servers` ### Requirement: Delivery: three increments -The library SHALL be built in three increments: (1) the interface, the `runtime` and the native implementation with their tests; (2) the browser implementation with its tests and the interop lane; (3) trystero on webcpp::webrtc, with webcpp::asio and webcpp::crypto, its `backend` gone, trystero keeping its dropping of text messages and of messages larger than a room frame and its per-minute window of connections. +The library SHALL be built in three increments: (1) the interface, the `runtime` and the native implementation with their tests; (2) the browser implementation with its tests and the interop lane; (3) trystero on webcpp::webrtc, with webcpp::asio, webcpp::beast for its relays and webcpp::crypto, its `backend`'s WebRTC gone, trystero keeping its policies. #### Scenario: Order - **WHEN** the tasks are read - **THEN** increment 2 follows increment 1 and increment 3 is a change of trystero's ### Requirement: Delivery: the review's answers -The design SHALL provide no zero-copy receive for now (in the browser the bytes must leave the JavaScript heap anyway, and natively `rtc::binary` is a `std::vector` in libdatachannel's allocator, so the one copy into the caller's buffer puts the bytes under the user's allocator) and SHALL provide separate event operations with the policies above rather than one wait returning a variant. +The design SHALL provide no zero-copy receive for now (in the browser the bytes must leave the JavaScript heap anyway, and natively they leave libdatachannel's queue by one copy into the caller's buffer) and SHALL provide separate event operations with the policies above rather than one wait returning a variant. -#### Scenario: One copy -- **WHEN** a message is received natively -- **THEN** the only copy the library makes of its bytes is the one into the caller's dynamic buffer +#### Scenario: One copy into the caller's buffer +- **WHEN** a message is received natively into a dynamic buffer that offers one contiguous region for it +- **THEN** the library copies its bytes once, from libdatachannel's queue into that region diff --git a/libraries/webrtc/openspec/changes/genesis/tasks.md b/libraries/webrtc/openspec/changes/genesis/tasks.md index 8a8b882..24a8cdf 100644 --- a/libraries/webrtc/openspec/changes/genesis/tasks.md +++ b/libraries/webrtc/openspec/changes/genesis/tasks.md @@ -1,46 +1,49 @@ # Tasks -Nothing is built. There is no plan and no reference code: group 0 writes them, and the proposal -is not accepted before it is done. Sections cited are those of `reference/spec.md`. A checked -task is done. +Each task points to its section in `reference/plan.md`, which holds its files, interfaces, tests +and expected output. A checked task of group 0 is done in this proposal; a checked task of an +increment is done in `reference/source/`, built and tested as `reference/STATUS.md` records. ## 0. Before the proposal can be accepted -- [ ] 0.1 Write `reference/plan.md`: the implementation plan, one task per step with its files, interfaces, steps, code and expected output, in the three increments of section 10 -- [ ] 0.2 Write the reference code: the interface of section 4 (types, `runtime`, `basic_peer_connection`, `basic_data_channel`, `error`) and a first native implementation over libdatachannel, as files under `reference/source/`, with the tests of section 8 it passes; then update `reference/STATUS.md` -- [ ] 0.3 Obtain the owner's decisions of section 11: libdatachannel's MPL-2.0 licence, and whether the no-exceptions message is the compiler's or a stub's -- [ ] 0.4 Check the draft against webcpp::asio's genesis (its bridge and the executors) and against trystero's genesis (its `backend`, section 3's table), and fix any difference +- [x] 0.1 Write `reference/plan.md`: the implementation plan in the three increments, one task per step with its files, interfaces, tests and expected output, done 2026-11-14 +- [x] 0.2 Write the reference code: the interface (types, `runtime`, `basic_peer_connection`, `basic_data_channel`, `error`) and the native implementation over libdatachannel's C API, under `reference/source/`, with the native tests it passes against the superproject's pinned libdatachannel; update `reference/STATUS.md`, done 2026-11-14 +- [x] 0.3 Obtain the owner's decisions: libdatachannel's MPL-2.0 licence, accepted; and, in place of the question on the compile-time message without exceptions, the native backend on libdatachannel's C API, so that the library works with exceptions on and off (design.md, D4 and D16), done 2026-11-14 +- [x] 0.4 Check the draft against webcpp::asio's genesis and its built bridge, against webcpp::beast's browser WebSocket as built (its D3, D7, D9 to D12), and against trystero's `backend` at `e9326e9` with the shared connection and the preservation of early native frames; fix every difference or say why it stays (design.md, "What changed since the specification"), done 2026-11-14 - [x] 0.5 The draft specification, with the owner's decisions of 2026-10-10 and the controller's rulings on the review (section 2), done 2026-10-10 (`reference/spec.md`) - [x] 0.6 The review's answers: no zero-copy receive for now, and separate event operations with the policies of section 5.2 (section 10), done 2026-10-10 +- [x] 0.7 Record the owner's decision that webcpp::webrtc stays a library of its own on webcpp::asio, not a part of webcpp::beast, with its reasons (design.md, D1), done 2026-11-14 +- [x] 0.8 Propose: the status `proposed`, the pull request, the public discussion (the owner's), done 2026-11-14 on webcpporg/proposals#12, where the discussion is held ## 1. Increment 1: the interface, the `runtime` and the native implementation -- [ ] 1.1 The repository `webcpporg/webrtc` as a superproject submodule: `build.jam`, `meta/libraries.json`, `config.hpp` (includes ``, defines `WEBCPP_WEBRTC_NO_EXCEPTIONS`, the `UNSUPPORTED_*` macros, the `#error` under `__wasi__`), the configuration test built three times -- [ ] 1.2 The enumerations and the input and output value types of section 4 (`sdp_type`, the states, `ice_transport_policy`, `ice_server`, `configuration`, `session_description_view`, `ice_candidate_view`, `data_channel_init`, `basic_session_description`, `basic_ice_candidate`) -- [ ] 1.3 `options` and `runtime_options`, and the `error` category `webcpp.webrtc` with its ten enumerators (section 5.1) -- [ ] 1.4 The event machinery common to both backends: the coalescing of states, the bounded queues, one wait of a kind, the cancelled wait that consumes nothing (section 5.2), testable without a platform -- [ ] 1.5 The native `runtime`: thread pool size, `rtc::Cleanup()` on destruction, one at a time, the count of peer connections (section 5.3) -- [ ] 1.6 The native `basic_peer_connection`: `make`, descriptions, candidates and the end of candidates, states, `create_data_channel`, `async_accept_data_channel`, `close`, destruction with `resetCallbacks()` (sections 5.1 to 5.3) -- [ ] 1.7 The native `basic_data_channel`: open, close, receive in libdatachannel's pull mode, send, text, buffered amount, `max_message_size` and `max_buffered_amount` (section 5.4) -- [ ] 1.8 Native exceptions: every call into libdatachannel caught and turned into a value; the native headers declare nothing under `WEBCPP_WEBRTC_NO_EXCEPTIONS`; the headers-alone and `webcpp.compile-diagnostic` tests (section 6) -- [ ] 1.9 Native tests: two peers in one process, every case section 8 names, allocation through a counting resource, destruction under ThreadSanitizer, `run()` returning only once closed, the `runtime` stopping libdatachannel's threads before `main` returns -- [ ] 1.10 Measure whether a never-read native channel stalls the connection's other channels (section 5.4) and record the finding in the documentation -- [ ] 1.11 Documentation: the library's page, libdatachannel's justification, the table of differences (section 7), Doc Comments, the reference, examples -- [ ] 1.12 Lint, the lanes that apply to a native-only increment, and the review; increment 1 complete +- [x] 1.1 The library's build: `build.jam` with `//headers`, `//webrtc` and the feature `webcpp-webrtc-unsupported`, `meta/libraries.json`, `config.hpp` with `WEBCPP_WEBRTC_NO_EXCEPTIONS`, the unsupported policy and the `#error` under WASI, the configuration test built three times (plan: Task 1.1) +- [x] 1.2 The enumerations and the input and output value types (plan: Task 1.2) +- [x] 1.3 `options` and `runtime_options`, and the `error` category `webcpp.webrtc` with its ten enumerators (plan: Task 1.3) +- [x] 1.4 The event machinery common to both backends: pending operations in the handler's allocator with their work and cancellation, the coalescing of states, the bounded queues, one wait of a kind, the cancelled wait that consumes nothing; tested without a platform, with exceptions on and off (plan: Task 1.4) +- [x] 1.5 The native `runtime`: thread pool size, `rtcPreload` and `rtcCleanup`, the count of peer connections; one at a time a precondition (plan: Task 1.5) +- [x] 1.6 The native `basic_peer_connection` over the C API: `make`, descriptions, candidates and the end of candidates, states, `create_data_channel`, `async_accept_data_channel`, `close`, destruction through `rtcDeletePeerConnection` (plan: Task 1.6) +- [x] 1.7 The native `basic_data_channel`: open, close, receive in libdatachannel's pull mode, send, text, buffered amount, the bounds, the drain on close and destruction (plan: Task 1.7) +- [x] 1.8 Exceptions: the native suite passes built with `exception-handling=off`; no header throws, tries or catches (plan: Task 1.8) +- [x] 1.9 Native tests: two peers in one process, the cases the semantics name, allocation through a counting resource, destruction under ThreadSanitizer, `run()` returning only once closed (plan: Task 1.9) +- [x] 1.10 Measure whether a never-read native channel stalls the connection's other channels: it does, and destroying it releases them; pinned by `test/stall_test.cpp` (plan: Task 1.10) +- [ ] 1.11 Measure the C API's cost on receipt against the C++ API's `receive()`, and state the ratio in the documentation (plan: Task 1.11) +- [ ] 1.12 Documentation: the library's page, libdatachannel's justification and licence, the table of differences, the cancellation and error tables, Doc Comments checked by MrDocs, examples (plan: Task 1.12) +- [ ] 1.13 The repository `webcpporg/webrtc` from one import commit, the superproject's change (submodule, lanes, the libdatachannel target's message, chapter 15), the whole lint, the lanes of a native-only increment, the review (plan: Task 1.13) ## 2. Increment 2: the browser implementation and the interop lane -- [ ] 2.1 Wait for webcpp::asio's bridge and suspension variants (its genesis), and take their names -- [ ] 2.2 The emscripten `runtime`: the page's census of `RTCPeerConnection`s kept in JavaScript, `max_peer_connections` -- [ ] 2.3 The emscripten `basic_peer_connection`: descriptions through promises, candidates, states, channels, events entering through the bridge, the registration removed and the handlers nulled on destruction (sections 5.1 to 5.3) -- [ ] 2.4 The emscripten `basic_data_channel`: the byte-bounded receive queue and `receive_overflow`, `message_too_large` closing the channel, send, buffered amount (section 5.4) -- [ ] 2.5 `bind_address` and the other differences of section 7 under `WEBCPP_WEBRTC_UNSUPPORTED_ERROR` and `WEBCPP_WEBRTC_UNSUPPORTED_IGNORE` -- [ ] 2.6 Emscripten tests: every case of section 8 in one page, both suspension variants, exceptions on and off, allocation -- [ ] 2.7 The interop lane: a native peer and a headless-Chrome peer, signalled through a local relay, with Chrome's two flags and `bind_address` `127.0.0.1`, both suspension variants -- [ ] 2.8 Lint, all lanes, the review; increment 2 complete +- [ ] 2.1 The browser imports, `EM_ASM` in inline functions that catch JavaScript's exceptions in JavaScript, as webcpp::beast's (plan: Task 2.1) +- [ ] 2.2 The emscripten `runtime`: the page's census of `RTCPeerConnection`s kept in JavaScript, `max_peer_connections` (plan: Task 2.2) +- [ ] 2.3 The emscripten `basic_peer_connection`: one intrusive registration of webcpp::asio's bridge, staged arrivals and one notification, promises followed through the bridge, errors by name, destruction and shutdown (plan: Task 2.3) +- [ ] 2.4 The emscripten `basic_data_channel`: the receive queue charged on arrival to `max_received_bytes`, `receive_overflow`, `message_too_large` closing the channel, sends refused before the browser sees them (plan: Task 2.4) +- [ ] 2.5 `bind_address` and the other differences under the unsupported policy, its inline namespace and its link test (plan: Task 2.5) +- [ ] 2.6 Emscripten tests: every applicable case in one page, both suspension variants, exceptions on and off, allocation (plan: Task 2.6) +- [ ] 2.7 The interop lane: a native peer and a headless-Chrome peer, signalled through a local relay, with Chrome's two flags and `bind_address` `127.0.0.1`, both suspension variants (plan: Task 2.7) +- [ ] 2.8 Lint, all lanes, the review; increment 2 complete (plan: Task 2.8) ## 3. Increment 3: trystero on webcpp::webrtc -- [ ] 3.1 A change of trystero's (its own proposal) that replaces `backend`, `native/peer_connection.hpp`, `native/data_channel.hpp` and `browser/backend.hpp` with this library, using the table of section 3 -- [ ] 3.2 trystero keeps its policies: dropping text messages, dropping binaries larger than a room frame, its per-minute window of connections, and the merge of the two states -- [ ] 3.3 trystero's native and browser suites pass unchanged on the new library; its `backend` is gone; webcpp::webrtc is recorded as its dependency +- [ ] 3.1 A change of trystero's (its own proposal) that replaces the WebRTC of its `backend`, `native/peer_connection.hpp`, `native/data_channel.hpp` and `browser/backend.hpp` with this library, using design.md's table "trystero's backend, part by part" (plan: Increment 3, step 1) +- [ ] 3.2 trystero keeps its policies: the shared connection and its adoption, dropping text messages and binaries larger than a room frame, the bound of 64 frames and 10 seconds, its per-minute window of connections, and the merge of the two states (plan: Increment 3, step 2) +- [ ] 3.3 trystero's native and browser suites pass unchanged on the new library; webcpp::webrtc is recorded as its dependency (plan: Increment 3, step 3)