diff --git a/AGENTS.md b/AGENTS.md index c721dc3..0d31605 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,32 +51,43 @@ holds only what is specific to trystero. alone in a call of their own, without it, so the lint analyses the timer, the sealer and the WebSockets without exceptions too. trystero raises nothing of its own; a raise would go through `boost::throw_exception`. -- **The external dependencies.** libsecp256k1 (every room), libdatachannel - and OpenSSL (the native backend) are not part of Boost. `build.jam` finds - them with webcpp's `webcpp.external` and `webcpp.external-found` - (`tools/webcpp.jam`): where `-sSECP256K1_ROOT=`, - `-sSECP256K1_EMSCRIPTEN_ROOT=`, `-sLIBDATACHANNEL_ROOT=` and - `-sOPENSSL_ROOT=` on b2's command line say, a relative one from b2's - working directory, never the environment, - else in the superproject's `.local/secp256k1-native`, - `.local/secp256k1-emscripten`, `.local/libdatachannel` and - `.local/openssl` when it holds the library's header, where webcpp's CI - actions install them, until webcpp builds them from `third_party/`; so the - reference and the lint need no `-s`. A library found in neither is looked - for, natively outside Windows, in `/usr/include` or `/usr/local/include`, - where a system install is legitimate. A `-s` - that names a directory without its library's header stops the build, - naming it. A library that no candidate holds leaves trystero out, its - targets skipped, with one message that names the library and every place - it looked, so that `b2 test` builds every other library; with - `webcpp-require-external=on`, as the CI builds, it stops the build - instead. With MSVC the names are CMake's and Shining - Light's: `libsecp256k1`, linked with `SECP256K1_STATIC` defined, which a - static libsecp256k1 needs on Windows, and `libssl` and `libcrypto`, also - searched in `lib/VC/x64/MD`. libdatachannel is a - C++ library: it must be built with the same standard library as the - program that links it (libc++ for clang on macOS, libstdc++ for GCC), or - the program does not link, though the native headers still compile alone. +- **The dependencies.** libsecp256k1 (every room) remains an external + installation, found through `webcpp.external` and `webcpp.external-found` + at `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=`, then + `.local/secp256k1-native` or `.local/secp256k1-emscripten`. Native system + fallback outside Windows is allowed only for this dependency. A missing + installation leaves trystero out unless `webcpp-require-external=on`. + MSVC links its static `libsecp256k1.lib` with `SECP256K1_STATIC`. + The native backend instead names `/webcpp/third_party//libdatachannel`, + which builds pinned libdatachannel 0.24.6, libjuice, usrsctp and libsrtp as + separate static archives against `/webcpp/third_party//openssl` and its + matching generated headers. These are the same OpenSSL target used by + Asio and Beast, so a combined application has one provider. No + `LIBDATACHANNEL_ROOT`, `OPENSSL_ROOT` or installed binary is consulted. + Initialize their sources with `git submodule update --init --recursive + third_party/libs/libdatachannel third_party/libs/openssl`. Native builds + need CMake 3.21 or newer in addition to OpenSSL's Perl and Make/nmake. + B2 forwards the configured compiler, C++ ABI, runtime and optimization + flags, and isolates artifacts by their effective configuration. The + upstream source trees stay unchanged; verified staged copies are built. +- **Native threading.** libdatachannel always uses worker threads, so every + consumer of `/webcpp/trystero//native` must declare `multi`, + including native headers-alone and reference targets. An explicit + single-threaded native backend fails with an actionable B2 diagnostic. + Asio and Beast still support their own single-threaded OpenSSL builds. +- **Native channel handoff.** Valid frames received before a message handler + is installed wait in an app-resource FIFO, at most 64 frames for 10 s from + the first. Overflow or expiry closes the channel; close clears the queue. + `native/timer.hpp` holds the existing `native::timer`, still included by + `native/backend.hpp`, whose generation invalidates queued expiries. + Installing a receiver posts a resource-allocated flush, never an inline + call. Each frame checks the current handler and open channel, and a message + already posted ahead of the flush drains older frames when a receiver + exists. A transport closed during adoption, before binding, forgets its + negotiation and restarts announcements. `native_peer_connection` tests + real queued callbacks, FIFO, replacement, close, limits and resource release; + `shared` tests closure during adoption, and interop controls native open + delivery while a JS peer sends both rooms' presence first. - **embind.** Every program on emscripten links `-lembind`, which `/webcpp/trystero//trystero` adds as a linker flag: `on`, b2's own feature, is not free, and b2 ignores it among usage requirements. @@ -278,6 +289,15 @@ holds only what is specific to trystero. while another room pings; (9) a held handshake frame recovering in both id orders with no false password report. Crossed adoption races allow retries but fail by connection count above four constructions per side. + - Recovered-peer relay scenarios wait for fresh, currently joined peers on + both sides within the existing 30 s setup bound, then require a fresh + round-trip message before injecting a relay fault. A join reported by one + side alone does not prove the other's handshake completed. The controlled + `delayNextRecovery` fixture delays one outbound direction of the first + recovered channel for 12 s, beyond the C++ handshake deadline; a subsequent + connection must complete the setup. A departure after the relay fault + still fails. Console errors remain fatal, with RTCError fields recorded + alongside peer events so a failure is not reduced to `OperationError`. - Every peer gathers its ICE candidates on the machine alone: the C++ peers get `stun:127.0.0.1:9`, where nothing answers, in place of Trystero's public STUN servers, the native peer binds its connections to diff --git a/README.md b/README.md index 08d8dab..7bec36d 100644 --- a/README.md +++ b/README.md @@ -64,16 +64,16 @@ send a wrong room proof, reported by the lower id only. ## Building inside the superproject trystero is developed inside the webcpp superproject, as a Boost library is -developed inside Boost. Besides Boost, it needs three libraries that are not -part of it, until webcpp builds them from `third_party/`: +developed inside Boost. Its TLS and WebRTC dependencies are built from +pinned sources; only libsecp256k1 needs an external installation: | Library | Needed by | Found where | | --- | --- | --- | | libsecp256k1 0.8.0, with its `schnorrsig` and `extrakeys` modules | every room: it signs the Nostr events peers meet through | `-sSECP256K1_ROOT=` natively, `-sSECP256K1_EMSCRIPTEN_ROOT=` for its emscripten build, else `.local/secp256k1-native` and `.local/secp256k1-emscripten` | -| libdatachannel 0.24.6 | the native backend | `-sLIBDATACHANNEL_ROOT=`, else `.local/libdatachannel` | -| OpenSSL 3 | the native backend | `-sOPENSSL_ROOT=`, else `.local/openssl` | +| libdatachannel 0.24.6 | the native backend | `/webcpp/third_party//libdatachannel`, from pinned source submodules | +| OpenSSL 3.5.9 | the native backend | `/webcpp/third_party//openssl`, also used by Asio and Beast | -Each `-s`, on b2's command line, names a directory with the library's +The libsecp256k1 `-s` option, on b2's command line, names a directory with the library's `include/` and `lib/`; the environment is never read. Without it, the library is looked for in the superproject's `.local/` directory the table names, where webcpp's CI installs it, and else, natively outside Windows, in @@ -95,7 +95,7 @@ project uses the rooms and the browser backend through libsecp256k1 and Boost.JSON's definitions, compiled once per variant, and on emscripten embind and `BOOST_ASIO_DISABLE_THREADS`. A native program uses `/webcpp/trystero//native`, which adds libdatachannel and OpenSSL, and -declares `on` itself, as `example/Jamfile` does: b2 lets +declares `multi` and `on` itself, as `example/Jamfile` does: b2 lets no usage requirement override a build's `exception-handling=off`. ## The examples @@ -189,7 +189,7 @@ struct application { ``` webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//native on : native ; + : /webcpp/trystero//native multi on : native ; ``` @@ -212,11 +212,11 @@ says otherwise. ### 1. Install the tools -git, CMake, clang (the Xcode command line tools), Python 3, Node, OpenSSL 3, -Boost 1.92 and b2: +git, CMake 3.21 or newer, clang (the Xcode command line tools), Python 3, +Node, Perl, Make, Boost 1.92 and b2: ```sh -brew install cmake openssl@3 boost boost-build node +brew install cmake boost boost-build node ``` ### 2. Create a workspace @@ -262,28 +262,22 @@ cmake --build build-secp256k1-native && cmake --install build-secp256k1-native cmake --build build-secp256k1-emscripten && cmake --install build-secp256k1-emscripten ``` -### 6. Build libdatachannel +### 6. Initialize the native dependencies -libdatachannel's CMake finds OpenSSL where `OPENSSL_ROOT_DIR` says, which -Homebrew's OpenSSL needs, and the build where `webcpp/.local/openssl` links. It is built with the compiler that builds the -programs, clang: a program built with GCC and libstdc++ does not link against -a libdatachannel built with libc++. +The recursive checkout already includes pinned OpenSSL, libdatachannel, +libjuice, usrsctp, plog and libsrtp sources. For an existing checkout: ```sh -openssl=$(brew --prefix openssl@3) -ln -s "$openssl" webcpp/.local/openssl - -git clone --recurse-submodules --branch v0.24.6 \ - https://github.com/paullouisageneau/libdatachannel.git -cmake -S libdatachannel -B build-libdatachannel -DCMAKE_BUILD_TYPE=Release \ - -DNO_WEBSOCKET=ON -DNO_EXAMPLES=ON -DNO_TESTS=ON -DOPENSSL_ROOT_DIR=$openssl \ - -DCMAKE_INSTALL_PREFIX=$PWD/webcpp/.local/libdatachannel -cmake --build build-libdatachannel && cmake --install build-libdatachannel +git -C webcpp submodule update --init --recursive third_party/libs/openssl third_party/libs/libdatachannel ``` -The three libraries are now where the build looks for them, in -`webcpp/.local/`, which git ignores: no variable is needed, in this terminal -or another. +B2 builds them with the selected compiler, runtime and C++ ABI when the +native backend is first needed. Each upstream checkout remains unchanged. +The generated headers and static archives are kept together by build +configuration. Asio, Beast and Trystero share one OpenSSL provider in a +combined application; no system OpenSSL or installed libdatachannel is used. +Native Trystero targets declare `multi` because WebRTC runs +worker threads. The supplied examples and tests declare it already. ### 7. Tell b2 its compilers and Boost diff --git a/build.jam b/build.jam index 1cda839..6bc8db5 100644 --- a/build.jam +++ b/build.jam @@ -10,33 +10,16 @@ project /webcpp/trystero ; -# libsecp256k1, libdatachannel and OpenSSL, which webcpp does not build -# until it builds them from third_party/, are found where -# -sSECP256K1_ROOT=, -sSECP256K1_EMSCRIPTEN_ROOT=, -# -sLIBDATACHANNEL_ROOT= and -sOPENSSL_ROOT= on b2's command line -# say, a relative one from b2's working directory, else in the -# superproject's .local/, where webcpp's CI installs them, else, natively -# outside Windows, in /usr/include or /usr/local/include, where a system -# install is legitimate (webcpp.external and webcpp.external-found). The -# environment is never read. When none holds a library, trystero is left -# out, with one message that names it, unless the build gives -# webcpp-require-external=on, as the CI does, which stops it instead. +# Only libsecp256k1 is externally installed. Native WebRTC and OpenSSL are +# pinned source dependencies, built together for the consumer's B2 variant. +import errors ; import webcpp ; -# MSVC's names are CMake's there: libsecp256k1.lib, and OpenSSL's libssl.lib -# and libcrypto.lib, which an installation of Shining Light Productions, as -# GitHub's Windows images have, keeps in lib/VC/x64/MD. A static -# libsecp256k1 on Windows needs SECP256K1_STATIC, or its header declares -# every function imported from a DLL. # tag::dependencies[] local secp256k1-root = [ webcpp.external trystero : libsecp256k1 : SECP256K1_ROOT : secp256k1-native : secp256k1.h : native ] ; local secp256k1-emscripten-root = [ webcpp.external trystero : libsecp256k1 : SECP256K1_EMSCRIPTEN_ROOT : secp256k1-emscripten : secp256k1.h : emscripten ] ; -local libdatachannel-root = [ webcpp.external trystero : libdatachannel - : LIBDATACHANNEL_ROOT : libdatachannel : rtc/rtc.hpp : native ] ; -local openssl-root = [ webcpp.external trystero : OpenSSL : OPENSSL_ROOT : openssl - : openssl/ssl.h : native ] ; lib secp256k1 : : secp256k1 emscripten $(secp256k1-emscripten-root)/lib : : $(secp256k1-emscripten-root)/include ; @@ -45,24 +28,8 @@ lib secp256k1 : : libsecp256k1 msvc : : $(secp256k1-root)/include SECP256K1_STATIC ; lib secp256k1 : : secp256k1 $(secp256k1-root)/lib : : $(secp256k1-root)/include ; -lib datachannel : : datachannel $(libdatachannel-root)/lib - : : $(libdatachannel-root)/include - $(libdatachannel-root)/lib ; -lib ssl : : libssl msvc $(openssl-root)/lib - $(openssl-root)/lib/VC/x64/MD - : : $(openssl-root)/include ; -lib ssl : : ssl $(openssl-root)/lib - : : $(openssl-root)/include ; -lib crypto : : libcrypto msvc $(openssl-root)/lib - $(openssl-root)/lib/VC/x64/MD - : : $(openssl-root)/include ; -lib crypto : : crypto $(openssl-root)/lib - : : $(openssl-root)/include ; -# Searched libraries, used only through : built as dependencies, with -# the properties of what uses them. Requested alone, by b2 at the -# superproject's root or b2 libs/trystero, their alternatives would be matched -# against a request without the 20 each inherits, and none chosen. -explicit secp256k1 datachannel ssl crypto ; +# Searched libraries are used only through usage requirements. +explicit secp256k1 ; # end::dependencies[] # The dependencies of the rooms: libsecp256k1, the emscripten build of it on @@ -76,8 +43,10 @@ rule trystero-dependencies ( properties * ) # uses it is built. rule native-dependencies ( properties * ) { - return [ webcpp.external-found trystero : libdatachannel OpenSSL - : $(properties) ] ; + if single in $(properties) + { + errors.user-error "Trystero's native backend uses worker threads. Add multi to the consuming target or pass threading=multi." ; + } } # On emscripten, the browser has no threads (the event loop drives Asio), and @@ -100,5 +69,5 @@ alias trystero : : @trystero-dependencies # a build's exception-handling=off. # tag::native[] alias native : : @native-dependencies - : : trystero datachannel ssl crypto ; + : : trystero /webcpp/third_party//libdatachannel ; # end::native[] diff --git a/doc/Jamfile b/doc/Jamfile index 4f6032c..3ac1a63 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -15,5 +15,5 @@ webcpp.doc trystero : trystero.adoc ; # brings libdatachannel and OpenSSL, and the browser build's define of # build.jam, which a requirement conditioned on the emscripten toolset does # not give it. -webcpp.reference trystero : /webcpp/trystero//native +webcpp.reference trystero : /webcpp/trystero//native multi /webcpp//emscripten-reference BOOST_ASIO_DISABLE_THREADS ; diff --git a/doc/building.adoc b/doc/building.adoc index 6d386b8..7175d46 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -8,10 +8,9 @@ == Building trystero is header-only, and is developed inside the webcpp superproject, as -a Boost library is developed inside Boost. Besides Boost, it needs three -libraries that are not part of it, which the build finds where b2's command -line says, else in the superproject's `.local/`, until webcpp builds them -from `third_party/`: +a Boost library is developed inside Boost. Its native TLS and WebRTC +dependencies are built from pinned sources. Only libsecp256k1 needs an +external installation: [cols="2,2,3",options="header"] |=== @@ -25,14 +24,14 @@ from `third_party/`: | libdatachannel 0.24.6 | the native backend -| `-sLIBDATACHANNEL_ROOT=`, else `.local/libdatachannel` +| `/webcpp/third_party//libdatachannel`, built from `third_party/libs/libdatachannel` -| OpenSSL 3 +| OpenSSL 3.5.9 | the native backend -| `-sOPENSSL_ROOT=`, else `.local/openssl` +| `/webcpp/third_party//openssl`, shared by the Asio, Beast and Trystero build graphs |=== -Each `-s` names a directory with the library's `include/` and `lib/`, on b2's +The libsecp256k1 `-s` option names a directory with the library's `include/` and `lib/`, on b2's command line; the environment is never read, so that a variable a shell keeps from another day never replaces `.local/` without a word. Without it, the library is looked for in the directory of `.local/` that the table names, @@ -44,11 +43,9 @@ header stops the build, naming it. A library found nowhere leaves trystero out: its tests and examples are skipped, the build says so once, naming the library and where it looked, and every other library builds; with `webcpp-require-external=on`, as the continuous integration builds, it stops -the build instead. With MSVC, the libraries are CMake's -`libsecp256k1.lib`, which a program links statically with `SECP256K1_STATIC` -defined, and OpenSSL's `libssl.lib` and `libcrypto.lib`, also looked for in -`lib/VC/x64/MD`, where the installer of Shining Light Productions puts them. -trystero's `build.jam` declares them so: +the build instead. With MSVC, libsecp256k1 uses CMake's +`libsecp256k1.lib`, linked statically with `SECP256K1_STATIC` defined. +trystero's `build.jam` declares that external dependency so: [listing] ---- @@ -74,14 +71,18 @@ embind is linked as a flag, `-lembind`, rather than with b2's own free among usage requirements, so a program that used it would not link. A native program uses `/webcpp/trystero//native`, which adds libdatachannel -and OpenSSL: +and the same source-built OpenSSL used by Asio and Beast: [listing] ---- include::{library-root}/build.jam[tag=native] ---- -The native backend's WebRTC needs exceptions (<>), +The native backend uses worker threads, so each consumer declares +`multi`. Its OpenSSL dependency is the matching threaded variant; +a single-threaded native backend is rejected before compilation. + +The native backend's WebRTC also needs exceptions (<>), and b2 lets no usage requirement override a build's `exception-handling=off`, so each program and test that uses it declares `on` itself, as the examples do: @@ -119,7 +120,7 @@ include::{webcpp-root}/tools/ci/emsdk.jam[tag=emsdk] include::{webcpp-root}/tools/ci/emsdk.jam[tag=emscripten] ---- -With it and the three libraries found, from the root of a webcpp checkout, +With it, libsecp256k1 installed and the pinned source submodules initialized, from the root of a webcpp checkout, these build the tests and the examples, natively and on emscripten: [source,bash] @@ -129,7 +130,7 @@ b2 toolset=emscripten libs/trystero/test libs/trystero/example ---- [#trystero-building-dependencies] -=== The three libraries +=== Preparing the dependencies libsecp256k1 is built twice: natively, and with Emscripten for the browser. Its small tables keep the browser's download small: @@ -155,27 +156,27 @@ cmake --build build-secp256k1-emscripten && cmake --install build-secp256k1-emsc where `webcpp` is the checkout of the superproject: each is installed in the directory of `.local/` where the build looks for it. -libdatachannel is built with the compiler and the standard library that -build the programs: a program built with GCC and `libstdc{plus}{plus}` does -not link against a libdatachannel built with `libc{plus}{plus}`, though the -native headers still compile alone. Its own WebSocket is not used, so it is -built without it, and its CMake finds OpenSSL where `OPENSSL_ROOT_DIR` says, -which Homebrew's OpenSSL needs, and which `.local/openssl` links for the build -too: +Initialize the native dependencies from the superproject root: [source,bash] ---- -openssl=$(brew --prefix openssl@3) # or wherever OpenSSL 3 is -ln -s "$openssl" webcpp/.local/openssl - -git clone --recurse-submodules --branch v0.24.6 \ - https://github.com/paullouisageneau/libdatachannel.git -cmake -S libdatachannel -B build-libdatachannel -DCMAKE_BUILD_TYPE=Release \ - -DNO_WEBSOCKET=ON -DNO_EXAMPLES=ON -DNO_TESTS=ON -DOPENSSL_ROOT_DIR=$openssl \ - -DCMAKE_INSTALL_PREFIX=$PWD/webcpp/.local/libdatachannel -cmake --build build-libdatachannel && cmake --install build-libdatachannel +git submodule update --init --recursive third_party/libs/openssl third_party/libs/libdatachannel ---- +Install CMake 3.21 or newer, Perl and Make (native Windows Perl and nmake +with MSVC). B2 builds OpenSSL, libdatachannel and its pinned nested +libjuice, usrsctp and libsrtp sources for the configured compiler, standard +library, runtime and build variant. Upstream sources are verified and +copied to a disposable build directory; the checkout is never patched. +The resulting headers and separate static archives stay in B2's variant +directory, and the final link contains exactly one OpenSSL archive pair. + +libdatachannel's own WebSocket, examples and tests are disabled; media +transport remains enabled. System OpenSSL and installed libdatachannel +binaries are never fallback providers. A combined Asio/Beast/Trystero +application uses the same native `multi` configuration for all +three libraries. + [#trystero-building-examples] === Running the examples diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 3b1374c..65033fe 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -22,6 +22,12 @@ of every version are on webcpp's index page. === webcpp 0.1.0 // tag::0.1.0[] +* Fixed native multiroom handoffs losing early presence frames, and + negotiations stalled by a channel closing before room binding. +* Changed the native backend to build pinned libdatachannel sources and their +dependencies through B2, sharing source-built OpenSSL with Asio and Beast. +* Changed native builds to require `threading=multi`; the backend uses workers. +* Fixed GCC compilation of native WebSocket coroutine callbacks. * Changed room construction to `app::join`, sharing connections between rooms. * *Breaking change:* Removed `room_config`; construct `app` and use `join` with `app_config` and `room_options`. diff --git a/doc/native.adoc b/doc/native.adoc index 0938507..dde013c 100644 --- a/doc/native.adoc +++ b/doc/native.adoc @@ -58,6 +58,21 @@ transfers assemble their buffer in the room's resource. A text message, as a pee send, or a binary one larger than any room frame, is dropped on libdatachannel's thread: neither can be a frame. +Valid binary frames that arrive before the message handler is installed wait +in a FIFO in the app's resource. The queue holds at most 64 frames for at most +10 seconds from its first frame. Overflow or expiry closes the channel; +closing or destroying it discards the pending frames. The existing native +timer invalidates an expiry already queued when the queue drains or closes. +Installing a receiver posts delivery on the executor with the app's +allocator. It never calls the receiver inline, and delivery checks the current +handler and channel before each frame, so a handler may replace itself or +close the channel. A message already queued ahead of that delivery drains +older frames first when a receiver is available. + +If a transport closes during adoption, before the room obtains a binding, +the room forgets that negotiation and restarts announcements. Its later close +event cannot leave signaling marked connected with no binding. + [#trystero-native-libdatachannel] === What the backend asks of libdatachannel diff --git a/doc/roadmap.adoc b/doc/roadmap.adoc index b7ef226..be5ef58 100644 --- a/doc/roadmap.adoc +++ b/doc/roadmap.adoc @@ -21,7 +21,7 @@ echoes the offerer's `msid` into the answer. . *Trystero's other features.* Request actions (`kind: 'request'`), decisions on incoming transfers and their progress, the application's own handshake, passive rooms, and the other strategies, among them MQTT and BitTorrent trackers. -. *The external libraries from webcpp's own build.* libsecp256k1, -libdatachannel and OpenSSL are found where b2's command line or the -superproject's `.local/` says until webcpp builds them from `third_party/` +. *libsecp256k1 from webcpp's own build.* libsecp256k1 is still found where +b2's command line or the superproject's `.local/` says. Native OpenSSL and +libdatachannel already build from pinned `third_party/` sources (<>). diff --git a/doc/testing.adoc b/doc/testing.adoc index b6c681c..bfb19d3 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -124,7 +124,10 @@ include::{library-root}/test/Jamfile[tag=allocation] | `native_peer_connection`, `native_room` | Two libdatachannel connections wired to each other, each handler on the executor, and whole native rooms over real libdatachannel connections, - bound to 127.0.0.1. + bound to 127.0.0.1. A controlled executor holds real channel callbacks to + prove pre-handler FIFO delivery, a 65th message ahead of the posted flush, + handler replacement and destruction, the 64-frame and 10-second bounds, + and allocation and release through the channel's resource. | `browser_event_loop`, `browser_websocket`, `browser_websocket_bound`, `browser_websocket_late_events`, `browser_sealer`, `browser_data_channel`, `browser_peer_connection` | The browser backend, on emscripten under node, which has the page's @@ -259,18 +262,30 @@ and run the unit tests with GCC 14 and with clang 18 against `libstdc{plus}{plus}` in a Linux container, Ubuntu 24.04, with `docker run` and the network `none`, which leaves the loopback alone: every test passes, which shows that none reaches beyond the machine -(<>). libsecp256k1 and libdatachannel are -built before, on the runner, Ubuntu 24.04 too, with the lane's compiler -against the runner's OpenSSL 3, and the container, which holds the same -compilers and OpenSSL's development files, sees them where the runner put -them. +(<>). libsecp256k1 is installed before +running the container. B2 builds the pinned OpenSSL, libdatachannel and +nested source dependencies inside the container with the lane's compiler, +runtime and static link configuration. These builds need no network access. + +[#trystero-testing-provider] +=== The common OpenSSL provider + +The native `provider-integration` lane builds and runs one application that +uses Asio TLS, Beast and Trystero's native backend together. It compares the +compiled OpenSSL version with the loaded implementation and constructs TLS +and WebRTC state. The run is bounded to 45 seconds and uses the threaded +release profile. The superproject's source dependency tests also check that +the final Unix executable has no dynamic OpenSSL or libdatachannel provider, +that each static archive occurs once and that dependent archives precede +OpenSSL in the link order. [#trystero-testing-report] === The test matrix The continuous integration runs trystero's tests in lanes, one toolset each, and its own lanes, the oracle once and the interop natively and on -emscripten, as `native.trystero.interop` and `emscripten.trystero.interop`. +emscripten, as `native.trystero.interop` and `emscripten.trystero.interop`, plus the +native `provider-integration` lane for the common TLS provider. Each lane builds from scratch and records what b2 built and ran; webcpp's `tools/report/report.py` merges the files of every lane into a matrix, where each cell says whether that program passed in that lane, or how it failed. diff --git a/example/Jamfile b/example/Jamfile index f8a89fe..3b5593f 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -18,7 +18,7 @@ webcpp.targets native emscripten ; # reports errors by throwing. # tag::native[] webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//native on : native ; + : /webcpp/trystero//native multi on : native ; # end::native[] # tag::browser[] webcpp.link quick_start : quick_start.cpp diff --git a/include/webcpp/trystero/native/backend.hpp b/include/webcpp/trystero/native/backend.hpp index bf3d73e..e8a42c8 100644 --- a/include/webcpp/trystero/native/backend.hpp +++ b/include/webcpp/trystero/native/backend.hpp @@ -14,13 +14,12 @@ #include #include #include +#include #include #include #include // lint-world: posts handlers only -#include // lint-world: posts handlers only #include // lint-world: the relays' TLS -#include // lint-world: Trystero's timers #include #include @@ -38,63 +37,6 @@ */ namespace webcpp::trystero::native { -/** - * An Asio timer whose waits are allocated in the room's resource. - * - * Tip: Asio cannot take back an expiry it has already queued, which it then completes as a - * success; so each wait carries its number, and `cancel`, a later `start` and the destructor end - * it, by changing the number or freeing it, before its handler runs. - * - * @see "The native backend", in the guide. - */ -class timer : public trystero::backend::timer { -public: - /** - * Constructs a timer, not started. - * - * @param ex The executor it fires on. - * @param memory The room's resource, which each wait is allocated in; it must outlive the - * timer's pending waits. - */ - timer(const boost::asio::any_io_executor& ex, std::pmr::memory_resource* memory) - : timer_(ex), - memory_(memory), - waits_( - std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), 0)) {} - - /** - * Calls `fire` on the executor once `delay` has passed, in place of a pending expiry. - * - * @param delay How long to wait. - * @param fire What to call when the timer expires; never called once the timer is cancelled, - * started again or destroyed, even when its expiry was already queued. - */ - void start(std::chrono::milliseconds delay, handler fire) override { - const std::uint64_t wait = ++*waits_; - timer_.expires_after(delay); - timer_.async_wait(boost::asio::bind_allocator( - std::pmr::polymorphic_allocator<>(memory_), - [waits = std::weak_ptr(waits_), wait, - fire = std::move(fire)](boost::system::error_code ec) mutable { - if (const auto current = waits.lock(); !ec && current && *current == wait) { - fire(); - } - })); - } - - /** Cancels the pending expiry, if any, whose handler is then never called. */ - void cancel() override { - ++*waits_; - timer_.cancel(); - } - -private: - boost::asio::steady_timer timer_; // lint-world: Trystero's timers - std::pmr::memory_resource* memory_; - // The number of the wait under way: a handler that finds another, or none, does nothing. - std::shared_ptr waits_; -}; - // The factory makes peer connections over libdatachannel, which need exceptions: without them // (WEBCPP_TRYSTERO_NO_EXCEPTIONS) it does not exist, and the timer, the sealer and the WebSockets // remain. diff --git a/include/webcpp/trystero/native/data_channel.hpp b/include/webcpp/trystero/native/data_channel.hpp index b4d1a6f..b4f521c 100644 --- a/include/webcpp/trystero/native/data_channel.hpp +++ b/include/webcpp/trystero/native/data_channel.hpp @@ -15,13 +15,18 @@ #ifndef WEBCPP_TRYSTERO_NO_EXCEPTIONS #include +#include #include #include // lint-world: posts handlers only +#include // lint-world: allocates the pending-frame flush #include // lint-world: posts handlers only #include +#include +#include #include +#include #include #include #include @@ -38,7 +43,9 @@ namespace webcpp::trystero::native { * * A text message, as a peer can send, or a binary one larger than any room frame * (`protocol::max_room_frame_bytes`), is dropped on libdatachannel's thread: neither can be a - * frame. + * frame. Binary frames received before the message handler is installed wait in the app's + * resource, in order, up to 64 frames for 10 seconds. Exceeding either bound closes the channel. + * Installing a receiver posts their delivery, so handler registration never calls it inline. * * Tip: a received message is copied once, out of libdatachannel's `std::vector` into the * backend's bytes, in the room's resource, on the executor: what runs on libdatachannel's threads @@ -80,7 +87,11 @@ class data_channel : public backend::data_channel, */ data_channel(private_tag /*tag*/, boost::asio::any_io_executor ex, std::shared_ptr channel, std::pmr::memory_resource* memory) - : ex_(std::move(ex)), channel_(std::move(channel)), memory_(memory) {} + : ex_(std::move(ex)), + channel_(std::move(channel)), + memory_(memory), + pending_(memory), + pending_timer_(ex_, memory) {} /** Destroys the wrapper, which closes the channel without reporting the close. */ ~data_channel() override { @@ -101,14 +112,25 @@ class data_channel : public backend::data_channel, void set_handlers(handlers h) override { h_ = std::allocate_shared(std::pmr::polymorphic_allocator<>(memory_), std::move(h)); + if (!pending_.empty() && h_->message && !flush_posted_) { + flush_posted_ = true; + boost::asio::post( + ex_, boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory_), + [weak = weak_from_this()] { + if (const auto self = weak.lock()) { + self->flush_posted_ = false; + self->flush_pending(); + } + })); + } } /** * Whether the channel is open. * - * @return libdatachannel's `isOpen()`. + * @return Whether this wrapper has not closed and libdatachannel's channel is open. */ - bool is_open() const override { return channel_->isOpen(); } + bool is_open() const override { return !closed_ && channel_->isOpen(); } /** * Sends a binary message; one the channel refuses, closed in between, is dropped, and its close @@ -119,7 +141,7 @@ class data_channel : public backend::data_channel, void send(std::span frame) override { // A channel closed in between refuses the frame, and its close event reports it. try { - if (channel_->isOpen()) { + if (is_open()) { channel_->send(reinterpret_cast(frame.data()), frame.size()); } } catch (...) { // NOLINT(bugprone-empty-catch) @@ -135,6 +157,8 @@ class data_channel : public backend::data_channel, /** Closes the channel, which the handler `close` reports; a refusal is ignored. */ void close() override { + closed_ = true; + clear_pending(); // A channel whose connection is gone may refuse to close, which leaves nothing to do. try { channel_->close(); @@ -179,22 +203,74 @@ class data_channel : public backend::data_channel, // The handlers run from a copy of the shared object, which a handler may replace. void on_open() { - if (const auto h = h_; h && h->open) { + if (const auto h = h_; !closed_ && h && h->open) { h->open(); } } void on_message(const rtc::binary& binary) { + if (!is_open()) { + return; + } + // An already posted message may be ahead of set_handlers' flush. A receiver now + // exists, so drain old frames before admitting the new one against the queue bound. + if (!pending_.empty() && h_ && h_->message) { + flush_pending(); + if (!is_open()) { + return; + } + } const auto h = h_; - if (!h || !h->message) { + if ((!h || !h->message || !pending_.empty()) && pending_.size() >= max_pending_frames) { + close(); return; } backend::bytes frame(binary.size(), memory_); std::memcpy(frame.data(), binary.data(), binary.size()); - h->message(std::move(frame)); + if (h && h->message && pending_.empty()) { + h->message(std::move(frame)); + return; + } + if (pending_.empty()) { + pending_timer_.start(std::chrono::seconds(10), + {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), + [weak = weak_from_this()] { + if (const auto self = weak.lock(); + self && !self->pending_.empty()) { + self->close(); + } + }}); + } + pending_.push_back(std::move(frame)); + } + + void clear_pending() { + pending_.clear(); + pending_timer_.cancel(); + } + + void flush_pending() { + while (!pending_.empty()) { + if (!is_open()) { + clear_pending(); + return; + } + const auto h = h_; + if (!h || !h->message) { + return; + } + auto frame = std::move(pending_.front()); + pending_.pop_front(); + if (pending_.empty()) { + clear_pending(); + } + h->message(std::move(frame)); + } } void on_closed() { + closed_ = true; + clear_pending(); if (const auto h = h_) { if (auto f = std::exchange(h->close, {})) { f(); @@ -212,6 +288,11 @@ class data_channel : public backend::data_channel, std::shared_ptr channel_; std::pmr::memory_resource* memory_; std::shared_ptr h_; + static constexpr std::size_t max_pending_frames = 64; + std::pmr::deque pending_; + timer pending_timer_; + bool flush_posted_ = false; + bool closed_ = false; }; } // namespace webcpp::trystero::native diff --git a/include/webcpp/trystero/native/timer.hpp b/include/webcpp/trystero/native/timer.hpp new file mode 100644 index 0000000..f2095a2 --- /dev/null +++ b/include/webcpp/trystero/native/timer.hpp @@ -0,0 +1,86 @@ +// 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_TRYSTERO_NATIVE_TIMER_HPP +#define WEBCPP_TRYSTERO_NATIVE_TIMER_HPP + +#include + +#include + +#include // lint-world: Trystero's timers +#include // lint-world: allocates timer waits +#include // lint-world: Trystero's timers +#include + +#include +#include +#include +#include +#include + +namespace webcpp::trystero::native { + +/** + * An Asio timer whose waits are allocated in the room's resource. + * + * Tip: Asio cannot take back an expiry it has already queued, which it then completes as a + * success; so each wait carries its number, and `cancel`, a later `start` and the destructor end + * it, by changing the number or freeing it, before its handler runs. + * + * @see "The native backend", in the guide. + */ +class timer : public trystero::backend::timer { +public: + /** + * Constructs a timer, not started. + * + * @param ex The executor it fires on. + * @param memory The room's resource, which each wait is allocated in; it must outlive the + * timer's pending waits. + */ + timer(const boost::asio::any_io_executor& ex, std::pmr::memory_resource* memory) + : timer_(ex), + memory_(memory), + waits_( + std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), 0)) {} + + /** + * Calls `fire` on the executor once `delay` has passed, in place of a pending expiry. + * + * @param delay How long to wait. + * @param fire What to call when the timer expires; never called once the timer is cancelled, + * started again or destroyed, even when its expiry was already queued. + */ + void start(std::chrono::milliseconds delay, handler fire) override { + const std::uint64_t wait = ++*waits_; + timer_.expires_after(delay); + timer_.async_wait(boost::asio::bind_allocator( + std::pmr::polymorphic_allocator<>(memory_), + [waits = std::weak_ptr(waits_), wait, + fire = std::move(fire)](boost::system::error_code ec) mutable { + if (const auto current = waits.lock(); !ec && current && *current == wait) { + fire(); + } + })); + } + + /** Cancels the pending expiry, if any, whose handler is then never called. */ + void cancel() override { + ++*waits_; + timer_.cancel(); + } + +private: + boost::asio::steady_timer timer_; // lint-world: Trystero's timers + std::pmr::memory_resource* memory_; + // The number of the wait under way: a handler that finds another, or none, does nothing. + std::shared_ptr waits_; +}; + +} // namespace webcpp::trystero::native + +#endif diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp index c8a242d..2189f6d 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/native/websocket.hpp @@ -219,8 +219,9 @@ class websocket_session : public std::enable_shared_from_this run() { using boost::asio::as_tuple; using boost::asio::use_awaitable; - auto [resolve_error, endpoints] = + auto resolve_result = co_await resolver_.async_resolve(url_.host, url_.port, as_tuple(use_awaitable)); + auto& [resolve_error, endpoints] = resolve_result; if (resolve_error || closing_) { co_return end(); } diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index eb9c62d..9c2f8a9 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -1127,6 +1127,11 @@ class room_impl final : public std::enable_shared_from_this, public r } } else if (c->live()) { bind_peer(peer, c); + } else { + // A native transport can close while adoption calls the log sink. No binding + // exists yet, so its queued end cannot remove_peer and forget this negotiation. + signaling_->forget(peer); + strategy_->restart_announcements(); } } diff --git a/test/Jamfile b/test/Jamfile index 8810464..849bc69 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -26,12 +26,12 @@ webcpp.targets native emscripten ; webcpp.headers-alone trystero : ../include : trystero.hpp trystero/*.hpp trystero/protocol/*.hpp trystero/detail/*.hpp ; webcpp.headers-alone trystero : ../include - : trystero/native/backend.hpp trystero/native/sealer.hpp + : trystero/native/backend.hpp trystero/native/sealer.hpp trystero/native/timer.hpp trystero/native/websocket.hpp - : /webcpp/trystero//native : native ; + : /webcpp/trystero//native multi : native ; webcpp.headers-alone trystero : ../include : trystero/native/data_channel.hpp trystero/native/peer_connection.hpp - : /webcpp/trystero//native on : native ; + : /webcpp/trystero//native multi on : native ; webcpp.headers-alone trystero : ../include : trystero/browser/*.hpp : : emscripten ; # config.hpp defines WEBCPP_TRYSTERO_NO_EXCEPTIONS exactly when webcpp has no @@ -73,21 +73,21 @@ webcpp.run connection : connection_test.cpp ; webcpp.run app_impl : app_impl_test.cpp ; # end::both-targets[] webcpp.run native_sealer : native_sealer_test.cpp - : /webcpp/trystero//native fixtures/expected/expected.json : native ; + : /webcpp/trystero//native multi fixtures/expected/expected.json : native ; # The WebSocket test is built with the standard libraries' own checks, libc++'s # extensive hardening and libstdc++'s assertions, so that a completion that # touches a container its socket cleared fails at once, not one run in many. webcpp.run native_websocket : native_websocket_test.cpp - : /webcpp/trystero//native + : /webcpp/trystero//native multi _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS : native ; -webcpp.run native_timer : native_timer_test.cpp : /webcpp/trystero//native : native ; +webcpp.run native_timer : native_timer_test.cpp : /webcpp/trystero//native multi : native ; # tag::native[] webcpp.run native_peer_connection : native_peer_connection_test.cpp - : /webcpp/trystero//native on : native ; + : /webcpp/trystero//native multi on : native ; webcpp.run native_room : native_room_test.cpp - : /webcpp/trystero//native on : native ; + : /webcpp/trystero//native multi on : native ; # end::native[] # Every allocation of two rooms that exchange a payload goes through the @@ -128,3 +128,6 @@ webcpp.run browser_data_channel_no_exceptions : browser_data_channel_test.cpp webcpp.run browser_peer_connection_no_exceptions : browser_peer_connection_test.cpp : off : emscripten ; # end::no-exceptions[] + +# The combined Asio/Beast/Trystero provider has its own recurring native lane. +build-project provider ; diff --git a/test/native_peer_connection_test.cpp b/test/native_peer_connection_test.cpp index d769231..7f203bc 100644 --- a/test/native_peer_connection_test.cpp +++ b/test/native_peer_connection_test.cpp @@ -14,17 +14,22 @@ #include #include +#include #include #include +#include #include +#include #include #include #include +#include #include #include #include #include +#include #include #include @@ -75,7 +80,8 @@ struct pair { } } - void connect() { + void connect(std::pmr::memory_resource* channel_memory = nullptr, + const std::optional& channel_executor = {}) { offerer->set_handlers({ .ice_candidate = [this](std::string_view c) { @@ -103,7 +109,16 @@ struct pair { answerer_states.push_back(s); }, }); - offer_end = offerer->create_data_channel("data"); + if (channel_memory != nullptr || channel_executor) { + const auto native = + std::static_pointer_cast(offerer); + offer_end = trystero::native::data_channel::create( + channel_executor.value_or(io.get_executor()), + native->native_handle()->createDataChannel("data"), + channel_memory != nullptr ? channel_memory : std::pmr::get_default_resource()); + } else { + offer_end = offerer->create_data_channel("data"); + } watch(offer_end, offer_open, at_offerer, nullptr); offerer->set_local_description([this](backend::error_code ec, std::string_view type, std::string_view sdp) { @@ -149,6 +164,91 @@ struct pair { } }; +// Observes the native channel's posted callbacks without running them. This lets a test +// install a receiver after a real message is queued and before that message is dispatched. +struct queued_tasks { + std::mutex mutex; + std::deque> ready; + + std::size_t size() { + const std::scoped_lock lock(mutex); + return ready.size(); + } + + void run() { + for (;;) { + std::function f; + { + const std::scoped_lock lock(mutex); + if (ready.empty()) { + return; + } + f = std::move(ready.front()); + ready.pop_front(); + } + f(); + } + } +}; + +class queued_executor { + asio::any_io_executor inner_; + std::shared_ptr tasks_; + +public: + queued_executor(asio::any_io_executor inner, std::shared_ptr tasks) + : inner_(std::move(inner)), tasks_(std::move(tasks)) {} + + template + void execute(F f) const { + const auto operation = std::make_shared(std::move(f)); + const std::scoped_lock lock(tasks_->mutex); + tasks_->ready.emplace_back([operation] { (*operation)(); }); + } + + template + [[nodiscard]] auto query(Property p) const -> decltype(asio::query(inner_, p)) { + return asio::query(inner_, p); + } + + [[nodiscard]] queued_executor require(asio::execution::blocking_t::never_t p) const { + return {asio::require(inner_, p), tasks_}; + } + + template + [[nodiscard]] queued_executor prefer(Property p) const { + return {asio::prefer(inner_, p), tasks_}; + } + + friend bool operator==(const queued_executor& a, const queued_executor& b) noexcept { + return a.inner_ == b.inner_ && a.tasks_ == b.tasks_; + } +}; + +struct queued_pair : pair { + std::shared_ptr tasks = std::make_shared(); + + void connect(std::pmr::memory_resource* memory = nullptr) { + pair::connect(memory, asio::any_io_executor(queued_executor(io.get_executor(), tasks))); + require(BOOST_TEST(until([&] { return offer_open && answer_open; }))); + } + + bool until(const std::function& done, std::chrono::milliseconds limit = 10s) { + return run_until( + io, + [&] { + tasks->run(); + return done(); + }, + limit); + } + + void receive(std::size_t count) { + require(BOOST_TEST(run_until(io, [&] { return tasks->size() >= count; }))); + tasks->run(); + } +}; + void two_connections_open_a_data_channel_and_exchange_bytes() { pair p; p.connect(); @@ -186,6 +286,206 @@ void closing_one_end_is_seen_by_the_other() { BOOST_TEST(!p.off_thread); } +// Presence can reach the native executor before the posted open event hands a channel over +// from signaling. Installing the receiver afterwards must deliver those frames in order. +void messages_wait_for_the_receiver_during_handoff() { + queued_pair p; + p.connect(); + require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); + p.offer_end->set_handlers({}); + const backend::bytes first{2, 1, 0, 1, 'a'}; + const backend::bytes second{2, 1, 0, 1, 'b'}; + p.answer_end->send(first); + p.answer_end->send(second); + p.receive(2); + p.watch(p.offer_end, p.offer_open, p.at_offerer, nullptr); + require(BOOST_TEST(p.until([&] { return p.at_offerer.size() == 2; }))); + BOOST_TEST(p.at_offerer[0] == first); + BOOST_TEST(p.at_offerer[1] == second); +} + +void a_full_pending_queue_drains_in_order_and_uses_replacement_handlers() { + queued_pair p; + p.connect(); + require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); + p.offer_end->set_handlers({}); + for (std::uint8_t i = 0; i < 64; ++i) { + p.answer_end->send(backend::bytes{i}); + } + p.receive(64); + std::vector received; + // The 65th callback is already queued before set_handlers posts its flush. + p.answer_end->send(backend::bytes{64}); + require(BOOST_TEST(run_until(p.io, [&] { return p.tasks->size() >= 1; }))); + bool first = true; + bool registering = true; + p.offer_end->set_handlers({ + .open = {}, + .message = + [&](backend::bytes frame) { + BOOST_TEST(!registering); + received.push_back(frame[0]); + BOOST_TEST(first); + first = false; + p.offer_end->set_handlers({ + .open = {}, + .message = [&](backend::bytes later) { received.push_back(later[0]); }, + .close = {}, + .buffered_amount_low = {}, + }); + }, + .close = {}, + .buffered_amount_low = {}, + }); + registering = false; + require(BOOST_TEST(p.until([&] { return received.size() == 65; }))); + for (std::size_t i = 0; i < received.size(); ++i) { + BOOST_TEST_EQ(received[i], static_cast(i)); + } + // A later handoff must post a new flush after the first one has finished. + p.offer_end->set_handlers({}); + p.answer_end->send(backend::bytes{65}); + p.receive(1); + p.offer_end->set_handlers({ + .open = {}, + .message = [&](backend::bytes later) { received.push_back(later[0]); }, + .close = {}, + .buffered_amount_low = {}, + }); + require(BOOST_TEST(p.until([&] { return received.size() == 66; }))); + BOOST_TEST_EQ(received.back(), 65); +} + +void a_pending_queue_overflow_closes_the_channel() { + queued_pair p; + p.connect(); + require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); + bool closed = false; + p.offer_end->set_handlers({ + .open = {}, + .message = {}, + .close = [&] { closed = true; }, + .buffered_amount_low = {}, + }); + for (std::uint8_t i = 0; i < 65; ++i) { + p.answer_end->send(backend::bytes{i}); + } + require(BOOST_TEST(p.until([&] { return closed; }, 5s))); + BOOST_TEST(!p.offer_end->is_open()); +} + +void pending_messages_expire_without_a_receiver() { + queued_pair p; + p.connect(); + require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); + bool closed = false; + p.offer_end->set_handlers({ + .open = {}, + .message = {}, + .close = [&] { closed = true; }, + .buffered_amount_low = {}, + }); + const auto started = std::chrono::steady_clock::now(); + p.answer_end->send(backend::bytes{1}); + require(BOOST_TEST(p.until([&] { return closed; }, 12s))); + BOOST_TEST(std::chrono::steady_clock::now() - started >= 10s); +} + +void a_receiver_can_close_and_destroy_its_channel_during_pending_delivery() { + queued_pair p; + p.connect(); + require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); + p.offer_end->set_handlers({}); + p.answer_end->send(backend::bytes{1}); + p.answer_end->send(backend::bytes{2}); + p.receive(2); + int received = 0; + p.offer_end->set_handlers({ + .open = {}, + .message = + [&](const backend::bytes&) { + ++received; + p.offer_end->close(); + p.offer_end.reset(); + }, + .close = {}, + .buffered_amount_low = {}, + }); + require(BOOST_TEST(p.until([&] { return p.answer_closes == 1; }))); + BOOST_TEST_EQ(received, 1); +} + +class pending_memory : public std::pmr::memory_resource { +public: + std::atomic outstanding{0}; + + [[nodiscard]] std::unordered_set allocations() { + const std::scoped_lock lock(mutex_); + return allocations_; + } + +private: + std::mutex mutex_; + std::unordered_set allocations_; + + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + void* p = std::pmr::new_delete_resource()->allocate(bytes, alignment); + outstanding += bytes; + { + const std::scoped_lock lock(mutex_); + allocations_.insert(p); + } + return p; + } + + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + { + const std::scoped_lock lock(mutex_); + allocations_.erase(p); + } + outstanding -= bytes; + std::pmr::new_delete_resource()->deallocate(p, bytes, alignment); + } + + bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } +}; + +void pending_frames_and_delivery_use_the_channels_resource() { + pending_memory memory; + { + queued_pair p; + p.connect(&memory); + require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); + p.offer_end->set_handlers({}); + for (int i = 0; i < 64; ++i) { + p.answer_end->send(backend::bytes(1024, static_cast(i))); + } + p.receive(64); + // Deque bookkeeping can allocate the same byte count as a payload. Each + // delivered buffer must already belong to this resource before registration. + auto queued = memory.allocations(); + bool registering = true; + p.offer_end->set_handlers({ + .open = {}, + .message = + [&](backend::bytes frame) { + BOOST_TEST(!registering); + BOOST_TEST(frame.get_allocator().resource() == &memory); + BOOST_TEST_EQ(frame.size(), 1024U); + BOOST_TEST_EQ(queued.erase(frame.data()), 1U); + p.at_offerer.push_back(std::move(frame)); + }, + .close = {}, + .buffered_amount_low = {}, + }); + registering = false; + require(BOOST_TEST(p.until([&] { return p.at_offerer.size() == 64; }))); + } + BOOST_TEST_EQ(memory.outstanding.load(), 0U); +} + void a_malformed_candidate_fails_without_throwing() { asio::io_context io; const auto pc = trystero::native::peer_connection::create(io.get_executor(), {}, loopback, @@ -222,7 +522,13 @@ void the_backend_makes_at_most_its_budget_in_a_minute() { int main() { two_connections_open_a_data_channel_and_exchange_bytes(); closing_one_end_is_seen_by_the_other(); + messages_wait_for_the_receiver_during_handoff(); + a_full_pending_queue_drains_in_order_and_uses_replacement_handlers(); + a_pending_queue_overflow_closes_the_channel(); + pending_messages_expire_without_a_receiver(); + a_receiver_can_close_and_destroy_its_channel_during_pending_delivery(); a_malformed_candidate_fails_without_throwing(); the_backend_makes_at_most_its_budget_in_a_minute(); + pending_frames_and_delivery_use_the_channels_resource(); return boost::report_errors(); } diff --git a/test/oracle/Jamfile b/test/oracle/Jamfile index b1d46b0..f081437 100644 --- a/test/oracle/Jamfile +++ b/test/oracle/Jamfile @@ -32,7 +32,7 @@ webcpp.drive interop_browser : interop/peer.cpp : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH 2400 : interop/run.mjs : --browser : emscripten ; webcpp.drive interop_native : interop/native_peer.cpp - : /webcpp/trystero//native on 2400 + : /webcpp/trystero//native multi on 2400 _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS : interop/run.mjs : --native : native ; diff --git a/test/oracle/interop/js.html b/test/oracle/interop/js.html index 0382171..d912785 100644 --- a/test/oracle/interop/js.html +++ b/test/oracle/interop/js.html @@ -31,6 +31,16 @@ window.events = [] const record = (kind, fields = {}) => window.events.push({kind, ...fields}) +// CDP may display an RTCError only as "OperationError". Keep its useful fields +// beside the peer events without suppressing the original console failure. +const consoleError = console.error.bind(console) +console.error = (...args) => { + record('console-error', {arguments: args.map(value => value && typeof value === 'object' + ? {name: value.name, message: value.message, detail: value.errorDetail, + cause: value.sctpCauseCode, stack: value.stack} + : String(value))}) + consoleError(...args) +} const log = (category, text) => { const line = `[${(performance.now() / 1000).toFixed(2)}s] ${category}: ${text}` console.log(line) @@ -71,8 +81,33 @@ const receivedRoomActions = new Map() const encoder = new TextEncoder() const decoder = new TextDecoder() +// In the delayed-native-open regression, send presence immediately, but keep room actions +// until the native peer advertises its first token. This makes the first room's direct +// handshake work while the second still requires the native side to keep its early presence. +const holdActionsUntilPresence = params.get('holdActionsUntilPresence') +const heldActions = new Map() +const seenNativePresence = new WeakSet() +const sendChannel = RTCDataChannel.prototype.send +if (holdActionsUntilPresence) { + RTCDataChannel.prototype.send = function (data) { + const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) + : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : null + if (bytes?.[0] === 1 && !seenNativePresence.has(this)) { + const queue = heldActions.get(this) ?? [] + queue.push(data) + heldActions.set(this, queue) + return + } + return sendChannel.call(this, data) + } +} const watchChannel = channel => { channels.push(channel) + channel.addEventListener('error', ({error}) => record('channel-error', { + channel: channels.indexOf(channel), state: channel.readyState, + name: error?.name, message: error?.message, + detail: error?.errorDetail, cause: error?.sctpCauseCode, + })) channel.addEventListener('message', ({data}) => { if (!(data instanceof ArrayBuffer)) return const b = new Uint8Array(data) @@ -91,6 +126,13 @@ return } if (b.length < 4 || b[0] !== 2) return + if (holdActionsUntilPresence && !seenNativePresence.has(channel)) { + seenNativePresence.add(channel) + const frames = heldActions.get(channel) ?? [] + if (frames.length) record('actions-released-after-presence', {count: frames.length}) + for (const frame of frames) sendChannel.call(channel, frame) + heldActions.delete(channel) + } const token = decoder.decode(b.subarray(4, 4 + ((b[2] << 8) | b[3]))) if (b[1] === 1) advertised.add(token) else advertised.delete(token) @@ -301,6 +343,36 @@ record('dropped') } +// Delay one outbound direction of the next connection past the C++ handshake deadline. +// The page can announce its own join while C++ is still pending. A later connection +// exchanges normally, so a recovery check must observe both sides before testing the relay. +window.delayNextRecovery = () => { + const existing = new Set(channels) + const send = RTCDataChannel.prototype.send + let delayed = null + let finished = false + const queue = [] + RTCDataChannel.prototype.send = function (data) { + if (finished || existing.has(this) || (delayed && delayed !== this)) return send.call(this, data) + if (!delayed) { + delayed = this + record('recovery-delayed') + const timer = setTimeout(() => { + finished = true + if (this.readyState === 'open') for (const frame of queue) send.call(this, frame) + queue.length = 0 + }, 12_000) + this.addEventListener('close', () => { + clearTimeout(timer) + finished = true + queue.length = 0 + record('delayed-recovery-closed') + }, {once: true}) + } + queue.push(data) + } +} + // Publishes `count` signals, each from a fresh peer id that starts with `prefix`, on the topic of the room's peer // `to`, or on the room's own topic, through a WebSocket of its own to the first relay. Records `kind` once every one is // sent. diff --git a/test/oracle/interop/native_peer.cpp b/test/oracle/interop/native_peer.cpp index a9b6448..0225ec6 100644 --- a/test/oracle/interop/native_peer.cpp +++ b/test/oracle/interop/native_peer.cpp @@ -24,6 +24,7 @@ // | --room3Delay | the ms before joining room3, optional (0) | // | --idle | the app's idle_timeout in ms, optional (123,333) | // | --handshake | every room's handshake_timeout in ms, optional (10,000) | +// | --delayOpen | defer native open delivery while transport messages arrive, optional | // | --ping2 | any value: ping each peer of room2 every second, optional | #include #include @@ -32,6 +33,7 @@ #include #include #include +#include #include #include @@ -48,6 +50,7 @@ #include #include #include +#include namespace trystero = webcpp::trystero; @@ -148,11 +151,112 @@ trystero::room join(trystero::app& app, const std::string& room_id, return std::move(*joined); } +// A controlled native handoff: the transport is open, but signaling receives its open event +// 100 ms later. Real messages still use the native wrapper, including its pre-handoff queue. +class delayed_channel : public trystero::backend::data_channel, + public std::enable_shared_from_this { +public: + delayed_channel(const boost::asio::any_io_executor& ex, + std::shared_ptr channel) + : timer_(ex), channel_(std::move(channel)) {} + + void set_handlers(handlers h) override { + timer_.cancel(); + opening_ = + h.open ? std::make_shared>(std::move(h.open)) : nullptr; + if (opening_) { + const auto weak = weak_from_this(); + h.open = [weak] { + if (const auto self = weak.lock()) { + record("delayed-open"); + self->timer_.expires_after(std::chrono::milliseconds(100)); + self->timer_.async_wait([weak](boost::system::error_code ec) { + if (const auto channel = weak.lock(); channel && !ec && channel->opening_) { + channel->released_ = true; + const auto callback = channel->opening_; + (*callback)(); + } + }); + } + }; + } + channel_->set_handlers(std::move(h)); + } + + bool is_open() const override { return released_ && channel_->is_open(); } + + void send(std::span frame) override { channel_->send(frame); } + + std::size_t buffered_amount() const override { return channel_->buffered_amount(); } + + void close() override { + timer_.cancel(); + channel_->close(); + } + +private: + boost::asio::steady_timer timer_; + std::shared_ptr channel_; + std::shared_ptr> opening_; + bool released_ = false; +}; + +// Keeps the fixture's channel observer at both ends without changing SDP or ICE handling. +class observed_connection : public trystero::backend::peer_connection { + using channel = std::shared_ptr; + using observer = std::function; + +public: + observed_connection(std::shared_ptr pc, observer observe) + : pc_(std::move(pc)), observe_(std::move(observe)) {} + + void set_handlers(handlers h) override { + if (h.data_channel) { + h.data_channel = [observe = observe_, deliver = std::move(h.data_channel)]( + channel c) mutable { deliver(observe(std::move(c))); }; + } + pc_->set_handlers(std::move(h)); + } + + channel create_data_channel(std::string_view label) override { + auto c = pc_->create_data_channel(label); + return c ? observe_(std::move(c)) : nullptr; + } + + void set_local_description( + trystero::handler done) + override { + pc_->set_local_description(std::move(done)); + } + + void set_remote_description(std::string_view type, std::string_view sdp, + trystero::handler done) override { + pc_->set_remote_description(type, sdp, std::move(done)); + } + + void add_ice_candidate(std::string_view candidate, + trystero::handler done) override { + pc_->add_ice_candidate(candidate, std::move(done)); + } + + [[nodiscard]] bool has_remote_description() const override { + return pc_->has_remote_description(); + } + + void close() override { pc_->close(); } + +private: + std::shared_ptr pc_; + observer observe_; +}; + /** The native backend, which records each peer connection it makes, for the scenarios that count * them. */ class counting_backend : public trystero::native::backend { public: - using trystero::native::backend::backend; + explicit counting_backend(boost::asio::any_io_executor ex, + trystero::native::backend_config config) + : trystero::native::backend(ex, std::move(config)), ex_(std::move(ex)) {} std::shared_ptr make_peer_connection( std::span servers, @@ -160,9 +264,19 @@ class counting_backend : public trystero::native::backend { auto pc = trystero::native::backend::make_peer_connection(servers, memory); if (pc) { record("made-connection"); + if (delay_open) { + return std::make_shared(pc, [this](auto channel) { + return std::make_shared(ex_, std::move(channel)); + }); + } } return pc; } + + bool delay_open = false; + +private: + boost::asio::any_io_executor ex_; }; /** @@ -341,6 +455,7 @@ int main(int argc, char* argv[]) { auto args = arguments(argc, argv); boost::asio::io_context io; counting_backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + backend.delay_open = !args["delayOpen"].empty(); trystero::app app(io.get_executor(), backend, app_config_of(args)); app.on_error([](std::string_view peer, boost::system::error_code ec, std::string_view what) { record("error", {{"peer", peer}, {"error", ec.message()}, {"what", what}}); diff --git a/test/oracle/interop/run.mjs b/test/oracle/interop/run.mjs index 78ed16c..25fa9ec 100644 --- a/test/oracle/interop/run.mjs +++ b/test/oracle/interop/run.mjs @@ -8,6 +8,7 @@ // headless Chrome, over a local Nostr relay (relay.mjs) or, with --public, Trystero's public relays. // // node interop/run.mjs [--public] [--browser ] [--native ] [--chrome ] [--verbose] +// Add --scenario to reproduce one scenario; no match fails the run. // // With --browser, the browser's C++ peer meets Trystero JS; with --native, the native C++ peer (a process) does. // b2's driven tests interop_browser and interop_native (../Jamfile) pass the program they linked, after their @@ -39,6 +40,7 @@ const args = process.argv.slice(2) const option = name => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined) const usePublic = args.includes('--public') const verbose = args.includes('--verbose') +const scenarioFilter = option('--scenario') const browserPeer = option('--browser') const nativePeer = option('--native') if (!browserPeer && !nativePeer) throw new Error('pass --browser or --native ') @@ -302,6 +304,7 @@ const results = [] const ice = 'stun:127.0.0.1:9' const scenario = async (name, body) => { + if (scenarioFilter && !name.includes(scenarioFilter)) return const started = Date.now() deathsBefore = deaths const pages = [] @@ -469,17 +472,51 @@ const floodScenario = (name, cppKind) => return null }) +// These pair scenarios have one remote peer. Ignore old joins and any new join followed by a leave. +const peerPresentAfter = (events, start) => { + let present = false + for (const event of events.slice(start)) { + if (event.kind === 'peer-join') present = true + else if (event.kind === 'peer-leave') present = false + } + return present +} + // After the exchange, the relay sends every client a text longer than a relay's longest (1 MiB): the C++ peer closes // that relay's connection rather than read it, says so, reconnects, and goes on with the peer it joined. Then the relay // sends the text after every subscription: each reconnection is closed at once, and the C++ peer tries again within a // bound that doubles every time, rather than every few seconds forever. -const oversizedRelayTextScenario = (name, cppKind) => +const oversizedRelayTextScenario = (name, cppKind, recoverFirst = false, delayRecovery = false) => scenario(name, async open => { const params = {room: room(), ...relayParams} const cpp = await open(cppKind, {...params, self: '00000000000000000000'}) const js = await open('js', params) const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000) if (!ok) return 'the exchange did not complete in 30 s' + if (recoverFirst) { + const before = {cpp: (await cpp.events()).length, js: (await js.events()).length} + if (delayRecovery) await js.value('window.delayNextRecovery()') + await js.value('window.drop()') + // A local join does not prove the remote handshake completed. Keep the existing + // recovery bound, accepting only fresh joins that have not since left on either side. + const recovered = async () => peerPresentAfter(await cpp.events(), before.cpp) && + peerPresentAfter(await js.events(), before.js) + if (!(await until(recovered, 30_000))) { + return 'both peers did not recover from the initial connection loss within 30 s' + } + const text = `recovered before relay fault ${params.room}` + await js.value(`window.chat1(${JSON.stringify(text)})`) + if (!(await until(async () => (await js.events()).some(e => e.kind === 'chat' && e.text === `echo: ${text}`), 10_000))) { + return 'the recovered connection did not exchange a fresh message' + } + if (delayRecovery && !(await js.events()).some(e => e.kind === 'delayed-recovery-closed')) { + return 'the controlled one-way handshake delay did not end its connection' + } + } + // Recovery before this fault belongs to setup. Only subsequent departures violate the + // guarantee that losing the signaling relay leaves the established data channel intact. + const cppStart = (await cpp.events()).length + const jsStart = (await js.events()).length left.relay.broadcast(JSON.stringify(['NOTICE', 'x'.repeat(1024 * 1024 + 1)])) const lost = await until(async () => (await cpp.log()).includes(`lost ${left.relay.url}`), 10_000) if (!lost) return 'the C++ peer did not close the relay that sent the long text' @@ -496,7 +533,14 @@ const oversizedRelayTextScenario = (name, cppKind) => console.log(` the C++ peer lost the relay ${seen.length} times, each time to try again within ${seen.join(', ')} ms`) if (!lostAgain) return 'the C++ peer was not closed three times in 30 s' if (!seen.every((bound, i) => i === 0 || bound > seen[i - 1])) return `the bounds did not grow: ${seen.join(', ')}` - if ([...await cpp.events(), ...await js.events()].some(e => e.kind === 'peer-leave')) return 'a peer left' + const text = `still connected after relay faults ${params.room}` + await js.value(`window.chat1(${JSON.stringify(text)})`) + if (!(await until(async () => (await js.events()).slice(jsStart).some(e => e.kind === 'chat' && e.text === `echo: ${text}`), 10_000))) { + return 'the established data channel stopped exchanging after the relay faults' + } + if ([...(await cpp.events()).slice(cppStart), ...(await js.events()).slice(jsStart)].some(e => e.kind === 'peer-leave')) { + return 'a peer left after the relay fault' + } return null }) @@ -958,6 +1002,8 @@ const scenarios = async () => { await reflectScenario('Its own offer sent back as an offer is refused; C++ joins', 'cpp', 'offer') await floodScenario('A flood of announcements from fresh ids is bounded; C++ goes on', 'cpp') await oversizedRelayTextScenario('A relay text longer than 1 MiB is not read; C++ reconnects', 'cpp') + await oversizedRelayTextScenario('A recovered browser peer survives oversized relay messages', 'cpp', true) + await oversizedRelayTextScenario('Browser relay setup waits for both peers after a one-way handshake delay', 'cpp', true, true) await twoRoomsOneConnectionScenario('C++ and Trystero JS share one connection between two rooms', 'cpp') await threeRoomsScenario('Three rooms share one connection, the third joined later by presence', 'cpp') await pageFirstScenario('A room the page joined first binds over the connection within 5 s', 'cpp') @@ -974,6 +1020,21 @@ const scenarios = async () => { await pairScenario('Native C++ offers (lower id), Trystero JS answers; native leaves', {cppKind: 'native', cppSelf: '00000000000000000000', leaver: 'cpp'}) await pairScenario('Trystero JS offers, native C++ answers (higher id), with a password; JS leaves', {cppKind: 'native', cppSelf: 'zzzzzzzzzzzzzzzzzzzz', password: 'secret', leaver: 'js'}) if (!usePublic) { + await scenario('Native C++ preserves both rooms when presence precedes native open delivery', async open => { + const params = {room: room(), room2: room(), ...relayParams} + const cpp = await open('native', {...params, self: '00000000000000000000', delayOpen: 1}) + const js = await open('js', {...params, holdActionsUntilPresence: 1}) + if (!(await until(() => twoRoomsComplete(cpp, js), 60_000))) { + return 'the two rooms did not complete in 60 s after delayed native open delivery' + } + if (!(await cpp.events()).some(e => e.kind === 'delayed-open')) return 'no native open was delayed' + if (!(await js.events()).some(e => e.kind === 'actions-released-after-presence')) { + return 'no JS actions waited for native presence' + } + const counts = await connectionCounts(cpp, 'native', js) + return overBound(counts) || counts.jsConnected !== 1 + ? `connections ${JSON.stringify(counts)}` : null + }) await malformedCandidateScenario('A malformed ICE candidate from a peer does not stop native C++', 'native') await refusedRelayScenario('A relay URL of another scheme reports a close; native C++ goes on', 'native') await textMessagesScenario('Text messages on the data channel do not reach or stop native C++', 'native') @@ -987,6 +1048,8 @@ const scenarios = async () => { await reflectScenario('Its own offer sent back as an offer is refused; native C++ joins', 'native', 'offer') await floodScenario('A flood of announcements from fresh ids is bounded; native C++ goes on', 'native') await oversizedRelayTextScenario('A relay text longer than 1 MiB is not read; native C++ reconnects', 'native') + await oversizedRelayTextScenario('A recovered native peer survives oversized relay messages', 'native', true) + await oversizedRelayTextScenario('Native relay setup waits for both peers after a one-way handshake delay', 'native', true, true) await twoRoomsOneConnectionScenario('Native C++ and Trystero JS share one connection between two rooms', 'native') await threeRoomsScenario('Native C++: three rooms share one connection, the third joined later by presence', 'native') await pageFirstScenario('Native C++: a room the page joined first binds over the connection within 5 s', 'native') @@ -1083,6 +1146,7 @@ try { left.relay = await startRelay() relayParams = usePublic ? {} : {relays: left.relay.url} await scenarios() + if (!results.length) throw new Error(`no scenario matched ${JSON.stringify(scenarioFilter)}`) console.log(`relay: ${left.relay.stats.events} events forwarded, ${left.relay.stats.rejected} rejected`) const failed = results.filter(r => !r.ok).length console.log(failed ? `${failed} of ${results.length} scenarios failed` : `all ${results.length} scenarios passed`) diff --git a/test/provider/Jamfile b/test/provider/Jamfile new file mode 100644 index 0000000..a438ce5 --- /dev/null +++ b/test/provider/Jamfile @@ -0,0 +1,17 @@ +# 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) + +import webcpp ; +webcpp.targets native ; +webcpp.original python3 ; + +# Keep ownership with Trystero so CI provisions its external secp256k1. +# The common executable names all three public dependency aliases. +webcpp.drive combined : ../../../../tools/openssl/test//combined_provider + : release multi on + 60 + : driver.py : : native ; +webcpp.lane provider-integration : combined : native ; diff --git a/test/provider/driver.py b/test/provider/driver.py new file mode 100644 index 0000000..b62c31a --- /dev/null +++ b/test/provider/driver.py @@ -0,0 +1,20 @@ +# 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) + +"""Run the combined native Asio, Beast and Trystero provider consumer bounded.""" + +from pathlib import Path +import subprocess +import sys + + +def main() -> None: + program = Path(sys.argv[1]).resolve() + subprocess.run([str(program)], check=True, timeout=45) + + +if __name__ == '__main__': + main() diff --git a/test/provider/package-lock.json b/test/provider/package-lock.json new file mode 100644 index 0000000..f61b81a --- /dev/null +++ b/test/provider/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "webcpp-trystero-provider-fixture", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webcpp-trystero-provider-fixture", + "version": "0.0.0", + "license": "BSL-1.0" + } + } +} diff --git a/test/provider/package.json b/test/provider/package.json new file mode 100644 index 0000000..6405ef3 --- /dev/null +++ b/test/provider/package.json @@ -0,0 +1,6 @@ +{ + "name": "webcpp-trystero-provider-fixture", + "version": "0.0.0", + "private": true, + "license": "BSL-1.0" +} diff --git a/test/shared_test.cpp b/test/shared_test.cpp index a714264..0facfb1 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -1385,6 +1385,35 @@ void crossed_connections_recover() { BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 2U; })); } +// A native channel can close on its transport thread during the adoption log, before the +// room gets a binding. The queued close must not leave signaling permanently connected. +void a_connection_closed_during_adoption_can_reconnect() { + fixture f{true}; + auto config = app_config("AAAAAAAAAAAAAAAAAAF3"); + std::vector made; + bool closed = false; + f.net.on_made = [&](std::size_t pc, std::span) { + made.push_back(pc); + }; + config.log = [&](std::string_view category, std::string_view text) { + if (!closed && category == "webrtc" && text.ends_with(" adopted")) { + closed = true; + for (const auto pc : made) { + if (const auto connection = f.net.find(pc)) { + connection->close(); + } + } + } + }; + trystero::app a(f.io.get_executor(), f.net, std::move(config)); + trystero::app b(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZF4")); + const auto a1 = join(a, "r1"); + const auto b1 = join(b, "r1"); + BOOST_TEST(run_until(f, [&] { return a1.peers().size() == 1 && b1.peers().size() == 1; }, 15s)); + BOOST_TEST(closed); + BOOST_TEST_EQ(f.net.live_connections(), 2U); +} + // flood isolation. B floods r1 with 10,000 inline messages to an action without a handler // (A's queue keeps 1024) while r2 pings and chats: every r2 message arrives and every ping // completes without error while r1's flood is queued. The virtual clock stays fixed while posts @@ -1915,6 +1944,10 @@ int main(int argc, const char* const argv[]) { a_passwordless_room_is_open_to_the_apps_other_rooms, }, {"crossed_connections_recover", crossed_connections_recover}, + { + "a_connection_closed_during_adoption_can_reconnect", + a_connection_closed_during_adoption_can_reconnect, + }, { "a_flood_in_one_room_does_not_starve_another", a_flood_in_one_room_does_not_starve_another,