diff --git a/AGENTS.md b/AGENTS.md index 55a1f27..fe82992 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,53 +14,163 @@ holds only what is specific to trystero. topic prefixes `"Trystero@"` and `"Trystero:"`, the handshake's `"__trystero_pw"`, every protocol constant and message layout under `include/webcpp/trystero/protocol/`, the default relays in their order, and - the names embind exports, `trystero_dispatch` and the chat's `join` and - `send`. A rename never replaces the word `trystero`: + the names the chat's page calls, `joinRoom` and `sendText`, and the interop + page's `window.leave`. A rename never replaces the word `trystero`: it uses an exact C++ pattern (`namespace webcpp::trystero`, ``, the headers + unchanged, and the README names what derives from Trystero. Comments cite + Trystero's code as `dist/:`, the files of + `@trystero-p2p/core` 0.26.0 as published. +- **The core and the platform.** ``, the headers directly under `include/webcpp/trystero/`, `protocol/` and `detail/` are the core: the rooms over the backend interface of `backend.hpp`, which build on both targets, native and emscripten. - `meta/include-boundaries.json` keeps them free of the two backends, of - libdatachannel, OpenSSL and Emscripten, and the lint fails an include that - crosses it. `browser/` is the browser backend, over the page's WebRTC - through embind, which builds only on emscripten; `browser/src.hpp` holds - the embind registration of `trystero_dispatch`, which a program includes - once. `native/` is the native backend, over libdatachannel, Boost.Beast - and OpenSSL, which builds only natively. `test/Jamfile` compiles each - header alone on the targets that build it, in four calls. -- **The native backend's exceptions.** libdatachannel reports errors by - throwing, and `native/data_channel.hpp` and `native/peer_connection.hpp` - catch them, so they, and `native::backend`, which makes their objects, sit - behind `#ifndef WEBCPP_TRYSTERO_NO_EXCEPTIONS` and do not exist without - exceptions: code that uses them does not compile there. The native timer, - sealer and WebSockets, and everything else of trystero, compile without - exceptions. Every test and program that uses the native backend's WebRTC - declares `on`, with the reason in a comment, and so - does the headers-alone call of `data_channel.hpp` and - `peer_connection.hpp`, which declare nothing without exceptions: - `/webcpp/trystero//native` cannot, since b2 ignores a non-free feature among - usage requirements, so a user's `exception-handling=off` would reach them. - The lint names those two headers as left out of its analysis without - exceptions; `backend.hpp`, `sealer.hpp` and `websocket.hpp` are compiled - 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`. + `meta/include-boundaries.json` keeps them free of the platform backend, of + its WebRTC and webcpp::webrtc, of libdatachannel, OpenSSL and Emscripten, + and the lint fails an include that crosses it. `platform/` is the platform + backend, `platform::backend` (`platform/backend.hpp`): one class that + implements the backend interface on both targets, never one per target. + `webrtc/` is its WebRTC, over webcpp::webrtc, on both targets: one peer + connection and one data channel, which hold + `webcpp::webrtc::basic_peer_connection` and `basic_data_channel` over a + `std::pmr::polymorphic_allocator` on the app's resource and keep + trystero's policies over them. Its relays are one session of webcpp::beast + on both targets (`platform/websocket.hpp`), natively over Boost.Beast's + own stream and in a page over webcpp::beast's page `WebSocket`. Its timer + is the core's `detail::timer` over webcpp::asio's `steady_timer`, the one + timer on both targets. Its clocks are the standard library's on both + targets, `std::chrono::system_clock` floored to whole seconds + (`unix_now`) and `std::chrono::steady_clock` (`steady_now`), which + Emscripten reads from the page's `Date.now()` and `performance.now()`. + Two parts are the target's own, chosen by `WEBCPP_TARGET_EMSCRIPTEN`, + config's (neither the library nor its tests test `__EMSCRIPTEN__`): the + sealer (`platform/sealer.hpp`), natively OpenSSL's AES-256-GCM and in a + page `crypto.subtle` through webcpp::asio's `browser::async_await`; and + the platform's one source of randomness, + `platform::detail::fill_random` (`platform/entropy.hpp`), whose result is + checked: natively OpenSSL's `RAND_bytes`, in a page + `crypto.getRandomValues`, at most 65536 bytes a call, from an `EM_ASM` + block that catches what it throws (Emscripten's `getentropy` let a + missing or throwing one through into WebAssembly). Without randomness + `random()` aborts the program and a seal fails with + `error::backend_failure`. `platform/page.hpp`, which builds only on + emscripten (an `#error` elsewhere), holds what a page's program uses beside + the backend, `platform::page_call` and `platform::js_string`; a program + includes no source file of trystero's: `/webcpp/asio//asio` links the + browser runtime. `test/Jamfile` compiles each header alone on the targets + that build it, in three calls: the core; `platform/backend.hpp`, + `entropy.hpp`, `sealer.hpp`, `websocket.hpp` and `webrtc/` on both + targets, with `/webcpp/trystero//platform`; and `platform/page.hpp` on + emscripten. +- **The backend interface stays.** The rooms hold the backend's peer + connections and data channels through `backend::peer_connection` and + `backend::data_channel`, abstract classes, as chapter 15 decided: the + memory relays (`test/support/memory_backend.hpp`) implement them for the + rooms of the tests, on both targets, where node has no WebRTC, and the + interop's native peer wraps the platform backend's (`delayed_channel`, + `observed_connection`). Their one implementation over a platform is + `webrtc/`, which webcpp::webrtc's table "trystero's backend, part by + part" maps part by part. The interface's clocks are std::chrono's, so + that no unit is converted at the seam: `factory::steady_now` returns the + `std::chrono::steady_clock::time_point` the core keeps + (`detail::time_point`), from an origin of the backend's, and + `factory::unix_now` a `std::chrono::sys_seconds`, which a Nostr event's + `created_at` and a subscription's `since` write. +- **Exceptions.** trystero's WebRTC is webcpp::webrtc's, which natively calls + libdatachannel's C API, where no exception crosses: every part of trystero, + the platform backend included, works with exceptions and without them on + both targets, and no program or test asks for `on`. + Every `platform_*` test but `platform_websocket` also runs with + `exception-handling=off`, its `_no_exceptions` twin, as the evidence. + trystero raises nothing of its own; a raise would go through + `boost::throw_exception`; natively the platform backend keeps a TLS + context OpenSSL cannot make as an error value (`tls_context()`), and its + `wss://` relays report a close. +- **webcpp::asio.** trystero names Asio as `webcpp::asio` wherever it builds + on emscripten (the core, the platform backend, the tests over the memory + relays, the examples and the browser's interop peer): natively it is + Boost.Asio itself, and on emscripten the backend webcpp::asio ships, a + service of whose `io_context` webcpp::webrtc's browser objects deliver + through, so the room's executor must be webcpp::asio's. The platform + backend names it everywhere, on both targets, its relays' WebSockets + included, which are webcpp::beast's over webcpp::asio. The guide's + reference reads every header for Emscripten's target, where webcpp::asio + and webcpp::beast are their browser implementations and + `platform/page.hpp` builds, with `/webcpp/trystero//platform` built + natively (`multi`) beside `/webcpp//emscripten-reference` + (`doc/Jamfile`). `/webcpp/trystero//trystero` brings `/webcpp/asio//asio`: + on emscripten every program is built in a suspension variant + (`webcpp-suspend=jspi` by default, or `asyncify`) and named after it + (the chat's `chat-program-60-d-jspi.js`), and the suites run in both. + A page's program runs its io_context from `main` under a work guard, as + webcpp::asio's model asks (the owner's decision of 2026-11-14): the page's + events post to it through the bridge, and the page calls C++ only through + `platform::page_call` (`platform/page.hpp`), a bridge function that posts, + never through embind. Under Asyncify an embind function called while + `main` is suspended returns a promise that never settles, and its second + call aborts a debug build. A page_call's handler lets no JavaScript error + out, webcpp::asio's rule for every handler, since one leaves `run` for + good: it checks the page's value before converting it, and the chat and + `platform_page` do (`platform_page` passes a number and `undefined`). Its + resource holds each call until the io_context runs it or is destroyed, so + it outlives the io_context (`platform_page_call`). + Every emscripten test that runs an io_context runs it from `main`, and + ends with `webcpp::test::exit_status`, since under Asyncify a `main` that + suspended loses what it returns; `platform_page` proves the program's + shape. Under Asyncify a room needs no more of its stack than + webcpp::asio's 8,192 bytes: its work runs in handlers, between the run's + waits, never on the stack when `run` suspends (in debug, the deepest + build, the chat's pages measured 1,032 bytes, the interop page 920, the + page tests 1,600 at most; in release, linked at `-O3`, 328, 348 and 384). + A test's cases are on that stack, since each calls the run family itself: + a test whose cases suspend runs each through `webcpp::test::run_case` + (`test/cases.hpp`), in a frame of its own, which `main`'s never holds, + whatever the link. `-O3` inlines every case into `main`, and a link + without optimization, b2's for release until 2026-11-15 and still a + program's own `-O0`, keeps their locals in `main`'s frame, + which the room test saw at 29,776 bytes, past the 8,192, at its first + suspension. `room_asyncify_release`, `app_impl_asyncify_release` and + `allocation_asyncify_release` run the deepest of those tests in release, + trystero's only programs that the CI's emscripten lane, building JSPI, + runs under Asyncify; linked at `-O3`, a `main` with every case inlined + fits (616 bytes for the room test), so they no longer catch one. There is + one timer, the core's `detail::timer` over webcpp::asio's `steady_timer`, + on both targets, which `timer` tests on both. - **The dependencies.** libsecp256k1 (every room) is webcpp's own build, `/third_party//secp256k1` (v0.8.0, from `third_party/libs/secp256k1`), which `/webcpp/trystero//trystero` names; its tables come from `webcpp-secp256k1-tables` (see `doc/building.adoc`). Nothing is installed outside the checkout, once the pinned submodules are initialised. - The native backend also 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 + `/webcpp/trystero//trystero` (`build.jam`'s `tag::trystero[]`) is the + rooms alone, the core: `parts`, its headers, Boost, webcpp::document + (`/webcpp/document//document`, with Boost.JSON's and Boost.Charconv's + definitions), config, webcpp::asio and libsecp256k1, and under Asyncify + the list that leaves Boost.JSON's parser uninstrumented + (**webcpp::document**, below); on no target does it bring webcpp::webrtc, + and the tests over the memory relays use it alone. + `/webcpp/trystero//platform` (`tag::platform[]`) is the platform backend's + target on both targets, the rooms and `platform-parts`, the backend over + `parts`, alternatives by `emscripten`, which a native program and + a page's program both name. A test of a part that parses no JSON + (`timer`, `platform_websocket_url`, `platform_page_call`, + `platform_page_sealer`, `platform_page_sealer_allocation` and their twins + without exceptions) links `parts` or `platform-parts` in place of the + rooms, `$(part)` or `$(platform-part)` in `test/Jamfile`, without that + list: Binaryen warns of a pattern that names none of a program's + functions. The backend's WebRTC is + webcpp::webrtc's, `/webcpp/webrtc//webrtc`, on both targets; natively it + 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. For the relays + `/webcpp/trystero//platform` also names, natively, `/webcpp/beast//tls`, + `/webcpp//boost_url` and `/webcpp/asio//tls`, whose embedded authorities + a program may trust in place of the system's, and on emscripten + `/webcpp/beast//browser` and `/webcpp//boost_url`, with no OpenSSL. 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 @@ -70,40 +180,136 @@ holds only what is specific to trystero. 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; + native consumer of `/webcpp/trystero//platform` must declare + `multi`, including native headers-alone and reference targets. + An explicit single-threaded native build of the platform backend fails + with an actionable B2 diagnostic; a page has no threads, and the target + asks for none on emscripten. Asio and Beast still support their own + single-threaded OpenSSL builds. +- **The runtime.** webcpp::webrtc's `runtime` caps the connections alive at + once and, natively, holds libdatachannel's process-wide state: at most one + exists in a process at a time. `platform::backend` makes one of its own, + in `backend_config::memory`, with `backend_config::runtime` (its + `max_peer_connections` 256 by default), or takes the program's + (`backend(ex, runtime, config)`, or `backend(ex, tls, runtime, config)`), + on both targets, and every connection and channel of the backend's WebRTC + keeps it alive through a `std::shared_ptr`, so that one a queued handler + holds after the backend is gone never outlives it. In a page + webcpp::webrtc's census of the page counts every runtime's connections. +- **The relays.** One session (`platform/websocket.hpp`) serves both + targets: resolve, connect, TLS, the handshake, a read loop and one write at + a time, on the room's executor, natively over Boost.Beast's own stream, + whose next layer is webcpp::beast's `bounded_handshake_stream` over the + transport, with a body limit of 0 (a refusal's body is never read), and + in a page over webcpp::beast's page `WebSocket` (`/webcpp/beast//browser`). + On both targets a write that fails ends the session at once, reporting one + close, unless it is already closing, when its read ends it. A relay's URL + is read with Boost.URL on both targets, by the same rules, which the + guide's "The relays" lists: an IPv6 address in brackets reaches the + resolver without them, the scheme in any case, a host decoded and in + lower case, an escaped dotted quad an address; userinfo, a fragment, a + port beyond 65535, an IPvFuture host and `http://` and `https://` (which a + page's `WebSocket` alone would take as `ws://` and `wss://`) are refused, + and what a page's URL parser reads otherwise fails closed: IPv4 shorthands + (`127.1`) and any host whose last label is a number, international names + (no A-labels: webcpp::idna is not used yet), tabs, newlines and + backslashes, and a path character outside RFC 3986, which a page escapes. + `platform_websocket_url` tests the rules on both targets. Each refusal + reports a close. Over TLS the connection sets `verify_peer` on its stream + whatever the program's context says, on both targets (webcpp::beast's page + stream refuses another mode, and reads the stream's before the + context's). Natively it sends the host (SNI), through + `webcpp::beast::set_server_name`, only when it is a name once decoded, and + checks the certificate against the URL's host, a name or an address, with + Asio's `host_name_verification`; in a page the browser does all three, and + the page's stream refuses a context with authorities added, client + credentials, options, a method other than `tls_client` or `sslv23_client`, + or a verify callback other than `host_name_verification` of the relay's + host, so that every `wss://` relay of such a context reports a close + (`platform_page_websocket_tls`). A relay's binary message is dropped, on + both targets: Nostr's messages are texts. The reads' and the writes' + completions are the session's own `transfer_handler`, a member pointer + with the room's allocator and no executor, never Asio's + `any_completion_handler`, whose `any_completion_executor` Asio made with + `new` for each operation (`platform_websocket_allocation`). On Windows the + system's authorities are none unless `SSL_CERT_FILE` or `SSL_CERT_DIR` + names some. A backend trusts the system's authorities by default + (`platform::make_tls_context()`, which in a page records only the policy + the page's stream asks for), or the program's context through the + constructors that take a `boost::system::result`; `tls_context()` returns + that result, and a backend whose context holds an error reports a close + for every `wss://` relay. The test's TLS server uses an authority and a + certificate for `localhost` embedded in `test/platform_websocket_test.cpp` + (EC P-256, valid from 2026-01-01 to 2126-01-01), which nothing else + trusts; its `embedded-roots` region is what the guide's page includes. +- **The backend's WebRTC policies** (`webrtc/`), on the executor, on both + targets: a text message, or a binary one larger than a room frame, is + dropped after `async_receive` (webcpp::webrtc reads every message into a + vector of the app's resource, at most `max_message_size`, 256 KiB); the + connection's state and its ICE state merge into one, as a page sees them; + a local candidate leaves as the JSON of an `RTCIceCandidateInit` and a + remote one is read from it; `buffered_amount_low` is reported when the + amount falls to 64 KiB after a send left it above. Natively a URL + libdatachannel cannot parse (`stuns:`) is left out by trying each URL + alone; in a page a refused server refuses the connection. The per-minute + window (`backend_config::max_peer_connections_per_minute`, 256) is + `platform::backend`'s, a `detail::construction_window` in + `backend_config::memory`, on both targets. `backend_config::bind_address` + is passed to webcpp::webrtc on both targets; a page leaves it empty, since + webcpp::webrtc refuses to bind there. +- **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, on both targets now. Overflow or expiry closes the channel; close + clears the queue. The timer is the factory's (`make_timer` with the app's + resource), whose waits a restart or a cancel invalidates. 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 read + ahead of the flush drains older frames when a receiver exists. A transport + closed during adoption, before binding, forgets its negotiation and + restarts announcements. `platform_peer_connection` tests real queued events + (the offerer made on an executor the test runs), FIFO, replacement, close, + limits and resource release (`webrtc::data_channel::pending_frames`); `shared` tests closure during adoption, and interop controls native open delivery while a JS peer sends both rooms' presence first. +- **A room frame advertises its room.** A frame of a local room's token that + a connection keeps records the token as the remote's advertisement, as its + presence does (64 tokens at most; a frame never ends the connection for a + 65th), and the room binds on it. Trystero sends a room's presence once per + connection, from the open of its channel, and Chrome can drop what a page + sends on an answering channel as it opens: measured in a 2-CPU Linux + container, 8 of 240 runs of the interop's delayed-open scenario, Chrome + logging "Send failed INVALID_STATE" for both presence frames and the native + peer's SCTP receiving neither. Waiting for presence alone left the room + unbound for good, with the page's frames of the room kept and expiring. + `connection` and `shared` drop the presence over the memory relays. - **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. -- **No JavaScript exception enters WebAssembly.** The browser backend makes - every call into JavaScript that can throw (a constructor, `JSON.parse`, a - `send`, a WebRTC or Web Crypto method) through `browser/js.hpp`, whose - JavaScript, defined once in `browser/src.hpp` with `EM_JS`, runs it inside - `try` and returns a value or the exception as a value, which the C++ turns - into the error its interface has. Every event of the page enters C++ - through a function of the same file that catches what still escapes, - puts WebAssembly's stack pointer and the loop's depth back as they were - before the call, reports it and lets the loop poll again. With - exceptions, `browser::dispatch` catches a C++ exception first, which - frees it: one that reached JavaScript would keep its object for good. A - message that is not a frame is dropped before it is read. The browser - tests run under node with exceptions and without them - (`*_no_exceptions`), and the interop lane passes both ways. + `/webcpp/asio//asio` adds as a linker flag, and `/webcpp/trystero//trystero` + brings: `on`, b2's own feature, is not free, and b2 ignores it + among usage requirements. +- **No JavaScript exception enters WebAssembly.** In a page the platform + backend's calls that can throw are caught in JavaScript and return what + failed as a value, which the C++ turns into the error its interface has: + a `WebSocket` constructor or `send` in webcpp::beast's page stream, which + turns a socket that cannot be made into an error, so that its relay + reports a close; a Web Crypto method in an `EM_ASM` block of an inline + function of `platform/sealer.hpp`, made inside an `async` function, so + that what it throws rejects its promise, whose settlement is read only when + it is an `ArrayBuffer`; `crypto.getRandomValues` in an `EM_ASM` block of + `platform/entropy.hpp`, which returns its failure. Every event and every + page call enters C++ through webcpp::asio's bridge, which restores + WebAssembly's stack pointer, catches a C++ exception in C++, which frees it + (one that reached JavaScript would keep its object for good), and only + posts. + webcpp::webrtc's JavaScript catches the page's WebRTC exceptions the same + way, and its events come through the same bridge, which posts to the + io_context. A message that is not a frame is dropped on the executor, + after webcpp::webrtc read it: a text as the few bytes it holds, a binary + one at most 256 KiB, past which the channel closes. The platform's tests + on emscripten (`platform_backend`, `platform_sealer`, + `platform_websocket_unreachable`, `platform_websocket_url` and every + `platform_page*`) run under + node with exceptions and without them (`*_no_exceptions`), and the + interop lane passes both ways. - **Bounded signaling.** Announcements are not sealed, so anyone who knows the app and room ids can announce any number of peer ids, and anyone who reads the relays can send any signal in any peer's name. @@ -140,15 +346,34 @@ holds only what is specific to trystero. negotiations with peers it is not connected to. A negotiation whose offer and answer expire without a connection is dropped, an idle one gives its place to a new peer, and a new peer beyond the bound is - refused and logged once. + refused and logged once. Idle means no connection and no offer of the + peer being opened (`negotiation::opening_offer`): the one idle longest + goes, and of those idle as long, as at one instant of a page's coarse + clock, the one taken first (`negotiation::admitted`), never the first in + id order. An offer the sealer is opening keeps its place, so new ids + that arrive meanwhile cannot have the room drop it unopened (`room`'s + `an_offer_being_opened_keeps_its_place` and + `a_flood_of_offers_at_one_instant_is_bounded`, over the memory backend's + `hold_sealer_opens`). + - A negotiation opens one offer of its peer at a time, as Trystero answers + one at a time (`dist/signal-handler.mjs:264-323`): another offer in that + name is ignored until it is opened, and the same offer through another + relay meanwhile has the answer sent there too, as Trystero's replay + records its relay. So the room opens at most 32 offers at once, and + offers in one name, however many, hold one open and one copy of an offer + (`room`'s `offers_in_one_name_are_opened_one_at_a_time`). As with + Trystero, a forged offer opened first has the peer's own, arriving + meanwhile, wait until the peer sends it again, 2 s later. - A room makes at most `max_connections_per_window` (64) connections in - any 57 s, however soon they end, and a page at most - `browser::backend::max_peer_connections` (256), counted from their - construction until the garbage collector frees them, as Chromium counts - them against its 500 (measured with headless Chrome: the 501st throws - "Cannot create so many PeerConnections", and a closed one counts until - a collection). The native backend makes at most - `backend_config::max_peer_connections_per_minute` (256). + any 57 s, however soon they end. The platform backend makes at most + `backend_config::max_peer_connections_per_minute` (256) in any minute, + for every app and room it serves, on both targets, and holds at most its + runtime's `max_peer_connections` (`backend_config::runtime`, 256) at + once: natively those alive, and in a page those webcpp::webrtc's census + of the page counts, from their construction until the garbage collector + frees them, as Chromium counts them against its 500 (measured with + headless Chrome: the 501st throws "Cannot create so many + PeerConnections", and a closed one counts until a collection). - A signal's fields are bounded in `protocol/signal.hpp`: the peer id (64 bytes; Trystero's are 20), the offer id, a sealed offer or answer (64 KiB) and a sealed candidate (16 KiB, above the 8192 bytes of @@ -156,18 +381,37 @@ holds only what is specific to trystero. - A room asks a peer below it to offer at most once in 5.3 s per relay, Trystero's announce interval, so a flood of low ids does not have the relays rate-limit the room. + - A strategy remembers the newest 4096 event ids + (`detail::nostr_strategy::remembered_events`) in a + `boost::unordered_flat_set` hashed with Boost.Hash2's `siphash_64` under + a key drawn from the backend's randomness when it is made, since a relay + chooses the ids (`room`'s `a_strategy_draws_the_key_of_its_event_ids`). + It remembers an id only once `protocol::nostr::has_own_id` found it to be + the SHA-256 of the event's NIP-01 serialization, which + `protocol::nostr::event_id` computes over an event whose one tag is its + topic's, as Trystero writes them; any other event is acted on every time, + as Trystero acts on every event, so that a relay that sends a forged + event under a genuine event's id first hides nothing (`room`'s + `a_forged_event_under_a_genuine_id_hides_nothing`). - A relay is a third party too. A text longer than 1 MiB closes its - connection on both backends. A relay that stops reading is dropped once - the text held unsent for it would pass 4 MiB - (`protocol::max_queued_relay_bytes`): the native queue on native - (`native::websocket_limits::max_queued_bytes`), the page WebSocket's - `bufferedAmount` in the browser. On native only, a relay that stops - answering is dropped once `idle_timeout` (30 s) passes with its - keep-alive ping unanswered (`backend_config::relay_limits`); the idle - timeout counts bytes received, and a ping waits for the write in - flight. A page's `WebSocket` cannot ping, so the browser has no idle - timeout. Each drop reports one close, and the room reconnects with its - backoff. + connection on both targets, in a page before it is copied into + WebAssembly (webcpp::beast's `read_message_max`, set before the + handshake, since a page can deliver a relay's first messages in the task + of its open: `platform_page_websocket_ingress`). A relay that stops + reading is dropped once the text held unsent for it would pass 4 MiB + (`protocol::max_queued_relay_bytes`): the session's own queue on both + targets (`platform::websocket_limits::max_queued_bytes`), and in a page + also the `WebSocket`'s `bufferedAmount`, which webcpp::beast's + `queue_limits::send` bounds to the same, past which the write fails. + In a page the texts a relay sent that wait for the executor are bounded + by webcpp::beast's `queue_limits::receive` (4 MiB), past which the + socket closes. Natively only, a relay that stops answering is dropped + once `idle_timeout` (30 s) passes with its keep-alive ping unanswered + (`backend_config::relay_limits`); the idle timeout counts bytes + received, and a ping waits for the write in flight. A page's + `WebSocket` cannot ping, and webcpp::beast's page stream refuses + keep-alive pings, so a page has no idle timeout. Each drop reports one + close, and the room reconnects with its backoff. - What a flood still does: joined peers, memory and connections stay safe, but a flooder who keeps sending new ids takes each place, or each connection of the window, as it frees, so new peers can be kept out for @@ -199,7 +443,8 @@ holds only what is specific to trystero. bindings. A kick ends only its binding; if the last binding was kicked, close at once. After departures, idle expiry is `app_config::idle_timeout`, 123,333 ms by default, 0 closes immediately. A remote must advertise the token - itself before any binding; forged relay announcements bind nothing. + itself before any binding, by its presence or a kept room frame; forged relay + announcements bind nothing. Rebinding after a kick or peer leave uses the larger of handshake timeout and 10 s plus 1 s, doubling to 5 minutes until a completed handshake or connection end. The lower id refuses bindings during its own-kick @@ -225,21 +470,31 @@ holds only what is specific to trystero. frames and reporting exact unsent bytes through `buffered`. Set `virtual_clock` before making timers: `advance`, `step` and `poll_ready` run due timers and ready work deterministically, in due-time and registration - order. Optional hook storage uses the default resource only when enabled; - allocation tests enable none. `connection`, `memory_backend`, `shared`, + order. The virtual clock is a `std::chrono::steady_clock::time_point` + from the clock's epoch, which `steady_now` returns, and `unix_now` reads + it as 2025-10-05T21:33:20Z plus its whole seconds; tests compare its + durations exactly. Optional hook storage uses the default resource only + when enabled; allocation tests enable none. `connection`, `memory_backend`, `shared`, `shared_no_exceptions` and `shared_hardened` cover these paths, with sanitizers and library hardening checking resource lifetimes. - **The oracle and the interop tests, trystero's own lanes.** `test/oracle/` pins Trystero 0.26.0 (`trystero`, `@trystero-p2p/core` and `@trystero-p2p/nostr`, with `ws` 8.22.0 and `@noble/secp256k1` 3.2.0 for - the local relay, which imports both) in its `package.json` and - `package-lock.json`, which `webcpp.original node` installs. Its `Jamfile` + the local relay, which imports both, and werift 0.24.4, the WebRTC the + twins give Trystero JS in Node as `rtcPolyfill`, which Trystero's README + names for Node) in its `package.json` and `package-lock.json`, which + `webcpp.original node --conditions=development` installs. Its `Jamfile` declares two own lanes. `oracle`, which names no target: `oracle.mjs` runs Trystero's own functions over the inputs of `test/fixtures/cases/protocol.json` and writes `expected.json`, which must equal `test/fixtures/expected/expected.json` byte for byte, the file the - `protocol` and `native_sealer` tests read; `update-expected` is its only - writer. `interop`, on native and emscripten (`native.trystero.interop` and + `protocol`, `signaling` and `platform_sealer` tests read, and `webcpp.twins` + runs every twin of `example/` through `run_twin.mjs` (below); + `update-expected` is the only writer of `expected.json` and of each + divergent twin's output. Trystero draws its self id from `Math.random` when + its core loads, so the oracle draws it from the fixture's pattern then: the + answerer's signals, which Trystero's own signal handler publishes for the + oracle's offers, carry it. `interop`, on native and emscripten (`native.trystero.interop` and `emscripten.trystero.interop` in the report): two driven tests, `interop_native` and `interop_browser`, whose driver `interop/run.mjs` meets the C++ peer, the native one as a process or the browser's in @@ -271,12 +526,12 @@ holds only what is specific to trystero. (`relay.options.strike`), which twelve peers in turn must survive and reconnect after; and the driver's own check that a native peer killed by a signal (`abort` on its standard input) is named at once. The - native peer and `native_websocket` are built with the standard + native peer and `platform_websocket` are built with the standard library's own checks (libc++'s extensive hardening, libstdc++'s assertions), so that a completion that touches a cleared container fails at once. Both lanes are of the kind `original`, so the CI gives them its Node. - - Shared scenarios on both backends cover: (1) two rooms on one + - Shared scenarios on both targets cover: (1) two rooms on one connection, with chat and 100 KB files both ways; (2) a third room joining later by presence; (3) the page's rooms joined before the C++ app's; (4) admission to a passwordless room by token and refusal by a @@ -300,7 +555,7 @@ holds only what is specific to trystero. - 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 - 127.0.0.1 (`native::backend_config::bind_address`), and the Trystero JS + 127.0.0.1 (`platform::backend_config::bind_address`), and the Trystero JS peers have `rtcConfig: {iceServers: []}`. - Chrome is `--chrome`, `CHROME`, or on macOS Playwright's `chrome-headless-shell` from its cache; elsewhere `CHROME` is required, @@ -348,7 +603,8 @@ holds only what is specific to trystero. `room_options::memory`, the app's resource when null, receives room state, bindings and drain waiters, negotiation records, rebinding counts and backoffs, sealed texts, relay sockets, signing context, - actions, outgoing frames, queues, transfers, JSON storage and handlers. + actions, outgoing frames, queues, transfers, the documents of the JSON + texts it reads, and handlers. Every touch runs on the app's executor; one thread needs no thread-safe resource, multiple threads require a strand. - **References and detachment.** Rooms hold the app strongly, the app @@ -363,29 +619,39 @@ holds only what is specific to trystero. operations. A room's own resource must outlive its state, retained values and pending operations. Declare both before the io_context, then the backend, app and rooms, and drain or destroy the io_context - before either resource. Browser resources live until pending promises - settle, in practice for the page's life. A raw resource pointer cannot - detect early destruction; a counting resource that checks nothing is - outstanding at destruction makes this the user's check. + before either resource. In a page the resources live until pending + promises settle, in practice for the page's life. A raw resource + pointer cannot detect early destruction; a counting resource that checks + nothing is outstanding at destruction makes this the user's check. - **Which resource.** A room allocates and frees on every event (a frame, a parsed text, a post, a log line), so a resource that reuses what is freed, a pool, suits a long-lived room; a `std::pmr::monotonic_buffer_resource` grows with every event and suits a short-lived one, or a test. - - **Containers.** Every container trystero declares is a `std::pmr` one, - but `trystero::bytes` (a `std::vector`) and - `trystero::payload` (a variant of `std::string`, `boost::json::value` and - `bytes`), the user's choice of `std::allocator`: + - **Containers.** Every container trystero declares is a `std::pmr` one + or a Boost container over `std::pmr::polymorphic_allocator`, but + `trystero::bytes` (a `std::vector`) and + `trystero::payload` (a variant of `std::string`, + `webcpp::document::document` and `bytes`), the user's choice of + `std::allocator`: `std::pmr::string` (and `peer_id`), `std::pmr::vector` (and `backend::bytes`, `protocol::bytes` and `pmr_bytes`), `std::pmr::deque`, - `std::pmr::map`, `std::pmr::set`, `std::pmr::unordered_map` and - `std::pmr::unordered_set`, built over its owner's resource. A struct that + `std::pmr::map` and `std::pmr::set`, and three Boost containers over + `std::pmr::polymorphic_allocator`: `boost::unordered_flat_set` (the event + ids a strategy remembers), `boost::circular_buffer` (the construction + window, the recent challenges) and + `boost::circular_buffer_space_optimized` (the replay cache), each built + over its owner's resource. A struct that holds them takes the room's `std::pmr::polymorphic_allocator<>` in its constructor, and a container of such structs is given it when it makes one (`try_emplace(key, allocator)`). A `std::pmr` container is never copied without an allocator: its copy constructor takes the default resource, so a copy names the resource - (`std::pmr::string(text, allocator)`). Moving keeps the resource. + (`std::pmr::string(text, allocator)`). Moving keeps the resource. No + type of trystero is a data structure meant for a shared segment, which + chapter 4 asks each library to state: every type is a run-time object + (apps, rooms, actions, sockets, handlers, the backend), routed through + `std::pmr` resources, and none is shareable. - **Shared objects** are made with `std::allocate_shared` over `std::pmr::polymorphic_allocator<>`, never with `std::make_shared`, `std::make_unique` or `new`; a timer is a `std::shared_ptr` for that @@ -410,21 +676,33 @@ holds only what is specific to trystero. takes a `std::pmr::memory_resource*` as its last parameter. Peer connections, data channels and received frames use the app's; relay sockets, sealers and room timers use the room's. The backend allocates - objects, handlers and their frames or texts through that resource. - - **Asio.** Every `boost::asio::post`, `dispatch`, timer wait and - `any_completion_handler` the room makes carries - `boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), - ...)`. A post through `boost::asio::any_io_executor` is wrapped by Asio in + objects, handlers and their frames or texts through that resource; the + backend's WebRTC gives webcpp::webrtc's objects a + `std::pmr::polymorphic_allocator` on the app's resource, and binds it + over the handler of each operation it starts. The platform backend's own + state, its copy of `bind_address`, its window of constructions + (`detail::construction_window`) and its own `webcpp::webrtc::runtime`, is + in `backend_config::memory`, the default resource unless the program + gives one, on both targets; it must not be null, and must outlive the + backend and every connection of its runtime. `platform_backend` proves + it on both targets, with none of that state in the default resource. + - **Asio** (webcpp::asio). Every `webcpp::asio::post`, `dispatch`, timer + wait and `any_completion_handler` the room makes carries + `webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), + ...)`. A post through `webcpp::asio::any_io_executor` is wrapped by Asio in a function object allocated with `std::allocator`, from Asio's per-thread recycling cache, which calls `std::aligned_alloc` on a miss (measured: two per post, in every round of five posts, natively and on emscripten). So `detail::post` posts through the executor of an `io_context` when the room's executor is one, where Asio allocates the - operation as the handler's allocator says; on another executor the - wrapper stays Asio's. A user's completion handler is allocated as its - own associated allocator says: the room never binds its allocator over - it, and the page shows `bind_allocator` with the room's resource. When - the room erases a completion handler's type + operation as the handler's allocator says, and a page's sealer awaits + each Web Crypto promise through it so too + (`platform_page_sealer_allocation` proves it, against two C library + allocations a seal or an open before); on another executor, a strand for + one, the wrapper stays Asio's. A user's completion handler is allocated + as its own associated allocator says: the room never binds its allocator + over it, and the page shows `bind_allocator` with the room's resource. + When the room erases a completion handler's type (`detail::completion`, an `any_completion_handler`), it records whether the handler's associated executor is the room's, which only the concrete type tells without allocating; such a completion runs from an operation @@ -433,55 +711,113 @@ holds only what is specific to trystero. type-erased executor wraps it with `std::allocator` (measured: telling the executor apart through the erased type cost two `operator new` calls a completion, and Asio's wrapper a `std::aligned_alloc`). - - **Boost.JSON** allocates through `json_resource` (`json_resource.hpp`), - a `boost::container::pmr::memory_resource` that forwards to a - `std::pmr::memory_resource`, header-only: `boost::container::pmr`'s own - global resources are compiled (`BOOST_CONTAINER_DECL`), and the CI - installs Boost's headers alone. The room's JSON storage is - `boost::json::make_shared_resource(memory)`, made once when - the room is constructed, since a value a handler keeps may outlive the - room. Text is parsed by a `boost::json::parser` over that storage, never - by `boost::json::parse`, whose temporaries beyond a stack buffer come - from the default resource; JSON is written by a - `boost::json::serializer` whose stack is the resource. + - **webcpp::document** is allocator-aware: a + `webcpp::document::pmr::document` allocates through a + `std::pmr::polymorphic_allocator` its image, one buffer in + which Boost.Interprocess's `rbtree_best_fit` heap holds every value, + strings included, with offsets for pointers, and the working state of + what reads or writes it (the parser's state, the path and the pending + key and text, the tree's record of each change, the writer's stack), + each piece freed before the call that made it returns. trystero reads + every text with `webcpp::document::parse(text, options, allocator)` into + a document of the room's resource (of the app's for a remote + candidate), and keeps no owner of its own around it: the caller's text + bound is `parse_options::max_bytes`, a protocol text nests at most 16 + deep (`protocol::json::max_protocol_depth`), and the image, 4 KiB at + first, grows in place to at most twice that bound and 64 KiB + (`protocol::json::protocol_limits`, as `max_document_bytes`). A JSON + payload's image grows to at most 96 times its length and 64 KiB + (`protocol::json::image_bytes_per_text_byte`, a value of one character + and its comma being a node of 192 bytes, so every valid payload fits), + or the room's `room_options::max_json_document_bytes`, 64 MiB by + default, the smaller (`protocol::json::payload_limits`); its depth is + document's 256. Under Asyncify `/webcpp/trystero//trystero` links + `-sASYNCIFY_REMOVE=@asyncify-remove.json`, which leaves Boost.JSON's + recursive descent (`basic_parser<...>::parse_*`, which never suspends) + uninstrumented: instrumented, a cold debug build overflowed node's stack + at about 150 levels, so a peer's first payload nested 256 deep crashed + the page; the room test sends one first. `parts` and `platform-parts` + leave the list out, for the tests of parts that parse no JSON, whose + programs have none of the parser's functions. A text the room writes + is appended field by field to a `std::pmr::string` of its resource, its + strings quoted by `webcpp::document::quote`, which allocates only + through that string, and a JSON payload is written by + `webcpp::document::stringify_to` in pieces of 8 bytes, which no standard + library's string keeps outside its own object. A `pmr::document` is + never move-assigned across resources inside trystero: that copies the + image, and raises `std::bad_alloc` through `boost::throw_exception` when + the target has no room, which a build without exceptions must not reach; + a received one is moved by construction alone. - **Payloads.** `detail::payload_traits` has `std::pmr::string` and `std::pmr::vector` (`webcpp::trystero::pmr_bytes`) beside - the standard types, and `decode(incoming& message, - std::pmr::memory_resource* memory)` takes the resource for every type: - the `std::pmr` types are built in it, and `boost::json::value` in the - room's JSON storage, which the message carries. `std::string`, `bytes` - and `payload` stay as they are, with `std::allocator`: the user's - choice, and a received `bytes`, or the binary of a `payload`, is a copy - of the frame, which starts in the app's resource. An owning pmr binary - payload is moved when its message buffer and the room use the same - resource, and copied once otherwise; chunked transfers assemble their - buffer in the room's resource. A received std::pmr::string always copies - the text once into the room's resource. `encode` - takes the resource too, for what keeps the payload alive. + the standard types, and `decode(incoming& message, const decoding& to)` + takes the room's `detail::decoding` for every type, its resource and its + bound on a JSON payload's image: the `std::pmr` types are built in the + resource, `webcpp::document::pmr::document` among them, and a rejected + `async_receive` completes with an empty one there, through + `detail::empty_payload`, which allocates nothing and raises nothing: an + empty container, and for a document `basic_document::nothing`, which + holds no image and whose root reads `undefined`. + `std::string`, `bytes`, `webcpp::document::document` and `payload` stay + as they are, with `std::allocator`: the user's choice, and a received + `bytes`, or the binary of a `payload`, is a copy of the frame, which + starts in the app's resource. The two document types mirror + `std::string` and `std::pmr::string`, with no alias of trystero's: a + handle of a received document refers to its document object, and + moving the document invalidates it, document's own rule, which the + action's Doc Comments state. + An owning pmr binary payload is moved when its message buffer and the + room use the same resource, and copied once otherwise; chunked transfers + assemble their buffer in the room's resource. A received + std::pmr::string always copies the text once into the room's resource. + `encode` takes the resource too, for what keeps the payload alive. - **The protocol** (`protocol/`) takes a `std::pmr::memory_resource*` as the last parameter of every function that returns what it allocates, with `std::pmr::get_default_resource()` as its default, and returns `std::pmr` types; `protocol::nostr::verify` uses `secp256k1_context_static` and allocates nothing. - **Outside the resource**, stated on the page: libdatachannel's and - OpenSSL's own allocations, with the `std::string` and `rtc::Description` - libdatachannel's API takes and returns; `emscripten::val`'s JavaScript - heap; the JSON storage's counter, which Boost.JSON allocates with - `operator new` once per room; Asio's own once-per-context allocations + OpenSSL's own allocations, with the copy libdatachannel's C API makes of + a message before webcpp::webrtc reads it; `emscripten::val`'s JavaScript + heap; Asio's own once-per-context allocations (its services and the scheduler's first operation); the wrapper Asio puts - around a post through an executor that is not an `io_context`'s; the - native backend's posts from libdatachannel's threads, which carry Asio's - default allocator, since the resource is touched only on the room's - executor; and Boost.Beast's and Asio's state inside the native WebSocket - (its stream, its resolver's results, its coroutines' frames); the - payload types `std::string`, `bytes` and `payload`, with - `std::allocator`; and, on Emscripten, the C library's `select()`, which - Asio's reactor calls on every wait of an io_context with a timer or a - socket, and which callocs an array on every call (the test replaces it, - below). The browser's `event_loop` and the test's `memory_network` are - shared by every room of a page or of a test, and allocate the entries - of their registrations and their relays through the resource they are - constructed with; a registered callback stays in its own resource. + around a post through an executor that is not an `io_context`'s, which + webcpp::webrtc's completions get, through `any_io_executor`; + webcpp::webrtc's posts from libdatachannel's threads, with the copies of + what they carry, in Asio's default allocator, since the resource is + touched only on the room's executor; natively, for each relay + connection, what Boost.Beast, Asio and OpenSSL allocate of their own, + which takes no allocator: the streams' state, the WebSocket's write + buffer, Asio's two TLS buffers, the resolver's state and results, the + handshake's request and response with their fields, the response's + header at most 8 KiB and no byte of a refusal's body (webcpp::beast's + `bounded_handshake_stream`, the session's next layer natively, with a + body limit of 0), the verify callback and its copy of the host, the timers' + waits, the idle timer's again at each read, and each keep-alive ping's + frame, while the WebSocket's operations, read buffer and queued texts are + in the room's resource and a message allocates nothing else outside it + (`platform_websocket_allocation`); in a page the stream's own state is + there too, made with `std::allocator_arg` and the room's allocator, and + what stays outside is, for each relay connection, the page resolver's + results (three `operator new`, and two more for a host longer than a + short string's 10 bytes) and, for each event of the page's `WebSocket`, + the C library's allocation of embind's `std::string` of its type in + webcpp::beast's `deliver`, and for a message a second, of its data's + type, in its `receive_message`: two a message, which + `platform_page_relay_allocation` counts exactly, a change needing + webcpp::beast and webcpp::asio; + the payload types `std::string`, `bytes`, `webcpp::document::document` + and `payload`, with `std::allocator`; on Emscripten, the C library's + `select()`, which Asio's reactor calls on + every wait of an io_context with a timer or a socket, and which callocs + an array on every call (the test replaces it, below), and under Asyncify + the unwind data of every suspension of the run (the test counts it + apart, below); and in a page, the storage of the bridge's map of pending + Web Crypto promises, in the io_context's allocator, made for the first + and grown when more are pending at once than it holds (the WebSocket and + `page_call` registrations are intrusive; a socket's events are posted in + the room's resource, a `page_call`'s in the resource it is given). The + test's `memory_network` allocates its relays in its own resource. - **The proof** is `test/allocation_test.cpp`, on both targets, which counts the global `operator new`, replaced, and the C library's allocation functions, where the platform lets a program see them: glibc's @@ -489,26 +825,36 @@ holds only what is specific to trystero. has weak definitions the test replaces and forwards to `emscripten_builtin_*`, macOS reports each to `malloc_logger`, and MSVC's are not counted, nor any under AddressSanitizer, whose own allocator - reports to none of these. Two rooms over the memory relays exchange a - payload, a `std::pmr::string`, a `pmr_bytes` and a `boost::json::value` - in turn, while both counts see none and the counting resources of the two - configurations see the rooms'; and two rooms with a password, a log sink - and the network's state in a resource of its own are made, join, exchange - a payload that travels in chunks, measure a round trip, one says goodbye, - both are destroyed and the io_context is drained, while `operator new` - sees exactly the two rooms' JSON storage counters and the C library - nothing, and the rooms' resources have nothing out once the io_context - has drained. Two apps with two rooms each also prove one binary payload - copy into a distinct room resource, with size-specific counters, and - no extra copy when resources match; their global count sees only four - JSON storage counters and all resources return to zero. + reports to none of these. It keeps every global allocation it counts, + by its address, in a table of a fixed size until it is freed. Two rooms + over the memory relays exchange a payload, a `std::pmr::string`, a + `pmr_bytes` and a `webcpp::document::pmr::document` in turn, and + neither `operator new` nor the C library sees an allocation, none out + when the window closes, while the counting resources of the two + configurations see the rooms'; the same exchange with a handler that + plants an `operator new`, left out until the window closes, and a call + of the C library sees exactly those, so the zeros are not vacuous. Each + text a room reads (a relay's event carrying an offer, a relay's `OK`, a + signal, a handshake message, a candidate) is parsed into a document of + a counting resource, which holds its image until the document goes, + with no global allocation. Two rooms with a password, a log sink and the + network's state in a resource of its own are made, join, exchange a + payload that travels in chunks, measure a round trip, one says goodbye, + both are destroyed and the io_context is drained, while neither + `operator new` nor the C library sees an allocation, and the rooms' + resources have nothing out once the io_context has drained. Two apps + with two rooms each also prove one binary payload copy into a distinct + room resource, with size-specific counters, and no extra copy when + resources match; their global counts are zero, and all resources + return to zero. The counting resources also count a return of memory they never gave, a pmr object freed through the wrong resource, which must be none. Only the thread `main` runs on is counted: the C library reports allocations from every thread, and a system thread's are not the rooms'. Asio's once-per-context allocations are made first (its timer service, its reactor, the scheduler's first operation, and room in its timer queue - for 256 waits); without them the count is 8, not 2. The replaced + for 256 waits); without them, the 6 they make would still be out at the + drain. The replaced `operator new` raises an alignment below `sizeof(void*)` and rounds the size to a multiple of the alignment, since `std::aligned_alloc` refuses both (measured: macOS refuses the alignments 1, 2 and 4, Emscripten 1 and @@ -520,9 +866,29 @@ holds only what is specific to trystero. calls on every wait of the io_context the test drives (measured: thousands of calls while two rooms exchange one payload): the replacement keeps the array on the stack, so that the count sees the rooms' - allocations rather than the C library's wait. -- **No twins.** Every example needs the public relays or a browser, so each - is a `webcpp.link`, linked and never run, and has no `.expected` and no - twin in Trystero's language. The chat page's site is written by + allocations rather than the C library's wait. Under Asyncify its + `run_for` suspends, and Asyncify allocates the unwind data with the C + library's `malloc` (measured: 22 in the second case before it was + marked): the test wraps `Asyncify.allocateData` in JavaScript, which sets + a flag while it runs, and counts what the C library allocates then + apart, as webcpp::asio's own allocation test does. +- **The examples and their twins.** The quick start and each + `diff_` program run natively in the lane `relayed` + (`example/Jamfile`), each over a Nostr relay of its own on 127.0.0.1, + which `example/run_over_relay.mjs` starts and names in + `TRYSTERO_RELAY_URL`, and passes when it ends by itself having printed its + `.expected`; its peers stay on the machine (a backend bound to 127.0.0.1, + and `stun:127.0.0.1:9`). Each has its twin under `test/oracle/twins/`, + which `test/oracle/run_twin.mjs` runs over a relay of its own: the quick + start's agrees, and a difference's records what Trystero prints in its own + `.expected`. Two peers of one program are two apps, and the quick start + fixes their self ids, since a random id would print differently on every + run; a twin's second peer is another page (`test/oracle/page.mjs`), since + Trystero JS has one `selfId` per page, so the quick start's twin prints + names where the program prints its ids. Without `TRYSTERO_RELAY_URL` the + quick start meets over Trystero's public relays and STUN servers, as a + user's program does. + The chat page alone is a `webcpp.link`, linked and never run, without a + twin (`test/oracle/twins/without-twin.txt`); its site is written by `b2 toolset=emscripten libs/trystero/example/chat//site` under the build directory, never in the tree. diff --git a/README.md b/README.md index e6cac45..87ce9e7 100644 --- a/README.md +++ b/README.md @@ -7,25 +7,29 @@ public Nostr relays and exchange messages directly, over WebRTC data channels. The wire is Trystero's: a room joined from C++ and the same room joined from Trystero's JavaScript are one room. -A room runs on two targets, through a backend of each: +A room runs on two targets, native and emscripten, through one platform +backend: -| Backend | Header | Target | Built on | -| --- | --- | --- | --- | -| the browser's | `` | emscripten | the page's `WebSocket`, `RTCPeerConnection` and `crypto.subtle`, through embind | -| the native one | `` | native | libdatachannel for WebRTC, Boost.Beast for the relays' WebSockets, OpenSSL for TLS and AES-GCM | +| Header | Target | What it holds | +| --- | --- | --- | +| `` | native and emscripten | `platform::backend`: webcpp::webrtc for WebRTC, natively over libdatachannel and in a page over its `RTCPeerConnection`; webcpp::beast for the relays' WebSockets, natively Boost.Beast's and in a page its `WebSocket`, their URLs read with Boost.URL; webcpp::asio's timers; and per target the sealer and the randomness, natively OpenSSL's AES-GCM and `RAND_bytes`, in a page `crypto.subtle` and `getentropy` | +| `` | emscripten | `platform::page_call` and `platform::js_string`, what a page's program uses beside the backend | `` is the rooms themselves, which build on both targets -and include neither backend. Every name is in the namespace -`webcpp::trystero`. Messages, binary data and pings are ported; audio and -video tracks are not yet. +and leave the platform backend out. The backend's WebRTC is +[webcpp::webrtc](https://github.com/webcpporg/webrtc)'s, the same peer +connection and data channel on both targets, and trystero's Asio is +[webcpp::asio](https://github.com/webcpporg/asio), Boost.Asio itself +natively: a program runs its `io_context` from `main` on both targets, in +the browser under a work guard, where `run` suspends into the page's event +loop and the page's calls into C++ only post to it. Every name is in the +namespace `webcpp::trystero`. Messages, binary data and pings are ported; +audio and video tracks are not yet. trystero raises no exception of its own: an operation that can fail completes -with an error code. The rooms, the protocol and the browser backend compile -without exceptions. The native backend's WebRTC needs them, since -libdatachannel reports errors by throwing: without exceptions, or with -`WEBCPP_NO_EXCEPTIONS` or `WEBCPP_TRYSTERO_NO_EXCEPTIONS` defined, -`native::data_channel`, `native::peer_connection` and `native::backend` do -not exist, and the native timer, sealer and WebSockets remain. +with an error code. Every part of it, the platform backend included, compiles +and works without exceptions: webcpp::webrtc calls libdatachannel's C API, +where none crosses. An `app` represents this program in one application: one peer id and one connection per remote peer, shared by its rooms, with one immutable password @@ -45,12 +49,13 @@ state, bindings, actions, relays, handlers and JSON; null uses the app's resource. A received owning binary payload moves when its message buffer and room resources match, and is copied once otherwise; received pmr text is always copied once. Completion handlers use their own associated allocator, -which `boost::asio::bind_allocator` sets. The app's resource must outlive +which `webcpp::asio::bind_allocator` sets. The app's resource must outlive its handle, all its rooms, retained values and pending operations; each room's resource must outlive its values and operations too. Declare both before the io_context and drain or destroy it first; in a browser keep them -for the page's life. Pools suit long-lived apps and rooms. libdatachannel, -OpenSSL and the browser retain their own internal allocations. +for the page's life. Pools suit long-lived apps and rooms. webcpp::webrtc's +connections and channels use the app's resource; libdatachannel, OpenSSL +and the browser retain their own internal allocations. A passwordless app's rooms are open to peers already connected through any of its rooms: presence reveals their tokens. A protected app uses a separate @@ -64,14 +69,20 @@ 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. Its TLS and WebRTC dependencies are built from -pinned sources, and so is libsecp256k1: +developed inside Boost. It builds on webcpp::asio, webcpp::webrtc and, for +the relays, webcpp::beast, three libraries of the superproject; its +TLS and WebRTC dependencies are built from pinned sources, and so is +libsecp256k1: | 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 | `/third_party//secp256k1`, from `third_party/libs/secp256k1` | -| 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 | +| webcpp::asio | every room | `/webcpp/asio//asio` | +| webcpp::webrtc | the platform backend's WebRTC | `/webcpp/webrtc//webrtc` | +| webcpp::beast | the platform backend's relays: their WebSockets, and natively their TLS | natively `/webcpp/beast//tls`, Boost.Beast over the source-built OpenSSL; in a page `/webcpp/beast//browser`, over the page's `WebSocket` | +| Boost.URL | the platform backend's relays: their URLs | `/webcpp//boost_url`, built from Boost's sources once per variant | +| libdatachannel 0.24.6 | the platform backend natively, through webcpp::webrtc | `/webcpp/third_party//libdatachannel`, from pinned source submodules | +| OpenSSL 3.5.9 | the platform backend natively: TLS, AES-GCM and randomness | `/webcpp/third_party//openssl`, also used by Asio and Beast | The tables of libsecp256k1 follow `webcpp-secp256k1-tables`: `auto` is window 15 and comb 11x6 natively (a larger program, faster signing and verification) and window 2 and @@ -82,114 +93,169 @@ or `large`. With the pinned source submodules initialized, b2 libs/trystero/test libs/trystero/example b2 toolset=emscripten libs/trystero/test libs/trystero/example -build the tests and the examples natively and on emscripten, with the -emscripten toolset that `user-config.jam` registers against emsdk. A b2 -project uses the rooms and the browser backend through -`/webcpp/trystero//trystero`, which adds trystero's headers, Boost's, -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 `multi` and `on` itself, as `example/Jamfile` does: b2 lets -no usage requirement override a build's `exception-handling=off`. +build the tests natively and on emscripten, and the chat's program on +emscripten, with the emscripten toolset that `user-config.jam` registers +against emsdk; the quick start and the programs of the differences run in +the lane `relayed` (below). A b2 program uses the rooms and the platform +backend through `/webcpp/trystero//platform`, on both targets, as the +examples' Jamfiles do. +The target adds `/webcpp/trystero//trystero`, the rooms alone: trystero's +headers, Boost's, webcpp::asio, which links embind on emscripten, +libsecp256k1 and webcpp::document with Boost.JSON's and Boost.Charconv's +definitions, compiled once per variant. Beside +them it adds webcpp::webrtc and Boost.URL on both targets; natively +libdatachannel and OpenSSL, through webcpp::webrtc, webcpp::beast's `//tls` +and webcpp::asio's `//tls`, whose embedded authorities a program may trust in +place of the system's; and in a page webcpp::beast's `//browser`, with no +OpenSSL. A native program declares `multi` itself; a program on +emscripten is built in webcpp::asio's suspension variant, +`webcpp-suspend=jspi` by default or `asyncify`. A project whose rooms run +over a backend of its own, as the tests' memory relays do, uses +`/webcpp/trystero//trystero` alone. ## The examples -Three examples come with the library. Each needs the public relays or a -browser, so the build links them and never runs them. - | Example | What it is | Target | | --- | --- | --- | -| `example/native_quick_start.cpp` | a native program that joins the room `lobby`, greets every peer and prints what it receives | native | -| `example/quick_start.cpp` | the browser quick start, a `.js` and `.wasm` to embed in a page | emscripten | +| `example/quick_start.cpp` | the quick start: two peers of one program meet in the room `lobby`, greet each other, print what they receive, and leave | native | +| `example/diff_*.cpp` | the programs of the page's appendix "Differences", each showing one difference from Trystero | native | | `example/chat/` | a chat page whose room is C++ compiled to WebAssembly | emscripten | -The native quick start, whole: - - +The quick start and the programs of the differences run in the lane +`relayed`, each over a Nostr relay of its own on 127.0.0.1, whose URL +`example/run_over_relay.mjs` gives the program in `TRYSTERO_RELAY_URL`; each +passes when it ends by itself having printed its `.expected`. Each has its +twin, the same program on Trystero JS, under `test/oracle/twins/`. The chat +needs a browser, so the build links its program and never runs it. + +The quick start, whole: two apps of one program, `alice` and `bob`, each a +peer with the id the program gives it, join the room `lobby` of the app +`webcpp-trystero-quick-start`; alice greets bob when he joins, bob answers +from a coroutine, each prints what it received, after its sender's id, and +both leave, which ends the program. Without `TRYSTERO_RELAY_URL` it meets +over Trystero's public relays and STUN servers, as a program that names +none does. + + ```cpp -#include -#include -#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include #include #include -#include +#include +namespace asio = boost::asio; namespace trystero = webcpp::trystero; -int main() { - boost::asio::io_context io; - trystero::native::backend backend(io.get_executor()); - trystero::app app(io.get_executor(), backend, {.app_id = "webcpp-trystero-quick-start"}); - auto joined = app.join("lobby"); - if (!joined) { - std::cerr << "not joined: " << joined.error().message() << '\n'; - return 1; +namespace { + +/** What one peer's app is made with: its id, and the relay `relay` names, or the public ones. */ +trystero::app_config config_for(std::string_view self_id, const char* relay) { + trystero::app_config config; + config.app_id = "webcpp-trystero-quick-start"; + // An id of the program's own, where an app would draw 20 random characters, so that what each + // peer prints of the other is the same on every run. + config.self_id = self_id; + if (relay != nullptr) { + // The peers stay on this machine: the relay given, and a STUN server where nothing answers + // in place of Trystero's public ones, beside a backend bound to the loopback. + config.relay_urls = {relay}; + config.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; } - trystero::room room = std::move(*joined); - auto chat = room.make_action("chat"); + // Without a relay, both lists stay empty: Trystero's defaults, as a user's program has them, + // the public relays its app id selects and Trystero's public STUN servers. + // A connection closes as soon as no room uses it, so that the program ends once both leave. + config.idle_timeout = std::chrono::milliseconds{0}; + return config; +} - room.on_peer_join([&](std::string_view peer) { - trystero::send_options to_peer{.targets = {trystero::peer_id(peer)}, .metadata = {}}; - chat.async_send("hello from a native peer", std::move(to_peer), - [](boost::system::error_code) {}); - }); - chat.on_message([](const std::string& text, const trystero::message_info& info) { - // flushed: into a pipe too, since the program runs until it is stopped - std::cout << info.from << ": " << text << '\n' << std::flush; - }); - io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +/** bob's part: waits for a message, prints it, answers its sender, and leaves the room. */ +asio::awaitable answer(trystero::room& lobby, trystero::action& chat) { + // as_tuple hands the error over as a value: a room left first ends the wait without throwing. + auto [ec, text, info] = co_await chat.async_receive(asio::as_tuple(asio::use_awaitable)); + if (ec) { + co_return; + } + std::cout << info.from << ": " << text << '\n'; + auto [failed] = co_await chat.async_send("hello back", {.targets = {info.from}, .metadata = {}}, + asio::as_tuple(asio::use_awaitable)); + if (failed) { + std::cerr << "not delivered: " << failed.message() << '\n'; + } + co_await lobby.async_leave(asio::as_tuple(asio::use_awaitable)); } -``` -The browser quick start's app and the room it joins, which a page keeps alive as long as the tab: - -```cpp -/** The room the page joined, and its actions. */ -struct lobby { - trystero::room room; - trystero::action chat = room.make_action("chat"); - trystero::action echo = room.make_action("echo"); -}; - -/** What the page keeps alive: event loop, backend, app, and the room it joined. */ -struct application { +} // namespace + +int main() { + // The relay the lane starts on 127.0.0.1, or none: Trystero's public relays. + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - trystero::app app{loop.get_executor(), backend, {.app_id = "webcpp-trystero-quick-start"}}; - std::optional joined; - - /** Joins the lobby and makes its actions; null, with the reason printed, when the app refuses - * (a room of that id joined already, or 64 rooms). */ - lobby* join() { - auto result = app.join("lobby"); - if (!result) { - const std::string reason = result.error().message(); - std::printf("not joined: %s\n", reason.c_str()); - return nullptr; - } - return &joined.emplace(std::move(*result)); + // One backend for both apps, whose connections stay on the loopback beside a local relay. + trystero::platform::backend_config local; + if (relay != nullptr) { + local.bind_address = "127.0.0.1"; } -}; + trystero::platform::backend backend(io.get_executor(), local); + + // Two apps, two peers, each with its own id, in the same room. + trystero::app alice(io.get_executor(), backend, config_for("alice", relay)); + trystero::app bob(io.get_executor(), backend, config_for("bob", relay)); + auto alice_lobby = alice.join("lobby"); + auto bob_lobby = bob.join("lobby"); + if (!alice_lobby || !bob_lobby) { + std::cerr << "not joined\n"; + return 1; + } + auto alice_chat = alice_lobby->make_action("chat"); + auto bob_chat = bob_lobby->make_action("chat"); + + // alice greets each peer once its handshake completes, prints the answer, and leaves. + alice_lobby->on_peer_join([&](std::string_view peer) { + alice_chat.async_send("hello", {.targets = {trystero::peer_id(peer)}, .metadata = {}}, + [](boost::system::error_code ec) { + if (ec) { + std::cerr << "not delivered: " << ec.message() << '\n'; + } + }); + }); + alice_chat.on_message([&](const std::string& text, const trystero::message_info& info) { + std::cout << info.from << ": " << text << '\n'; + alice_lobby->async_leave([](boost::system::error_code) {}); + }); + asio::co_spawn(io, answer(*bob_lobby, bob_chat), asio::detached); + + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} ``` -`example/Jamfile` declares each program on its own target: +It prints bob's line, then alice's: - + ``` -webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//native multi on : native ; +alice: hello +bob: hello back ``` - +`example/Jamfile` declares it natively, built with `multi`, and +run by its driver, `run_over_relay.mjs`, over a relay of its own: + + ``` -webcpp.link quick_start : quick_start.cpp - : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH : emscripten ; +webcpp.drive quick_start : quick_start.cpp + : /webcpp/trystero//platform multi : run_over_relay.mjs : : native ; ``` `b2 toolset=emscripten libs/trystero/example/chat//site` copies the chat page @@ -197,12 +263,12 @@ and its program into `site/` beside the program, under the build directory and out of the tree, one per variant, and prints that directory. On another toolset it stops, saying that the page is built on emscripten alone. -## From an empty directory to a native peer and the chat +## From an empty directory to the quick start and the chat -These steps go from an empty directory to the native quick start and the -chat page talking to each other over the public Nostr relays, on macOS with -Homebrew. Every command runs in the workspace directory of step 2 unless it -says otherwise. +These steps go from an empty directory to the quick start's two peers +meeting over the public Nostr relays, and to two tabs of the chat page +talking to each other there, on macOS with Homebrew. Every command runs in +the workspace directory of step 2 unless it says otherwise. ### 1. Install the tools @@ -245,9 +311,9 @@ git -C webcpp submodule update --init --recursive third_party/libs/openssl third ``` 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 +platform backend is first needed natively. 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. @@ -263,47 +329,60 @@ using emscripten : : $PWD/emsdk/upstream/emscripten/em++ EOF ``` -### 7. Build the native quick start and the chat page +### 7. Build the quick start and the chat page ```sh cd webcpp -b2 --user-config=../user-config.jam libs/trystero/example//native_quick_start-program +b2 --user-config=../user-config.jam libs/trystero/example//quick_start b2 --user-config=../user-config.jam toolset=emscripten libs/trystero/example/chat//site ``` -The first build also compiles Boost.JSON's definitions, and the first -emscripten build Emscripten's system libraries, which takes a few minutes. +The first command builds the quick start and runs it once over a Nostr relay +of its own on 127.0.0.1, which Node runs with the packages +`libs/trystero/test/oracle` pins, installed by npm at the first run; it +passes when the program prints its `.expected`. The first build also +compiles OpenSSL, libdatachannel, and Boost.JSON's and Boost.Charconv's +definitions, which webcpp::document uses, and the first emscripten build +Emscripten's system libraries, which takes a few minutes. The second command ends by printing the chat site's directory, `bin/libs/trystero/example/chat/emscripten-6.0.11/debug/address-model-32/cxxstd-20-iso/link-static/target-os-none/site`, -which holds `index.html`, `chat-program.js` and `chat-program.wasm`. +which holds `index.html`, `chat-program.js` and its WebAssembly, +`chat-program-60-d-jspi.wasm`, named after webcpp::asio's suspension +variant: JSPI, which Chrome 137 and later run; `webcpp-suspend=asyncify` +builds one that every browser runs. ### 8. Run them -In a terminal, from `webcpp`, start the native quick start. It runs until you -stop it with Ctrl-C: +In a terminal, from `webcpp`, run the quick start. Without +`TRYSTERO_RELAY_URL` its two peers meet over Trystero's public relays; +within a few seconds it prints what each received, and ends: ```sh -`find bin/libs/trystero/example -name native_quick_start-program -type f` +`find bin/libs/trystero/example/quick_start.test -name quick_start -type f` ``` -In a second terminal, from the workspace, serve the chat page: + +``` +alice: hello +bob: hello back +``` + +Then serve the chat page: ```sh -cd webcpp python3 -m http.server 8000 -d `find bin/libs/trystero/example/chat -name site -type d` ``` -Open , write `webcpp-trystero-quick-start` as the app -and `lobby` as the room, and press Join. Within a few seconds the native quick -start joins as a peer: the page shows "1 peer", the native peer's id "joined", -and its greeting, "hello from a native peer". What you send from the page is -printed in the native quick start's terminal, after the page's peer id: - -``` -eXfaPSb9aXpUL1KNqF8M: hello from the page -``` +Open in two tabs, and press Join in each, with the +page's app, `webcpp-trystero-chat`, and room, `lobby`. Within a few seconds +each tab shows the other's id, its first six characters, "joined", and +counts it as a peer; what you send from one tab appears in the other, under +the sender's id. Every tab that joins the same app and room joins the same +chat, and so does any Trystero JS page. -Every browser tab that joins the same app and room joins the same chat. +A native peer and a page meet too: the lane `interop` of `test/oracle` +meets the native peer, and the browser's, with Trystero JS pages in headless +Chrome (The tests, below). ### When something goes wrong @@ -321,9 +400,9 @@ Every browser tab that joins the same app and room joins the same chat. ## The tests `test/` compiles every public header alone, on each target that builds it: -the rooms, the protocol and their details on both targets, the native -backend natively, against libdatachannel and OpenSSL and with exceptions -whatever the build asks, and the browser backend on emscripten. It also +the rooms, the protocol and their details, the platform backend and the +backend's WebRTC on both targets, natively against webcpp::webrtc's +libdatachannel and OpenSSL, and `platform/page.hpp` on emscripten. It also checks that `` defines `WEBCPP_TRYSTERO_NO_EXCEPTIONS` exactly when webcpp has no exceptions, and when a program defines `WEBCPP_NO_EXCEPTIONS`. diff --git a/asyncify-remove.json b/asyncify-remove.json new file mode 100644 index 0000000..e83fc74 --- /dev/null +++ b/asyncify-remove.json @@ -0,0 +1 @@ +["*boost::json::basic_parser<*>::parse_*"] diff --git a/build.jam b/build.jam index 27dc04b..0f631b8 100644 --- a/build.jam +++ b/build.jam @@ -5,47 +5,82 @@ # https://www.boost.org/LICENSE_1_0.txt) # # trystero, serverless WebRTC rooms, wire compatible with Trystero. A program -# uses /webcpp/trystero//trystero, the rooms and the browser backend, or -# /webcpp/trystero//native for the native backend. +# uses /webcpp/trystero//platform, the rooms and the platform backend, on +# both targets; /webcpp/trystero//trystero is the rooms alone, over a backend +# of the program's own, as the tests' memory relays are. project /webcpp/trystero ; # libsecp256k1 (every room) is webcpp's build of it, /third_party//secp256k1: # v0.8.0 from the submodule third_party/libs/secp256k1, with the tables the # feature webcpp-secp256k1-tables chooses (small on emscripten, large natively; -# CODING-GUIDELINES.md chapter 5). Native WebRTC and OpenSSL are pinned source -# dependencies too, built together for the consumer's B2 variant. +# CODING-GUIDELINES.md chapter 5). WebRTC is webcpp::webrtc's, whose native +# libdatachannel and its OpenSSL are pinned source dependencies, built +# together for the consumer's B2 variant. import errors ; -# The native backend's own dependencies, checked only when a target that -# uses it is built. -rule native-dependencies ( properties * ) +# The platform backend's own dependencies, checked only when a target that +# uses it is built: natively its WebRTC, libdatachannel's through +# webcpp::webrtc, runs on worker threads. +rule platform-dependencies ( properties * ) { - if single in $(properties) + if single in $(properties) && ! emscripten in $(properties) { - errors.user-error "Trystero's native backend uses worker threads. Add multi to the consuming target or pass threading=multi." ; + errors.user-error "Trystero's platform backend uses worker threads natively. Add multi to the consuming target or pass threading=multi." ; } } -# On emscripten, the browser has no threads (the event loop drives Asio), and -# the browser backend reaches the page through embind: -lembind, what b2's -# on links, which as a usage requirement it would drop (measured: a -# program then fails to link, undefined _embind_register_function), since -# b2 takes only free features from usage requirements. +# The rooms: Asio is webcpp::asio, natively Boost.Asio itself, on emscripten +# the shipped backend, without threads (main runs it), which links embind. +# Every JSON text the rooms read or write is webcpp::document's, which brings +# Boost.JSON's parser and Boost.Charconv's definitions. +# +# Under Asyncify, Boost.JSON's recursive descent, basic_parser's parse_* +# functions, is left uninstrumented (asyncify-remove.json), since none +# suspends. Instrumented, a level of a parse took some 6.5 KB of node's +# stack in a debug build before the engine optimized it, so that a peer's +# first JSON payload nested 256 deep, document's default, overflowed node's +# 984 KB at about 150 levels; uninstrumented, at 400, and in a release build +# past 1,000 (measured). A program whose own parse suspends from a +# selector's callback cannot link trystero under Asyncify; under JSPI +# nothing is left out. +# +# trystero is parts and that list. parts, the same headers and dependencies +# without it, is for a program of a part that parses no JSON, as trystero's +# tests of the timer, a relay's URL, a page's calls and the sealer are +# (test/Jamfile): such a program has none of the parser's functions, and +# Binaryen warns of a pattern of the list that names none. +path-constant WEBCPP_TRYSTERO_ROOT : . ; # tag::trystero[] -alias trystero : : - : : include /boost//headers /webcpp//boost_json - /webcpp/config//config /third_party//secp256k1 - emscripten:BOOST_ASIO_DISABLE_THREADS - emscripten:-lembind ; +alias parts : : + : : include /boost//headers /webcpp/document//document + /webcpp/config//config /webcpp/asio//asio /third_party//secp256k1 ; +alias trystero : : : : parts + emscripten,asyncify:"-sASYNCIFY_REMOVE=@\"$(WEBCPP_TRYSTERO_ROOT)/asyncify-remove.json\"" + ; # end::trystero[] -# The native backend needs exceptions: libdatachannel reports errors by -# throwing, and data_channel.hpp and peer_connection.hpp catch them. Each -# headers-alone call, test and program of it declares -# on itself, since b2 lets no usage requirement override -# a build's exception-handling=off. -# tag::native[] -alias native : : @native-dependencies - : : trystero /webcpp/third_party//libdatachannel ; -# end::native[] +# The platform backend, one for both targets: its WebRTC is webcpp::webrtc's, +# its relays' WebSockets webcpp::beast's, their URLs read with Boost.URL, +# built from Boost's sources once per variant. Natively webcpp::webrtc brings +# the pinned libdatachannel and OpenSSL, and works with exceptions on and +# off, through libdatachannel's C API; so does the backend. Its relays run +# over the same OpenSSL (//tls), and webcpp::asio's //tls adds webcpp's +# embedded authorities, which a program may trust in place of the system's +# (make_tls_client_context). On emscripten webcpp::webrtc and webcpp::beast +# bind the page's RTCPeerConnection and WebSocket (//browser), and no +# OpenSSL is linked. +# +# platform is platform-parts and the rooms. platform-parts, the backend over +# parts, without the rooms' Asyncify list, is for trystero's tests of the +# backend's parts that parse no JSON (above). +# tag::platform[] +alias platform-parts : : emscripten + : : parts /webcpp/webrtc//webrtc + /webcpp/beast//browser /webcpp//boost_url ; +alias platform-parts : : @platform-dependencies + : : parts /webcpp/webrtc//webrtc + /webcpp/beast//tls /webcpp/asio//tls + /webcpp//boost_url ; +alias platform : : : : platform-parts trystero ; +# end::platform[] diff --git a/doc/Jamfile b/doc/Jamfile index 3ac1a63..980c01c 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -8,12 +8,15 @@ import webcpp ; webcpp.doc trystero : trystero.adoc ; -# No single target builds every header: the browser backend's build only on +# No single target builds every header: a page's header builds only on # emscripten, whose own headers hold only for wasm32's types, so the # reference reads every header for Emscripten's target, as em++ compiles -# (/webcpp//emscripten-reference), with the native backend's target, which -# 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 multi - /webcpp//emscripten-reference BOOST_ASIO_DISABLE_THREADS ; +# (/webcpp//emscripten-reference), with the platform backend's target, built +# natively, which brings webcpp::webrtc, webcpp::beast, Boost.URL, +# libdatachannel and OpenSSL. The platform backend's Asio and Beast are +# webcpp::asio and webcpp::beast, their browser implementations there, so it +# parses with no configuration of Boost.Asio's (measured: the page builds +# without BOOST_ASIO_DISABLE_THREADS, which Boost.Beast over Boost.Asio +# needed). +webcpp.reference trystero : /webcpp/trystero//platform multi + /webcpp//emscripten-reference ; diff --git a/doc/acknowledgements.adoc b/doc/acknowledgements.adoc index eda544c..bca9d6f 100644 --- a/doc/acknowledgements.adoc +++ b/doc/acknowledgements.adoc @@ -20,6 +20,7 @@ trystero's own code, which is under the Boost Software License alone. The BIP-340 signatures of the Nostr events are https://github.com/bitcoin-core/secp256k1[libsecp256k1]'s, by the Bitcoin -Core contributors, under the MIT License. The native backend's WebRTC is -https://github.com/paullouisageneau/libdatachannel[libdatachannel]'s, by +Core contributors, under the MIT License. The platform backend's WebRTC is, +natively, webcpp::webrtc's over +https://github.com/paullouisageneau/libdatachannel[libdatachannel], by Paul-Louis Ageneau, under the Mozilla Public License 2.0. diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 1df5aea..3537e55 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -8,11 +8,12 @@ == Allocation A webcpp library lets its user choose where its allocations come from. -trystero does it through `std::pmr`, header-only, with an app resource and -an optional resource for each room. +trystero does it through `std::pmr`, header-only, with an app resource, an +optional resource for each room, and a resource for the platform backend's +own state. [#trystero-allocation-resource] -=== The app's resource and the room's +=== The app's resource, the room's and the backend's * `app_config::memory`, `std::pmr::get_default_resource()` by default, receives the app's state, configuration copy including its password, self id, @@ -25,8 +26,15 @@ an optional resource for each room. * `room_options::memory`, the app's resource when null, receives the room's state, bindings and their drain waiters, negotiation records, rebinding counts and backoffs, sealed texts, relays, actions, queues, outgoing - frames, transfers, JSON storage and handlers. The signing context is - made there with `secp256k1_context_preallocated_create`. + frames, transfers, the documents of the JSON texts it reads, and handlers. + The signing context is made there with + `secp256k1_context_preallocated_create`. +* `platform::backend_config::memory`, `std::pmr::get_default_resource()` by + default, receives the platform backend's own state: its copy of + `bind_address`, its window of constructions and its own webcpp::webrtc + runtime. It must be non-null, and outlive the backend and every connection + of its runtime. What the backend makes for an app or a room is in the + resource given with that call instead (<>). * Adoption replaces negotiation handlers with the app's; ending a negotiation clears the room's handlers. Detachment fails and frees a binding's drain waiters and removes its registrations before returning. @@ -36,7 +44,11 @@ an optional resource for each room. resource; otherwise it is copied once into the room's resource. A chunked transfer assembles its buffer in the room's resource. Received `std::pmr::string` text is always copied once into the room's resource. - JSON is parsed in the room's own JSON storage; the app parses no JSON. + A JSON text is parsed into a `webcpp::document::pmr::document` of the + room's resource, a remote candidate into one of the app's, and a JSON + payload received as a `webcpp::document::pmr::document` into one of the + room's resource: the document's image, which holds every value, strings + included, and the working state of the parse that made it. All resource access runs on the app's executor. A resource need not be thread-safe when that executor runs on one thread; several `io_context` @@ -57,14 +69,18 @@ include::{library-root}/test/allocation_test.cpp[tag=config] The app's resource must outlive its state: the app handle, every room of it, retained values allocated there and every pending operation. A room's own resource must outlive that room, its retained `std::pmr::string`, -`pmr_bytes` and `boost::json::value` values, and its pending operations. +`pmr_bytes` and `webcpp::document::pmr::document` values, and its pending +operations. +The backend's resource must outlive the backend and every connection of its +own runtime, which a handler the `io_context` still holds may keep alive. Destroying a handle closes its work but queued completions can still free -memory. Declare both `app_config::memory` and `room_options::memory` -resources before the `io_context`, then construct the backend, app and -rooms. Drain or destroy the `io_context` before destroying either resource. -In the browser, keep them until all pending promises settle: the page's -`event_loop` registrations retain their handlers, so in practice resources -live for the page's life. +memory. Declare the `backend_config::memory`, `app_config::memory` and +`room_options::memory` resources before the `io_context`, then construct the +backend, app and rooms. Drain or destroy the `io_context` before destroying +any of these resources. +In the browser, keep them until all pending promises settle: a pending +`async_await` holds its handler, so in practice resources live for the page's +life. No check in debug builds catches the misuse: trystero holds a raw pointer and cannot see the resource end, and the use comes after the room is gone, @@ -83,7 +99,7 @@ short-lived one, or a test. A completion handler is the user's, and is allocated as its own associated allocator says: the room never binds its allocator over it. -`boost::asio::bind_allocator` gives one the room's resource. The allocation +`webcpp::asio::bind_allocator` gives one the room's resource. The allocation test makes the allocator of a resource: [source] @@ -110,17 +126,24 @@ it with `std::allocator`. [#trystero-allocation-containers] === Containers and shared objects -Every container trystero declares is a `std::pmr` one: `std::pmr::string` -(and `peer_id`), `std::pmr::vector` (and `backend::bytes`, -`protocol::bytes` and `pmr_bytes`), `std::pmr::deque`, `std::pmr::map`, -`std::pmr::set`, `std::pmr::unordered_map` and `std::pmr::unordered_set`, -built over their owner's resource; `app_config`, `room_options`, `send_options`, +Every container trystero declares is a `std::pmr` one or a Boost container +over `std::pmr::polymorphic_allocator`: `std::pmr::string` (and `peer_id`), +`std::pmr::vector` (and `backend::bytes`, `protocol::bytes` and +`pmr_bytes`), `std::pmr::deque`, `std::pmr::map` and `std::pmr::set`, and +`boost::unordered_flat_set` (the event ids a strategy remembers), +`boost::circular_buffer` (the construction window, the recent challenges) +and `boost::circular_buffer_space_optimized` (the replay cache), built over +their owner's resource; `app_config`, `room_options`, `send_options`, `message_info` and `backend::ice_server` hold them too. Two types stay the user's choice of `std::allocator`: `trystero::bytes`, a `std::vector`, and `trystero::payload`, a variant of -`std::string`, `boost::json::value` and `bytes`. A received `bytes`, or the -binary of a `payload`, is a copy of the frame, which starts in the app's -resource. +`std::string`, `webcpp::document::document` and `bytes`. A received +`bytes`, or the binary of a `payload`, is a copy of the frame, which starts +in the app's resource; a received `webcpp::document::document` is in the +standard allocator, its image and the working state of its parse, as +document's `document` is. `webcpp::document::pmr::document` is document's +own allocator-aware type, over `std::pmr::polymorphic_allocator`, +which receives in the room's resource. A struct that holds `std::pmr` containers takes the room's `std::pmr::polymorphic_allocator<>` in its constructor, and a container of @@ -133,6 +156,15 @@ Shared objects are made with `std::allocate_shared` over `std::pmr::polymorphic_allocator<>`, never with `std::make_shared`, `std::make_unique` or `new`; a timer is a `std::shared_ptr` for that reason. +No type of trystero is a data structure meant for a shared segment, one that +a process builds there and another maps and uses in place: every type is a +run-time object, an app, a room, an action, a socket, a handler or the +backend, routed through the `std::pmr` resources above, or a value one takes +or gives. A `std::pmr` container holds its resource and its storage at +absolute addresses of its process, as a handler holds a callable, so none is +shareable in the sense of Boost.Interprocess, and none takes an `Allocator` +template parameter for it. + [#trystero-allocation-handlers] === Handlers @@ -149,33 +181,69 @@ into its resource with the allocator-extended move. A move assignment carries the source's allocator with its target. [#trystero-allocation-asio] -=== Asio, the backends, Boost.JSON and the protocol +=== Asio, the backends, webcpp::document and the protocol -*Asio.* Every `post`, `dispatch`, timer wait and `any_completion_handler` -the room makes carries `boost::asio::bind_allocator` over its resource. A -post through `boost::asio::any_io_executor` is wrapped by Asio in a function +*Asio,* webcpp::asio's, which natively is Boost.Asio itself. Every `post`, +`dispatch`, timer wait and `any_completion_handler` the room makes carries +`webcpp::asio::bind_allocator` over its resource. A post through +`webcpp::asio::any_io_executor` is wrapped by Asio in a function object allocated with `std::allocator`, from Asio's per-thread recycling cache, which calls `std::aligned_alloc` on a miss (measured: two per post, -in every round of five posts, natively and on emscripten). So the room posts -through the executor of an `io_context` when its executor is one, where Asio -allocates the operation as the handler's allocator says; on another -executor, as the browser's `event_loop` executor, the wrapper stays Asio's. +in every round of five posts, natively and on emscripten). So the room, and +the platform backend's sealer, post through the executor of an `io_context` +when the executor they were given is one, where Asio allocates the operation +as the handler's allocator says, and in a page the sealer awaits each Web +Crypto promise through it too, so that its settlement is posted the same way. +On another executor, a strand over the `io_context` for one, the wrapper +stays Asio's (<>). The executor is the +program's: the examples and the tests give the app and the backend the +executor of their `io_context`. *The backends.* Each method of `backend::factory` that makes an object takes a `std::pmr::memory_resource*` as its last parameter. Peer connections, data channels and received frames use the app's resource; relay sockets, sealers and room timers use the room's. Objects and their handlers allocate -through that supplied resource. - -*Boost.JSON* allocates through `json_resource`, a -`boost::container::pmr::memory_resource` that forwards to a -`std::pmr::memory_resource`, header-only: the global resources of -`boost::container::pmr` are compiled, and webcpp's CI installs Boost's headers -alone. The room's JSON storage is made once, when the room is constructed, -since a value a handler keeps may outlive the room. Text is parsed by a -`boost::json::parser` over that storage, never by `boost::json::parse`, -whose temporaries beyond a stack buffer come from the default resource, and -JSON is written by a `boost::json::serializer` whose stack is the resource. +through that supplied resource. The backend's WebRTC +(<>) gives webcpp::webrtc's connections and +channels a `std::pmr::polymorphic_allocator` on the app's resource, which +their state, their queues, their texts and their operations use: each +operation's handler is bound to it. The platform backend's relays are one +session of webcpp::beast's on both targets, made in the room's resource with +its handlers, its queued texts and its read buffer, and each of its +operations' handlers carries the room's allocator, so that what Asio and +Beast allocate for them is there too. Natively Boost.Beast's stream state +stays Beast's (<>); in a page the WebSocket +stream's own state is in the room's resource too, since the stream is made +with `std::allocator_arg` and the room's allocator. The +platform backend's own state, its copy of `bind_address`, its window of +constructions and its own runtime, is in `backend_config::memory` +(<>): the test `platform_backend`, on both +targets, makes a backend while a counting resource is the default one, which +sees none of it, and sees `backend_config::memory` given all of it back once +the backend is destroyed. + +*webcpp::document* is allocator-aware: a `webcpp::document::pmr::document` +allocates through a `std::pmr::polymorphic_allocator` its image, +one buffer in which Boost.Interprocess's `rbtree_best_fit` heap holds every +value, strings included, with offsets for pointers, and the working state of +what reads or writes it: the parser's state, the path and the pending key +and text of the value being read, the tree's record of each change, and the +writer's stack, each freed before the call that made it returns. trystero +reads each text with `webcpp::document::parse(text, options, allocator)` +into a document of the room's resource, of the app's for a remote +candidate: its image starts at 4 KiB and grows in place, twice as large +each time, up to twice the caller's bound and 64 KiB for a protocol text, +and for a JSON payload up to 96 times its length and 64 KiB, which every +valid payload fits, or the room's `room_options::max_json_document_bytes`, +64 MiB by default, the smaller: the most a peer's payload takes of the +room's resource. A text given whole leaves Boost.JSON's parser no state to +suspend. A text the room writes is +appended field by field to a `std::pmr::string` of its resource, its +strings quoted by `webcpp::document::quote`, which allocates only through +that string, and a JSON payload is written by +`webcpp::document::stringify_to` in pieces of 8 bytes, which no standard +library's string keeps outside its own object, its writer's stack in the +document's own allocator. *The protocol* (`protocol/`) takes a `std::pmr::memory_resource*` as the last parameter of every function that returns what it allocates, with the @@ -186,31 +254,91 @@ nothing. [#trystero-allocation-outside] === What stays outside the resource -* libdatachannel's and OpenSSL's own allocations, with the `std::string` and - `rtc::Description` libdatachannel's API takes and returns; +* libdatachannel's and OpenSSL's own allocations, the copy libdatachannel's C + API makes of a message before webcpp::webrtc reads it into the frame, and, + natively, webcpp::webrtc's copies of what libdatachannel's threads report, + in the standard allocator; * what `emscripten::val` holds, in the JavaScript heap; -* the counter of the room's JSON storage, which Boost.JSON allocates with - `operator new`, once per room; -* Asio's own once-per-context allocations: its services and the scheduler's - first operation; +* Asio's own once-per-context allocations: its services, in a page + webcpp::asio's bridge among them, and the scheduler's first operation; * the wrapper Asio puts around a post through an executor that is not the - executor of an `io_context`; -* the native backend's posts from libdatachannel's threads, which carry - Asio's default allocator, since the resource is touched only on the room's - executor; -* Boost.Beast's and Asio's state inside the native WebSocket: its stream, - its resolver's results, its coroutines' frames; -* the payload types `std::string`, `bytes` and `payload`, with - `std::allocator`, the user's choice; + executor of an `io_context`, a strand for one, and, given such an + executor, around the settlement of each Web Crypto promise of a page's + sealer; +* webcpp::webrtc's posts from libdatachannel's threads, which carry Asio's + default allocator, since the resource is touched only on the room's + executor; and the wrapper Asio puts around webcpp::webrtc's completions, + which it posts through `webcpp::asio::any_io_executor`; +* natively, for each relay connection, what Boost.Beast and Asio allocate of + their own, which takes no allocator from a handler: the state of the + WebSocket stream and of the TCP stream under it, the WebSocket's write + buffer, made at its first write, and, over TLS, the two 17 KiB buffers of + Asio's TLS stream; the resolver's state and its results, with what the C + library's `getaddrinfo` allocates on Asio's resolver thread; the WebSocket + handshake's request and response and the header fields of both, the + response's header at most 8 KiB, which webcpp::beast's bounded handshake + layer reads through Beast's own parser, reading no byte of the body of a + response that refuses the upgrade (before it, Beast read such a body up to + its default 8 MiB: an 8 MiB body held about 18 MiB at its peak), and + keeping a header line split between two reads in the room's resource; + over TLS, the verify callback Asio's `set_verify_callback` + makes with `new`, with the copy of the host that `host_name_verification` + holds, a `std::string`; each wait of Beast's timers, from Asio's + per-thread recycling cache, which calls `std::aligned_alloc` on a miss: + the TCP stream's deadline over the connection and the TLS handshake, and + the WebSocket's handshake, idle and close timeouts, the idle one started + again at each read, so a wait of a message's; and each keep-alive ping's + frame, with `new`. The WebSocket's operations, its read buffer and its + queued texts are in the room's resource on both targets, since each of its + handlers carries the room's allocator, and natively a message allocates + nothing else outside it: `operator new` sees none from the send of a text + to the receipt of its echo (the test `platform_websocket_allocation`). The + reads' and the writes' completions are a handler of the session's own, + with no executor of its own: Asio's `any_completion_handler`, whose + executor is of another type than the stream's, had Asio make an + `any_completion_executor` with `new` for each operation and wrap each + completion in a function object of its recycling cache (measured: six + `operator new` and four of its blocks for a text sent and its echo + received); +* in a page, for each relay connection, the results webcpp::asio's page + resolver makes with `new`, which takes no allocator: Asio's list of one + entry, its shared count and the entry's storage, three allocations, and two + copies of the host when it is longer than a short string holds (10 bytes + in a page: `relay.damus.io`, of 14, is longer); and, for each event of the page's + `WebSocket`, its open, each message and its close, the C library's + allocation embind makes for the `std::string` into which webcpp::beast's + page stream reads the event's type (`event["type"].as()` in + its `deliver`), and for a message a second, for the type of its data + (`data.typeOf().as()` in its `receive_message`), each freed + before the call that made it returns: two for each message a relay sends. + The test `platform_page_relay_allocation` counts exactly these, no more + and no fewer, from a connection's call to its open, for one message and + for ten, and from its close to the page's close event. The stream's own + state, its operations, the messages it holds and the read buffer are in + the room's resource, and the page's `WebSocket` makes the handshake; + avoiding embind's strings, and the resolver's results, needs a change to + webcpp::beast's page stream and to webcpp::asio's page resolver; +* the payload types `std::string`, `bytes`, `webcpp::document::document` and + `payload`, with `std::allocator`, the user's choice; * on Emscripten, the C library's `select()`, which Asio's reactor calls on every wait of an `io_context` with a timer or a socket, and which callocs - an array on every call. - -The browser's `event_loop` and the test's memory relays are shared by every -room of a page or of a test: they allocate the entries of their -registrations and their relays through the resource they are constructed -with, and a registered callback stays in its own resource, a room's for a -room's object. + an array on every call; +* on Emscripten under Asyncify, the unwind data Asyncify allocates whenever + the browser program's `run` suspends; +* in the browser, the storage of the map in which webcpp::asio's bridge finds + each pending Web Crypto promise, in the allocator of the `io_context`, + made for the first and grown when more are pending at once than it holds, + and kept until the `io_context` is destroyed. The rest of a page's seal or + open, the wait for its promise and the post of its settlement, is in the + room's resource when the backend's executor is that of an `io_context`: the + test `platform_page_sealer_allocation`, after a first seal and open, sees + neither `operator new` nor the C library allocate from the start of a seal + or an open to its completion. The registrations of a WebSocket and of a + `page_call` are intrusive, the events of a socket are posted in the room's + resource, and the calls of a `page_call` in the resource it is given. + +The test's memory relays are shared by every room of a test: they allocate +their relays through the resource they are constructed with. [#trystero-allocation-proof] === The proof @@ -221,34 +349,48 @@ where the platform lets a program see them: glibc's are replaced and forward to `+__libc_*+`, Emscripten's dlmalloc has weak definitions the test replaces, and macOS reports each to `malloc_logger`; MSVC's are not counted, nor any under AddressSanitizer, whose own allocator reports to none of these. Only -the thread `main` runs on is counted. +the thread `main` runs on is counted, and every global allocation it counts +is kept, by its address, in a table of a fixed size until it is freed. * Two rooms over the memory relays exchange a payload, a - `std::pmr::string`, a `pmr_bytes` and a `boost::json::value` in turn, - while both counts see none and the counting resources of the two - configurations see the rooms'. + `std::pmr::string`, a `pmr_bytes` and a `webcpp::document::pmr::document` + in turn, the document written by the sender and parsed by the receiver: + neither `operator new` nor the C library sees an allocation, none is out + when the window closes, and the counting resources of the two + configurations see the rooms'. The same exchange, with a handler that + allocates outside the resources, an `operator new` it leaves out until the + window closes and a call of the C library, sees exactly those: the zeros + are not for want of counting. +* Each text a room reads, a relay's event carrying an offer, a relay's + `OK`, a signal, a handshake message and a candidate, is parsed into a + document of a counting resource: neither `operator new` nor the C library + sees an allocation, and the image goes back to the resource with the + document. * Two rooms with a password, a log sink and the relays' state in a resource of its own are made, join, exchange a payload that travels in chunks, measure a round trip, one says goodbye, both are destroyed and the - `io_context` is drained. From the first construction to the drain, - `operator new` sees exactly the two rooms' JSON storage counters and the C - library nothing. Once the rooms are destroyed their resources still have - memory out, the operations they left pending, and none once the - `io_context` has drained. - + `io_context` is drained. From the first construction to the drain, while + the rooms and the relay read and write their JSON texts, neither + `operator new` nor the C library sees an allocation. Once the rooms are + destroyed their resources still have memory out, the operations they left + pending, and none once the `io_context` has drained. * Two apps with two rooms each exchange binary payloads, one room using the app's resource and one its own. Size-specific counters prove one payload copy into the distinct room resource, and no extra copy when resources - match. From construction through the drain the global counter sees only - four JSON storage counters, and every resource ends with nothing out. + match. From construction through the drain neither `operator new` nor the + C library sees an allocation, and every resource ends with nothing out. The counting resources also count a return of memory they never gave, a `std::pmr` object freed through the wrong resource, which must be none. Asio's once-per-context allocations are made before anything is counted; -without them the count is 8, not 2. On Emscripten the test also replaces -`select()` with one that keeps its array on the stack, so that the count -sees the rooms' allocations rather than the C library's wait. The test is -declared in `test/Jamfile`: +without them, the 6 they make would still be out at the drain. On +Emscripten the test also replaces `select()` with one that keeps its array +on the stack, so that the count +sees the rooms' allocations rather than the C library's wait; and, under +Asyncify, where the test's own `run_for` suspends, it marks Asyncify's +allocation of a suspension's unwind data and counts it apart, as +webcpp::asio's allocation test does. The test runs in both of +webcpp::asio's suspension variants. It is declared in `test/Jamfile`: [listing] ---- diff --git a/doc/browser.adoc b/doc/browser.adoc deleted file mode 100644 index 1f8590a..0000000 --- a/doc/browser.adoc +++ /dev/null @@ -1,152 +0,0 @@ -// 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) - -[#trystero-browser] -== The browser backend - -In the browser, `browser::backend` implements the backend interface over the -page's own `WebSocket`, `RTCPeerConnection`, `RTCDataChannel`, `setTimeout` -and `crypto.subtle`, through embind's `emscripten::val`, and -`browser::event_loop` runs the room's executor from the page's events. One -of each serves every app and room of the page. Apps with different -passwords use distinct self ids and share no connection or presence. - -[#trystero-browser-loop] -=== Driving Asio from the page's event loop - -In a browser nothing may block, and the page's JavaScript event loop is the -only source of events. An `io_context` never runs on its own there: -`browser::event_loop` drives it without ever calling `run()`. - -* Every JavaScript event that reaches the library, a socket's message, a - settled promise, an ICE candidate or a timer, is dispatched to its - handler, and is followed by `io_context::poll()`, which runs everything - that became ready. -* Work given to the loop's executor, `browser::executor`, while no - JavaScript event is being handled posts to the `io_context` and schedules - one `poll()` in a microtask. -* The loop holds a work guard on the `io_context`, so a `poll()` never - leaves it stopped. - -So nothing runs while nothing happens, and a handler runs as soon as its -event does. Two alternatives were rejected: `poll()` from -`emscripten_set_main_loop` costs 60 wake-ups a second and stops in hidden -tabs, where `requestAnimationFrame` does; `poll()` on a fixed interval costs -wake-ups and up to an interval of latency. The backend's timers are -`setTimeout`, so their expiry is a JavaScript event like any other. - -[#trystero-browser-javascript] -=== How JavaScript reaches {cpp} - -The page calls one function, `trystero_dispatch`, which -`` exports. A JavaScript handler is that -function bound to the event loop, a registration and a slot. An object -registers a callback with the loop and removes it when it is destroyed, so a -late event for a destroyed object finds nothing; a destroyed loop marks every -handler it made as dead. - -Text that crosses into JavaScript is decoded straight from the WebAssembly -memory a view points into, by a `TextDecoder` the loop keeps, and text that -comes back is encoded by a `TextEncoder` straight into a string of the object's -resource: no `std::string` is made to carry either. - -[#trystero-browser-exceptions] -=== No JavaScript exception enters WebAssembly - -The browser backend makes every call into JavaScript that can throw, a -constructor, `JSON.parse`, a `send`, a WebRTC or Web Crypto method, through -one function defined once in `browser/src.hpp` with `EM_JS`, which runs it -inside `try` and returns a value or the exception as a value; the {cpp} turns -that into the error its interface has. Every event of the page enters {cpp} -through a function of the same file that catches what still escapes, puts -WebAssembly's stack pointer and the loop's depth back as they were before the -call, reports it and lets the loop poll again. With exceptions, -`browser::dispatch` catches a {cpp} exception first, which frees it: one that -reached JavaScript would keep its object for good. So a program that uses -the browser backend may be built with exceptions or without them, and a -peer's malformed message never stops the page's loop. - -[#trystero-browser-bounds] -=== What a page bounds - -* A data channel message that is not an `ArrayBuffer`, as a text message a - peer sends, or that is larger than any room frame - (`protocol::max_room_frame_bytes`), is dropped before it is read: neither - can be a frame. -* A relay's text longer than 1 MiB (`protocol::max_relay_message_bytes`) is - not copied into WebAssembly: the socket closes, and reports the close. -* A text that would take the socket's `bufferedAmount` beyond 4 MiB - (`protocol::max_queued_relay_bytes`), as when a relay stops reading, drops - the socket, which reports one close at once. A page's `WebSocket` cannot - ping, so the browser has no idle timeout, which the native backend has - (<>). -* A page makes at most `browser::backend::max_peer_connections` (256) peer - connections across all apps and rooms it serves, counted from their construction until the garbage collector - frees them, as Chromium counts them against its own 500 (measured with - headless Chrome: the 501st throws "Cannot create so many - PeerConnections", and a closed one counts until a collection). Beyond, - the rooms report each negotiation they cannot start, and the rest of - Chromium's count stays free for what the page makes without a room. - -Peer connections, data channels and received frames use the app's resource; -relay sockets and sealed signaling texts use the room's. Presence or reuse -binds another room without making another peer connection. - -[#trystero-browser-page] -=== What a page needs - -* A secure context: https, or http on `localhost` or `127.0.0.1`. Elsewhere - `crypto.subtle`, which seals the signaling, does not exist, and every - sealing operation fails with `error::backend_failure`. -* No threads: Emscripten's threads need a cross-origin isolated page, so - trystero uses none. `/webcpp/trystero//trystero` defines - `BOOST_ASIO_DISABLE_THREADS` on emscripten, and the loop drives Asio on - the page's one thread. -* A program that lives as long as the page: the event loop must outlive - every room and object it serves. -* Boost.JSON's definitions, which a program links from `/webcpp//boost_json`, - which `/webcpp/trystero//trystero` brings and which builds on emscripten - as on every target. - -[#trystero-browser-chat] -=== A page and its program - -The chat example is a page whose room is {cpp}: the program joins and sends, -and the page only draws. It keeps the loop, the backend and the room for the -page's life, and makes the action `chat` twice: once as `std::string_view`, -to receive a message as a view of its frame, and once as `std::string`, to -send by moving the text: - -[source] ----- -include::{examples}/chat/chat.cpp[tag=state] ----- - -The page calls `join` with the app and the room its user typed, and the -program joins and sets its handlers; a received message goes from its frame -straight into a JavaScript string: - -[source] ----- -include::{examples}/chat/chat.cpp[tag=join] ----- - -`send` shows the message at once, and reports a failure in the page's log: - -[source] ----- -include::{examples}/chat/chat.cpp[tag=send] ----- - -The two functions are what the program exports to the page, through embind: - -[source] ----- -include::{examples}/chat/chat.cpp[tag=bindings] ----- - -Any Trystero JS page, or any other page of the chat, that joins the same app -and room is in the same chat (<>). diff --git a/doc/building.adoc b/doc/building.adoc index fafaa34..3356968 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -8,8 +8,11 @@ == Building trystero is header-only, and is developed inside the webcpp superproject, as -a Boost library is developed inside Boost. Its native TLS and WebRTC -dependencies, and libsecp256k1, are built from pinned sources: +a Boost library is developed inside Boost. It builds on three libraries of +webcpp's: webcpp::asio; webcpp::webrtc, the platform backend's WebRTC; and +webcpp::beast, its relays' WebSockets, on both targets. +Its native TLS and WebRTC dependencies, and libsecp256k1, are built from +pinned sources: [cols="2,2,3",options="header"] |=== @@ -19,12 +22,30 @@ dependencies, and libsecp256k1, are built from pinned sources: | every room: it signs the Nostr events peers meet through | `/third_party//secp256k1`, built from `third_party/libs/secp256k1` +| webcpp::asio +| every room +| `/webcpp/asio//asio`: natively Boost.Asio, on emscripten the backend it ships + +| webcpp::webrtc +| the platform backend's WebRTC, on both targets +| `/webcpp/webrtc//webrtc`, the superproject's `libs/webrtc` + +| webcpp::beast +| the platform backend's relays: their WebSockets, and natively their TLS +| `/webcpp/beast//tls` natively, Boost.Beast over the source-built OpenSSL; + `/webcpp/beast//browser` in a page, over the page's `WebSocket` + +| Boost.URL +| the platform backend's relays: their URLs, on both targets +| `/webcpp//boost_url`, built from Boost's sources once per variant + | libdatachannel 0.24.6 -| the native backend +| the platform backend natively, through webcpp::webrtc | `/webcpp/third_party//libdatachannel`, built from `third_party/libs/libdatachannel` | OpenSSL 3.5.9 -| the native backend +| the platform backend natively: its WebRTC, its relays' TLS, its sealer and + its randomness | `/webcpp/third_party//openssl`, shared by the Asio, Beast and Trystero build graphs |=== @@ -38,55 +59,87 @@ window 4, and a smaller program. A program that wants otherwise asks for [#trystero-building-project] === In a b2 project -A b2 project uses the rooms and the browser backend through -`/webcpp/trystero//trystero`, which adds trystero's headers, Boost's, -libsecp256k1 and Boost.JSON's definitions, compiled once per variant, and, -on emscripten, embind and `BOOST_ASIO_DISABLE_THREADS`, since the page has no -threads: +A program uses trystero through `/webcpp/trystero//platform`, the rooms and +the platform backend (<>), on either target: natively, +built with `threading=multi`, and in a page. `/webcpp/trystero//trystero` +is the rooms alone, which adds trystero's headers, Boost's, webcpp::asio, +libsecp256k1 and webcpp::document with Boost.JSON's and Boost.Charconv's +definitions, compiled once per variant, and no +WebRTC on any target: a program that runs its rooms over a backend of its +own, as trystero's tests run whole rooms over the memory relays +(<>), needs no more: [listing] ---- include::{library-root}/build.jam[tag=trystero] ---- -embind is linked as a flag, `-lembind`, rather than with b2's own -`on`: that feature is not free, and b2 ignores a feature that is not -free among usage requirements, so a program that used it would not link. - -A native program uses `/webcpp/trystero//native`, which adds libdatachannel -and the same source-built OpenSSL used by Asio and Beast: +`/webcpp/trystero//trystero` is `parts`, which brings those dependencies, +and, under Asyncify, the list that leaves Boost.JSON's recursive descent +out of Asyncify's instrumentation (<>). A program of +a part that parses no JSON, as trystero's tests of the timer, a relay's +URL, a page's calls and the sealer are, links `parts`, or `platform-parts` +(below), in place of the rooms: it has none of the parser's functions, and +Binaryen warns of a pattern of the list that names none. + +On emscripten webcpp::asio builds without threads, since the page has none, +links embind, and links its runtime in the suspension variant the build +asks, `webcpp-suspend=jspi` by default or `asyncify`; a program is named +after it, as the chat's `chat-program-60-d-jspi.js`. embind is linked as a +flag, `-lembind`, rather than with b2's own `on`: that feature is +not free, and b2 ignores a feature that is not free among usage +requirements, so a program that used it would not link. + +`/webcpp/trystero//platform` adds the platform backend to the rooms: +`platform-parts`, the backend over `parts`, with an alternative for each +target, which trystero's tests of the backend's parts that parse no JSON +link alone. Natively it adds webcpp::webrtc, with +libdatachannel and the same source-built OpenSSL used by Asio and Beast; +webcpp::beast's TLS over that OpenSSL for the relays' WebSockets, +`/webcpp/beast//tls`; Boost.URL, which reads the relays' URLs; and +webcpp::asio's `//tls`, whose `make_tls_client_context()` gives a program +webcpp's embedded authorities in place of the system's, which the backend +trusts by default (<>). In a page it adds +webcpp::webrtc, over the page's own `RTCPeerConnection`; webcpp::beast's +`//browser`, over the page's `WebSocket`; and Boost.URL, which reads the +relays' URLs there too. A page links no OpenSSL: [listing] ---- -include::{library-root}/build.jam[tag=native] +include::{library-root}/build.jam[tag=platform] ---- -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. +Natively the platform backend's WebRTC, libdatachannel's, uses worker +threads, so each consumer declares `multi`. Its OpenSSL +dependency is the matching threaded variant; a single-threaded native +program that uses the backend is rejected before compilation, with an error +that says to add `multi`. A page has no threads, and needs none. -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: +The platform backend works with exceptions and without them +(<>), so a program builds as it asks, as the +examples do, the quick start natively with `multi`, which the +build runs over a relay of its own (<>): [listing] ---- -include::{examples}/Jamfile[tag=native] +include::{examples}/Jamfile[tag=quick-start] ---- -and as trystero's own tests of the native backend's connections do: +and as trystero's own tests of the platform backend do, on each target that +builds them, once without exceptions too, a test of a part that parses no +JSON over `platform-parts` (`$(platform-part)`): [listing] ---- -include::{library-root}/test/Jamfile[tag=native] +include::{library-root}/test/Jamfile[tag=platform] ---- -A browser program is linked for the web, with a memory that grows: +A page's program is linked for the web, with a memory that grows, as the +chat's is: [listing] ---- -include::{examples}/Jamfile[tag=browser] +include::{examples}/chat/Jamfile[tag=page] ---- [#trystero-building-emscripten] @@ -140,27 +193,35 @@ three libraries. [#trystero-building-examples] === Running the examples -The three examples need the public relays or a browser, so the build links -them and never runs them: `native_quick_start.cpp`, natively; -`quick_start.cpp`, a `.js` and a `.wasm` to embed in a page; and the chat, -a page whose room is {cpp} (<>). The quick starts -meet in the room `lobby` of the app `webcpp-trystero-quick-start`, over the -public relays; the chat joins the app and the room its user types, the room -`lobby` of the app `webcpp-trystero-chat` unless the user changes them, and -meets the quick starts when the user types theirs. +The quick start and the programs of the appendix "Differences" +(<>) run natively in the lane `relayed`, each over a +Nostr relay of its own on 127.0.0.1, which `example/run_over_relay.mjs` +starts and names to the program in `TRYSTERO_RELAY_URL`: a program passes +when it ends by itself having printed its `.expected`. Node runs the relay, +with the packages `test/oracle` pins. The first command runs the lane, the +second the quick start alone: + +[source,bash] +---- +b2 libs/trystero/example//relayed +b2 libs/trystero/example//quick_start +---- -The native quick start is built as a program of its own, and runs until it -is stopped: +The quick start's executable stays under the build directory. Run without +`TRYSTERO_RELAY_URL`, it meets over Trystero's public relays and STUN +servers, as a program that names none does, and prints the same two lines +(<>) within seconds, then ends: [source,bash] ---- -b2 libs/trystero/example//native_quick_start-program -`find bin/libs/trystero/example -name native_quick_start-program -type f` +`find bin/libs/trystero/example/quick_start.test -name quick_start -type f` ---- -The chat is a page and its program, which the target `site` copies into a -directory of its own under the build directory, out of the tree, and prints. -The page is served from `localhost`, where `crypto.subtle` exists: +The chat needs a browser, so the build links its program and never runs it +(<>). The target `site` copies the page and its +program into a directory of its own under the build directory, out of the +tree, and prints it. The page is served from `localhost`, where +`crypto.subtle` exists: [source,bash] ---- @@ -168,8 +229,8 @@ b2 toolset=emscripten libs/trystero/example/chat//site python3 -m http.server 8000 -d `find bin/libs/trystero/example/chat -name site -type d` ---- -At http://localhost:8000, joining the app `webcpp-trystero-quick-start`, in -place of the page's `webcpp-trystero-chat`, and the room `lobby` brings the -native quick start in as a peer within seconds: its greeting appears in the -chat, and what the page sends is printed in its terminal. On another toolset, `site` stops the build, saying that the page is -built on emscripten alone. +At http://localhost:8000, two tabs that join the same app and room, the +page's `webcpp-trystero-chat` and `lobby` unless their user changes them, +meet over the public relays within seconds: each counts the other as a peer, +and what one sends appears in the other. On another toolset, `site` stops +the build, saying that the page is built on emscripten alone. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 4fe66d6..49c3753 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,10 +16,37 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Changed libsecp256k1 to come from `/third_party//secp256k1`, not an external - installation: `-sSECP256K1_ROOT` and `-sSECP256K1_EMSCRIPTEN_ROOT` are gone, and - `webcpp-secp256k1-tables` chooses its tables. -* Changed `app::join` to `+[[nodiscard]]+`, so a dropped room or its refusal is diagnosed. +* *Breaking change:* Changed `native::` and `browser::` to one +`platform::backend` (link `/webcpp/trystero//platform`), and a backend's +`now_ms()` and `unix_seconds()` to `steady_now()` and `unix_now()`, of +`std::chrono`. +* *Breaking change:* Changed trystero's Asio to webcpp::asio; a page's `main` +runs its `io_context` under a work guard, and calls in through +`platform::page_call` of `platform/page.hpp`. +* *Breaking change:* Changed JSON payloads to `webcpp::document::document` +and `webcpp::document::pmr::document`, sent as `JSON.stringify` writes them, +for `boost::json::value` and `json_resource`; `payload` has no copy +assignment, and programs link Boost.Charconv too. +* *Breaking change:* Changed relays to verify TLS in any verify mode, drop +binary messages, and refuse URLs a page reads otherwise and TLS contexts a +page cannot honour. +* *Breaking change:* Changed `protocol::` to take webcpp::document's values, +removing `json::parse` and `make_id`; `append_string` returns its error, and +`proposal::size` is a `std::uint64_t`. +* *Breaking change:* Changed libsecp256k1 to `/third_party//secp256k1`, with +`webcpp-secp256k1-tables` for its tables and no `-sSECP256K1_ROOT`, and +`app::join` to `+[[nodiscard]]+`. +* Fixed relays hiding a genuine Nostr event, slowing rooms with colliding ids +or making them read an 8 MiB refusal, and rooms dropping or piling up +simultaneous offers. +* Added `room_options::max_json_document_bytes` for a received JSON payload; +every JSON text is read in the room's resource within bounds, and a self id +not UTF-8 is replaced by a random one. +* Fixed unreachable IPv6 relays, signals unlike Trystero's, 32-bit receivers +misreading 4 GiB offers, pages ignoring a failing `crypto.getRandomValues` or +dropping early frames, and rooms never binding after a lost presence. +* Changed the quick start to one native program, and added programs showing +differences beside Trystero JS's output. // end::unreleased[] [#trystero-changelog-0-1-0] diff --git a/doc/design.adoc b/doc/design.adoc index 35dbd34..929ac78 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -31,20 +31,28 @@ | `room.hpp`, `detail/*.hpp` | the Nostr strategy, signaling, bindings, action wire and room API -| Browser backend -| `browser/*.hpp` -| `emscripten::val` over the browser's APIs, and the event loop +| Backend's WebRTC +| `webrtc/*.hpp` +| webcpp::webrtc's peer connections and data channels, and trystero's + policies over them, on both targets -| Native backend -| `native/*.hpp` -| libdatachannel, Boost.Beast, OpenSSL and Asio's timers +| Platform backend +| `platform/*.hpp` +| webcpp::webrtc, webcpp::beast (natively Boost.Beast, in a page its + `WebSocket`), Boost.URL, webcpp::asio's timers, and per target the sealer + and the randomness: OpenSSL natively, Web Crypto and + `crypto.getRandomValues` in a page; and, in a page, `page_call` and `js_string` |=== Everything above the backend interface is the core, which builds on both -targets: the same room runs over the browser's APIs, over libdatachannel, and -over the memory relays of the tests (<>). The core never -includes a backend, libdatachannel, OpenSSL or Emscripten: a boundary of the -library's own, which webcpp's lint checks, keeps it so. +targets: the same room runs over the browser's WebRTC and libdatachannel's, +both through webcpp::webrtc, and over the memory relays of the tests +(<>). The core never includes the platform backend, the +backend's WebRTC, webcpp::webrtc, libdatachannel, OpenSSL or Emscripten: a +boundary of the library's own, which webcpp's lint checks, keeps it so. Its +Asio is webcpp::asio: natively Boost.Asio itself, on emscripten the backend +webcpp::asio ships, whose `io_context` webcpp::webrtc's browser objects +deliver their events to. [#trystero-design-sharing] === Connections shared by the rooms of an app @@ -105,20 +113,92 @@ library's own, which webcpp's lint checks, keeps it so. The backend is a handful of abstract classes rather than template parameters. Each of its operations is a call into JavaScript or into a network stack, so a virtual call costs nothing measurable, while the room's -code stays free of templates over the platform and of `#ifdef`, and the test -backend and the browser backend are interchangeable at run time. Every -handler a backend invokes runs on the room's executor, after the call that -caused it has returned, never inside it: the room calls these operations from -inside handlers whose state a completion run there would change under them. +code stays free of templates over the platform and of `#ifdef`, and the +tests' memory relays and the platform backend are interchangeable at run +time. Every handler a backend invokes runs on the room's executor, after the +call that caused it has returned, never inside it: the room calls these +operations from inside handlers whose state a completion run there would +change under them. + +One class, `platform::backend`, implements the interface on both targets, +in place of a backend of each: the owner's decision 3 of trystero's +refactor (2026-11-14), since webcpp::asio, webcpp::beast and webcpp::webrtc +give both targets one interface, where everything but WebRTC was written +twice. The abstract classes stay, for the memory relays, which run whole +rooms on both targets where node has no WebRTC, and for the interop's native +peer, which wraps the platform backend. Only the sealer and the source of +randomness are chosen per target, by `WEBCPP_TARGET_EMSCRIPTEN`, until +webcpp::crypto exists (<>). [#trystero-design-webrtc] -=== Why the browser's own WebRTC +=== Why webcpp::webrtc + +The platform backend's WebRTC is webcpp::webrtc's: the W3C's API in Asio's +model, one interface natively, over libdatachannel's C API, and in the +browser, over the page's own `RTCPeerConnection`. It replaces the backend's +own wrappers of each, so that trystero keeps only its policies over WebRTC, +the same on both targets. In the browser it binds the page's objects, not +libdatachannel's WebAssembly port, datachannel-wasm, which has no media and +hides the `RTCPeerConnection` it wraps; natively its C API lets the backend +work without exceptions. The backend interface stays a handful of abstract +classes (<>): the rooms of the tests run over the +memory relays, on both targets, where node has no WebRTC, and the interop's +native peer wraps the platform backend's connections. + +[#trystero-design-backend-webrtc] +=== The backend's WebRTC + +The platform backend makes its peer connections and data channels the same +way on both targets, in `` and +`data_channel.hpp`: `webrtc::peer_connection` and `webrtc::data_channel` hold +webcpp::webrtc's `basic_peer_connection` and `basic_data_channel` over a +`std::pmr::polymorphic_allocator` on the app's resource, keep a wait of each +kind pending on them, re-armed on the executor, and report what each +completes with through the backend interface. What is trystero's, and stays +in them, over webcpp::webrtc: -libdatachannel's WebAssembly port, datachannel-wasm, has no media and hides -the `RTCPeerConnection` it wraps. Binding the browser's objects directly -through `emscripten::val` is smaller than that wrapper, reports every error, -and leaves the browser's whole WebRTC stack (capture, codecs, playout) within -reach for media. +* The states. A connection reports one state, which merges its connection + state and its ICE state as a page sees both: failed when either failed, + then closed, disconnected, connected (or ICE completed), connecting (or ICE + checking), and new. +* The candidates. A local candidate leaves as the JSON of an + `RTCIceCandidateInit`, the form Trystero JS adds with `addIceCandidate`; a + remote one is read from that JSON, at most 16 KiB of it. Natively it + carries `sdpMid` and an `sdpMLineIndex` of 0, and no user name fragment, as + libdatachannel gives none; a candidate whose text is not UTF-8, which JSON + cannot carry, is not reported. +* The frames. A channel reads every message as it comes, with + `async_receive`, into a vector of the app's resource, which the message + handler then owns. A text message, as a peer can send, or a binary one + larger than any room frame, is dropped there, on the executor: neither can + be a frame. What reaches the executor is bounded by webcpp::webrtc: a + message is at most `max_message_size`, 256 KiB, which natively + libdatachannel cuts a longer one to, and past which in the browser, or past + 16 MiB of unread messages, the channel closes. A binary payload moves when + its message buffer and the room use the same resource, and is copied once + otherwise; chunked transfers assemble their buffer in the room's resource. +* The frames no room has read. 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, + Trystero's pending-data bounds. Overflow or expiry closes the channel; + closing or destroying it discards the pending frames. The backend's 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 read ahead of that delivery + drains older frames first when a receiver is available. +* The pace. The channel reports the buffered amount falling to 64 KiB, after + a send left it above, as `onbufferedamountlow` does. +* The caps. The backend makes at most + `backend_config::max_peer_connections_per_minute` connections in any + minute, on both targets, its own policy against floods + (<>): in a page a collection frees closed + connections from the census, after which only this window bounds how fast + a flood makes new ones. The `runtime` of webcpp::webrtc caps the + connections alive at once, the backend's own or the program's + (<>), in a page over the page's census + (<>). [#trystero-design-text] === Text is a view, a copy is a decision @@ -129,9 +209,27 @@ key, a member, a capture of a handler that runs later. * The digests the protocol takes are fed the parts of their input: nothing is concatenated to hash it. -* Signals and relay messages are read as views into the parsed document; the - JSON the room writes goes into one reserved buffer, escaped by Boost.JSON's - serializer, and a Nostr event's id is hashed over those same bytes. +* Every JSON text is webcpp::document's. Signals, relay messages, handshake + messages and candidates are parsed by `webcpp::document::parse` into a + `webcpp::document::pmr::document` of the room's or the app's resource, + which holds its image and the parse's working state, and read as views + into it; each caller bounds its text, and the image grows to at most + twice that bound and 64 KiB (<>). The JSON the room + writes goes field by field into one reserved buffer, its strings quoted by + `webcpp::document::quote`, the quoting of `JSON.stringify` itself, and a + Nostr event's id is hashed over those same bytes. Building each text as a + document and writing it again was set aside: it would copy every string + into a node of some 200 bytes, then write it once more. trystero keeps no + owner of its own around a document: an earlier one, a buffer of the + room's resource under an external document, retried twice as large when a + parse filled it, gave way to document's own allocator, whose image grows + in place. +* A JSON payload is a document of document's own types, + `webcpp::document::document` in the standard allocator, the user's + choice, and `webcpp::document::pmr::document`, received in the room's + resource, as a text is a `std::string` or a `std::pmr::string`. A handle + keeps document's rule: it refers to its document object, and moving the + document invalidates it. * A frame is written once, inside its room envelope, and shared by every target; a received frame becomes the buffer of the message delivered from it, and a view handler reads it in place. @@ -141,12 +239,19 @@ The asynchronous operations are the exception, for the reason <> gives. [#trystero-design-dependencies] -=== Optional native dependencies +=== Dependencies -libdatachannel is under the MPL 2.0 and OpenSSL under the Apache License -2.0. Both are needed only by the native backend, which a browser program -never includes: `/webcpp/trystero//trystero` depends on neither, and -`/webcpp/trystero//native` adds them, as OpenSSL is optional for Asio. +trystero builds on webcpp::asio, and its platform backend on webcpp::webrtc +and webcpp::beast. `/webcpp/trystero//trystero` is the rooms alone: it brings +`/webcpp/asio//asio`, which links embind on emscripten, and on no target +webcpp::webrtc. A program names `/webcpp/trystero//platform` on both +targets, which adds the backend to the rooms: `/webcpp/webrtc//webrtc` and +`/webcpp//boost_url` on both; natively webcpp::webrtc's libdatachannel, +under the MPL 2.0, and OpenSSL, under the Apache License 2.0, and for the +relays `/webcpp/beast//tls` and `/webcpp/asio//tls`, whose embedded +authorities a program may trust in place of the system's; in a page +`/webcpp/beast//browser`, over the page's `WebSocket`. Neither libdatachannel +nor OpenSSL is in a page's program, as OpenSSL is optional for Asio. [#trystero-design-licensing] === Licensing diff --git a/doc/differences.adoc b/doc/differences.adoc index 95fbcc2..a3c948c 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -63,6 +63,9 @@ These features of Trystero are not ported, each for its reason: Trystero's defaults; and the backend is what a polyfill would be. |=== +A feature not ported has no program among the differences below: trystero +has nothing of it to run beside its twin. + [#trystero-differences-behaviour] === Where a ported feature behaves otherwise @@ -78,6 +81,8 @@ These features of Trystero are not ported, each for its reason: | Reuse over a live connection | binds on any signal of that peer id | binds only a peer that advertised the room's token itself, and by reuse only on their first meeting over that connection | a forged announcement must not bind an innocent peer +| A room frame before the peer's presence for the room | kept until the room binds by presence or by reuse | also taken as the peer's advertisement of the room, which binds it | a forged announcement cannot reuse, so a presence that Chrome dropped as the page's channel opened would otherwise leave the room unbound for good; only the peer writes its connection's frames + | Announcements after a peer leaves | restarted after every leave | restarted only when no live connection to that peer remains | over a live connection, rebinding goes through the connection | Presence after binding | sent when a room registers | also sent again when a room binds by reuse or at its rebinding time | it makes the other side, Trystero JS included, bind at once @@ -90,9 +95,9 @@ These features of Trystero are not ported, each for its reason: | Rooms per app | unbounded; a peer advertising a 65th is dropped by the other side | `join` refuses the 65th, counting rooms in their farewell | the 65th would cost every connection of the app -| A connection whose last room was kicked | idle 123,333 ms | closed at once | a bound: a failed peer holds no connection, as today +| A connection whose last room was kicked | idle 123,333 ms | closed at once | a bound: a failed peer holds no connection -| Relay sockets and the Nostr key | shared by the rooms of the page, topics batched per socket | per room, as today | not part of this decision; invisible to peers; shared through the app in a later change +| Relay sockets and the Nostr key | shared by the rooms of the page, topics batched per socket | per room | not part of this decision; invisible to peers; shared through the app in a later change | Relay and ICE configuration | the first room's relays; each negotiating room's RTC configuration | the app's, for every room | one configuration for what the rooms share @@ -102,27 +107,542 @@ These features of Trystero are not ported, each for its reason: | Renegotiation and media over a shared connection | routed through a control room, streams owned per room; a connection with any media is destroyed when its last room goes | not ported | media is on the roadmap (<>) -| Passive rooms | presence only for active rooms | not ported | as today +| Passive rooms | presence only for active rooms | not ported | not ported yet: a room always announces itself | Crossed duplicate connections | first registered wins at each side; crossed, both lose and meet again | the same | matching Trystero's rule is what keeps a {cpp} and a Trystero JS side agreeing +| A Nostr event a relay repeats, or that several relays carry | acted on each time | acted on once among the 4096 newest event ids, when its id is checked to be its own, the SHA-256 of its NIP-01 serialization; an event with any other id is acted on each time and its id never kept | every relay of the room carries each event; an id taken unchecked would let a relay hide a genuine event behind a forged one it sends first under the same id, or fill the room's resource with the ids kept + +| A relay's text, a signal or a handshake message past its bound | parsed with `JSON.parse` whatever its length, under the relay's own limit | dropped before it is read: 68,608 bytes for a relay's text, 66,560 for a signal, 1,024 for a handshake message (<>) | the bounds are those of the fields Trystero sends, so no text a Trystero peer writes is refused; a longer one would cost the room its length to read + +| A protocol text of thousands of values | parsed | refused once its image passes twice its bound and 64 KiB | no Trystero message holds more than a few dozen values, and a document's value takes some 200 bytes of image + +| A protocol text nested deeper than 16 | parsed | dropped as a malformed one is | no Trystero message nests deeper than 4, a relay's event and its tags, and each level of a parse is a level of recursion, which a hostile relay would otherwise take to 256 + +| A self id that is not UTF-8 | impossible: a JavaScript string | set aside for a random one, with a configuration report | JSON carries UTF-8 alone, and a signal writes the id as a JSON string + +| A JSON payload's number that a double cannot hold: an integer past 2^53^, a decimal of more digits, one past a double's range | sent as the nearest double, and one past a double's range as `null`: a JavaScript number is a double | sent exact, as webcpp::document holds it; a Trystero JS peer reads the nearest double, or `Infinity` | webcpp::document keeps every number exact, and writes each one a double holds as JavaScript does + +| A JSON payload nested deeper than 256, or holding a lone surrogate | delivered: `JSON.parse` takes both | not delivered | webcpp::document's defaults: a bounded depth, and strings that are UTF-8 + +| A JSON payload whose document passes the room's `room_options::max_json_document_bytes`, 64 MiB by default: some 350,000 values of one character | delivered: `JSON.parse` has no bound but the page's memory | not delivered (<>) | each value of a document is a node of 192 bytes of image, 96 times its text at most, so a program bounds what a peer's JSON may take of its room's resource; every payload within the bound is delivered + +| The characters of a random id (the self id, offer ids, nonces, subscription ids) | each of the 62 alike, from `Math.random` | one random byte each, at its remainder in 62: each of the first eight characters from 5 of the 256 bytes, each other from 4, about 5.95 bits a character | the bytes come from the backend's secure randomness, not `Math.random`; the bias costs about 0.005 bits a character, below log2(62) + +|=== + +Each difference a program can show has one, `example/diff_.cpp`, +with its twin, the same program on Trystero 0.26.0, in `test/oracle/twins/` +(<>); <> gives the +reason of each other row. + +[#trystero-differences-shown] +=== The differences, shown + +Each difference below is shown by a {cpp} program and, but for the last, +its twin, the same program written for Trystero JS: the part of the {cpp} +program that differs, the twin whole, then what the twin printed on Trystero +0.26.0, then what the {cpp} program printed. Both ran, and the outputs are +theirs: a program and its twin each join over a Nostr relay of their own on +127.0.0.1, whose URL is in their environment, `TRYSTERO_RELAY_URL`, and two +peers of one program meet there, as two apps in {cpp} and as two pages in +Trystero JS (<>). The lane `relayed` runs the +programs again, and the oracle lane the twins, and each fails when its +program no longer prints what is shown here. The twins of the programs of +`example/` agree with {n-twins-agreeing} of them, the quick start among them +(<>), and diverge from {n-twins-divergent}, each a +difference below; {n-examples-without-twin} programs have no twin, the last +difference below and the chat page, each with its reason in +`test/oracle/twins/without-twin.txt`. + +[#trystero-differences-already-joined] +==== Joining a room already joined + +Trystero JS:: `joinRoom` with the id of a room the page holds returns that +room. +trystero:: `app::join` refuses with `error::already_joined` while a room of +that id is joined. +Why:: A `room` is a handle whose destruction leaves the room: two handles of +one room would leave it twice. + +[source] +---- +include::{examples}/diff_already_joined.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_already_joined.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_already_joined.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_already_joined.expected[] +---- + +[#trystero-differences-rooms] +==== Rooms per app + +Trystero JS:: `joinRoom` joins every room a page asks for: the 65th, 66th and +67th rooms of one `appId` are each a room. It advertises every room of the +app over every connection of the app, and a peer that is advertised a 65th +room token over one connection drops that connection, "too many advertised +rooms" (`dist/shared-peer.mjs:457`). +trystero:: `app::join` refuses a 65th room with `error::too_many_rooms`. A +room still in its farewell, the 99 ms of `async_leave`, counts, so another +room can be joined once that leave has completed. +Why:: A 65th room would be advertised over every connection of the app, and +each Trystero JS peer at the other end would drop the connection. + +[source] +---- +include::{examples}/diff_rooms_per_app.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_rooms_per_app.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_rooms_per_app.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_rooms_per_app.expected[] +---- + +[#trystero-differences-self-id] +==== The self id + +Trystero JS:: A page has one `selfId`, drawn once when Trystero's module +loads, and every room of every app announces it, so a peer that meets the +page in two apps sees the same id in both. Its one manager of shared +connections keys them by app id, so the two apps share the id and not their +connections. +trystero:: Each app draws its own self id and holds its own connections, so a +peer that meets the program in rooms of two apps sees two ids, and two rooms +of one app show one. A program that wants one id across apps names it, +`app_config::self_id`. +Why:: No static state, so that one process holds several peers; an id shared +across apps is the program's choice, and never reaches another app's wire +unless the program chooses it. + +[source] +---- +include::{examples}/diff_self_id.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_self_id.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_self_id.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_self_id.expected[] +---- + +[#trystero-differences-passwords] +==== Passwords across rooms + +Trystero JS:: Each `joinRoom` takes its own password, so one page joins a +lobby with one password and a kitchen with another, and a peer that joins +both meets the page as one peer, over one connection that carries both +rooms' password handshakes. +trystero:: A password is an app's, `app_config::password`, the same for every +room of the app and never changed: rooms of different passwords are rooms of +separate apps, each with its own self id and connections, so the other peer +meets two peers. +Why:: The sealed negotiation that makes a connection authenticates one +password before any room of the app reuses it; the wire stays Trystero's. + +[source] +---- +include::{examples}/diff_passwords.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_passwords.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_passwords.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_passwords.expected[] +---- + +[#trystero-differences-relay-config] +==== Relay and ICE configuration + +Trystero JS:: The first room a page joins, while it holds no other, opens the +relays, and every room joined while one remains uses them, whatever relays +it was given. A connection is made with the RTC configuration of the room +that negotiates it, and a room that binds over it later shares it. So a +kitchen joined with a second configuration after the lobby uses the lobby's +relays and the lobby's ICE servers. +trystero:: Relays and ICE servers are the app's, for every room of the app: a +room with another configuration is a room of another app, which uses its +own. A room hands out neither its relays' sockets nor its connections, so +the program gives each app a backend that records what the app asks of the +platform's. +Why:: One configuration for what the rooms of an app share. + +[source] +---- +include::{examples}/diff_relay_config.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_relay_config.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_relay_config.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_relay_config.expected[] +---- + +[#trystero-differences-relay-sockets] +==== Relay sockets + +Trystero JS:: A page opens one WebSocket per relay, which every room of the +page shares, its topics batched on it; `getRelaySockets` returns them. +trystero:: Each room opens its own. The program counts the WebSockets its app +asks of the backend, since a room hands out none. +Why:: Not part of the decision that shares connections between rooms; peers +see no difference. The rooms of an app may share their relays' sockets in a +later change. + +[source] +---- +include::{examples}/diff_relay_sockets.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_relay_sockets.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_relay_sockets.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_relay_sockets.expected[] +---- + +[#trystero-differences-peer-join] +==== `on_peer_join` does not replay the joined peers + +Trystero JS:: A newly set `onPeerJoin` is called at once with each peer +already joined. +trystero:: A room reports a join from its executor, after the call to `join` +has returned, to the handler set then, so a handler set right after `join` +sees every join; `peers()` lists the joined peers for a handler set later. +Why:: A join is an event, reported once; the peers joined are the room's +state, which `peers()` reads. + +[source] +---- +include::{examples}/diff_peer_join.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_peer_join.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_peer_join.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_peer_join.expected[] +---- + +[#trystero-differences-peers] +==== `peers()` lists ids + +Trystero JS:: `getPeers` returns an object that maps each joined peer's id to +its `RTCPeerConnection`, of the class given as `rtcPolyfill` when one is +given. +trystero:: `peers()` returns the joined peers' ids. +Why:: A connection is the backend's, webcpp::webrtc's over a page's object in +the browser and over libdatachannel's natively, shared by the app's rooms, +and the room does not hand it out. + +[source] +---- +include::{examples}/diff_peers.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_peers.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_peers.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_peers.expected[] +---- + +[#trystero-differences-send] +==== A send to a peer that has not joined fails + +Trystero JS:: The send warns on the console, "no peer with id ... found", +and resolves. +trystero:: `async_send` completes with `error::no_such_peer`. With several +targets, the send still goes to the others, and completes with the first +failure. +Why:: An operation that fails says so with its error code, which a program +can act on, and a console's warning is not. + +[source] +---- +include::{examples}/diff_send_to_absent_peer.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_send_to_absent_peer.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_send_to_absent_peer.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_send_to_absent_peer.expected[] +---- + +[#trystero-differences-json-numbers] +==== A JSON payload's numbers that a double cannot hold + +Trystero JS:: A JSON payload is sent as `JSON.stringify` writes a JavaScript +value, whose numbers are doubles: `JSON.parse` reads an integer past 2^53^, +or a decimal of more digits than a double keeps, as the nearest double, and a +number past a double's range as `Infinity`, which `JSON.stringify` writes as +`null`. +trystero:: A `webcpp::document::document` holds each number exactly, and a room +sends it as the document writes it, each number a double holds as JavaScript +writes it. A Trystero JS peer that receives the payload reads the nearest +double, or `Infinity`. +Why:: webcpp::document keeps every number exact, and writes each one a double +holds as JavaScript does. + +[source] +---- +include::{examples}/diff_json_numbers.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_json_numbers.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_json_numbers.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_json_numbers.expected[] +---- + +[#trystero-differences-json-refused] +==== A JSON payload nested deeper than 256, holding a lone surrogate, or past the room's bound + +Trystero JS:: `JSON.parse` reads a payload nested deeper than 256, a string +that holds a lone surrogate, `"\ud800"`, as `JSON.stringify` writes one, and +an array of any length, so a room delivers all three. +trystero:: A room reads a JSON payload with webcpp::document's defaults, into +an image of at most `room_options::max_json_document_bytes`, 64 MiB by +default, and delivers none: a text nested deeper than 256 is refused, and so +is a lone surrogate, and an array of 1,000 zeros, whose nodes need some +190 KB, in a room whose bound is 64 KiB. The room goes on, and delivers the +payloads sent after them. +Why:: webcpp::document's defaults: a bounded depth, and strings that are +UTF-8; and each value of a document is a node of 192 bytes of image, 96 +times its text at most, so a program bounds what a peer's JSON may take of +its room's resource. Every payload within the bound is delivered: its image +is first bounded by 96 times its length and 64 KiB, which every valid text +fits (<>). + +The program's room sets the bound: + +[source] +---- +include::{examples}/diff_json_refused.cpp[tag=bound,indent=0] +---- + +A Trystero JS page sends such payloads, and no {cpp} peer sends a lone +surrogate, which a document's UTF-8 strings cannot hold. So the program's +other peer sends what a page sends: each payload's JSON text, as +`JSON.stringify` writes the value, as a text payload, which the backend its +app is given marks as JSON on the wire. + +[source] +---- +include::{examples}/diff_json_refused.cpp[tag=example,indent=0] +---- + +.The twin, on Trystero JS +[source,javascript] +---- +include::{twins}/diff_json_refused.mjs[lines=7..] +---- + +.Trystero JS prints +[listing] +---- +include::{twins}/diff_json_refused.expected[] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_json_refused.expected[] +---- + +[#trystero-differences-self-id-not-utf8] +==== A self id that is not UTF-8 + +Trystero JS:: Has none: it draws its `selfId` when its module loads and takes +none from a program. +trystero:: An app given a self id that is not UTF-8 sets it aside for 20 +random characters, and reports `error::invalid_configuration` to +`app::on_error`. +Why:: JSON carries UTF-8 alone, and a signal writes the id as a JSON string. + +This program has no twin, since no program of Trystero's can give it an id +(`test/oracle/twins/without-twin.txt`), and it joins no room, so it needs no +relay: it runs with the ordinary examples. + +[source] +---- +include::{examples}/diff_self_id_not_utf8.cpp[tag=example,indent=0] +---- + +.trystero prints +[listing] +---- +include::{examples}/diff_self_id_not_utf8.expected[] +---- + +[#trystero-differences-unshown] +=== The differences no program shows + +These rows of <> have no program, each for +its reason. + +[cols="2,5",options="header"] |=== +| Behaviour | Why no program shows it + +| A peer kicked from a room, or that kicked us, over a live connection; frames after the higher id's own kick; a connection whose last room was kicked +| A kick follows a room proof that fails over a live connection, and two {cpp} apps never send one: an app has one password for every room, and apps of different passwords share no connection. A Trystero JS page that mixes passwords does, so the interop lane's wrong room proofs show trystero's side, against a page and not a twin (<>), and the `shared` test holds the rest over the memory relays. + +| Reuse over a live connection +| Only a forged announcement shows it: a third party that publishes, in a peer's name, a room token that peer never advertised, which neither API publishes. The `shared` test forges one over the memory relays. + +| A room frame before the peer's presence for the room +| Both APIs advertise a room before its first frame on a connection, so only a presence lost on the way shows it: Chrome drops it, rarely, when a page sends as its answering channel opens, and the interop lane's delayed-open scenario met it; the `connection` and `shared` tests drop it over the memory relays. + +| Announcements after a peer leaves +| What differs is what a room publishes to its relays after a peer leaves it while their connection stays, which neither API reports: the peers see the same joins and leaves. + +| Presence after binding +| A frame on the connection, which neither API reports; what it changes is how soon the other side binds, a time that no two runs print alike. -*`on_peer_join` does not replay the joined peers.* Trystero calls a newly -assigned `onPeerJoin` with each peer already joined. A room reports a join -from its executor, after the call to `join` has returned, so a -handler set right after `join` sees every join; `peers()` lists the -joined peers for a handler set later. +| An answer to an earlier challenge +| It needs a handshake answer that arrives after a newer challenge, a race between two bindings that no program sets up on a real network; the `shared` test holds it over the memory relays, whose frames it holds and releases. -*`peers()` lists ids.* Trystero's `getPeers` maps each id to its -`RTCPeerConnection`. A connection is the backend's, a page's object in the -browser and libdatachannel's natively, and the room does not hand it out. +| Relay sockets and the Nostr key: the key +| Which key signs a room's events only the relay sees; neither a room nor a peer reports it. The sockets are shown (<>). -*A send to a peer that has not joined fails.* Trystero warns on the console -and resolves; `async_send` completes with `error::no_such_peer`, since an -operation that fails says so with its error code. +| `idle_timeout` +| Not a behaviour: both keep an idle connection 123,333 ms, and Trystero JS takes the same setting under its test-only name, so a program and its twin would agree. -No example of trystero runs under the build, since each needs the public -relays or a browser, so none has a twin in Trystero's language, and the -interop lane, not a twin, compares trystero with Trystero -(<>). +| Frames waiting for a bound room's handler +| A state Trystero JS passes through between a binding and its room's data handler, which its rooms set as they bind; no program reaches it through the API. + +| Renegotiation and media over a shared connection; passive rooms +| Not ported: trystero has nothing of them to run. + +| Crossed duplicate connections +| Not a difference: both keep the connection registered first. + +| A Nostr event a relay repeats, or that several relays carry +| What an event changes when it comes twice is the signaling's work, offers and answers made again, which neither API reports: a program sees one join either way, and over honest relays an event's id is always its own. The `protocol` and `room` tests hold the dedup, forged ids included. + +| A relay's text, a signal or a handshake message past its bound; a protocol text of thousands of values, or nested deeper than 16 +| No Trystero peer writes such a text, so only a relay or a peer that means harm sends one, and what changes is whether the room reads it, which neither API reports. The `protocol` and `signaling` tests hold the bounds. + +| The characters of a random id +| A bias of about 0.005 bits a character, which only a count over many ids shows, and a count of random characters prints something else on every run. +|=== diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index 97f396e..f086999 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -26,15 +26,15 @@ and chunked action frames, control frames, envelopes and presence are what Trystero's own functions compute from the same inputs, byte for byte. _Held by_ `protocol`, against the values the `oracle` lane has Trystero 0.26.0 write, and by the `oracle` lane, which fails when Trystero would write -other values than those committed; and by `native_sealer`, which opens what -Trystero JS sealed with Web Crypto. +other values than those committed; and by `platform_sealer`, natively and on +emscripten, which opens what Trystero JS sealed with Web Crypto. . [[trystero-invariant-3]]*A peer with another password never joins a protected {cpp} app's rooms.* Its initial signals do not open under the app's password, so it obtains no shared connection into that domain. Every room of that app uses the same immutable password. This promise concerns the {cpp} app's admission; an upstream JS page that mixes passwords retains its one-way handshake exposure (<>). _Held -by_ `room` (`the_same_password_joins_and_another_does_not`), `native_room` +by_ `room` (`the_same_password_joins_and_another_does_not`), `platform_room` (`another_password_never_joins`), and password-domain tests of `shared` and `interop`. . [[trystero-invariant-4]]*A payload larger than a frame travels in chunks, @@ -44,9 +44,18 @@ bytes, and arrives whole, from either peer. _Held by_ `room` file transfers of the `interop` lane. . [[trystero-invariant-5]]*Every allocation of an app and its rooms goes through their resources,* but what <> lists: from its -construction until its `io_context` has drained, the global `operator new` -sees only the room's JSON storage counter, and the C library nothing. _Held -by_ `allocation`, natively and on emscripten. +construction until its `io_context` has drained, neither the global +`operator new` nor the C library sees an allocation, while its rooms read +and write their JSON texts and exchange text, binary and JSON payloads of +the `std::pmr` types and `webcpp::document::pmr::document`; over the +platform backend's relays, natively a message adds nothing, and in a page +each of a relay's connections adds its resolver's results and each event of +its `WebSocket` embind's string of the event's type, two for a message. +_Held by_ `allocation`, natively and on emscripten; for a page's sealer, +`platform_page_sealer_allocation`; and for the relays, +`platform_websocket_allocation` natively and +`platform_page_relay_allocation` in a page, which counts exactly what is +listed. . [[trystero-invariant-6]]*No unit test reaches beyond the loopback.* The rooms of the unit tests meet over the memory relays, the native tests' peer connections bind to 127.0.0.1 and gather their candidates there alone, and @@ -66,11 +75,14 @@ reflection scenarios of the `interop` lane. . [[trystero-invariant-8]]*A relay that stops reading is dropped.* Once the text held unsent for it would pass 4 MiB, the connection is dropped, and reports one close, after which the room reconnects with its backoff, as it -does to any relay that closes. _Held by_ `native_websocket` +does to any relay that closes. _Held by_ `platform_websocket` (`a_relay_that_stops_reading_is_dropped_at_the_queue_bound`, a close before -2000 texts of 64 KiB, and one only) natively, and `browser_websocket_bound` -on emscripten, with exceptions and without them, which also checks that the -socket never holds more than 4 MiB; the reconnection by `room` +2000 texts of 64 KiB, and one only) natively, and on emscripten, with +exceptions and without them, by `platform_page_websocket_bound`, where the +page's `WebSocket` holds what is unsent, which also checks that it never +holds more than 4 MiB, and `platform_page_websocket_late_events`, where the +session's queue does, which checks one close and no message after it; the +reconnection by `room` (`a_relay_that_closes_at_once_is_tried_less_and_less_often`). . [[trystero-invariant-9]]*One connection per remote peer per app is shared diff --git a/doc/native.adoc b/doc/native.adoc deleted file mode 100644 index dde013c..0000000 --- a/doc/native.adoc +++ /dev/null @@ -1,147 +0,0 @@ -// 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) - -[#trystero-native] -== The native backend - -Natively, `native::backend` implements the backend interface over -https://github.com/paullouisageneau/libdatachannel[libdatachannel] for -WebRTC, Boost.Beast for the relays' WebSockets, OpenSSL for TLS and AES-GCM, -and Asio's timers. A native room is the same room as a browser's or Trystero -JS's: they meet over the same relays and exchange the same frames. One -backend serves every app and room of the program, with separate app -objects and distinct self ids for different passwords, beside the executor it runs -on, and a native program runs that executor's `io_context` itself, blocking -on it or polling it (<>). - -[#trystero-native-exceptions] -=== Exceptions - -trystero raises no exception of its own, but libdatachannel reports errors by -throwing, and the native backend's data channel and peer connection catch -what it throws on refused input and complete with `error::backend_failure`. -So they need exceptions: without them, or with `WEBCPP_NO_EXCEPTIONS` or -`WEBCPP_TRYSTERO_NO_EXCEPTIONS` defined, `native::data_channel`, -`native::peer_connection` and `native::backend`, which makes their objects, -do not exist, and code that uses them does not compile. The native timer, -sealer and WebSockets, and the rest of trystero, are unchanged. - -``, which every header includes first, defines -`WEBCPP_TRYSTERO_NO_EXCEPTIONS` when webcpp has no exceptions -(`WEBCPP_HAS_EXCEPTIONS` is not defined: the compiler has none, or the -program defined `WEBCPP_NO_EXCEPTIONS`); a developer may define it for -trystero alone in a build that has them. -Each program and test that uses the native backend's WebRTC declares -`on` itself, whatever the build asks -(<>). One function of the backend throws: its -constructor, a `boost::system::system_error` when OpenSSL cannot make the -TLS context or load the system's certificate authorities. - -[#trystero-native-threads] -=== Threads - -libdatachannel delivers its events on threads of its own. The backend never -runs a handler there: each event copies what it carries and is posted to the -room's executor, through a weak reference, so an event that arrives after its -object is gone does nothing. Every handler of the room and every completion -runs on the executor, as in the browser. An application that runs the -`io_context` on several threads gives the app a strand, shared by all its rooms. - -A received data channel message is copied once, out of libdatachannel's -`std::vector` into the app's resource, on the executor. A view -handler reads it there. A binary payload moves when its message buffer -and the room use the same resource, and is copied once otherwise; chunked -transfers assemble their buffer in the room's resource. A text message, as a peer can -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 - -* Automatic negotiation is off, so an offer or an answer exists only when the - signaling asks for one, as in the browser. -* Every object libdatachannel hands out is held by the backend: - libdatachannel keeps only weak references. -* Local candidates leave as the JSON of an `RTCIceCandidateInit`, the form - Trystero JS adds with `addIceCandidate`. -* The `rtc::PeerConnection` object and its control block are made in the - app's resource; what that object allocates inside libdatachannel is - libdatachannel's (<>). - -[#trystero-native-config] -=== Its configuration - -`native::backend_config` is what the backend makes its peer connections -with, beside the app's `ice_servers`: - -[cols="1,3",options="header"] -|=== -| Member | What it is - -| `bind_address` -| The local address every peer connection binds to, as `"127.0.0.1"`; empty - means every interface but the loopback. Bound to the loopback, the peers - of one machine connect with no other network, which a test wants; a peer - bound there reaches no other machine. - -| `max_peer_connections_per_minute` -| The most peer connections the backend makes in any minute, for every room - in every app it serves together, 256: beyond, it makes none, and a room reports each - negotiation it cannot start. A room makes at most 64 in any 57 s however - its peers behave (<>), so the default lets four - rooms do so at once. A connection still counts against its negotiating - room's 57 s window after adoption by the app; presence and reuse make none. - -| `relay_limits` -| What the relays' WebSockets tolerate of a relay that stops reading or - answering, `native::websocket_limits` (<>). -|=== - -[#trystero-native-relays] -=== The relays - -The relays are reached over Boost.Beast: `ws://` in the clear, `wss://` over -TLS with SNI and host name verification. The backend verifies relays against -the system's certificate authorities; `tls_context()` gives the -`boost::asio::ssl::context` to an application with authorities of its own. A -relay whose certificate does not verify is unreachable, and the room retries -it later as it would any other. The WebSockets are Beast's rather than -libdatachannel's own, so the relays run on the room's executor like -everything else. - -A relay is a third party, and the backend bounds what one can make the room -hold: - -* A text longer than 1 MiB (`protocol::max_relay_message_bytes`) closes the - connection before it is copied, as in the browser. -* A relay that stops reading is dropped once the text held unsent for it - would pass 4 MiB (`websocket_limits::max_queued_bytes`, which is - `protocol::max_queued_relay_bytes` on both backends). -* A relay that stops answering is dropped once `idle_timeout` (30 s) passes - with its keep-alive ping unanswered: halfway through, the connection sends - a ping. The timeout counts bytes received, and a ping waits for the write - in flight, so a relay that reads under about 2 KB/s is closed during a - 64 KiB text. Signaling texts are 2 to 4 KB, so a real room meets it only - with a relay slower than about 200 B/s. - -Each drop reports one close, and the room reconnects with its backoff -(<>). A page has no idle timeout: its -`WebSocket` cannot ping (<>). diff --git a/doc/overview.adoc b/doc/overview.adoc index e8e23d5..9ae4e24 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -25,63 +25,77 @@ The library provides: the peers that join and leave, measures round trips, and leaves with Trystero's farewell; * `action`, a named channel of messages: text, JSON - (`boost::json::value`), binary, or any of the three, with optional JSON + (webcpp::document's), binary, or any of the three, with optional JSON metadata, of any size, sent inline or in chunks with backpressure; * one immutable password per app, part of every room's sealed signaling key and challenge handshake; separate passwords use separate apps and ids; * every asynchronous operation as an Asio initiating function, so it - completes with a callback, `boost::asio::use_awaitable`, - `boost::asio::deferred` or any other completion token; -* an `app` per program in one application and password domain, with one identity and one - connection per remote peer shared by its rooms; + completes with a callback, `webcpp::asio::use_awaitable`, + `webcpp::asio::deferred` or any other completion token of webcpp::asio, + which natively is Boost.Asio itself; +* an `app` per program in one application and password domain, with one + identity and one connection per remote peer shared by its rooms; * a resource for the app and an optional resource for each room, which receive their allocations (<>); -* a backend interface that separates the room from the platform, and its - two implementations, for the browser and for native programs. +* a backend interface that separates the room from the platform, and the + platform backend, one implementation of it for native programs and for + pages, whose WebRTC is webcpp::webrtc's on both. [#trystero-overview-targets] -=== Two backends +=== Two targets, one backend `` is the rooms themselves, which build on both of -trystero's targets, native and emscripten, and include neither backend. -Each backend is a header of its own: +trystero's targets, native and emscripten, and leave the platform backend +out. The backend is a header of its own, beside a page's: [cols="1,1,3",options="header"] |=== -| Backend | Target | Built on +| Header | Target | What it holds -| `` -| emscripten -| the page's `WebSocket`, `RTCPeerConnection`, `RTCDataChannel`, - `setTimeout` and `crypto.subtle`, through embind (<>) +| `` +| native and emscripten +| `platform::backend`: webcpp::webrtc for WebRTC, natively over + libdatachannel and in a page over its `RTCPeerConnection` and + `RTCDataChannel`; webcpp::beast for the relays' WebSockets, natively + Boost.Beast's and in a page its `WebSocket`, their URLs read with + Boost.URL; webcpp::asio's timers; and per target the sealer and the + randomness, natively OpenSSL's AES-GCM and `RAND_bytes`, in a page + `crypto.subtle` and `crypto.getRandomValues` (<>) -| `` -| native -| libdatachannel for WebRTC, Boost.Beast for the relays' WebSockets, - OpenSSL for TLS and AES-GCM, and Asio's timers (<>) +| `` +| emscripten +| `platform::page_call` and `platform::js_string`, what a page's program + uses beside the backend (<>) |=== -Both run the same room, and both meet Trystero JS peers. Every name is in the -namespace `webcpp::trystero`. +The backend runs the same room on both targets, and meets Trystero JS peers +on both. Every name is in the namespace `webcpp::trystero`. [#trystero-overview-requirements] === Requirements * A {cpp}20 compiler. -* Boost 1.92: Asio, Container (its `pmr` base class), Core, Hash2, JSON and - System; and Beast for the native backend. +* Boost 1.92: Asio, Assert, Charconv and JSON (whose definitions + webcpp::document links, its parser and its numbers), Circular Buffer, + Container (its `pmr` base class), Endian, Hash2, System and Unordered for + the rooms; URL for the platform backend's relays, and Beast for them + natively. +* webcpp::document for every JSON text, webcpp::asio, and webcpp::webrtc + and webcpp::beast for the platform backend's WebRTC and relays + (<>). * https://github.com/bitcoin-core/secp256k1[libsecp256k1] 0.8.0, with its `schnorrsig` and `extrakeys` modules, for the BIP-340 signatures of Nostr events: every room needs it. webcpp builds it from its pinned source, `/third_party//secp256k1`. -* In the browser: Emscripten 6.0.11, the version webcpp pins, and a page +* In the browser: Emscripten 6.0.11, the version webcpp pins, a page served from a secure context (https, or http on `localhost`), where - `crypto.subtle` exists. + `crypto.subtle` exists, and a program whose `main` runs its `io_context` + (<>). * Natively: - https://github.com/paullouisageneau/libdatachannel[libdatachannel] 0.24.6 - and OpenSSL 3, and exceptions (<>). + https://github.com/paullouisageneau/libdatachannel[libdatachannel] 0.24.6, + through webcpp::webrtc, and OpenSSL 3. trystero raises no exception of its own: an operation that can fail -completes with an error code. The rooms, the protocol and the browser -backend compile without exceptions; so do the native timer, sealer and -WebSockets. +completes with an error code. Every part of it, the platform backend +included, compiles and works without exceptions +(<>). diff --git a/doc/platform.adoc b/doc/platform.adoc new file mode 100644 index 0000000..da15050 --- /dev/null +++ b/doc/platform.adoc @@ -0,0 +1,549 @@ +// 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) + +[#trystero-platform] +== The platform backend + +`platform::backend` implements the backend interface on both targets, one +class for a native program and for a page +(``, `/webcpp/trystero//platform`). Its +WebRTC is webcpp::webrtc's, natively +https://github.com/paullouisageneau/libdatachannel[libdatachannel]'s and in a +page the page's own `RTCPeerConnection` and `RTCDataChannel` +(<>); its relays' WebSockets are +webcpp::beast's, natively Boost.Beast's own and in a page its `WebSocket`; +its timers are webcpp::asio's `steady_timer`. Two parts are the target's own, +chosen by `WEBCPP_TARGET_EMSCRIPTEN`: the sealer, natively OpenSSL's AES-GCM +and in a page `crypto.subtle`, and the source of randomness, natively +OpenSSL's generator and in a page `crypto.getRandomValues`, called from +JavaScript that catches what it throws. Its clocks are the standard +library's on both: `std::chrono::system_clock` for Nostr's `created_at`, and +`std::chrono::steady_clock` for its timing, which Emscripten reads from the +page's `Date.now()` and `performance.now()`. + +A room over it is the same room as a browser's or Trystero JS's: they meet +over the same relays and exchange the same frames. One backend serves every +app and room of the program, with separate app objects and distinct self ids +for different passwords, beside the executor it runs on, and the program runs +that executor's `io_context` itself: natively blocking on it or polling it +(<>), in a page from `main`, as webcpp::asio's +model has it (<>). + +[#trystero-platform-config] +=== Its configuration + +`platform::backend_config` is what the backend makes its peer connections, +its relays and its own state with, beside the app's `ice_servers`: + +[cols="1,3",options="header"] +|=== +| Member | What it is + +| `bind_address` +| The local address every peer connection binds to, as `"127.0.0.1"`; empty + means every interface but the loopback. Bound to the loopback, the peers + of one machine connect with no other network, which a test wants; a peer + bound there reaches no other machine. Natively only: a page's + `RTCPeerConnection` cannot bind, and webcpp::webrtc refuses every + connection a page asks it to bind, so a page leaves it empty. + +| `max_peer_connections_per_minute` +| The most peer connections the backend makes in any minute, for every room + in every app it serves together, 256: beyond, it makes none, and a room + reports each negotiation it cannot start. A room makes at most 64 in any + 57 s however its peers behave (<>), so the + default lets four rooms do so at once. A connection still counts against + its negotiating room's 57 s window after adoption by the app; presence and + reuse make none. + +| `runtime` +| What the backend's own webcpp::webrtc runtime is made with, + `webcpp::webrtc::runtime_options`: its `max_peer_connections`, the most + connections alive at once, 256 by default, beyond which the backend makes + none and a room reports each negotiation it cannot start; and, natively, + `thread_pool_size`, libdatachannel's threads, its own default when 0. + Unused when the backend is given the program's runtime + (<>). + +| `relay_limits` +| What the relays' WebSockets tolerate of a relay that stops reading or + answering, `platform::websocket_limits` (<>). + +| `memory` +| The resource of the backend's own state, the default resource unless the + program gives one: its copy of `bind_address`, its window of constructions + and its own runtime. It must not be null, and must outlive the backend and + every connection of its runtime. What the backend makes for an app or a + room is in the resource given with that call instead + (<>). +|=== + +[#trystero-platform-runtime] +=== The runtime + +webcpp::webrtc's `runtime` caps the peer connections alive at once, and, +natively, holds what libdatachannel keeps for the whole process, its threads +and its global state. A backend makes one of its own, with +`backend_config::runtime`, or takes the program's: `platform::backend(ex, +runtime, config)`, or `platform::backend(ex, tls, runtime, config)` with the +program's TLS context too (<>). Each of its +connections and channels keeps that runtime alive, so that one which +outlives the backend, in a handler the `io_context` still holds, never +outlives the runtime. A connection gives its place back once it is gone. + +Natively a process holds one runtime at a time, since libdatachannel's state +is the process's: a program with several backends at once, or that uses +webcpp::webrtc beside trystero, makes one `webcpp::webrtc::runtime` before +its `io_context` and gives it to each. + +In a page the cap counts every `RTCPeerConnection` of the page, every +program and runtime of it together, from its construction until the garbage +collector frees it, as Chromium counts them against its own 500 (measured +with headless Chrome: the 501st throws "Cannot create so many +PeerConnections", and a closed one counts until a collection): +webcpp::webrtc's census of the page counts every connection it makes, with +any runtime. The default, 256, is half of Chromium's, so that a closed +connection still counts until a collection the page cannot ask for, while +the rest of Chromium's count stays free for what the page makes without a +room. + +[#trystero-platform-relays] +=== The relays + +The relays are reached over webcpp::beast, on both targets with the same +session: natively over Boost.Beast's own WebSocket, in a page over its +`WebSocket`; `ws://` in the clear, `wss://` over TLS. Each connection is a +chain of Asio operations on the room's executor (resolve, connect, TLS, the +handshake, then one read after another, and one write at a time), whose +handlers carry the room's allocator, so that what Asio and Beast allocate +for them, the read buffer among it, is in the room's resource +(<>); the reads' and the writes' handlers have no +executor of their own, so that Asio wraps none of their completions. In a +page the stream's own state is there too. What stays outside it is listed in +<>: natively, for each connection, what Beast, +Asio and OpenSSL allocate of their own, which takes no allocator (their +streams' state, the resolver's, the handshake's request and response, the +verify callback, their timers' waits and each keep-alive ping's frame), and +a message allocates nothing more than the wait of the idle timer, from +Asio's per-thread cache; in a page, for each connection, the resolver's +results, and for each event of the page's `WebSocket` the string embind makes +of its type, two for a message. A write that fails ends the connection, +which reports its close at once. A relay's messages are texts (NIP-01): a +binary one is dropped, on both targets. The WebSockets are Beast's rather +than libdatachannel's own, so the relays run on the room's executor like +everything else. + +A relay's URL is read with Boost.URL, on both targets, by the same rules. +It accepts `ws://` and `wss://`, the scheme in any case; a host name, with +its escapes decoded, in lower case; an IPv4 address as a dotted quad +(`ws://127.0.0.1:7447/`), also with escaped digits, which is then an +address and not a name; an IPv6 address in brackets +(`ws://[2001:db8::1]:7447/`), whose address without them is what the +resolver looks up, and which the handshake names as it is written; and a +port up to 65535, the scheme's when the URL names none. It refuses a URL of +another scheme, `http://` and `https://` among them, which a page's +`WebSocket` alone would take as `ws://` and `wss://`; one without a host, +with userinfo or with a fragment; an IPvFuture address (`ws://[v1.x]/`); +and a host with a byte that a page's URL parser refuses in a host, escaped +or not: a space or a control character, or one of `#`, `%`, `/`, `:`, +`<`, `>`, `?`, `@`, `[`, `+\+`, `]`, `^` and `|`. + +It fails closed on what a page's URL parser accepts but reads otherwise: an +IPv4 address in another form than a dotted quad, which a page reads as the +address and the system's resolver might reach under another name, as the +shorthand `127.1`, octal or hexadecimal parts (`0x7f.0.0.1`), a final dot or +a single number, and so any host whose last label is a number, which a page +reads as an address or refuses; an international domain name, which a page +turns into its A-label (`+xn--bcher-kva.example+` for `bücher.example`) and +this parser does not, with its bytes beyond ASCII escaped or not; a tab, a +newline or a backslash anywhere in the URL, which a page drops or reads as a +slash; and a character that RFC 3986 allows in no path, as a space, `{` or a +byte beyond ASCII, which a page escapes and Boost.URL refuses. A refused URL makes the relay report a close, as an unreachable one +does, and the room retries it later as it would any other. + +Over TLS the connection asks for the relay's verification on both targets, +whatever the verify mode of the context: it sets `verify_peer` on its stream. +A program's context made as Asio makes a client's, +`ssl::context(ssl::context::tls_client)`, whose verify mode is `verify_none`, +still has every relay verified; the context itself is left as it is. +Natively the connection names the relay's host to the server (SNI) when it +is a name, never when it is an address, verifies the relay's certificate +against the context's authorities, and checks it against the URL's host, a +name or an address, with a verify callback of its own: of the context, its +authorities, its client certificate, its options and its protocol versions +hold, and its verify mode and verify callback do not. In a page the browser +does all three, against its own authorities, and webcpp::beast's page stream +refuses a context that asks for what a page cannot honour: authorities +added, a client certificate or key, options, a method other than +`tls_client` or `sslv23_client`, or a verify callback other than +`host_name_verification` of the relay's host. Such a context makes no +`WebSocket`, and every `wss://` relay reports a close. By default the backend +makes its TLS context with +`platform::make_tls_context()`: natively TLS 1.2 or newer, and the system's +certificate authorities, those OpenSSL's default verify paths name; in a +page a context that records only the policy the page's stream asks for, a +client that verifies its peer. A relay whose certificate does not verify is +unreachable, and the room retries it later. + +On Windows OpenSSL's default verify paths are a `cert.pem` file and a +`certs` directory in its build-time directory, `SSL` under the common +program files (`C:\Program Files\Common Files\SSL` on a usual machine), +which neither Windows nor webcpp fills, and OpenSSL reads no Windows +certificate store by default: there the system's authorities are none +unless `SSL_CERT_FILE` or `SSL_CERT_DIR` names some. `make_tls_context()` +succeeds there all the same, and no `wss://` relay verifies, so a Windows +program gives the backend its own context, webcpp's embedded roots as below. + +A native application that trusts other authorities makes its context and +gives it to the backend: webcpp's embedded Mozilla roots, which read no +file of the system, with `webcpp::asio::make_tls_client_context()`, or a +private authority with `webcpp::asio::make_tls_client_context(pem)`: + +[source] +---- +include::{library-root}/test/platform_websocket_test.cpp[tag=embedded-roots,indent=0] +---- + +The backend takes the context as `make_tls_client_context` returns it, a +`boost::system::result`: one that holds an error, as when OpenSSL cannot +make the backend's own, is kept, `tls_context()` returns it, and every +`wss://` relay reports a close while the `ws://` ones are still reached. No +constructor throws. `tls_context()` also gives the context itself, which an +application may configure further before the backend connects to a relay, +natively; in a page what it adds that the page cannot honour, as above, has +every `wss://` relay report a close. + +A relay is a third party, and the backend bounds what one can make the room +hold: + +* A text longer than 1 MiB (`protocol::max_relay_message_bytes`) closes the + connection before it is copied, in a page before it enters WebAssembly, + the relay's first texts too: the bound is set before the handshake, since + a page can deliver a relay's first messages in the same task as its open. +* A relay that stops reading is dropped once the text held unsent for it + would pass 4 MiB (`websocket_limits::max_queued_bytes`, which is + `protocol::max_queued_relay_bytes`): the session's own queue, and in a page + also what its `WebSocket` holds unsent, its `bufferedAmount`, which + webcpp::beast's `queue_limits::send` bounds to the same. +* In a page, the texts a relay sent that wait for the room's executor are + bounded too, at webcpp::beast's `queue_limits::receive`, 4 MiB: past it + the socket closes. +* Natively, a relay that answers the handshake with a status other than 101 + has its response's header read, at most 8 KiB, and no byte of its body, + and the connection reports its close; the room retries with its backoff. + Beast's WebSocket stream reads the response with a parser of its own, + inside its handshake, whose limits none of its options reaches, so the + session's next layer is webcpp::beast's bounded handshake layer + (`websocket::bounded_handshake_stream`, with `response_limits::body` 0), + which reads the response through Beast's parser within those bounds and + hands the handshake no more: a relay's refusal with a body of 4 MiB made + the room's thread allocate 4,199,353 bytes before it, and 5,144 now, the + connection's own state among them (`platform_websocket_allocation`). In a + page the browser makes the handshake. +* Natively, a relay that stops answering is dropped once `idle_timeout` + (30 s) passes with its keep-alive ping unanswered: halfway through, the + connection sends a ping. The timeout counts bytes received, and a ping + waits for the write in flight, so a relay that reads under about 2 KB/s is + closed during a 64 KiB text. Signaling texts are 2 to 4 KB, so a real room + meets it only with a relay slower than about 200 B/s. A page's `WebSocket` + cannot ping, and webcpp::beast's page stream refuses keep-alive pings, so a + page has no idle timeout. + +Each drop reports one close, and the room reconnects with its backoff +(<>). + +[#trystero-platform-randomness] +=== Randomness and sealing + +The backend's randomness, the room's keys and nonces, and the IV of each +seal come from the platform's one secure source, its result checked: +OpenSSL's `RAND_bytes` natively, and in a page `crypto.getRandomValues`, at +most 65536 bytes a call, which the backend calls from JavaScript that catches +what it throws: a page whose `getRandomValues` is missing or throws has no +randomness, and no JavaScript exception enters WebAssembly, where Emscripten's +`getentropy` let it through. When it has none, `random()` aborts the program, +since nothing is safe without it, and a seal fails with +`error::backend_failure`. + +The sealer is asynchronous on both targets, as Web Crypto is: natively it +works synchronously and posts its completion, and in a page it awaits each +Web Crypto promise with webcpp::asio's `browser::async_await`, under a key it +imports on its first operation, while the operations that arrive meanwhile +wait with a copy of their text. A completion never runs inside the call that +started it. A settlement that is not an `ArrayBuffer`, which only a page whose +`crypto.subtle` was replaced gives, fails the seal or the open with +`error::backend_failure`. + +[#trystero-platform-exceptions] +=== Exceptions + +trystero raises no exception of its own, and the platform backend works with +exceptions and without them on both targets, as the rest of trystero does. +Natively libdatachannel reports errors by throwing, but webcpp::webrtc calls +its C API, which catches what it throws and returns a code: a refused +description, candidate or channel completes with `error::backend_failure`, a +connection the platform refuses is not made, and no exception crosses into +trystero. In a page no JavaScript exception enters WebAssembly +(<>). + +``, which every header includes first, defines +`WEBCPP_TRYSTERO_NO_EXCEPTIONS` when webcpp has no exceptions +(`WEBCPP_HAS_EXCEPTIONS` is not defined: the compiler has none, or the +program defined `WEBCPP_NO_EXCEPTIONS`); a developer may define it for +trystero alone in a build that has them. It changes nothing in trystero's +behaviour. No function of the backend throws, its constructors included: when +OpenSSL cannot make the relays' TLS context, the backend keeps the error as a +value, which `tls_context()` returns, and every `wss://` relay reports a +close, as an unreachable one does (<>). + +[#trystero-platform-native] +=== Natively + +[#trystero-platform-threads] +==== Threads + +libdatachannel delivers its events on threads of its own. Neither +webcpp::webrtc nor the backend runs a handler there: webcpp::webrtc posts each +event to the room's executor, through a weak reference, so an event that +arrives after its object is gone does nothing. Every handler of the room and +every completion runs on the executor, as in a page. An application that runs +the `io_context` on several threads gives the app a strand, shared by all its +rooms. A native program that uses the backend is built with `threading=multi` +(<>). + +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-platform-libdatachannel] +==== What the backend asks of libdatachannel + +What libdatachannel does is webcpp::webrtc's: its C API, which works without +exceptions, automatic negotiation off, so that an offer or an answer exists +only when the signaling asks for one, as in a page, and every object it +hands out held until its owner lets it go. The backend adds: + +* Its connections bind to `backend_config::bind_address`. +* A TURN URL with a user name and a credential is written + `turn:user:credential@host`, the form libdatachannel parses + (webcpp::webrtc's `ice_server`). +* A URL libdatachannel cannot parse, as a `stuns:` one, a scheme it does not + know, is left out of the connection, each URL being tried alone, where a + page's `RTCPeerConnection` refuses the whole connection. +* What libdatachannel allocates inside itself is libdatachannel's + (<>). + +[#trystero-platform-page] +=== In a page + +In a page the backend is given the executor of the program's `io_context`, +which the program runs from `main`. One backend serves every app and room of +the page. Apps with different passwords use distinct self ids and share no +connection or presence. ``, which builds +only on emscripten, holds what a page's program uses beside it: +`platform::page_call` and `platform::js_string`. + +[#trystero-platform-run] +==== The program runs its io_context + +A page's program is the shape of any program of webcpp::asio: `main` makes +the `io_context`, the backend, the app and its rooms, and calls `io.run()`, +which runs the rooms' handlers on the stack of `main` and suspends into the +browser's event loop whenever nothing is ready (webcpp::asio's run family, +in either suspension variant). + +* The page's events reach {cpp} through webcpp::asio's bridge, a service of + the `io_context`: a socket's open, message or close, a settled Web Crypto + promise, and webcpp::webrtc's events are each posted to the `io_context`, + and run when the run family resumes, never inside the event. +* The backend's timers are webcpp::asio's `steady_timer`, in the reactor's + timer queue: they fire while the program runs its `io_context`. +* The program holds a work guard on the `io_context` for the page's life: a + page that waits for its user, or for its peers, has no work of its own, and + without the guard `run` would return. +* The page reaches {cpp} through `platform::page_call`, a function of + webcpp::asio's bridge that the program hands to the page, and whose every + call only posts its work to the `io_context`. Nothing calls `run`, `poll` + or `dispatch` from a JavaScript event: while `run` is suspended, an event + sees the `io_context` as running in this thread, and a call of the run + family there fails at its first suspension (webcpp::asio's guide, "Who may + call it"). Nor is a page's call an embind function: under Asyncify, while + the `run` of `main` is suspended, an embind function returns a promise + that never settles, and its second call aborts a debug build (measured + with Emscripten 6.0.11). +* The handler of a `page_call` is a handler of the run, and lets no + JavaScript error out, webcpp::asio's rule for every handler, which its + guide gives where it says what a JavaScript error out of a handler does: + an error that leaves it leaves `run` with it, and the program's run never + resumes (measured with Emscripten 6.0.11 under node: the process ends with + the error, in either suspension variant). A page may pass any value, so + the handler checks its type before it converts it, with `isString()`, + `isNumber()` or `typeOf()`, and reads a field only of what is neither + `null` nor `undefined`: embind's `as()` of a number throws a + `BindingError`, and a field of `undefined` a `TypeError`. The handler is + given the page's value as it is when the handler runs, not when the page + called: a JavaScript object the page changes meanwhile is seen changed. +* A `page_call` posts each call in the resource it is given, which holds the + call until the `io_context` runs it or is destroyed: the resource outlives + the `io_context`. A call through a function the page kept after its + `page_call` was destroyed, or after the `io_context` was, reaches nothing, + and a `page_call` destroyed after its `io_context` is harmless. + +So nothing runs while nothing happens, a handler runs as soon as the run +family resumes after its event, and a turn of `max_handlers_per_turn` +handlers is followed by a yield, which lets the page render. A handler's +{cpp} exception propagates out of `run` to `main`, as it does natively. + +[#trystero-platform-javascript] +==== How JavaScript reaches {cpp} + +Every function the page calls with an event, or with a call of its own +(`platform::page_call`), is made by webcpp::asio's bridge, for a +registration and a key that is never reused, and only posts to the +`io_context`: an object registers when it is made and removes its +registration when it is destroyed, so a late event for a destroyed object +finds nothing. The relays' sockets are webcpp::beast's, whose page stream +also scopes each event to its connection, so that an event of a socket +already dropped reaches nothing. A Web Crypto promise is awaited with +webcpp::asio's `browser::async_await`, whose settlement is posted the same +way and whose operation is outstanding work until it settles. webcpp::webrtc's +objects receive the page's WebRTC events through the same bridge. Their +JavaScript is linked into every program on emscripten by `/webcpp/asio//asio`: +a program includes no source file of trystero's. + +Text that crosses into JavaScript is decoded straight from the WebAssembly +memory a view points into, `platform::js_string`, and text that comes back +is encoded straight into storage of the object's resource: no `std::string` +is made to carry either. + +[#trystero-platform-javascript-exceptions] +==== No JavaScript exception enters WebAssembly + +The backend makes every call into JavaScript that can throw, a `WebSocket` +constructor or `send`, a Web Crypto method, `crypto.getRandomValues`, in +JavaScript that catches what it throws: webcpp::beast's page stream turns a +socket that cannot be made into an error, and its relay reports its close; a +Web Crypto call is made inside an `async` function, so that what it throws +becomes the rejection of its promise, which the {cpp} turns into the error +its interface has, and its settlement is read only when it is an +`ArrayBuffer`; and `crypto.getRandomValues`, missing or throwing, is a +platform without randomness (<>). +webcpp::webrtc's JavaScript catches the page's WebRTC exceptions the same +way. The bridge's functions catch what still escapes a delivery, put +WebAssembly's stack pointer back and report it, and with exceptions a {cpp} +exception is caught in {cpp}, which frees it. So a page's program may be +built with exceptions or without them, and a peer's malformed message never +stops it. + +[#trystero-platform-bounds] +==== What a page bounds + +* A data channel message is read by webcpp::webrtc, a text as the UTF-8 it + holds and a binary one as its bytes, and dropped on the executor when it is + a text, as a peer can send, or larger than any room frame + (`protocol::max_room_frame_bytes`): neither can be a frame. webcpp::webrtc + bounds what it reads: a message past `max_message_size` (256 KiB), or + unread messages past `max_received_bytes` (16 MiB), close the channel. +* A relay's texts are bounded as natively, the first ones it sends in the + task of its open too, and its socket's `bufferedAmount` and its texts + waiting for the executor too (<>); a binary + message is dropped; a page has no idle timeout. +* A page makes at most `runtime_options::max_peer_connections` (256) peer + connections across all apps and rooms it serves, counted from their + construction until the garbage collector frees them + (<>), and at most + `backend_config::max_peer_connections_per_minute` (256) in any minute, as + natively. Beyond, the rooms report each negotiation they cannot start. + +Peer connections, data channels and received frames use the app's resource; +relay sockets, their events, timers and sealed signaling texts use the +room's. Presence or reuse binds another room without making another peer +connection. + +[#trystero-platform-needs] +==== What a page needs + +* A secure context: https, or http on `localhost` or `127.0.0.1`. Elsewhere + `crypto.subtle`, which seals the signaling, does not exist, and every + sealing operation fails with `error::backend_failure`. +* No threads: Emscripten's threads need a cross-origin isolated page, so + trystero uses none. Its Asio is webcpp::asio's, built without threads when + the program has no pthread ABI, and `main` runs it on the page's one + thread. +* A suspension variant of webcpp::asio, which `/webcpp/trystero//platform` + brings: `webcpp-suspend=jspi`, the default, for a browser with JavaScript + Promise Integration, or `asyncify` for any other. The `run` of `main` + suspends in either, and a page loads a variant its browser runs: the + chat's site is built in one, JSPI unless the build asks for + `webcpp-suspend=asyncify` (<>). +* Under Asyncify, no more of its stack than webcpp::asio's 8,192 bytes + (webcpp::asio's guide, "Asyncify's stack"). A room's work runs in + handlers, between the run's waits, so that when `run` suspends the stack + holds the frames of `main` and of webcpp::asio alone. In a `debug` build, + the deepest, the chat's two pages, which joined one room over the public + relays, met over WebRTC and exchanged a message, suspended at most 1,032 + bytes deep, the interop test's page in its 26 scenarios at most 920, and + the tests of a page's program at most 1,600; in a `release` build, linked + at `-O3`, 328, 348 and 384 (measured on 2026-11-15, Emscripten + 6.0.11). A program that runs the `io_context` from deep in its own code, + under large frames, measures its own suspensions and asks for more with + `asyncify-stack-size`, as webcpp::asio's guide says; trystero's tests run + each case in a frame of its own instead (<>). +* A program that runs its `io_context` from `main` for as long as the page + lives, under a work guard: the `io_context` must outlive every room and + object it serves, and its handlers run only while it runs. +* webcpp::document, with Boost.JSON's and Boost.Charconv's definitions, and + Boost.URL's definitions, which a program links from + `/webcpp/document//document` and `/webcpp//boost_url`, which + `/webcpp/trystero//platform` brings and which build on emscripten as on + every target. + +[#trystero-platform-chat] +==== A page and its program + +The chat example is a page whose room is {cpp}: the program joins and sends, +and the page only draws. It keeps the `io_context`, the backend and the room +for the page's life, and makes the action `chat` twice: once as +`std::string_view`, to receive a message as a view of its frame, and once as +`std::string`, to send by moving the text: + +[source] +---- +include::{examples}/chat/chat.cpp[tag=state] +---- + +The program joins the app and the room its user typed, and sets its +handlers; it reads the page's form only once it knows it holds two strings, +since its handler lets no JavaScript error out +(<>), and a received message goes from its frame +straight into a JavaScript string: + +[source] +---- +include::{examples}/chat/chat.cpp[tag=join] +---- + +`send_message` ignores a value that is not a string, shows the message at +once, and reports a failure in the page's log: + +[source] +---- +include::{examples}/chat/chat.cpp[tag=send] +---- + +`main` keeps the chat, makes the page's two calls, each a +`platform::page_call`, which it hands to the page, and runs the `io_context`, +under a work guard, for the page's life. The page calls `joinRoom` and +`sendText` from its own events, a form's submission, and each call only posts +its work to the `io_context`: + +[source] +---- +include::{examples}/chat/chat.cpp[tag=main] +---- + +Any Trystero JS page, or any other page of the chat, that joins the same app +and room is in the same chat (<>). diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 000e935..086d258 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -54,6 +54,19 @@ comes back to 3.3 s only once a connection stayed open for 60 s, so that a relay that closes the room at once after each open is tried less and less often. +A relay may repeat an event, and every relay of the room carries it, so a +room acts on an event once: it remembers the ids of the newest 4096 events it +received (`detail::nostr_strategy::remembered_events`) and drops one it +remembers. An id is whatever a relay sends, so the room remembers one only +once it has checked that it is the event's own, the SHA-256 of the event's +NIP-01 serialization (`protocol::nostr::has_own_id`), and acts on an event +whose id is not its own each time it comes, as Trystero acts on every event: +a relay cannot have the room drop a genuine event by sending a forged one +under its id first. The room indexes the ids with SipHash under a key it +draws when it is made: no relay can choose ids that fall together, as it can +in the standard library's unseeded hash, where each lookup would walk all of +them. + [#trystero-protocol-signaling] === Signaling @@ -71,6 +84,70 @@ the data channel opens: the app adopts the connection, and signals from a bound peer are ignored. A live connection is reused for another room only after the peer advertised that room's token itself on the connection. +[#trystero-protocol-json] +=== JSON texts + +Every JSON text a room reads or writes is webcpp::document's. A text is read +by `webcpp::document::parse` into a `webcpp::document::pmr::document` of the +room's resource, or of the app's for a candidate, which holds its image and +the parse's working state, and read through its handles as views; a key +written twice keeps its last value, as `JSON.parse` keeps it. Each caller +bounds what it reads, as `parse_options::max_bytes`, and drops a longer text +before reading it, as it drops a malformed one: + +[cols="2,1,3",options="header"] +|=== +| Text | Bound | Why + +| a relay's text | 68,608 bytes | an event that carries the longest signal, with 2 KiB for its other fields +| a signal | 66,560 bytes | a sealed offer or answer of 64 KiB with the longest ids, and 1 KiB to spare +| a handshake message | 1,024 bytes | ten times Trystero's longest, 99 bytes +| a remote candidate | 16 KiB | the bound of a sealed candidate, which its opened JSON never passes +|=== + +The image grows in place, twice as large each time, to at most twice the +bound and 64 KiB (`protocol::json::protocol_limits`, as +`parse_options::max_document_bytes`): a text Trystero writes holds a few dozen +values, and a text of thousands of values, which would need a hundred times +its length, is refused once its image has grown to that bound. A protocol +text nests at most 16 deep (`protocol::json::max_protocol_depth`, as +`parse_options::max_depth`), where Trystero's nest 4 deep at most, so that a +hostile relay's text takes the parse's recursion no deeper. A document keeps +no hashed index, so no key read twice, or chosen to collide, makes a parse +slower than the logarithm of its object's size: no text costs a room more +than a multiple of its bound to read. + +A JSON payload, received as either document type, is read into an image of +at most 96 times its length and 64 KiB (`protocol::json::payload_limits`): +each value of a document is a node of 192 bytes, and one of a single +character takes two bytes of text with its comma, so every valid payload +fits. The room's `room_options::max_json_document_bytes`, 64 MiB by default, +bounds that image whatever the payload, so that a program bounds what a +peer's JSON may take of its room's resource: some 350,000 values of one +character pass the default (<>). A +payload's other bounds are the room's `max_receive_bytes` and document's +defaults, values nested at most 256 deep; and document refuses a lone +surrogate, `"\ud800"`, which `JSON.parse` takes. A payload past any of them +is not delivered. + +A parse recurses once a level of nesting. Under Asyncify, the build leaves +Boost.JSON's recursive descent, the `+parse_*+` functions of its +`basic_parser`, out of Asyncify's instrumentation (`asyncify-remove.json`, which +`/webcpp/trystero//trystero` links), since none of them suspends: instrumented, +a level took some 6.5 KB of the engine's stack in a debug build before the +engine optimized the code, so a peer's first payload nested 256 deep +overflowed node's stack at about 150 levels; uninstrumented, it reaches 400, +and in a release build more than 1,000. The room test sends such a payload +first, in both suspension variants. + +A text the protocol writes is a fixed shape of a few strings and numbers, +appended field by field, its strings quoted by `webcpp::document::quote`, the +bytes `JSON.stringify` writes. A string that is not UTF-8 cannot be quoted, and +the writer returns that error: the only such string a program gives that is +ever written, its self id, is set aside for a random one when the app is +made, with a configuration report to `app::on_error`, and a local candidate +whose text is not UTF-8, which no browser's is, is not sent. + [#trystero-protocol-channel] === The data channel @@ -108,12 +185,20 @@ withdrawal detaches only that room. The connection routes by token: | Room frame for another room of the app, not bound to this connection | Keep it, at most 64 frames per connection, all expiring 10 s after the - first. Bind only when the peer advertised the token and no backoff runs. + first, and record its token as the peer's advertisement, below 64 tokens. + Bind when no backoff runs. | Room frame for any other token | Drop it silently; keep the connection. |=== +A room frame is the peer's own advertisement of its room, as its presence +is: only the peer writes to its connection. Trystero sends a room's presence +once per connection, from the open of the channel, and Chrome can drop what a +page sends on an answering channel as it opens (its log says "Send failed +INVALID_STATE"): a room waiting for that presence alone would never bind the +peer, whose frames of the room keep coming. + On binding, kept frames arrive before later frames; a kept `@_leave` discards itself and everything kept before it for that token. There is no buffer for a bound room awaiting its handler: delivery is installed in the @@ -129,7 +214,13 @@ to that peer, and that peer only. Action frames are Trystero's action wire, version 2: an inline frame carries the payload whole; a larger payload is an offer, accepted or refused by the receiver, then chunks of at most 16,370 bytes, in order. Integers and -float64 values are big-endian, as JavaScript's `DataView` writes them. +float64 values are big-endian, as JavaScript's `DataView` writes them. An +offer's size is a float64 that must be a whole number from 1 to 2^53^ - 1, +JavaScript's `Number.MAX_SAFE_INTEGER` (`protocol::max_offer_size`), as +Trystero checks it: any other makes the frame malformed, and the room kicks +its sender, as Trystero does. The size is read in 64 bits on every target, +so a 32-bit one too compares the whole size with `max_receive_bytes`, and +refuses a transfer beyond it as Trystero does. [cols="1,3",options="header"] |=== @@ -177,18 +268,31 @@ what each costs a room. negotiations with peers it is not connected to. A negotiation whose offer and answer expire without a connection is dropped, an idle one gives its place to a new peer, and a new peer beyond the bound is refused and logged - once. + once. A negotiation is idle when it holds no connection and no offer of its + peer is being opened: the one idle longest gives its place, and of those + idle as long, as every negotiation is at one instant of a page's coarse + clock, the one the room took first. So an offer whose sealed text the + backend is still opening (Web Crypto's asynchronous step in a page) keeps + its place however many new ids arrive meanwhile, and is acted on once it + opens. +* A negotiation opens one offer of its peer at a time, as Trystero answers + one at a time: until it is opened, another offer in that name is ignored, + and the same offer through another relay has the answer sent there too. + So the room opens at most 32 offers at once, and offers sent in one name, + however many, hold one open and one copy of an offer. As with Trystero, a + forged offer opened first has the peer's own, arriving meanwhile, wait + until the peer sends it again, 2 s later. * A room makes at most `max_connections_per_window` (64) connections in any - 57 s, however soon they end, and a page at most 256 - (<>); the native backend makes at most 256 a - minute (<>). + 57 s, however soon they end; the platform backend makes at most 256 a + minute on both targets (<>), and a page holds at + most 256 (<>). * A signal's fields are bounded in `protocol/signal.hpp`: the peer id (64 bytes; Trystero's are 20), the offer id (64 bytes), a sealed offer or answer (64 KiB) and a sealed candidate (16 KiB, above the 8192 bytes of plaintext Trystero takes). * A relay is a third party too: its texts are bounded at 1 MiB, what the room holds unsent for it at 4 MiB, and, natively, its silence at 30 s - (<>). + (<>). [cols="2,1,3",options="header"] |=== diff --git a/doc/quick-start.adoc b/doc/quick-start.adoc index 732a7b6..a7a8c57 100644 --- a/doc/quick-start.adoc +++ b/doc/quick-start.adoc @@ -7,68 +7,88 @@ [#trystero-quick-start] == Quick start -The two smallest programs that join a room: one for the browser, one native. -Both use an empty app password and join the room `lobby` of -`webcpp-trystero-quick-start`, so they -meet each other, and any Trystero JS page that joins the same room, -`joinRoom({appId: 'webcpp-trystero-quick-start'}, 'lobby')`, meets them -both. <> builds and runs them. +The quick start is one native program with two peers in it, `alice` and +`bob`: each is an app of its own, with an id the program gives it, and both +join the room `lobby` of the app `webcpp-trystero-quick-start`. alice greets +bob when he joins, bob answers, each prints what it received, and both +leave, which ends the program. In the browser the same rooms run in a page, +as the chat example shows (<>). +<> builds and runs both. -[#trystero-quick-start-browser] -=== In the browser +[#trystero-quick-start-native] +=== Two peers in one program -A browser program keeps five things alive for as long as its page: an -`io_context`, the `browser::event_loop` that drives it from the page's -JavaScript events, the `browser::backend` that implements the platform over -the browser's APIs, the app that owns its identity and shared connections, -and the room joined through that app. Actions are made from the room by name and -payload type: +An app is one peer: its id among the peers, its relays and its STUN servers. +The program gives each app its id, `app_config::self_id`, where an app would +draw 20 random characters, so that what it prints is the same on every run. +It meets over the relay whose URL is in the environment, +`TRYSTERO_RELAY_URL`, which the lane `relayed` starts on 127.0.0.1, and +then keeps its peers on the machine; without it, the program uses +Trystero's public relays and STUN servers, as every program that names none +does: [source] ---- include::{examples}/quick_start.cpp[tag=includes] -include::{examples}/quick_start.cpp[tag=application] +include::{examples}/quick_start.cpp[tag=config] ---- -`` is included in exactly one source file -of the program: it defines the functions the page calls into the library -with. - -Handlers are set once the application exists. This program greets every peer -that completes the handshake, prints every `chat` message, and starts a -coroutine that answers the `echo` action: +`main` makes one `platform::backend` for both apps, joins each app to the +room, and makes in each room the action `chat`, whose messages are +`std::string`. alice greets each peer that joins, once its handshake +completes, with a message to that peer alone, and prints what she receives, +after its sender's id, then leaves. bob's part is a coroutine. `run` +returns once no work is left: each room closes its relays as it leaves, and +each connection closes as soon as no room uses it: [source] ---- include::{examples}/quick_start.cpp[tag=main] ---- -The coroutine awaits messages with `async_receive` and answers with -`async_send`. `boost::asio::as_tuple` turns the error into a value, so -leaving the room ends the loop instead of throwing: +bob awaits the first message with `async_receive`, prints it after its +sender's id, answers its sender with `async_send`, and leaves with +`async_leave`. `asio::as_tuple` hands each error over as a value, so a +room left first ends the wait instead of throwing: [source] ---- -include::{examples}/quick_start.cpp[tag=coroutine] +include::{examples}/quick_start.cpp[tag=answer] ---- -`main` returns at once. Nothing blocks in a browser: every JavaScript event -that reaches the library runs its handlers and then whatever became ready on -the `io_context` (<>). +The program prints bob's line, then alice's: -[#trystero-quick-start-native] -=== Natively +[listing] +---- +include::{examples}/quick_start.expected[] +---- + +Its twin on Trystero JS prints the same two lines. Trystero draws one +`selfId` per page, so bob is a second page there, and each peer prints the +other's name where the {cpp} program prints the id it gave the app: + +[source,javascript] +---- +include::{twins}/quick_start.mjs[lines=7..] +---- + +[#trystero-quick-start-browser] +=== In the browser -The same app and its joined room, natively, whole: a program that greets every peer that joins -and prints what it receives on `chat`. A native program runs its -`io_context` itself, since there is no event loop of a page to drive it, and -the native backend posts what libdatachannel's threads report to it: +In a page the same app and room are {cpp} compiled to WebAssembly, over the +page's own WebSocket and `RTCPeerConnection`. The chat example keeps what a +page's program keeps for as long as the page lives: an `io_context`, the +`platform::backend` on its executor, the app, the room joined through it, +and its actions: [source] ---- -include::{examples}/native_quick_start.cpp[tag=program] +include::{examples}/chat/chat.cpp[tag=state] ---- -`io.run()` returns only when the program is stopped: the room keeps its -relays and its peers for as long as it lives. +<> shows how it joins, sends, and runs its +`io_context` from `main`, and <> serves it. +Two tabs of the chat that join the same app and room meet; so do a native +peer and a page, which the lane `interop` proves with Trystero JS pages in +headless Chrome (<>). diff --git a/doc/roadmap.adoc b/doc/roadmap.adoc index 87de050..f16a2e5 100644 --- a/doc/roadmap.adoc +++ b/doc/roadmap.adoc @@ -17,7 +17,8 @@ the page's `MediaStreamTrack` objects. Natively they would be libdatachannel's RTP tracks, whose encoding, decoding and capture are the application's. What that needs was measured: libdatachannel keeps only weak references to tracks, answers with every codec offered unless the answer is pruned, and -echoes the offerer's `msid` into the answer. +echoes the offerer's `msid` into the answer. Media will be an interface of +webcpp::webrtc's, which the backends' WebRTC is. . *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. diff --git a/doc/testing.adoc b/doc/testing.adoc index 3c5ed9f..32eab88 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -26,7 +26,10 @@ The memory network identifies connection ends with `std::size_t` ids. paired end. A `filter` delivers, drops or holds frames; a held frame holds all later frames from its sending end behind it, preserving channel order until `release`. Deferred `open` calls open each end separately; `inject` -and `fail` supply malformed frames and transport failure. +and `fail` supply malformed frames and transport failure. With +`hold_sealer_opens`, every sealer's opens wait, as Web Crypto's take their +time in a page, until `release_sealer_opens` completes them in order; +`held_sealer_opens` counts them. With `channel_capacity` enabled, the channel queues bytes and drains up to `drain_per_post` per post. It delivers a frame only after its last byte @@ -37,11 +40,12 @@ backoffs and late frames are tested without wall-clock sleeps. Optional fault hooks allocate outside the measured resources only when enabled; the allocation test leaves them disabled. -A test of the native backend's own WebRTC binds its connections to the -loopback, `native::backend_config::bind_address` set to `"127.0.0.1"`, and -names a STUN server where nothing answers, `stun:127.0.0.1:9`, in place of -Trystero's public ones: the loopback's host candidate is then the only one, -and it is enough. +A native test of the platform backend's own WebRTC binds its connections to +the loopback, `platform::backend_config::bind_address` set to +`"127.0.0.1"`, and names a STUN server where nothing answers, +`stun:127.0.0.1:9`, in place of Trystero's public ones: the loopback's host +candidate is then the only one, and it is enough. A page cannot bind, and +leaves `bind_address` empty (<>). [#trystero-testing-library] === How trystero is tested @@ -49,8 +53,9 @@ and it is enough. trystero's tests are under `test/`, each declared in `test/Jamfile`, and each guarantee of <> names the tests that hold it. They run on two targets: {n-tests} tests in all, {n-tests-native} natively and -{n-tests-emscripten} on emscripten, under node. The protocol, the rooms and -the allocation test run on both: +{n-tests-emscripten} on emscripten, under node, each in both of webcpp::asio's +suspension variants, JSPI and Asyncify. The protocol, the rooms, the timer +and the allocation test run on both: [listing] ---- @@ -58,14 +63,20 @@ include::{library-root}/test/Jamfile[tag=both-targets] include::{library-root}/test/Jamfile[tag=allocation] ---- +The timer's test, of a part that parses no JSON, links `parts` (`$(part)`) +in place of the rooms, the Jamfile's own requirement, without their Asyncify +list (<>). + [cols="1,3",options="header"] |=== | Test | What it checks | the public headers -| Each compiled alone, on each target that builds it: the core on both, the - native backend natively, against libdatachannel and OpenSSL, and the - browser backend on emscripten. +| Each compiled alone, on each target that builds it: the core, and the + platform backend's `backend.hpp`, `entropy.hpp`, `sealer.hpp` and + `websocket.hpp` with the backend's WebRTC, on both, natively against + webcpp::webrtc's libdatachannel and OpenSSL and in a page over its own + objects; and `platform/page.hpp`, on emscripten alone. | `config`, `config_developer_defined`, `config_all_off` | `` defines `WEBCPP_TRYSTERO_NO_EXCEPTIONS` @@ -77,19 +88,30 @@ include::{library-root}/test/Jamfile[tag=allocation] | `protocol` | The protocol against values Trystero JS 0.26.0 computed itself: topics, room tokens, the relay shuffle, sealed text, Nostr event ids, inline and - chunked action frames, control frames, envelopes and presence, and the - bounds of a signal's fields. + chunked action frames, control frames, envelopes and presence, a JSON + payload's numbers and key order, and the bounds of a signal's fields. + +| `signaling` +| The signaling and the Nostr strategy alone: as an answerer, the signals + Trystero JS 0.26.0's own signal handler published for the same offers, + byte for byte, a signal or a relay's text read at its bound and + dropped one byte past it, and a relay's text read 16 deep and dropped one + level deeper. -| `room` +| `room`, `room_asyncify_release` | Whole rooms in one process, over the memory relays: every payload format, 100 KB transfers both ways, ping, passwords right and wrong, leaving and returning, a room moved over a joined one, ICE servers checked as WebRTC checks them, floods of announcements and of forged, replayed and reflected - signals, a relay that closes at once or rate-limits, a three-peer mesh, - coroutines and view handlers. - -| `app_impl` -| Configuration copying and validation, resource ownership, weak room + signals, offers being opened that keep their places when new ids arrive + at the same instant, one offer of a peer opened at a time, a relay that + closes at once or rate-limits, a three-peer mesh, coroutines and view + handlers, JSON payloads read in the room's resource up to its bound, and a + rejected document receive. + +| `app_impl`, `app_impl_asyncify_release` +| Configuration copying and validation, a self id that is not UTF-8 set + aside, resource ownership, weak room registration, shared adoption, stale replacement, reentrant adoption, last-user closure and quiet destruction with pending work. @@ -105,51 +127,162 @@ include::{library-root}/test/Jamfile[tag=allocation] | Multiple apps and rooms with one connection per remote peer, adoption races, presence and reuse, room isolation, departures, idle connections, password-domain isolation, invalid room proofs, transient handshake recovery, - fairness, bounds and - resource ownership. The suite also runs without exceptions and with + fairness, bounds, a handshake message read at its bound and failing one + byte past it, and resource ownership. The suite also runs without exceptions and with standard-library hardening; sanitizers check lifetimes and detachment. -| `allocation` +| `allocation`, `allocation_asyncify_release` | Every allocation of two apps and their rooms goes through their resources (<>). -| `native_sealer`, `native_websocket`, `native_timer` -| The native backend, part by part, natively: the sealer opens what Trystero - JS sealed with Web Crypto; the WebSocket, against a Beast server in the - same process, opens, sends in order, closes once, and drops a relay that - sends too much, stops reading or stops answering, while one that answers - its pings stays; the timer never fires once cancelled, restarted or - destroyed. - -| `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. A controlled executor holds real channel callbacks to - prove pre-handler FIFO delivery, a 65th message ahead of the posted flush, +| `timer` +| The timer over webcpp::asio's `steady_timer`, which the platform backend + makes on both targets: a wait fires once, in the timer's resource, and one + cancelled, restarted or destroyed never fires, even when its expiry was + already queued. + +| `platform_backend`, `platform_sealer`, `platform_websocket_unreachable`, + `platform_websocket_url`, and each `_no_exceptions` +| The platform backend on both targets, natively and on emscripten under + node, which has the page's WebSocket and Web Crypto but no WebRTC. The + backend itself keeps its own state, its copy of `bind_address`, its window + of constructions and its own runtime, in `backend_config::memory`, none of + it in the default resource, and gives it all back when it is destroyed + (<>); its clocks are the standard library's, + its randomness fills what it is given, differently each time, beyond a + piece of its source too (65536 bytes in a page), its executor is the one + it was given and its TLS context is made. The sealer opens what Trystero JS + sealed with Web Crypto, seals a text that opens again in Trystero's form, + takes a text sealed under another key, or no sealed text, for a wrong + password, completes after the call that started it, never inside it, and + completes each of two seals and two opens given in one call, which in a + page wait while it imports its key; in a page without `crypto.subtle` it + fails with `error::backend_failure`. A relay it cannot reach, of a URL the + session refuses, `http://` and `https://` among them, reports exactly one + close, after the call that made it, and so does one of a port on 127.0.0.1 + or `::1` where nothing listens, which is attempted: natively its TCP + connection fails, and in a page node's `WebSocket` is made and closes + before it opens. A relay's URL is read as a page reads it, and what a + page's URL parser reads otherwise is refused, by the same rules on both + targets. + +| `platform_websocket` +| The relays' WebSocket natively, built with the standard libraries' checks, + against Beast servers in the same process: it opens, sends in order, + closes once, reaches a relay at an IPv6 address (where the kernel opens a + socket of IPv6's family; elsewhere the case prints that it does not apply + and checks nothing), opens over TLS with the relay's name sent (SNI) + against a test authority, refuses a certificate for another name or of an + authority not trusted, also with a program's context whose verify mode is + `verify_none`, keeps a TLS context's error in the backend, drops a binary + message, closes once when the connection ends during a write, and drops a + relay that sends too much, stops reading or stops answering, while one + that answers its pings stays. + +| `platform_websocket_allocation`, `platform_websocket_allocation_no_exceptions` +| Natively, a relay's message allocates nothing outside the room's resource: + from the send of a text to the receipt of its echo, ten times, the global + `operator new` counts none on the room's thread + (<>); and a relay that refuses the upgrade + with a body of 4 MiB has its response's header read alone, the room's + thread allocating less than 64 KiB until the close. + +| `platform_peer_connection`, `platform_room`, and each `_no_exceptions` +| Natively, two connections of the backend's WebRTC, over webcpp::webrtc's + libdatachannel, wired to each other, each handler on the executor, and + whole rooms over the platform backend and real connections, bound to + 127.0.0.1. A controlled executor holds the offerer's events to prove + pre-handler FIFO delivery, a 65th message read 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 - WebSocket, Web Crypto and microtasks but no WebRTC: the loop and its - recovery from exceptions that escape a callback, the WebSocket's URLs, its - bound on what a relay holds unsent and its silence once dropped, the - sealer's completions, a data channel's refusal of what is no frame, and - the page's peer connections, made or refused, and their census. + and allocation and release through the connection's resource; a peer of + webcpp::webrtc's own sends a text, which is dropped between two frames; + malformed candidates and descriptions fail without throwing, and so does a + candidate one byte past its bound, which at the bound is added; a local + candidate that is not UTF-8 is not written; the backend + makes at most its budget in a minute, holds at most its runtime's cap at + once, and leaves out a URL libdatachannel cannot parse. Both run once more + without exceptions. + +| `platform_page_websocket_bound`, `platform_page_websocket_late_events`, + `platform_page_websocket_ingress`, `platform_page_websocket_tls`, + `platform_page_data_channel`, `platform_page_peer_connection`, + `platform_page`, `platform_page_call`, `platform_page_handlers`, + `platform_page_sealer`, `platform_page_sealer_allocation`, + `platform_page_relay_allocation`, and each `_no_exceptions` +| The platform backend in a page, on emscripten under node, each test's + `main` running its `io_context` as a page's program does: the relays' + WebSocket, its bound on what a relay holds unsent, both the session's own + queue and the page's `bufferedAmount`, which webcpp::beast's send limit + bounds, and its silence once dropped; its refusal of a text past 1 MiB that + a relay sends in the same task as its open, and of a binary message; a + program's context of `tls_client`, whose verify mode is `verify_none`, + reaching a `wss://` relay, and the contexts a page cannot honour refused; + what a relay's connection and each of its messages allocate outside the + room's resource, exactly; over webcpp::webrtc's browser + objects and a page's `RTCPeerConnection` of the test's, a data channel's + refusal of what is no frame, and the page's peer connections, made or + refused, webcpp::webrtc's census of them and the backend's window of + constructions, which holds in a page as natively; and the shape of a + page's program, whose work guard keeps a page with no room yet running, + and whose `platform::page_call` functions, called from JavaScript while + `run` is suspended, return at once, only post, and reach the room, twice + in a row under Asyncify too, while a value of the wrong type is ignored + and breaks nothing; a call through a function the page kept after its + `page_call`, or its `io_context`, was destroyed reaches nothing, and the + handler reads the page's value as it is when it runs, and a number within + its range; the relay socket's and the sealer's handlers run outside the + page's events; a page whose `crypto.getRandomValues` throws or is missing + has no randomness and fails a seal, and one whose `crypto.subtle` settles + with something other than an `ArrayBuffer` fails a seal and an open, with + `error::backend_failure`, no JavaScript exception entering WebAssembly; and + a seal and an open allocate nothing outside the room's resource, neither + with `operator new` nor with the C library's functions. |=== -The native backend's connections need exceptions whatever the build asks -(<>), and each browser test is also built -without exceptions, as a program that uses the browser backend may be: +The platform backend's tests run on each target that builds them, and once +more without exceptions (<>), as a program +that uses the backend may be built, but for `platform_websocket`, which +runs once, with the standard libraries' checks. The tests of a relay's URL, +a page's calls and the sealer in a page, parts that parse no JSON, link +`platform-parts` (`$(platform-part)`) in place of the backend and the rooms: [listing] ---- -include::{library-root}/test/Jamfile[tag=browser] +include::{library-root}/test/Jamfile[tag=platform] +include::{library-root}/test/Jamfile[tag=page] include::{library-root}/test/Jamfile[tag=no-exceptions] ---- -From the root of a webcpp checkout, with the three libraries of -<> found, each of these builds and runs the tests, +Under Asyncify each suspension saves the frames from `main` down to the call +that suspends, in webcpp::asio's 8,192 bytes (webcpp::asio's guide, +"Asyncify's stack"). A room's own work is never among those frames +(<>), but a test's cases are: each case calls the +run family itself. So a test whose cases suspend runs each through +`webcpp::test::run_case` (`test/cases.hpp`), in a frame of its own, which +the frame of `main` never holds, whatever the link. At `-O3` a case that +`main` alone calls is inlined into it, and a program linked without +optimization, as b2 linked a `release` build until 2026-11-15 and as +`-O0` still links one, then saves every case's locals in the +frame of `main` at each suspension: the room test's `main` saved 29,776 +bytes so, and the test stopped at its first suspension. b2 links a `release` +build at `-O3` now, where even a `main` with every case inlined fits, and +the deepest build is `debug`. The room, `app_impl` and allocation tests, +whose cases hold whole apps, run once more under Asyncify in a `release` +build, as a page ships them, in the own lane `asyncify` on emscripten, which +the CI's emscripten lane, building JSPI, runs no other way (a target that +names `asyncify` belongs in a lane of emscripten's, since a +build with no emscripten configured cannot expand that feature); their +deepest suspensions wrote 564, 440 and 408 bytes +there, and 2,344, 2,068 and 2,020 in `debug` (measured on 2026-11-15 with +Emscripten 6.0.11): + +[listing] +---- +include::{library-root}/test/Jamfile[tag=asyncify-release] +---- + +From the root of a webcpp checkout, with libsecp256k1 found +(<>), each of these builds and runs the tests, natively, under AddressSanitizer and UndefinedBehaviorSanitizer, and on emscripten: @@ -160,16 +293,19 @@ b2 libs/trystero/test address-sanitizer=norecover undefined-sanitizer=norecover b2 toolset=emscripten libs/trystero/test ---- -The {n-linked} examples are linked and never run, since each needs the -public relays or a browser. b2 compares timestamps, so a result that counts -is built from scratch, with `b2 -a`. +The chat page's program is linked and never run, since it is a page; the +quick start and the programs of the appendix "Differences" run over a relay +of their own in the lane `relayed` (<>), and the one +of them that needs no relay with the ordinary examples, `b2 +libs/trystero/example`. b2 compares timestamps, so a result that counts is +built from scratch, with `b2 -a`. [#trystero-testing-lanes] === The oracle and the interop lanes Two lanes of trystero's own, declared in `test/oracle/Jamfile`, check it against Trystero itself, pinned at 0.26.0 by `test/oracle/package.json` and -`package-lock.json`, with Node: +`package-lock.json`, with Node, run as `node --conditions=development`: [listing] ---- @@ -179,8 +315,9 @@ include::{library-root}/test/oracle/Jamfile[tag=oracle] `oracle`, which names no target, runs Trystero's own functions over the inputs of `test/fixtures/cases/protocol.json` and checks that they still write `test/fixtures/expected/expected.json` byte for byte, the values the -`protocol` and `native_sealer` tests reproduce; `update-expected` is its only -writer. +`protocol` and `platform_sealer` tests reproduce, and runs the twins of the +examples (<>); `update-expected` is the only writer +of the expected values and of each divergent twin's output. [listing] ---- @@ -254,6 +391,49 @@ b2 -a --dump-tests --out-xml=native.trystero.interop.xml libs/trystero/test/orac b2 -a --dump-tests --out-xml=emscripten.trystero.interop.xml toolset=emscripten libs/trystero/test/oracle//interop ---- +[#trystero-testing-twins] +=== The examples over a relay, and their twins + +The quick start and each program of the appendix "Differences" +(<>) meet over a Nostr relay of their own, the +interop's `test/oracle/interop/relay.mjs` on 127.0.0.1, in the lane +`relayed`, natively, which `example/Jamfile` declares: its driver, +`example/run_over_relay.mjs`, starts the relay, runs the program with the +relay's URL in its environment, `TRYSTERO_RELAY_URL`, which the program +reads, and passes when the program exits with 0 having printed its +`.expected`. + +[listing] +---- +include::{library-root}/example/Jamfile[tag=quick-start] +include::{library-root}/example/Jamfile[tag=differences] +---- + +Each of these programs has its twin in `test/oracle/twins/`, the same +program on Trystero 0.26.0, which the oracle lane runs through +`test/oracle/run_twin.mjs`: a relay of its own, its URL in +`TRYSTERO_RELAY_URL`, and the twin, whose output must be the program's +`.expected`, or, for a difference, its own `.expected`, which must differ. +The twins agree with {n-twins-agreeing} of the programs and diverge from +{n-twins-divergent}; {n-examples-without-twin} have none, each with its +reason in `test/oracle/twins/without-twin.txt`: the chat, a page that prints +nothing, and a difference whose original has no counterpart. + +Trystero JS has one self id per page, so a twin whose room meets a peer, as +a {cpp} program's second app does, runs that peer as a second page, a worker +thread with Trystero's modules of its own (`test/oracle/page.mjs`). Node has +no WebRTC: Trystero JS takes werift's `RTCPeerConnection` as `rtcPolyfill`, +the WebRTC for Node that Trystero 0.26.0's own README names, pinned at 0.24.4 +in `test/oracle/package.json` for the twins alone. The {cpp} programs whose +apps meet bind their connections to 127.0.0.1 with `stun:127.0.0.1:9`, and +the twins have no ICE server, so every peer stays on the machine. + +[source,bash] +---- +b2 -a --dump-tests --out-xml=native.trystero.relayed.xml libs/trystero/example//relayed +b2 -a libs/trystero/test/oracle//twins +---- + [#trystero-testing-container] === The container lanes @@ -270,20 +450,24 @@ runtime and static link configuration. These builds need no network access. === 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. +uses Asio TLS, Beast and Trystero's platform backend together, natively. It +compares the compiled OpenSSL version with the loaded implementation, makes +its WebRTC state through trystero's backend, a peer connection and a data +channel, and checks the backend's relay TLS context, all over the one +provider. The run is bounded to 45 seconds and uses the threaded release +profile, with exceptions as the build asks. 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`, plus the +and its own lanes, the oracle once, the examples over a relay natively, as +`native.trystero.relayed`, and the interop natively and on emscripten, as +`native.trystero.interop` and `emscripten.trystero.interop`, the release +Asyncify tests as `emscripten.trystero.asyncify`, 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 diff --git a/doc/trystero.adoc b/doc/trystero.adoc index 02367b2..60358b2 100644 --- a/doc/trystero.adoc +++ b/doc/trystero.adoc @@ -21,12 +21,13 @@ joined from Trystero's JavaScript are one room. This page teaches trystero section by section: what a room is, how a program joins one in the browser and natively, how its actions carry messages, where -its memory comes from, what each backend asks of its platform, the wire it +its memory comes from, what the platform backend asks of each target, the wire it speaks, and what it guarantees. Every program it shows is one of the -library's examples, which the build compiles and links on its target. None -is run by the build, since each needs the public relays or a browser, so the -page shows no output of theirs. The <> lists every name -the headers declare. +library's examples, which the build compiles and links on its target. The +build runs each that needs no browser over a Nostr relay of its own, and the +page shows what it prints, with its twin on Trystero JS; the chat, a page, +is linked and never run. The <> lists every name the +headers declare. include::overview.adoc[] @@ -38,9 +39,7 @@ include::usage.adoc[] include::allocation.adoc[] -include::browser.adoc[] - -include::native.adoc[] +include::platform.adoc[] include::protocol.adoc[] diff --git a/doc/usage.adoc b/doc/usage.adoc index afb8ec6..bbfdfaf 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -94,6 +94,9 @@ moved, or build it in place. Each room adds `room_options`: | `max_receive_bytes` | The most bytes the room reserves for incoming transfers across peers, 256 MiB. +| `max_json_document_bytes` +| The largest image a received JSON payload's document may take of the room's resource, webcpp::document's default, 64 MiB; a payload past it is not delivered (<>). + | `memory` | The room's own resource; null uses the app's resource. |=== @@ -172,7 +175,8 @@ plus 1 s, doubling after each further end to at most 5 minutes. A completed handshake or the connection's end resets the count. After its own kick the lower id refuses bindings until that time and keeps frames; the higher id drops frames until it sends presence, but accepts the lower id's presence. -A binding also requires the peer to have advertised the token itself. +A binding also requires the peer to have advertised the token itself, by +its presence or by a frame of the room on its connection. A peer on a protected app's shared connection already authenticated with that app's password through the initial sealed negotiation. A peer that knows it can still send a wrong room proof: only the lower id reports that @@ -195,22 +199,80 @@ messages travel and how they are received: | `std::string` | text | a copy of the bytes | `std::pmr::string` | text | a copy of the bytes, in the room's resource | `std::string_view` | text | a view of the frame it arrived in, valid during the handler -| `boost::json::value` | JSON | parsed, in the room's JSON storage +| `webcpp::document::document` | JSON | parsed into a document of its own, with the standard allocator +| `webcpp::document::pmr::document` | JSON | parsed into a document of the room's resource, which holds its image and the parse's working state | `trystero::bytes` | binary | a copy of the bytes | `trystero::pmr_bytes` | binary | the transfer's buffer, moved when resources match, otherwise copied once into the room's resource | `std::span` | binary | a view of the frame, valid during the handler -| `trystero::payload` | any | a `std::variant` of `std::string`, `boost::json::value` and `bytes`, by format +| `trystero::payload` | any | a `std::variant` of `std::string`, `webcpp::document::document` and `bytes`, by format |=== +A JSON payload is webcpp::document's: a `webcpp::document::document` the +program builds or parses, with the standard allocator, or a +`webcpp::document::pmr::document`, whose image a memory resource holds, the +room's when it is received; the pair mirrors `std::string` and +`std::pmr::string`. A {cpp} peer sends the +bytes `JSON.stringify` writes of the same value, which Trystero JS sends, +for every value JavaScript can hold: its strings, booleans and nulls, +its keys in JavaScript's order, array indices first, and every number a +double holds, written as JavaScript writes it. A number a double cannot +hold, an integer past 2^53^ or a decimal of more digits, is sent exact, as +webcpp::document holds it: a Trystero JS peer reads the nearest double, or +`Infinity` past a double's range. A text that does not parse is not +delivered, nor one nested deeper than 256 or holding a lone surrogate, +which `JSON.parse` takes, nor one whose document passes the room's +`room_options::max_json_document_bytes`, 64 MiB of image by default, some +350,000 values of one character, which a program lowers to bound what a +peer's JSON may take of its room's resource (<>). + +A document is moved, never copied: so `payload`, which may hold one, has no +copy assignment, and in a build without exceptions no copy constructor +either; nor has a document a default constructor there, where a program +makes one with `create()` or `webcpp::document::parse`, each of which +returns a result, given the resource's allocator for a +`webcpp::document::pmr::document`. A handle of a document's values refers to +the document object, as every handle of webcpp::document does: moving the +document invalidates it, so a handler that keeps a received document moves +it and reads it through the handles of the document it moved it into. A +`webcpp::document::pmr::document` move-assigned to one of another resource +copies its image into that resource, and raises `std::bad_alloc` through +`boost::throw_exception` when the resource has no room: a program without +exceptions keeps one by move construction, `std::optional::emplace` for +one. The room test sends one: + +[source] +---- +include::{library-root}/test/room_test.cpp[tag=json-send,indent=0] +---- + +receives it: + +[source] +---- +include::{library-root}/test/room_test.cpp[tag=json-receive,indent=0] +---- + +and reads it: + +[source] +---- +include::{library-root}/test/room_test.cpp[tag=json-read,indent=0] +---- + A message of another format than the action's type is not delivered to it. Several actions of different types may share a name: one receives as views, another sends by moving strings, as the chat does -(<>). +(<>). Messages arrive at the handler `on_message` sets, with a `message_info`: the sender's id and the metadata it passed. Without a handler they queue, up to 1024 per action, the oldest dropped first, for `async_receive`, which needs -an owning type: a view would outlive the message. Frames of an action that +an owning type: a view would outlive the message; a message of another +format, or a JSON text that does not parse, completes it with +`error::transfer_rejected` and an empty value, which allocates nothing: an +empty container, in the room's resource for a `std::pmr` type, and for a JSON +one webcpp::document's `nothing()`, a document with no image whose root reads +`undefined`. Frames of an action that arrived before it was made are kept, 64 per peer for 120 s, and delivered to it once it is. @@ -231,16 +293,17 @@ peers. === Completion tokens and ownership Every asynchronous operation is an Asio initiating function. With a callback -it calls it on the room's executor; with `boost::asio::use_awaitable` it -resumes a coroutine; with `boost::asio::deferred` it returns an operation -started later. +it calls it on the room's executor; with `webcpp::asio::use_awaitable` it +resumes a coroutine; with `webcpp::asio::deferred` it returns an operation +started later. webcpp::asio is Boost.Asio itself natively, so Boost.Asio's +tokens are the same there; on emscripten they are webcpp::asio's. Because a deferred operation starts after the call, the arguments of an asynchronous operation are owned: `async_send` takes its value by value, moved when the type owns its storage, copied once at the call into the room's -resource when it is a view, and serialized at once when it is a -`boost::json::value`; `send_options` owns its strings; and `async_ping` -copies the peer id at the call. Everything else that only reads text takes a +resource when it is a view, and written at once, into the room's resource, +when it is a JSON document; `send_options` owns its strings; and +`async_ping` copies the peer id at the call. Everything else that only reads text takes a `std::string_view`. [#trystero-usage-errors] diff --git a/example/Jamfile b/example/Jamfile index 3b5593f..74cf7cc 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -5,7 +5,7 @@ # https://www.boost.org/LICENSE_1_0.txt) # A program of rooms over Asio holds more sections than MSVC's object format -# allows by default (C1128, measured in native_quick_start): /bigobj. +# allows by default (C1128, measured in the native quick start): /bigobj. project : requirements /webcpp/trystero//trystero msvc:/bigobj ; @@ -13,17 +13,43 @@ import webcpp ; webcpp.targets native emscripten ; -# Each needs the public relays or a browser, so it is linked and never run. -# The native backend needs exceptions whatever the build asks: libdatachannel -# reports errors by throwing. -# tag::native[] -webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//native multi on : native ; -# end::native[] -# tag::browser[] -webcpp.link quick_start : quick_start.cpp - : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH : emscripten ; -# end::browser[] - -# The chat page, on emscripten: its program and the site it is served from. +# The chat page, on emscripten: its program and the site it is served from. A +# page, linked and never run. build-project chat ; + +# The programs that run over a Nostr relay of their own on 127.0.0.1, +# natively: run_over_relay.mjs starts it (test/oracle/interop/relay.mjs), +# gives the program its URL in TRYSTERO_RELAY_URL, and passes when the +# program prints its .expected. Each has its twin, on Trystero JS, under +# test/oracle/twins/. Node runs the relay with the packages test/oracle pins. +webcpp.original node --conditions=development : ../test/oracle ; +# The quick start (doc: #trystero-quick-start). +# tag::quick-start[] +webcpp.drive quick_start : quick_start.cpp + : /webcpp/trystero//platform multi : run_over_relay.mjs : : native ; +# end::quick-start[] +# The programs of the appendix "Differences" (doc: #trystero-differences). +# tag::differences[] +local differences = + diff_already_joined + diff_json_numbers + diff_json_refused + diff_passwords + diff_peer_join + diff_peers + diff_relay_config + diff_relay_sockets + diff_rooms_per_app + diff_self_id + diff_send_to_absent_peer + ; +for local difference in $(differences) +{ + webcpp.drive $(difference) : $(difference).cpp + : /webcpp/trystero//platform multi : run_over_relay.mjs : : native ; +} +webcpp.lane relayed : quick_start $(differences) : native ; +# One needs no relay, its app joining no room, and has no twin. +webcpp.example diff_self_id_not_utf8.cpp + : /webcpp/trystero//platform multi : native ; +# end::differences[] diff --git a/example/chat/Jamfile b/example/chat/Jamfile index 64209e6..7011a5f 100644 --- a/example/chat/Jamfile +++ b/example/chat/Jamfile @@ -9,7 +9,7 @@ # site/ beside the program, under the build directory, out of the tree, and # prints that directory, for any static server on localhost. -project : requirements /webcpp/trystero//trystero ; +project : requirements /webcpp/trystero//platform ; import errors ; import notfile ; @@ -19,8 +19,12 @@ webcpp.targets emscripten ; path-constant HERE : . ; +# The page's program, linked for the web with a memory that grows +# (doc: #trystero-building-project). +# tag::page[] webcpp.link chat : chat.cpp : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH : emscripten ; +# end::page[] # The page is for a browser, built on emscripten alone: asked for on another # toolset, site stops the build saying so, where b2 would otherwise skip it @@ -35,15 +39,20 @@ rule emscripten-only ( properties * ) } } -# A copy action rather than install, which knows chat-program.js but not the -# chat-program.wasm em++ writes beside it. The site is site/ beside the -# program, under its own target path, so that each variant has its own. +# A copy action rather than install, which knows the program's JavaScript but +# not the WebAssembly em++ writes beside it. webcpp::asio names the program +# after its suspension variant (chat-program-60-d-jspi.js) and the JavaScript +# loads its WebAssembly by that name: the JavaScript is copied as +# chat-program.js, which the page loads, and the WebAssembly as it is. The +# site is site/ beside the program, under its own target path, so that each +# variant has its own. actions site { set -e site="`dirname "$(>[1])"`/site" mkdir -p "$site" - cp "$(>[1])" "`dirname "$(>[1])"`/chat-program.wasm" "$(HERE)/index.html" "$site/" + cp "$(>[1])" "$site/chat-program.js" + cp "`echo "$(>[1])" | sed 's/\.js$/.wasm/'`" "$(HERE)/index.html" "$site/" echo "$site" } diff --git a/example/chat/chat.cpp b/example/chat/chat.cpp index 10d3bc0..b2416fd 100644 --- a/example/chat/chat.cpp +++ b/example/chat/chat.cpp @@ -8,15 +8,17 @@ // It joins over Trystero's public Nostr relays, so Trystero JS peers with the same app id and room // id are in the same chat. #include -#include -#include // once per program: the JavaScript export +#include +#include + +#include +#include -#include #include -#include #include #include +#include using emscripten::val; namespace trystero = webcpp::trystero; @@ -25,9 +27,8 @@ namespace { // tag::state[] struct chat { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + webcpp::asio::io_context io; + trystero::platform::backend backend{io.get_executor()}; std::unique_ptr app; // made at the first join, with that join's app id std::unique_ptr room; // The action "chat" twice: received as views of the frame, and sent by moving the text. @@ -37,13 +38,8 @@ struct chat { // end::state[] -chat& the_chat() { - static chat c; // the page's one chat; it lives as long as the tab - return c; -} - val js(std::string_view text) { - return the_chat().loop.text(text); + return trystero::platform::js_string(text); } val js(bool value) { @@ -57,19 +53,26 @@ void ui(const char* name, const Args&... args) { } // tag::join[] -void join_room(const std::string& app_id, const std::string& room_id) { - auto& c = the_chat(); - if (c.room) { +void join_room(chat& c, const val& form) { + // The page's value is checked before it is read: a page_call's handler lets no JavaScript + // error out of the run, which reading a field of null or undefined (a TypeError) or converting + // what is not a string (embind's BindingError) would. + if (c.room || form.isNull() || form.isUndefined()) { return; } + const val app_field = form["app"]; + const val room_field = form["room"]; + if (!app_field.isString() || !room_field.isString()) { + return; + } + const auto room_id = room_field.as(); if (!c.app) { trystero::app_config config; - config.app_id = app_id; + config.app_id = app_field.as(); config.log = [](std::string_view category, std::string_view text) { ui("log", category, text); }; - c.app = - std::make_unique(c.loop.get_executor(), c.backend, std::move(config)); + c.app = std::make_unique(c.io.get_executor(), c.backend, std::move(config)); } auto joined = c.app->join(room_id); if (!joined) { @@ -94,9 +97,12 @@ void join_room(const std::string& app_id, const std::string& room_id) { // end::join[] // tag::send[] -void send_message(std::string text) { - auto& c = the_chat(); - if (!c.room || text.empty()) { +void send_message(chat& c, const val& message) { + if (!c.room || !message.isString()) { + return; + } + auto text = message.as(); + if (text.empty()) { return; } ui("message", c.room->self_id(), std::string_view(text), true); @@ -111,10 +117,19 @@ void send_message(std::string text) { } // namespace -// tag::bindings[] -EMSCRIPTEN_BINDINGS(chat_example) { - emscripten::function("join", &join_room); - emscripten::function("send", &send_message); +// tag::main[] +int main() { + chat c; // the page's one chat, which lives as long as the tab, in main's run + // The page's two calls, functions of webcpp::asio's bridge that post their work to the + // io_context: joinRoom with the form's app and room, sendText with the text its user wrote. + const trystero::platform::page_call join(c.io.get_executor(), + [&c](const val& form) { join_room(c, form); }); + const trystero::platform::page_call send(c.io.get_executor(), + [&c](const val& text) { send_message(c, text); }); + val::global("chatUi").call("ready", join.function(), send.function()); + // The page waits for its user with no work at all: the guard keeps the run going. + const auto guard = webcpp::asio::make_work_guard(c.io); + c.io.run(); // lint-run: the page's program, suspended into the browser's event loop } -// end::bindings[] +// end::main[] diff --git a/example/chat/index.html b/example/chat/index.html index 6a64045..bf56cb8 100644 --- a/example/chat/index.html +++ b/example/chat/index.html @@ -82,7 +82,14 @@

trystero chat

add(p) } const showPeers = () => ($('peers').textContent = peers.size === 1 ? '1 peer' : `${peers.size} peers`) +// The program's two calls, which it hands over once its main runs: each posts its work to the +// program's io_context and returns at once. +let program = null window.chatUi = { + ready: (joinRoom, sendText) => { + program = {joinRoom, sendText} + $('join').disabled = false + }, joined: (self, room) => { $('who').innerHTML = '' const code = text => Object.assign(document.createElement('code'), {textContent: text}) @@ -110,14 +117,13 @@

trystero chat

}, log: (category, text) => $('log').append(`${category}: ${text}\n`), } -var Module = {onRuntimeInitialized: () => ($('join').disabled = false)} $('join-form').onsubmit = event => { event.preventDefault() - Module.join($('app').value.trim(), $('room').value.trim()) + program.joinRoom({app: $('app').value.trim(), room: $('room').value.trim()}) } $('send-form').onsubmit = event => { event.preventDefault() - Module.send($('text').value) + program.sendText($('text').value) $('text').value = '' } diff --git a/example/diff_already_joined.cpp b/example/diff_already_joined.cpp new file mode 100644 index 0000000..dfeb52b --- /dev/null +++ b/example/diff_already_joined.cpp @@ -0,0 +1,47 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): joining a room the app has +// joined already. Trystero's joinRoom returns the room it joined before; app::join refuses with +// error::already_joined, since a room is a handle whose destruction leaves. Its twin is +// test/oracle/twins/diff_already_joined.mjs. Both join over the relay whose URL is in the +// environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. + +#include +#include +#include + +#include + +#include +#include +#include + +namespace trystero = webcpp::trystero; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + boost::asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + // tag::example[] + trystero::app app(io.get_executor(), backend, + {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); + auto first = app.join("lobby"); + const auto second = app.join("lobby"); + std::cout << "the first join: " << (first ? std::string("a room") : first.error().message()) + << '\n' + << "the second join: " + << (second ? std::string("another room") : second.error().message()) << '\n'; + // end::example[] + if (first) { + first->async_leave([](boost::system::error_code) {}); + } + io.run(); // lint-run: the room's farewell, over the relay +} diff --git a/example/diff_already_joined.expected b/example/diff_already_joined.expected new file mode 100644 index 0000000..fb46897 --- /dev/null +++ b/example/diff_already_joined.expected @@ -0,0 +1,2 @@ +the first join: a room +the second join: the app has already joined a room of that id diff --git a/example/diff_json_numbers.cpp b/example/diff_json_numbers.cpp new file mode 100644 index 0000000..06762ac --- /dev/null +++ b/example/diff_json_numbers.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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): a JSON payload's numbers that +// a double cannot hold. Trystero JS sends a JSON payload as JSON.stringify writes a JavaScript +// value, whose numbers are doubles: an integer past 2^53 and a decimal of more digits than a +// double keeps are sent as the nearest double, and a number past a double's range, Infinity, as +// null. A webcpp::document::document holds each number exactly, and a room sends it as the +// document writes it. This program's room sends the payload a JSON text makes, and another peer of +// the same program prints what it receives. Two apps of one program meet in a room, as two pages +// would. Its twin is test/oracle/twins/diff_json_numbers.mjs. Both meet over the relay whose URL +// is in the environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. + +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trystero = webcpp::trystero; +namespace wd = webcpp::document; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + boost::asio::io_context io; + // The peers meet on this machine alone: every connection bound to the loopback, and a STUN + // server where nothing answers in place of Trystero's public ones. + trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + const auto config = [relay] { + trystero::app_config c; + c.app_id = "webcpp-trystero-differences"; + c.relay_urls = {relay}; + c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; + // The connection closes once no room uses it, so that the program ends when both leave. + c.idle_timeout = std::chrono::milliseconds{0}; + return c; + }; + trystero::app other_app(io.get_executor(), backend, config()); + auto other = other_app.join("lobby"); + trystero::app app(io.get_executor(), backend, config()); + auto joined = app.join("lobby"); + if (!other || !joined) { + std::cerr << "not joined\n"; + return 1; + } + trystero::room room = std::move(*joined); + const auto leave = [&] { + room.async_leave([](boost::system::error_code) {}); + other->async_leave([](boost::system::error_code) {}); + }; + // tag::example[] + // The numbers of the payload's JSON text, none of which a double holds: an integer past 2^53, + // a decimal of 34 digits, and a number past a double's range. + constexpr std::array numbers{ + "9007199254740993", + "0.1000000000000000000000000000000001", + "1e999", + }; + std::string text = "["; + for (const std::string_view number : numbers) { + text += text.size() > 1 ? "," : ""; + text += number; + } + text += ']'; + // This room sends the payload its JSON text makes, once it meets the other peer. + auto payload = room.make_action("payload"); + room.on_peer_join([&](std::string_view) { + wd::result value = wd::parse(text); + if (!value) { + std::cerr << "not parsed: " << value.error().message() << '\n'; + leave(); + return; + } + payload.async_send(std::move(*value), [](boost::system::error_code) {}); + }); + // What the other peer receives, number by number. + auto received = other->make_action("payload"); + received.on_message([&](const wd::document& value, const trystero::message_info&) { + for (std::size_t i = 0; i < numbers.size(); ++i) { + std::cout << numbers[i] << " arrives as " << value[i].stringify() << '\n'; + } + leave(); + }); + // end::example[] + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} diff --git a/example/diff_json_numbers.expected b/example/diff_json_numbers.expected new file mode 100644 index 0000000..d340df5 --- /dev/null +++ b/example/diff_json_numbers.expected @@ -0,0 +1,3 @@ +9007199254740993 arrives as 9007199254740993 +0.1000000000000000000000000000000001 arrives as 0.1000000000000000000000000000000001 +1e999 arrives as 1e+999 diff --git a/example/diff_json_refused.cpp b/example/diff_json_refused.cpp new file mode 100644 index 0000000..9634d2f --- /dev/null +++ b/example/diff_json_refused.cpp @@ -0,0 +1,288 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): a JSON payload nested deeper +// than 256, holding a lone surrogate, or whose document passes the room's bound. Trystero JS +// delivers all three, as JSON.parse reads them; a room here delivers none, since it reads a JSON +// payload with webcpp::document's defaults, at most 256 deep, and strings that are UTF-8, into an +// image of at most room_options::max_json_document_bytes, which this program's room sets to 64 KiB: +// an array of 1,000 zeros, a node of 192 bytes each, passes it. A Trystero JS page sends such +// payloads, and a C++ +// peer sends no lone surrogate, which a document's UTF-8 strings cannot hold, so the other peer of +// this program sends what a page sends: each payload's JSON text, as JSON.stringify writes the +// value, as a text payload, which the backend its app is given marks as JSON on the wire. This +// program's room receives the payloads, and a last one sent after them. Two apps of one program +// meet in a room, as two pages would. Its twin is test/oracle/twins/diff_json_refused.mjs. Both +// meet over the relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start +// on 127.0.0.1. + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trystero = webcpp::trystero; +namespace protocol = webcpp::trystero::protocol; +namespace wd = webcpp::document; + +namespace { + +// The action the payloads travel on. +constexpr std::string_view action_name = "payload"; + +// A data channel of the backend's, shared by its owners. +using channel_ptr = std::shared_ptr; + +// A data channel that forwards to another, and sends each text payload of the action as a JSON +// payload of the same text: the frame a Trystero JS page sends of a value whose JSON.stringify is +// that text. +class json_marking_channel final : public trystero::backend::data_channel { +public: + json_marking_channel(channel_ptr channel, std::pmr::memory_resource* memory) + : channel_(std::move(channel)), memory_(memory) {} + + void set_handlers(handlers h) override { channel_->set_handlers(std::move(h)); } + + [[nodiscard]] bool is_open() const override { return channel_->is_open(); } + + void send(std::span frame) override { + const auto envelope = protocol::decode_envelope(frame); + if (envelope && envelope->type == protocol::envelope::kind::room) { + const auto decoded = protocol::decode_action(envelope->payload); + const auto* const p = + decoded.frame ? std::get_if(&*decoded.frame) : nullptr; + if (p != nullptr && p->kind == protocol::frame_kind::inline_payload && + p->format == protocol::payload_format::text && p->name == action_name) { + const auto action = protocol::encode_inline(p->name, protocol::payload_format::json, + p->metadata, p->payload, memory_); + channel_->send(protocol::room_frame(envelope->token, action, memory_)); + return; + } + } + channel_->send(frame); + } + + [[nodiscard]] std::size_t buffered_amount() const override { + return channel_->buffered_amount(); + } + + void close() override { channel_->close(); } + +private: + channel_ptr channel_; + std::pmr::memory_resource* memory_; +}; + +// The channel `channel` marking its text payloads of the action as JSON, made in `memory`; null for +// none. +channel_ptr marking(channel_ptr&& channel, std::pmr::memory_resource* memory) { + if (!channel) { + return nullptr; + } + return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), + std::move(channel), memory); +} + +// A peer connection that forwards to another, and whose data channels, those it opens and those +// the remote peer opens, are json_marking_channel's. +class json_marking_connection final : public trystero::backend::peer_connection { +public: + json_marking_connection(std::shared_ptr connection, + std::pmr::memory_resource* memory) + : connection_(std::move(connection)), memory_(memory) {} + + void set_handlers(handlers h) override { + if (h.data_channel) { + h.data_channel = trystero::handler( + std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), + [memory = memory_, deliver = std::move(h.data_channel)]( + channel_ptr channel) mutable { deliver(marking(std::move(channel), memory)); }); + } + connection_->set_handlers(std::move(h)); + } + + channel_ptr create_data_channel(std::string_view label) override { + return marking(connection_->create_data_channel(label), memory_); + } + + void set_local_description( + trystero::handler done) + override { + connection_->set_local_description(std::move(done)); + } + + void set_remote_description(std::string_view type, std::string_view sdp, + trystero::handler done) override { + connection_->set_remote_description(type, sdp, std::move(done)); + } + + void add_ice_candidate(std::string_view candidate_json, + trystero::handler done) override { + connection_->add_ice_candidate(candidate_json, std::move(done)); + } + + [[nodiscard]] bool has_remote_description() const override { + return connection_->has_remote_description(); + } + + void close() override { connection_->close(); } + +private: + std::shared_ptr connection_; + std::pmr::memory_resource* memory_; +}; + +// A backend that forwards to another, and whose peer connections are json_marking_connection's. +class json_marking_backend final : public trystero::backend::factory { +public: + explicit json_marking_backend(trystero::backend::factory& backend) : backend_(backend) {} + + std::shared_ptr connect( + std::string_view url, trystero::backend::websocket::handlers h, + std::pmr::memory_resource* memory) override { + return backend_.connect(url, std::move(h), memory); + } + + std::shared_ptr make_peer_connection( + std::span servers, + std::pmr::memory_resource* memory) override { + // The connection is moved into the marking one below, which a const one could not be: + // through libstdc++'s polymorphic_allocator construction misc-const-correctness sees no + // change. + // NOLINTNEXTLINE(misc-const-correctness) + auto connection = backend_.make_peer_connection(servers, memory); + if (!connection) { + return nullptr; + } + return std::allocate_shared( + std::pmr::polymorphic_allocator<>(memory), std::move(connection), memory); + } + + std::shared_ptr make_timer( + std::pmr::memory_resource* memory) override { + return backend_.make_timer(memory); + } + + std::shared_ptr make_sealer( + std::array key, std::pmr::memory_resource* memory) override { + return backend_.make_sealer(key, memory); + } + + void random(std::span out) override { backend_.random(out); } + + std::chrono::sys_seconds unix_now() override { return backend_.unix_now(); } + + std::chrono::steady_clock::time_point steady_now() override { return backend_.steady_now(); } + +private: + trystero::backend::factory& backend_; +}; + +} // namespace + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + boost::asio::io_context io; + // The peers meet on this machine alone: every connection bound to the loopback, and a STUN + // server where nothing answers in place of Trystero's public ones. + trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + const auto config = [relay] { + trystero::app_config c; + c.app_id = "webcpp-trystero-differences"; + c.relay_urls = {relay}; + c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; + // The connection closes once no room uses it, so that the program ends when both leave. + c.idle_timeout = std::chrono::milliseconds{0}; + return c; + }; + // The other peer, as a Trystero JS page would be: its app's backend marks the text payloads of + // the action as JSON. + json_marking_backend marking_backend(backend); + trystero::app other_app(io.get_executor(), marking_backend, config()); + auto other = other_app.join("lobby"); + trystero::app app(io.get_executor(), backend, config()); + // tag::bound[] + // A room whose received JSON payloads take at most 64 KiB of its resource each. + auto joined = app.join("lobby", {.max_json_document_bytes = std::uint64_t{64} << 10U}); + // end::bound[] + if (!other || !joined) { + std::cerr << "not joined\n"; + return 1; + } + trystero::room room = std::move(*joined); + const auto leave = [&] { + room.async_leave([](boost::system::error_code) {}); + other->async_leave([](boost::system::error_code) {}); + }; + // tag::example[] + // The payloads the other peer sends, as JSON text, each an array of its label and a value: one + // nested 257 deep, one holding a lone surrogate, an array of 1,000 zeros past the room's bound, + // and a last one sent after them. + std::string zeros = "[0"; + for (std::size_t i = 1; i < 1000; ++i) { + zeros += ",0"; + } + const auto payloads = std::to_array>({ + {"nested 257 deep", std::string(256, '[') + std::string(256, ']')}, + {"holding a lone surrogate", R"("\ud800")"}, + {"of 1,000 zeros", zeros + "]"}, + {"sent after them", R"("plain")"}, + }); + // What this room delivers of them, by label, once the last has come. + auto payload = room.make_action(action_name); + std::vector delivered; + payload.on_message([&](const wd::document& value, const trystero::message_info&) { + delivered.emplace_back(value[0].value_or(std::string_view())); + if (delivered.back() != payloads.back().first) { + return; + } + for (const auto& sent : payloads) { + const bool came = std::ranges::find(delivered, sent.first) != delivered.end(); + std::cout << "the payload " << sent.first << ": " + << (came ? "delivered" : "not delivered") << '\n'; + } + leave(); + }); + // end::example[] + // The other peer sends each payload's text once it meets this room. An inline frame leaves at + // once, so they leave in the order of the sends, as a Trystero JS page awaits each. + auto sending = other->make_action(action_name); + other->on_peer_join([&](std::string_view) { + for (const auto& [label, value] : payloads) { + sending.async_send("[\"" + std::string(label) + "\"," + value + "]", + [](boost::system::error_code) {}); + } + }); + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} diff --git a/example/diff_json_refused.expected b/example/diff_json_refused.expected new file mode 100644 index 0000000..875a407 --- /dev/null +++ b/example/diff_json_refused.expected @@ -0,0 +1,4 @@ +the payload nested 257 deep: not delivered +the payload holding a lone surrogate: not delivered +the payload of 1,000 zeros: not delivered +the payload sent after them: delivered diff --git a/example/diff_passwords.cpp b/example/diff_passwords.cpp new file mode 100644 index 0000000..7c2fa3d --- /dev/null +++ b/example/diff_passwords.cpp @@ -0,0 +1,99 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): passwords across rooms. +// Trystero JS takes a password with each room, so that one page holds rooms of different +// passwords, over one connection to a peer it meets in several. A password here is an app's, the +// same for every room of the app and never changed, since the sealed negotiation that makes a +// connection authenticates that password before any room of the app reuses the connection: rooms +// of different passwords are rooms of separate apps, each with its own self id. This program joins +// a lobby with one password and a kitchen with another, as another peer of the same program does, +// and compares the peers its two rooms meet. Its twin is test/oracle/twins/diff_passwords.mjs. +// Both meet over the relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes +// start on 127.0.0.1. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace asio = boost::asio; +namespace trystero = webcpp::trystero; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + asio::io_context io; + // The peers meet on this machine alone: every connection bound to the loopback, and a STUN + // server where nothing answers in place of Trystero's public ones. + trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + const auto config = [relay](std::string_view password) { + trystero::app_config c; + c.app_id = "webcpp-trystero-differences"; + c.password = password; + c.relay_urls = {relay}; + c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; + // The connection closes once no room uses it, so that the program ends when all leave. + c.idle_timeout = std::chrono::milliseconds{0}; + return c; + }; + // The other peer, as another page would be, with the same passwords for the same rooms. + trystero::app other_one(io.get_executor(), backend, config("one")); + trystero::app other_two(io.get_executor(), backend, config("two")); + auto other_lobby = other_one.join("lobby"); + auto other_kitchen = other_two.join("kitchen"); + // tag::example[] + // A password is an app's: a room with another password is a room of another app. + trystero::app one(io.get_executor(), backend, config("one")); + trystero::app two(io.get_executor(), backend, config("two")); + auto lobby = one.join("lobby"); + auto kitchen = two.join("kitchen"); + // What the two rooms meet. + const auto report = [](std::string_view in_lobby, std::string_view in_kitchen) { + std::cout << "the lobby, with the password \"one\": joined\n" + << "the kitchen, with the password \"two\": joined\n" + << "the peer in both rooms: " + << (in_lobby == in_kitchen ? "one peer" : "two peers") << '\n'; + }; + // end::example[] + if (!other_lobby || !other_kitchen || !lobby || !kitchen) { + std::cerr << "not joined\n"; + return 1; + } + // The peer each of this program's rooms meets first; once both have met one, the program + // reports, and every room leaves. + const std::array rooms{&*lobby, &*kitchen}; + std::array met; + std::size_t meetings = 0; + for (std::size_t i = 0; i < rooms.size(); ++i) { + rooms[i]->on_peer_join([&, i](std::string_view peer) { + if (!met[i].empty()) { + return; + } + met[i] = peer; + if (++meetings < met.size()) { + return; + } + report(met[0], met[1]); + for (trystero::room* room : {&*lobby, &*kitchen, &*other_lobby, &*other_kitchen}) { + room->async_leave([](boost::system::error_code) {}); + } + }); + } + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} diff --git a/example/diff_passwords.expected b/example/diff_passwords.expected new file mode 100644 index 0000000..9444fd7 --- /dev/null +++ b/example/diff_passwords.expected @@ -0,0 +1,3 @@ +the lobby, with the password "one": joined +the kitchen, with the password "two": joined +the peer in both rooms: two peers diff --git a/example/diff_peer_join.cpp b/example/diff_peer_join.cpp new file mode 100644 index 0000000..57d5183 --- /dev/null +++ b/example/diff_peer_join.cpp @@ -0,0 +1,79 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): a join handler set once a +// peer has joined. Trystero calls a newly set onPeerJoin with each peer already joined; a room +// reports a join from its executor once, to the handler set then, and peers() lists the peers +// joined. Two apps of one program meet in a room, as two pages would. Its twin is +// test/oracle/twins/diff_peer_join.mjs. Both meet over the relay whose URL is in the environment, +// TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace asio = boost::asio; +namespace trystero = webcpp::trystero; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + asio::io_context io; + // The peers meet on this machine alone: every connection bound to the loopback, and a STUN + // server where nothing answers in place of Trystero's public ones. + trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + const auto config = [relay] { + trystero::app_config c; + c.app_id = "webcpp-trystero-differences"; + c.relay_urls = {relay}; + c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; + // The connection closes once no room uses it, so that the program ends when both leave. + c.idle_timeout = std::chrono::milliseconds{0}; + return c; + }; + trystero::app other_app(io.get_executor(), backend, config()); + auto other = other_app.join("lobby"); + trystero::app app(io.get_executor(), backend, config()); + auto joined = app.join("lobby"); + if (!other || !joined) { + std::cerr << "not joined\n"; + return 1; + } + trystero::room room = std::move(*joined); + const auto leave = [&] { + room.async_leave([](boost::system::error_code) {}); + other->async_leave([](boost::system::error_code) {}); + }; + // tag::example[] + int late_calls = 0; + room.on_peer_join([&](std::string_view) { + std::cout << "the handler set before the join: called\n"; + // Once the join is reported, another handler replaces this one. + asio::post(io, [&] { + room.on_peer_join([&late_calls](std::string_view) { ++late_calls; }); + asio::post(io, [&] { + std::cout << "the handler set after the join: " + << (late_calls == 0 ? "not called" : "called") << '\n' + << "peers: " << room.peers().size() << '\n'; + leave(); + }); + }); + }); + // end::example[] + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} diff --git a/example/diff_peer_join.expected b/example/diff_peer_join.expected new file mode 100644 index 0000000..e3c5a91 --- /dev/null +++ b/example/diff_peer_join.expected @@ -0,0 +1,3 @@ +the handler set before the join: called +the handler set after the join: not called +peers: 1 diff --git a/example/diff_peers.cpp b/example/diff_peers.cpp new file mode 100644 index 0000000..71d9a77 --- /dev/null +++ b/example/diff_peers.cpp @@ -0,0 +1,72 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences): what a room lists of its peers. +// Trystero's getPeers maps each joined peer's id to its RTCPeerConnection; room::peers lists the +// ids, since a connection is the backend's and the room does not hand it out. Two apps of one +// program meet in a room, as two pages would. Its twin is test/oracle/twins/diff_peers.mjs. Both +// meet over the relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start +// on 127.0.0.1. + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace trystero = webcpp::trystero; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + boost::asio::io_context io; + // The peers meet on this machine alone: every connection bound to the loopback, and a STUN + // server where nothing answers in place of Trystero's public ones. + trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + const auto config = [relay] { + trystero::app_config c; + c.app_id = "webcpp-trystero-differences"; + c.relay_urls = {relay}; + c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; + // The connection closes once no room uses it, so that the program ends when both leave. + c.idle_timeout = std::chrono::milliseconds{0}; + return c; + }; + trystero::app other_app(io.get_executor(), backend, config()); + auto other = other_app.join("lobby"); + trystero::app app(io.get_executor(), backend, config()); + auto joined = app.join("lobby"); + if (!other || !joined) { + std::cerr << "not joined\n"; + return 1; + } + trystero::room room = std::move(*joined); + const auto leave = [&] { + room.async_leave([](boost::system::error_code) {}); + other->async_leave([](boost::system::error_code) {}); + }; + // tag::example[] + room.on_peer_join([&](std::string_view peer_id) { + const auto peers = room.peers(); + std::cout << "peers: " << peers.size() << '\n' + << "the joined peer's entry: " + << (peers.size() == 1 && peers.front() == peer_id ? "its id" : "not its id") + << '\n'; + leave(); + }); + // end::example[] + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} diff --git a/example/diff_peers.expected b/example/diff_peers.expected new file mode 100644 index 0000000..804338c --- /dev/null +++ b/example/diff_peers.expected @@ -0,0 +1,2 @@ +peers: 1 +the joined peer's entry: its id diff --git a/example/diff_relay_config.cpp b/example/diff_relay_config.cpp new file mode 100644 index 0000000..ecae417 --- /dev/null +++ b/example/diff_relay_config.cpp @@ -0,0 +1,185 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): where a room's relays and ICE +// servers come from. Trystero JS opens the relays of the first room a page joins, and every room +// joined while one remains uses them, whatever relays it was given; and it makes a connection with +// the RTC configuration of the room that negotiates it, which the page's other rooms then share. A +// room here uses its app's relays and ICE servers, so a room joined with another configuration is +// a room of another app. Two peers of one program meet in a lobby with a first configuration, and +// in a kitchen with a second. Trystero JS hands out the page's relay sockets and a room's +// connection; a room here hands out neither, so each app of this program is given a backend that +// records what the app asks of the platform one. Its twin is +// test/oracle/twins/diff_relay_config.mjs. Both meet over the relay whose URL is in the +// environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = boost::asio; +namespace trystero = webcpp::trystero; + +namespace { + +// The relays and the ICE servers an app is configured with. +struct configuration { + std::string relay; // the one relay's URL + std::string stun; // the one STUN server's URL +}; + +// A backend that forwards to another, and records the relays and ICE servers asked of it. +class observing_backend final : public trystero::backend::factory { +public: + explicit observing_backend(trystero::backend::factory& backend) : backend_(backend) {} + + // The URLs of the relays it was asked to connect to. + [[nodiscard]] const std::set& relays() const { return relays_; } + + // The URLs of the ICE servers of the peer connections it was asked to make. + [[nodiscard]] const std::set& ice_servers() const { return ice_servers_; } + + std::shared_ptr connect( + std::string_view url, trystero::backend::websocket::handlers h, + std::pmr::memory_resource* memory) override { + relays_.emplace(url); + return backend_.connect(url, std::move(h), memory); + } + + std::shared_ptr make_peer_connection( + std::span servers, + std::pmr::memory_resource* memory) override { + for (const auto& server : servers) { + ice_servers_.insert(server.urls.begin(), server.urls.end()); + } + return backend_.make_peer_connection(servers, memory); + } + + std::shared_ptr make_timer( + std::pmr::memory_resource* memory) override { + return backend_.make_timer(memory); + } + + std::shared_ptr make_sealer( + std::array key, std::pmr::memory_resource* memory) override { + return backend_.make_sealer(key, memory); + } + + void random(std::span out) override { backend_.random(out); } + + std::chrono::sys_seconds unix_now() override { return backend_.unix_now(); } + + std::chrono::steady_clock::time_point steady_now() override { return backend_.steady_now(); } + +private: + trystero::backend::factory& backend_; + std::set relays_; + std::set ice_servers_; +}; + +} // namespace + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + asio::io_context io; + // The peers meet on this machine alone: every connection bound to the loopback, and STUN + // servers where nothing answers in place of Trystero's public ones. + trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + // Two configurations. The second relay is the same local relay under a path, which it accepts + // as it accepts any. + const configuration first{.relay = relay, .stun = "stun:127.0.0.1:9"}; + const configuration second{ + .relay = std::string(relay) + "/second", + .stun = "stun:127.0.0.1:19", + }; + const auto config = [](const configuration& c) { + trystero::app_config out; + out.app_id = "webcpp-trystero-differences"; + out.relay_urls = {std::pmr::string(c.relay)}; + out.ice_servers = {{.urls = {std::pmr::string(c.stun)}, .username = {}, .credential = {}}}; + // The connection closes once no room uses it, so that the program ends when all leave. + out.idle_timeout = std::chrono::milliseconds{0}; + return out; + }; + // The other peer, as another page would be: the lobby with the first configuration, the + // kitchen with the second. + trystero::app other_first(io.get_executor(), backend, config(first)); + trystero::app other_second(io.get_executor(), backend, config(second)); + auto other_lobby = other_first.join("lobby"); + auto other_kitchen = other_second.join("kitchen"); + // Each app of this program is given a backend that records what the app asks of the platform + // one. + observing_backend first_backend(backend); + observing_backend second_backend(backend); + // The configuration whose URL, and only it, a backend was asked for, of the two URLs given. + const auto which = [](const std::set& urls, const std::string& first_url, + const std::string& second_url) { + if (urls == std::set{first_url}) { + return "the first configuration's"; + } + return urls == std::set{second_url} ? "the second configuration's" : "another"; + }; + const auto relays_of = [&](const observing_backend& b) { + return which(b.relays(), first.relay, second.relay); + }; + const auto ice_servers_of = [&](const observing_backend& b) { + return which(b.ice_servers(), first.stun, second.stun); + }; + // tag::example[] + // A configuration is an app's: the kitchen, joined with the second, is a room of a second app. + trystero::app lobby_app(io.get_executor(), first_backend, config(first)); + trystero::app kitchen_app(io.get_executor(), second_backend, config(second)); + auto lobby = lobby_app.join("lobby"); + auto kitchen = kitchen_app.join("kitchen"); + // What each app's backend was asked for, once both rooms have met the other peer. + const auto report = [&] { + std::cout << "the lobby's relays: " << relays_of(first_backend) << '\n' + << "the kitchen's relays: " << relays_of(second_backend) << '\n' + << "the lobby's connection: " << ice_servers_of(first_backend) << " ICE servers\n" + << "the kitchen's connection: " << ice_servers_of(second_backend) + << " ICE servers\n"; + }; + // end::example[] + if (!other_lobby || !other_kitchen || !lobby || !kitchen) { + std::cerr << "not joined\n"; + return 1; + } + // Once each of this program's rooms has met the other peer, it reports, and every room leaves. + bool reported = false; + const auto met = [&](std::string_view) { + if (reported || lobby->peers().empty() || kitchen->peers().empty()) { + return; + } + reported = true; + report(); + for (trystero::room* room : {&*lobby, &*kitchen, &*other_lobby, &*other_kitchen}) { + room->async_leave([](boost::system::error_code) {}); + } + }; + lobby->on_peer_join(met); + kitchen->on_peer_join(met); + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} diff --git a/example/diff_relay_config.expected b/example/diff_relay_config.expected new file mode 100644 index 0000000..f70889b --- /dev/null +++ b/example/diff_relay_config.expected @@ -0,0 +1,4 @@ +the lobby's relays: the first configuration's +the kitchen's relays: the second configuration's +the lobby's connection: the first configuration's ICE servers +the kitchen's connection: the second configuration's ICE servers diff --git a/example/diff_relay_sockets.cpp b/example/diff_relay_sockets.cpp new file mode 100644 index 0000000..eac1f0c --- /dev/null +++ b/example/diff_relay_sockets.cpp @@ -0,0 +1,111 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): the relay sockets of a page's +// rooms. Trystero JS opens one WebSocket per relay for the page, which every room shares; each +// room here opens its own. Trystero JS hands out the page's sockets (getRelaySockets); a room here +// hands out none, so the app of this program is given a backend that counts the WebSockets the +// app asks of the platform one. Its twin is test/oracle/twins/diff_relay_sockets.mjs. Both join +// over the relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start on +// 127.0.0.1. + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = boost::asio; +namespace trystero = webcpp::trystero; + +namespace { + +// A backend that forwards to another, and counts the WebSockets asked of it. +class counting_backend final : public trystero::backend::factory { +public: + explicit counting_backend(trystero::backend::factory& backend) : backend_(backend) {} + + // How many WebSockets the app asked for. + [[nodiscard]] std::size_t websockets() const { return websockets_; } + + std::shared_ptr connect( + std::string_view url, trystero::backend::websocket::handlers h, + std::pmr::memory_resource* memory) override { + ++websockets_; + return backend_.connect(url, std::move(h), memory); + } + + std::shared_ptr make_peer_connection( + std::span servers, + std::pmr::memory_resource* memory) override { + return backend_.make_peer_connection(servers, memory); + } + + std::shared_ptr make_timer( + std::pmr::memory_resource* memory) override { + return backend_.make_timer(memory); + } + + std::shared_ptr make_sealer( + std::array key, std::pmr::memory_resource* memory) override { + return backend_.make_sealer(key, memory); + } + + void random(std::span out) override { backend_.random(out); } + + std::chrono::sys_seconds unix_now() override { return backend_.unix_now(); } + + std::chrono::steady_clock::time_point steady_now() override { return backend_.steady_now(); } + +private: + trystero::backend::factory& backend_; + std::size_t websockets_ = 0; +}; + +} // namespace + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + asio::io_context io; + trystero::platform::backend platform(io.get_executor()); + counting_backend backend(platform); + // tag::example[] + trystero::app app(io.get_executor(), backend, + {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); + auto lobby = app.join("lobby"); + auto kitchen = app.join("kitchen"); + // Once both rooms have started, which they do on the executor. + asio::post(io, [&] { + std::cout << "the WebSockets the two rooms opened to their one relay: " + << backend.websockets() << '\n'; + lobby->async_leave([](boost::system::error_code) {}); + kitchen->async_leave([](boost::system::error_code) {}); + }); + // end::example[] + if (!lobby || !kitchen) { + std::cerr << "not joined\n"; + return 1; + } + io.run(); // lint-run: the rooms' relays, over the network +} diff --git a/example/diff_relay_sockets.expected b/example/diff_relay_sockets.expected new file mode 100644 index 0000000..0a1e51c --- /dev/null +++ b/example/diff_relay_sockets.expected @@ -0,0 +1 @@ +the WebSockets the two rooms opened to their one relay: 2 diff --git a/example/diff_rooms_per_app.cpp b/example/diff_rooms_per_app.cpp new file mode 100644 index 0000000..7100524 --- /dev/null +++ b/example/diff_rooms_per_app.cpp @@ -0,0 +1,69 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): how many rooms an app holds. +// Trystero joins every room a page asks for, and a peer that advertises a 65th over one +// connection is dropped by the other side; app::join refuses the 65th with +// error::too_many_rooms, counting a room in its farewell, since the 65th would cost every +// connection of the app. Its twin is test/oracle/twins/diff_rooms_per_app.mjs. Both join over the +// relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace trystero = webcpp::trystero; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + boost::asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + trystero::app app(io.get_executor(), backend, + {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); + std::vector rooms; + // What a join gives, a room kept until the end or the error that refused it. + const auto join = [&](const std::string& room_id) { + auto joined = app.join(room_id); + if (!joined) { + return joined.error().message(); + } + rooms.push_back(std::move(*joined)); + return std::string("a room"); + }; + const auto leave_all = [&] { + for (auto& room : rooms) { + room.async_leave([](boost::system::error_code) {}); + } + }; + // tag::example[] + for (std::size_t n = 1; n <= 64; ++n) { + join("room-" + std::to_string(n)); + } + std::cout << "joins 1 to 64: " << rooms.size() << " rooms\n"; + std::cout << "join 65: " << join("room-65") << '\n'; + rooms.front().async_leave([&](boost::system::error_code) { + std::cout << "join 67, once room 1 has left: " << join("room-67") << '\n'; + leave_all(); + }); + std::cout << "join 66, while room 1 is leaving: " << join("room-66") << '\n'; + // end::example[] + io.run(); // lint-run: the rooms' announcements and farewells, over the relay +} diff --git a/example/diff_rooms_per_app.expected b/example/diff_rooms_per_app.expected new file mode 100644 index 0000000..6072db6 --- /dev/null +++ b/example/diff_rooms_per_app.expected @@ -0,0 +1,4 @@ +joins 1 to 64: 64 rooms +join 65: the app holds as many rooms as a peer accepts, 64 +join 66, while room 1 is leaving: the app holds as many rooms as a peer accepts, 64 +join 67, once room 1 has left: a room diff --git a/example/diff_self_id.cpp b/example/diff_self_id.cpp new file mode 100644 index 0000000..e7895d1 --- /dev/null +++ b/example/diff_self_id.cpp @@ -0,0 +1,104 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): the scope of the self id. +// Trystero JS draws one selfId for the page, which it announces in every room of every app; an +// app here draws its own, and keeps its connections, so that one program holds several peers, and +// one id across apps is the program's choice, app_config::self_id. This program joins two rooms of +// one app and a room of a second app, and another peer, two apps of the same program, compares the +// ids it meets there. Its twin is test/oracle/twins/diff_self_id.mjs. Both meet over the relay +// whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace asio = boost::asio; +namespace trystero = webcpp::trystero; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + asio::io_context io; + // The peers meet on this machine alone: every connection bound to the loopback, and a STUN + // server where nothing answers in place of Trystero's public ones. + trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + const auto config = [relay](std::string_view app_id) { + trystero::app_config c; + c.app_id = app_id; + c.relay_urls = {relay}; + c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; + // The connection closes once no room uses it, so that the program ends when all leave. + c.idle_timeout = std::chrono::milliseconds{0}; + return c; + }; + constexpr std::string_view first_app = "webcpp-trystero-differences"; + constexpr std::string_view second_app = "webcpp-trystero-differences-second"; + // The other peer, as another page would be: an app of each id, in the rooms this program joins. + trystero::app other_first(io.get_executor(), backend, config(first_app)); + trystero::app other_second(io.get_executor(), backend, config(second_app)); + auto other_lobby = other_first.join("lobby"); + auto other_kitchen = other_first.join("kitchen"); + auto other_second_lobby = other_second.join("lobby"); + // tag::example[] + // Each app draws a self id of its own, unless app_config::self_id names one for both. + trystero::app first(io.get_executor(), backend, config(first_app)); + trystero::app second(io.get_executor(), backend, config(second_app)); + auto lobby = first.join("lobby"); + auto kitchen = first.join("kitchen"); + auto second_lobby = second.join("lobby"); + // What the other peer meets in those three rooms. + const auto report = [](std::string_view in_lobby, std::string_view in_kitchen, + std::string_view in_second_lobby) { + std::cout << "two rooms of one app: " << (in_lobby == in_kitchen ? "one id" : "two ids") + << '\n' + << "rooms of two apps: " << (in_lobby == in_second_lobby ? "one id" : "two ids") + << '\n'; + }; + // end::example[] + if (!other_lobby || !other_kitchen || !other_second_lobby || !lobby || !kitchen || + !second_lobby) { + std::cerr << "not joined\n"; + return 1; + } + // The id each of the other peer's rooms meets first; once all three have met one, the program + // reports, and every room leaves. + const std::array observers{&*other_lobby, &*other_kitchen, &*other_second_lobby}; + std::array met; + std::size_t meetings = 0; + for (std::size_t i = 0; i < observers.size(); ++i) { + observers[i]->on_peer_join([&, i](std::string_view peer) { + if (!met[i].empty()) { + return; + } + met[i] = peer; + if (++meetings < met.size()) { + return; + } + report(met[0], met[1], met[2]); + for (trystero::room* room : {&*lobby, &*kitchen, &*second_lobby}) { + room->async_leave([](boost::system::error_code) {}); + } + for (trystero::room* room : observers) { + room->async_leave([](boost::system::error_code) {}); + } + }); + } + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it +} diff --git a/example/diff_self_id.expected b/example/diff_self_id.expected new file mode 100644 index 0000000..d15734e --- /dev/null +++ b/example/diff_self_id.expected @@ -0,0 +1,2 @@ +two rooms of one app: one id +rooms of two apps: two ids diff --git a/example/diff_self_id_not_utf8.cpp b/example/diff_self_id_not_utf8.cpp new file mode 100644 index 0000000..4cd322d --- /dev/null +++ b/example/diff_self_id_not_utf8.cpp @@ -0,0 +1,46 @@ +// 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) + +// A difference from Trystero (doc: #trystero-differences-behaviour): a self id that is not UTF-8. +// An app given one sets it aside for 20 random characters and reports error::invalid_configuration, +// since a signal writes the id as a JSON string, which carries UTF-8 alone. Trystero JS draws its +// selfId when its module loads and takes none from a program, so it has no such id, and this +// program no twin (test/oracle/twins/without-twin.txt). The app joins no room, so it needs no +// relay. + +#include +#include + +#include + +#include +#include +#include +#include + +namespace trystero = webcpp::trystero; + +int main() { + boost::asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + // tag::example[] + const std::string given = "caf\xE9"; // ISO 8859-1's "café": its last byte is no UTF-8 + trystero::app_config config; + config.app_id = "webcpp-trystero-differences"; + config.self_id = given; + trystero::app app(io.get_executor(), backend, std::move(config)); + app.on_error([](std::string_view, boost::system::error_code ec, std::string_view what) { + std::cout << "reported: " << ec.message() << ": " << what << '\n'; + }); + std::cout << "the self id given: " << given.size() << " bytes, not UTF-8\n" + << "the app's self id: " + << (app.self_id() == given + ? std::string("the one given") + : std::to_string(app.self_id().size()) + " random characters") + << '\n'; + // end::example[] + io.run(); // lint-run: delivers the report the app's constructor posted +} diff --git a/example/diff_self_id_not_utf8.expected b/example/diff_self_id_not_utf8.expected new file mode 100644 index 0000000..f1ac4d0 --- /dev/null +++ b/example/diff_self_id_not_utf8.expected @@ -0,0 +1,3 @@ +the self id given: 4 bytes, not UTF-8 +the app's self id: 20 random characters +reported: the configuration is unusable: self_id is not UTF-8, which no peer reads, so the app uses a random one diff --git a/example/diff_send_to_absent_peer.cpp b/example/diff_send_to_absent_peer.cpp new file mode 100644 index 0000000..11f67b8 --- /dev/null +++ b/example/diff_send_to_absent_peer.cpp @@ -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) + +// A difference from Trystero (doc: #trystero-differences): a send to a peer that has not joined. +// Trystero's send warns on the console and resolves; async_send completes with +// error::no_such_peer, since an operation that fails says so with its error code. Its twin is +// test/oracle/twins/diff_send_to_absent_peer.mjs. Both join over the relay whose URL is in the +// environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace trystero = webcpp::trystero; + +int main() { + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + if (relay == nullptr) { + std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; + return 1; + } + boost::asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + trystero::app app(io.get_executor(), backend, + {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); + auto joined = app.join("lobby"); + if (!joined) { + std::cerr << "not joined: " << joined.error().message() << '\n'; + return 1; + } + trystero::room room = std::move(*joined); + // tag::example[] + auto greeting = room.make_action("greeting"); + greeting.async_send("hello", {.targets = {"a-peer-that-has-not-joined"}}, + [&room](boost::system::error_code ec) { + std::cout << "the send to a peer that has not joined: " + << (ec ? "failed: " + ec.message() : "succeeded") << '\n'; + room.async_leave([](boost::system::error_code) {}); + }); + // end::example[] + io.run(); // lint-run: the room's announcement and farewell, over the relay +} diff --git a/example/diff_send_to_absent_peer.expected b/example/diff_send_to_absent_peer.expected new file mode 100644 index 0000000..9939f44 --- /dev/null +++ b/example/diff_send_to_absent_peer.expected @@ -0,0 +1 @@ +the send to a peer that has not joined: failed: no active peer with this id diff --git a/example/native_quick_start.cpp b/example/native_quick_start.cpp deleted file mode 100644 index a528d57..0000000 --- a/example/native_quick_start.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// 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 native quick start of the documentation (doc: #trystero-quick-start), which includes the -// tagged regions below: the browser quick start's app and room, as a native program. Trystero JS -// and browser peers in the same room are its peers. - -// tag::program[] -#include -#include -#include - -#include - -#include -#include -#include - -namespace trystero = webcpp::trystero; - -int main() { - boost::asio::io_context io; - trystero::native::backend backend(io.get_executor()); - trystero::app app(io.get_executor(), backend, {.app_id = "webcpp-trystero-quick-start"}); - auto joined = app.join("lobby"); - if (!joined) { - std::cerr << "not joined: " << joined.error().message() << '\n'; - return 1; - } - trystero::room room = std::move(*joined); - auto chat = room.make_action("chat"); - - room.on_peer_join([&](std::string_view peer) { - trystero::send_options to_peer{.targets = {trystero::peer_id(peer)}, .metadata = {}}; - chat.async_send("hello from a native peer", std::move(to_peer), - [](boost::system::error_code) {}); - }); - chat.on_message([](const std::string& text, const trystero::message_info& info) { - // flushed: into a pipe too, since the program runs until it is stopped - std::cout << info.from << ": " << text << '\n' << std::flush; - }); - - io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it -} - -// end::program[] diff --git a/example/quick_start.cpp b/example/quick_start.cpp index 867e988..6b6d2d1 100644 --- a/example/quick_start.cpp +++ b/example/quick_start.cpp @@ -5,24 +5,30 @@ // https://www.boost.org/LICENSE_1_0.txt) // The quick start of the documentation (doc: #trystero-quick-start), which includes the tagged -// regions below: a browser program whose app joins a room, greets every peer that joins, prints -// what it receives, and echoes another action from a coroutine. - +// regions below: two apps of one program, the peers alice and bob, join the room "lobby" of the +// app webcpp-trystero-quick-start; alice greets bob when he joins, bob answers from a coroutine, +// each prints what it received, and both leave, which ends the program. Its twin is +// test/oracle/twins/quick_start.mjs. Both meet over the relay whose URL is in the environment, +// TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1; without it, the program meets over +// Trystero's public relays, as a user's program does. + +// tag::program[] // tag::includes[] #include -#include -#include // once per program +#include #include +#include #include #include #include #include -#include +#include +#include #include -#include #include +#include namespace asio = boost::asio; namespace trystero = webcpp::trystero; @@ -30,75 +36,91 @@ namespace trystero = webcpp::trystero; namespace { -// tag::application[] -/** The room the page joined, and its actions. */ -struct lobby { - trystero::room room; - trystero::action chat = room.make_action("chat"); - trystero::action echo = room.make_action("echo"); -}; +// tag::config[] +/** What one peer's app is made with: its id, and the relay `relay` names, or the public ones. */ +trystero::app_config config_for(std::string_view self_id, const char* relay) { + trystero::app_config config; + config.app_id = "webcpp-trystero-quick-start"; + // An id of the program's own, where an app would draw 20 random characters, so that what each + // peer prints of the other is the same on every run. + config.self_id = self_id; + if (relay != nullptr) { + // The peers stay on this machine: the relay given, and a STUN server where nothing answers + // in place of Trystero's public ones, beside a backend bound to the loopback. + config.relay_urls = {relay}; + config.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; + } + // Without a relay, both lists stay empty: Trystero's defaults, as a user's program has them, + // the public relays its app id selects and Trystero's public STUN servers. + // A connection closes as soon as no room uses it, so that the program ends once both leave. + config.idle_timeout = std::chrono::milliseconds{0}; + return config; +} -/** What the page keeps alive: event loop, backend, app, and the room it joined. */ -struct application { - asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - trystero::app app{loop.get_executor(), backend, {.app_id = "webcpp-trystero-quick-start"}}; - std::optional joined; - - /** Joins the lobby and makes its actions; null, with the reason printed, when the app refuses - * (a room of that id joined already, or 64 rooms). */ - lobby* join() { - auto result = app.join("lobby"); - if (!result) { - const std::string reason = result.error().message(); - std::printf("not joined: %s\n", reason.c_str()); - return nullptr; - } - return &joined.emplace(std::move(*result)); +// end::config[] + +// tag::answer[] +/** bob's part: waits for a message, prints it, answers its sender, and leaves the room. */ +asio::awaitable answer(trystero::room& lobby, trystero::action& chat) { + // as_tuple hands the error over as a value: a room left first ends the wait without throwing. + auto [ec, text, info] = co_await chat.async_receive(asio::as_tuple(asio::use_awaitable)); + if (ec) { + co_return; } -}; - -// end::application[] - -// tag::coroutine[] -/** Answers every message of the "echo" action, one at a time. */ -asio::awaitable echo_back(trystero::action& echo) { - for (;;) { - auto [ec, text, info] = co_await echo.async_receive(asio::as_tuple(asio::use_awaitable)); - if (ec) { - co_return; // the room was left - } - co_await echo.async_send("echo: " + text, - trystero::send_options{.targets = {info.from}, .metadata = {}}, - asio::use_awaitable); + std::cout << info.from << ": " << text << '\n'; + auto [failed] = co_await chat.async_send("hello back", {.targets = {info.from}, .metadata = {}}, + asio::as_tuple(asio::use_awaitable)); + if (failed) { + std::cerr << "not delivered: " << failed.message() << '\n'; } + co_await lobby.async_leave(asio::as_tuple(asio::use_awaitable)); } -// end::coroutine[] +// end::answer[] } // namespace // tag::main[] int main() { - auto* app = new application; // a page's program lives as long as the tab - auto* lobby = app->join(); - if (lobby == nullptr) { + // The relay the lane starts on 127.0.0.1, or none: Trystero's public relays. + const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); + asio::io_context io; + // One backend for both apps, whose connections stay on the loopback beside a local relay. + trystero::platform::backend_config local; + if (relay != nullptr) { + local.bind_address = "127.0.0.1"; + } + trystero::platform::backend backend(io.get_executor(), local); + + // Two apps, two peers, each with its own id, in the same room. + trystero::app alice(io.get_executor(), backend, config_for("alice", relay)); + trystero::app bob(io.get_executor(), backend, config_for("bob", relay)); + auto alice_lobby = alice.join("lobby"); + auto bob_lobby = bob.join("lobby"); + if (!alice_lobby || !bob_lobby) { + std::cerr << "not joined\n"; return 1; } - - lobby->room.on_peer_join([lobby](std::string_view peer) { - trystero::send_options to_peer{.targets = {trystero::peer_id(peer)}, .metadata = {}}; - lobby->chat.async_send("hello", std::move(to_peer), [](boost::system::error_code ec) { - if (ec) { - std::cerr << "not delivered: " << ec.message() << '\n'; - } - }); + auto alice_chat = alice_lobby->make_action("chat"); + auto bob_chat = bob_lobby->make_action("chat"); + + // alice greets each peer once its handshake completes, prints the answer, and leaves. + alice_lobby->on_peer_join([&](std::string_view peer) { + alice_chat.async_send("hello", {.targets = {trystero::peer_id(peer)}, .metadata = {}}, + [](boost::system::error_code ec) { + if (ec) { + std::cerr << "not delivered: " << ec.message() << '\n'; + } + }); }); - lobby->chat.on_message([](const std::string& text, const trystero::message_info& info) { + alice_chat.on_message([&](const std::string& text, const trystero::message_info& info) { std::cout << info.from << ": " << text << '\n'; + alice_lobby->async_leave([](boost::system::error_code) {}); }); - asio::co_spawn(app->loop.get_executor(), echo_back(lobby->echo), asio::detached); + asio::co_spawn(io, answer(*bob_lobby, bob_chat), asio::detached); + + io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it } // end::main[] +// end::program[] diff --git a/example/quick_start.expected b/example/quick_start.expected new file mode 100644 index 0000000..420c228 --- /dev/null +++ b/example/quick_start.expected @@ -0,0 +1,2 @@ +alice: hello +bob: hello back diff --git a/example/run_over_relay.mjs b/example/run_over_relay.mjs new file mode 100644 index 0000000..e0669a1 --- /dev/null +++ b/example/run_over_relay.mjs @@ -0,0 +1,58 @@ +// 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) + +// Runs one example over a Nostr relay of its own on 127.0.0.1, test/oracle/interop/relay.mjs, and +// checks what it prints: the driver of the quick start and of each diff_ of the appendix +// "Differences", which the Jamfile declares with webcpp.drive, which gives it the native program +// last: +// +// node --conditions=development example/run_over_relay.mjs +// +// The relay's URL is in the program's environment, TRYSTERO_RELAY_URL, as in its twin's +// (test/oracle/run_twin.mjs). The run passes when the program exits with 0 having printed +// exactly .expected beside this script, every carriage return removed, as webcpp.example +// compares an example's output; otherwise it names the status, or shows the difference and what +// the program said on its standard error. webcpp.drive bounds the run. +import {spawn} from 'node:child_process' +import {readFileSync} from 'node:fs' +import {basename, dirname, extname, join} from 'node:path' +import {fileURLToPath} from 'node:url' +import {startRelay} from '../test/oracle/interop/relay.mjs' + +const program = process.argv.at(-1) +const name = basename(program, extname(program) === '.exe' ? '.exe' : '') +const expected = readFileSync(join(dirname(fileURLToPath(import.meta.url)), `${name}.expected`), 'utf8') + .replaceAll('\r', '') + +const relay = await startRelay() +const child = spawn(program, [], { + env: {...process.env, TRYSTERO_RELAY_URL: relay.url}, + stdio: ['ignore', 'pipe', 'pipe'], +}) +const output = [] +const errors = [] +child.stdout.on('data', data => output.push(data)) +child.stderr.on('data', data => errors.push(data)) +const [status, signal] = await new Promise((done, fail) => { + child.on('error', fail) + child.on('close', (code, killed) => done([code, killed])) +}) +relay.close() + +const printed = Buffer.concat(output).toString('utf8').replaceAll('\r', '') +const said = Buffer.concat(errors).toString('utf8') +const lines = text => text.split('\n').map(line => ` ${line}`).join('\n') +if (status !== 0) { + console.error(`${name} ended with ${signal ? `the signal ${signal}` : `status ${status}`}, having printed:\n` + + `${lines(printed)}\nand said:\n${lines(said)}`) + process.exit(1) +} +if (printed !== expected) { + console.error(`${name} printed:\n${lines(printed)}\nwhere ${name}.expected holds:\n${lines(expected)}\n` + + `and said:\n${lines(said)}`) + process.exit(1) +} +console.log(`${name}: printed ${name}.expected over ${relay.url}`) diff --git a/include/webcpp/trystero.hpp b/include/webcpp/trystero.hpp index 8ea9f2f..862258b 100644 --- a/include/webcpp/trystero.hpp +++ b/include/webcpp/trystero.hpp @@ -8,10 +8,10 @@ The apps and rooms of trystero, which build on every target: include this one header to make an app over a backend and join its rooms. - It leaves out the two backends, each with a dependency of its own target: - ``, which builds only on emscripten, and - ``, which brings libdatachannel and - OpenSSL. + It leaves out the platform backend, ``, + which brings webcpp::webrtc and webcpp::beast, natively libdatachannel and + OpenSSL, through `/webcpp/trystero//platform`, and a page's + ``, which builds only on emscripten. */ #ifndef WEBCPP_TRYSTERO_HPP #define WEBCPP_TRYSTERO_HPP @@ -21,7 +21,6 @@ #include #include #include -#include #include #include diff --git a/include/webcpp/trystero/app.hpp b/include/webcpp/trystero/app.hpp index a560300..e4c9747 100644 --- a/include/webcpp/trystero/app.hpp +++ b/include/webcpp/trystero/app.hpp @@ -15,7 +15,8 @@ #include #include -#include // lint-world: names the executor only +#include // lint-world: names the executor only + #include #include #include @@ -47,7 +48,7 @@ namespace webcpp::trystero { class app { public: /** The executor every handler and completion of the app and its rooms runs on. */ - using executor_type = boost::asio::any_io_executor; + using executor_type = webcpp::asio::any_io_executor; /** The most rooms an app holds at once: a Trystero JS peer drops a connection that advertises * more, its limit of 64 room tokens per connection. */ @@ -189,8 +190,8 @@ class app { if (!existing->leaving()) { return error::already_joined; } - // Trystero's rejoin (C/strategy.mjs:38): the old room's presence(0) goes before the - // new room's presence(1). + // Trystero's rejoin (dist/strategy.mjs:38): the old room's presence(0) goes before + // the new room's presence(1). existing->finish_farewell(); } if (impl_->counted_rooms() >= max_rooms) { diff --git a/include/webcpp/trystero/backend.hpp b/include/webcpp/trystero/backend.hpp index 3fc97a5..719e7d8 100644 --- a/include/webcpp/trystero/backend.hpp +++ b/include/webcpp/trystero/backend.hpp @@ -25,9 +25,9 @@ /** * The seam between the room and a platform: what a target must provide for a room to run on it. The - * browser provides it over `emscripten::val` (webcpp/trystero/browser), a native target over - * libdatachannel, Boost.Beast and OpenSSL (webcpp/trystero/native), and the tests over memory - * (test/support). + * platform backend provides it on both targets (webcpp/trystero/platform), over webcpp::webrtc, + * webcpp::beast and webcpp::asio, natively libdatachannel, Boost.Beast and OpenSSL, in a page its + * own WebRTC, WebSocket and Web Crypto; the tests provide it over memory (test/support). * * Tip: every handler a backend invokes runs on the room's executor, one at a time, and may destroy * the object that invoked it. A backend whose events arrive on other threads (libdatachannel) posts @@ -43,13 +43,13 @@ * The one exception is a data channel message, handed over by value: the receiver keeps the frame, * and taking ownership of it is what spares a copy. * - * Tip: every method that makes an object takes the room's memory resource last, and the backend - * allocates the object, its handlers and what it hands to the room (a frame, a text) through it, on - * the room's executor only. + * Tip: every method that makes an object takes a memory resource last, the app's for a peer + * connection and the room's for the rest, and the backend allocates the object, its handlers and + * what it hands to the room (a frame, a text) through it, on the room's executor only. */ namespace webcpp::trystero::backend { -/** A data channel frame, in the memory resource of the room it is for. */ +/** A data channel frame in a memory resource: a received one in the app's, as its connection. */ using bytes = std::pmr::vector; /** The error code every completion of a backend reports, empty on success. */ @@ -139,7 +139,7 @@ class data_channel { struct handlers { /** The channel opened. */ handler open; - /** A binary message arrived, handed over in the room's resource. */ + /** A binary message arrived, handed over in the app's resource. */ handler message; /** The channel closed; called once. */ handler close; @@ -319,8 +319,8 @@ class sealer { * browser, one per application natively, one per test. * * Each object it makes is allocated, with its handlers and what it hands to the room, in the memory - * resource it is given, the room's: that resource must outlive the object and every operation the - * object leaves pending. + * resource it is given, the app's for a peer connection and the room's for the rest: that resource + * must outlive the object and every operation the object leaves pending. * * @see "Allocation", in the guide. */ @@ -345,8 +345,8 @@ class factory { * Makes a peer connection that gathers its candidates through `servers`. * * @param servers The STUN and TURN servers, read during the call. - * @param memory The room's resource, which the connection, its channels, its handlers and its - * texts are allocated in. + * @param memory The app's resource, which the connection, its channels, its handlers and its + * texts are allocated in, as the app owns the connection once a room adopted it. * @return The connection, or null when the platform refuses to make one: the room then * reports the negotiation with that peer as failed, through `room::on_error`. */ @@ -381,18 +381,21 @@ class factory { virtual void random(std::span out) = 0; /** - * Wall-clock seconds since the Unix epoch, for Nostr's `created_at` and `since`. + * The wall clock, for Nostr's `created_at` and `since`: `Date.now()` in whole seconds. * - * @return The current time, in whole seconds. + * @return The current time, in whole seconds since the Unix epoch. */ - virtual std::int64_t unix_seconds() = 0; + virtual std::chrono::sys_seconds unix_now() = 0; /** - * A monotonic clock in milliseconds, for rate limits and timeouts, as `performance.now()`. + * A monotonic clock, for rate limits and timeouts, as `performance.now()`. * - * @return The current time, in milliseconds from an origin of the backend's. + * A room only subtracts and compares its times, so the origin is the backend's: the steady + * clock's epoch, or where a test's virtual clock starts. + * + * @return The current time. */ - virtual double now_ms() = 0; + virtual std::chrono::steady_clock::time_point steady_now() = 0; // lint-world: a type only }; } // namespace webcpp::trystero::backend diff --git a/include/webcpp/trystero/browser/backend.hpp b/include/webcpp/trystero/browser/backend.hpp deleted file mode 100644 index 73ecfcc..0000000 --- a/include/webcpp/trystero/browser/backend.hpp +++ /dev/null @@ -1,1026 +0,0 @@ -// 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_BROWSER_BACKEND_HPP -#define WEBCPP_TRYSTERO_BROWSER_BACKEND_HPP - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include // lint-world: getentropy, the page's entropy -#include // lint-world: binds an allocator only -#include // lint-world: posts handlers only - -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * The browser target: the backend interface over the page's own `WebSocket`, `RTCPeerConnection`, - * `RTCDataChannel`, `setTimeout` and `crypto.subtle`, through `emscripten::val`. It needs a secure - * context (https, or http on localhost), where `crypto.subtle` exists. - * - * Tip: its objects, their handlers and the frames and texts they hand to the room are in the room's - * resource; what `emscripten::val` holds is in the JavaScript heap, and the page's `event_loop` - * keeps its registrations in its own resource. - */ -namespace webcpp::trystero::browser { - -/** A JavaScript value, embind's `emscripten::val`. */ -using emscripten::val; - -namespace detail { - -/** A copy of bytes as a new `Uint8Array`, independent of the wasm memory. */ -inline val to_js(std::span data) { - return val::global("Uint8Array") - .new_(val(emscripten::typed_memory_view(data.size(), data.data()))); -} - -/** A copy of an `ArrayBuffer` or typed array's bytes, in `memory`. */ -inline backend::bytes from_js(const val& buffer, std::pmr::memory_resource* memory) { - const val view = val::global("Uint8Array").new_(buffer); - backend::bytes out(view["length"].as(), memory); - val(emscripten::typed_memory_view(out.size(), out.data())).call("set", view); - return out; -} - -/** - * Runs `f` on the loop's io_context after the current call, allocated in `memory`: how a - * completion that is known at once still reaches its handler later, never inside the call that - * started the operation. - */ -template -void defer(event_loop& loop, std::pmr::memory_resource* memory, F&& f) { - boost::asio::post( - loop.io(), - boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), std::forward(f))); - loop.schedule_poll(); -} - -/** - * Calls `done(true, value)` or `done(false, reason)` once a promise an operation returned - * settles, or `done(false, exception)` after the call when the operation threw instead. - */ -inline void then(event_loop& loop, const js_outcome& operation, handler done, - std::pmr::memory_resource* memory); - -/** Calls `done(true, value)` or `done(false, reason)` once a promise settles. */ -inline void then(event_loop& loop, const val& promise, handler done, - std::pmr::memory_resource* memory) { - const std::pmr::polymorphic_allocator<> allocator(memory); - const auto id = std::allocate_shared(allocator, 0); - *id = loop.add({std::allocator_arg, allocator, - [&loop, id, done = std::move(done)](int slot, val value) mutable { - loop.remove(*id); - done(slot == 0, std::move(value)); - }}); - promise.call("then", loop.handler(*id, 0), loop.handler(*id, 1)); -} - -inline void then(event_loop& loop, const js_outcome& operation, handler done, - std::pmr::memory_resource* memory) { - if (operation.ok) { - then(loop, operation.value, std::move(done), memory); - return; - } - defer(loop, memory, [done = std::move(done), reason = operation.value]() mutable { - done(false, std::move(reason)); - }); -} - -} // namespace detail - -/** - * A timer over the page's `setTimeout`. - * - * @see "The browser backend", in the guide. - */ -class timer : public backend::timer { -public: - /** - * Constructs a timer, not started, registered with the loop. - * - * @param loop The page's loop, which must outlive the timer. - * @param memory The room's resource, which the timer's registration and handler are allocated - * in. - */ - timer(event_loop& loop, std::pmr::memory_resource* memory) - : loop_(loop), - id_(loop.add({std::allocator_arg, std::pmr::polymorphic_allocator<>(memory), - [this](int /*slot*/, const val& /*value*/) { on_fire(); }})) {} - - /** Destroys the timer, which clears a pending `setTimeout`. */ - ~timer() override { - cancel(); - loop_.remove(id_); - } - - /** - * Calls `fire` once `delay` has passed, through `setTimeout`, in place of a pending expiry. - * - * @param delay How long to wait. - * @param fire What to call when the timer expires; never called once it is cancelled. - */ - void start(std::chrono::milliseconds delay, handler fire) override { - cancel(); - fire_ = std::move(fire); - handle_ = val::global("setTimeout")( - loop_.handler(id_, 0), val(static_cast(delay.count())), val::undefined()); - } - - /** Clears the pending `setTimeout`, if any, whose handler is then never called. */ - void cancel() override { - if (handle_.isUndefined()) { - return; - } - val::global("clearTimeout")(handle_); - handle_ = val::undefined(); - fire_ = nullptr; - } - -private: - void on_fire() { - handle_ = val::undefined(); - auto fire = std::exchange(fire_, nullptr); - if (fire) { - fire(); // may destroy this timer - } - } - - event_loop& loop_; - int id_; - val handle_ = val::undefined(); - handler fire_; -}; - -/** - * A WebSocket over the page's `WebSocket`. - * - * A text longer than `protocol::max_relay_message_bytes` is not copied into WebAssembly: the - * socket closes, and reports the close. A text that would take the socket's `bufferedAmount` - * beyond `protocol::max_queued_relay_bytes`, as when a relay stops reading, drops the socket, - * which reports one close at once. A page has no idle timeout: its `WebSocket` cannot ping. - * - * @see "The browser backend", in the guide. - */ -class websocket : public backend::websocket { -public: - /** - * Opens a WebSocket to `url`. - * - * A URL the page's `WebSocket` refuses with an exception (one that does not parse, another - * scheme, a fragment, mixed content, a policy of the page's) makes no socket: the handler - * `close` reports it after the call, as it reports a relay that cannot be reached. - * - * @param loop The page's loop, which must outlive the WebSocket. - * @param url The relay's URL, read during the call. - * @param h What the WebSocket reports. - * @param memory The room's resource, which the WebSocket's handlers, registration and received - * texts are allocated in. - */ - websocket(event_loop& loop, std::string_view url, handlers h, std::pmr::memory_resource* memory) - : loop_(loop), - memory_(memory), - h_(std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), - std::move(h))), - id_(loop.add({std::allocator_arg, std::pmr::polymorphic_allocator<>(memory), - [this](int slot, const val& event) { on_event(slot, event); }})) { - const auto made = detail::js_new(val::global("WebSocket"), loop_.text(url)); - if (!made.ok) { - detail::defer(loop_, memory_, [weak = std::weak_ptr(h_)] { - if (const auto h = weak.lock()) { - if (auto f = std::exchange(h->close, {})) { - f(); - } - } - }); - return; - } - socket_ = made.value; - socket_.set("onopen", loop_.handler(id_, 0)); - socket_.set("onmessage", loop_.handler(id_, 1)); - socket_.set("onclose", loop_.handler(id_, 2)); - } - - /** Destroys the WebSocket, which closes it without reporting the close. */ - ~websocket() override { - loop_.remove(id_); - if (socket_.isUndefined()) { - return; - } - for (const char* name : {"onopen", "onmessage", "onclose"}) { - socket_.set(name, val::null()); - } - socket_.call("close"); - } - - /** - * Sends a text message when the socket is open, its `readyState` 1; otherwise, or when the - * socket refuses it, drops it. - * - * A text that would take the bytes the socket holds unsent beyond - * `protocol::max_queued_relay_bytes` drops the socket instead, which reports its close. - * - * @param text The message, read during the call. - */ - void send(std::string_view text) override { - if (socket_.isUndefined() || socket_["readyState"].as() != 1) { - return; - } - const auto held = static_cast(socket_["bufferedAmount"].as()); - if (held + text.size() > protocol::max_queued_relay_bytes) { - drop(); - return; - } - detail::js_call(socket_, "send", loop_.text(text)); - } - - /** Closes the socket, which the handler `close` reports; one never made has reported it. */ - void close() override { - if (!socket_.isUndefined()) { - socket_.call("close"); - } - } - -private: - /** - * Drops a socket whose relay stopped reading: its close handshake could never complete, so the - * socket is detached and closed, and its close reported after the call, once. - */ - void drop() { - for (const char* name : {"onopen", "onmessage", "onclose"}) { - socket_.set(name, val::null()); - } - socket_.call("close"); - socket_ = val::undefined(); - detail::defer(loop_, memory_, [weak = std::weak_ptr(h_)] { - if (const auto h = weak.lock()) { - if (auto f = std::exchange(h->close, {})) { - f(); - } - } - }); - } - - /** Calls through a copy of the shared handlers: a handler may destroy this socket during its - * own call. */ - void on_event(int slot, const val& event) { - const auto h = h_; - if (slot == 0) { - if (h->open) { - h->open(); - } - } else if (slot == 1) { - const val data = event["data"]; - if (data.isString() && h->message) { - // The one copy, out of the JavaScript heap, of at most a relay's longest text: a - // longer one closes the socket, which reports the close, as the native one does. - const auto text = loop_.utf8(data, memory_, protocol::max_relay_message_bytes); - if (!text) { - socket_.call("close"); - return; - } - h->message(*text); - } - } else if (auto f = std::exchange(h->close, {})) { - f(); - } - } - - event_loop& loop_; - std::pmr::memory_resource* memory_; - std::shared_ptr h_; - int id_; - val socket_ = val::undefined(); -}; - -/** - * A data channel over the page's `RTCDataChannel`, its messages received as `ArrayBuffer` objects. - * - * A message that is not an `ArrayBuffer`, as a text one a peer sends, or that is larger than any - * room frame (`protocol::max_room_frame_bytes`), is dropped before it is read: neither can be a - * frame, and reading a text as bytes would make a typed array of the length its text says. - * - * @see "The browser backend", in the guide. - */ -class data_channel : public backend::data_channel { -public: - /** - * Wraps a channel of the page, and takes over its events. - * - * @param loop The page's loop, which must outlive the channel. - * @param channel The `RTCDataChannel`. - * @param memory The app's resource, which the channel's handlers, registration and received - * frames are allocated in. - */ - data_channel(event_loop& loop, val channel, std::pmr::memory_resource* memory) - : loop_(loop), - memory_(memory), - channel_(std::move(channel)), - id_(loop.add({std::allocator_arg, std::pmr::polymorphic_allocator<>(memory), - [this](int slot, const val& event) { on_event(slot, event); }})) { - channel_.set("binaryType", val("arraybuffer")); - channel_.set("bufferedAmountLowThreshold", val(static_cast(low_threshold))); - channel_.set("onopen", loop_.handler(id_, 0)); - channel_.set("onmessage", loop_.handler(id_, 1)); - channel_.set("onclose", loop_.handler(id_, 2)); - channel_.set("onbufferedamountlow", loop_.handler(id_, 3)); - } - - /** Destroys the wrapper, which closes the channel without reporting the close. */ - ~data_channel() override { - loop_.remove(id_); - for (const char* name : {"onopen", "onmessage", "onclose", "onbufferedamountlow"}) { - channel_.set(name, val::null()); - } - channel_.call("close"); - } - - /** - * Replaces the handlers, kept in a shared object so that one replacing them during its own call - * outlives the call. - * - * @param h The new handlers, kept in the channel's resource. - */ - void set_handlers(handlers h) override { - h_ = std::allocate_shared(std::pmr::polymorphic_allocator<>(memory_), - std::move(h)); - } - - /** - * Whether the channel is open. - * - * @return Whether its `readyState` is "open". - */ - [[nodiscard]] bool is_open() const override { - return channel_["readyState"].strictlyEquals(val("open")); - } - - /** - * Sends a binary message, copied into a new `Uint8Array`, when the channel is open; one the - * channel refuses, as one larger than its peer accepts, is dropped. - * - * @param frame The message, read during the call. - */ - void send(std::span frame) override { - if (is_open()) { - detail::js_call(channel_, "send", detail::to_js(frame)); - } - } - - /** - * The bytes queued to send. - * - * @return Its `bufferedAmount`. - */ - [[nodiscard]] std::size_t buffered_amount() const override { - return static_cast(channel_["bufferedAmount"].as()); - } - - /** Closes the channel, which the handler `close` reports. */ - void close() override { channel_.call("close"); } - -private: - /** Whether a message can be a room frame: an `ArrayBuffer` no larger than the largest one. */ - static bool is_frame(const val& data) { - return data.instanceof(val::global("ArrayBuffer")) && - data["byteLength"].as() <= - static_cast(protocol::max_room_frame_bytes); - } - - void on_event(int slot, const val& event) { - const auto h = h_; - if (!h) { - return; - } - switch (slot) { - case 0: - if (h->open) { - h->open(); - } - break; - case 1: - if (h->message && is_frame(event["data"])) { - h->message(detail::from_js(event["data"], memory_)); - } - break; - case 2: - if (auto f = std::exchange(h->close, {})) { - f(); - } - break; - default: - if (h->buffered_amount_low) { - h->buffered_amount_low(); - } - } - } - - event_loop& loop_; - std::pmr::memory_resource* memory_; - val channel_; - int id_; - std::shared_ptr h_; -}; - -/** - * A peer connection over the page's `RTCPeerConnection`. - * - * The state it reports merges its `connectionState` and its `iceConnectionState`. - * - * @see "The browser backend", in the guide. - */ -class peer_connection : public backend::peer_connection, - public std::enable_shared_from_this { -public: - /** - * Makes an `RTCPeerConnection` with `servers` as its `iceServers`. - * - * @param loop The page's loop, which must outlive the connection. - * @param servers The STUN and TURN servers, read during the call. - * @param memory The app's resource, which the connection, its handlers, registration, - * channels and texts are allocated in. - * @return The connection, or null when the browser refuses to make one: it throws for a - * server it cannot use, and when the page holds as many connections as it allows. The page's - * census counts the connection made, until the garbage collector frees it. - */ - static std::shared_ptr create(event_loop& loop, - std::span servers, - std::pmr::memory_resource* memory) { - val list = val::array(); - for (const auto& s : servers) { - val server = val::object(); - val urls = val::array(); - for (const auto& url : s.urls) { - urls.call("push", loop.text(url)); - } - server.set("urls", urls); - if (!s.username.empty()) { - server.set("username", loop.text(s.username)); - } - if (!s.credential.empty()) { - server.set("credential", loop.text(s.credential)); - } - list.call("push", server); - } - val config = val::object(); - config.set("iceServers", list); - const auto made = detail::js_new(val::global("RTCPeerConnection"), config); - if (!made.ok) { - return nullptr; - } - val::take_ownership(webcpp_trystero_js_census()).call("add", made.value); - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), - loop, made.value, memory); - } - - /** - * Wraps a connection of the page, and takes over its events; `create` makes one. - * - * @param loop The page's loop, which must outlive the connection. - * @param connection The `RTCPeerConnection`. - * @param memory The app's resource, which the connection's handlers, registration, channels - * and texts are allocated in. - */ - peer_connection(event_loop& loop, val connection, std::pmr::memory_resource* memory) - : loop_(loop), - memory_(memory), - id_(loop.add({std::allocator_arg, std::pmr::polymorphic_allocator<>(memory), - [this](int slot, const val& event) { on_event(slot, event); }})), - pc_(std::move(connection)) { - pc_.set("onicecandidate", loop_.handler(id_, 0)); - pc_.set("ondatachannel", loop_.handler(id_, 1)); - pc_.set("onconnectionstatechange", loop_.handler(id_, 2)); - pc_.set("oniceconnectionstatechange", loop_.handler(id_, 2)); - } - - /** Destroys the wrapper, which closes the connection without reporting the close. */ - ~peer_connection() override { - loop_.remove(id_); - for (const char* name : { - "onicecandidate", - "ondatachannel", - "onconnectionstatechange", - "oniceconnectionstatechange", - }) { - pc_.set(name, val::null()); - } - pc_.call("close"); - } - - /** - * Replaces the handlers, kept in a shared object so that one replacing them during its own call - * outlives the call. - * - * @param h The new handlers, kept in the connection's resource. - */ - void set_handlers(handlers h) override { - h_ = std::allocate_shared(allocator(), std::move(h)); - } - - /** - * Opens a data channel with `createDataChannel()`. - * - * @param label The channel's label, read during the call. - * @return The channel, made in the connection's resource, or null when the browser refuses - * to open one, as on a closed connection. - */ - std::shared_ptr create_data_channel(std::string_view label) override { - const auto made = detail::js_call(pc_, "createDataChannel", loop_.text(label)); - if (!made.ok) { - return nullptr; - } - return std::allocate_shared(allocator(), loop_, made.value, memory_); - } - - /** - * Creates and applies the offer or the answer the signaling state calls for, with - * `setLocalDescription()`. - * - * @param done Called once the promise settles, with the `localDescription`'s type and SDP, or - * with `error::backend_failure` when it is rejected or the connection is gone. - */ - void set_local_description( - handler done) override { - const std::weak_ptr weak = shared_from_this(); - detail::then(loop_, detail::js_call(pc_, "setLocalDescription"), - {std::allocator_arg, allocator(), - [weak, done = std::move(done)](bool ok, const val& /*value*/) mutable { - const auto self = weak.lock(); - const val local = self ? self->pc_["localDescription"] : val::null(); - if (!ok || local.isNull()) { - done(make_error_code(error::backend_failure), {}, {}); - return; - } - const auto type = self->loop_.utf8(local["type"], self->memory_); - const auto sdp = self->loop_.utf8(local["sdp"], self->memory_); - done({}, type, sdp); - }}, - memory_); - } - - /** - * Applies the remote peer's offer or answer, with `setRemoteDescription()`. - * - * @param type "offer" or "answer", read during the call. - * @param sdp The description's SDP, read during the call. - * @param done Called once the promise settles, or with `error::backend_failure` when it is - * rejected. - */ - void set_remote_description(std::string_view type, std::string_view sdp, - handler done) override { - val description = val::object(); - description.set("type", loop_.text(type)); - description.set("sdp", loop_.text(sdp)); - detail::then( - loop_, detail::js_call(pc_, "setRemoteDescription", description), - {std::allocator_arg, allocator(), - [done = std::move(done)](bool ok, const val& /*value*/) mutable { - done(ok ? backend::error_code{} : make_error_code(error::backend_failure)); - }}, - memory_); - } - - /** - * Adds a remote ICE candidate, with `addIceCandidate()`. - * - * The text comes from a peer: one `JSON.parse` refuses is dropped, as a candidate the browser - * refuses is. - * - * @param candidate_json The JSON of an `RTCIceCandidateInit`, read during the call. - * @param done Called once the candidate is added, or with `error::backend_failure` when the - * text is not JSON or the browser refuses the candidate. - */ - void add_ice_candidate(std::string_view candidate_json, - handler done) override { - const auto candidate = - detail::js_call(val::global("JSON"), "parse", loop_.text(candidate_json)); - detail::then( - loop_, - candidate.ok ? detail::js_call(pc_, "addIceCandidate", candidate.value) : candidate, - {std::allocator_arg, allocator(), - [done = std::move(done)](bool ok, const val& /*value*/) mutable { - done(ok ? backend::error_code{} : make_error_code(error::backend_failure)); - }}, - memory_); - } - - /** - * Whether a remote description was applied. - * - * @return Whether its `remoteDescription` is not null. - */ - bool has_remote_description() const override { return !pc_["remoteDescription"].isNull(); } - - /** Closes the connection and its channels. */ - void close() override { pc_.call("close"); } - - /** - * The browser's own `RTCPeerConnection`, what media will be added to. - * - * @return The connection. - * @see "Roadmap", in the guide. - */ - const val& native_handle() const { return pc_; } - -private: - std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } - - backend::connection_state state() const { - using backend::connection_state; - // Compared in JavaScript, so reading a state allocates nothing on the C++ side. - const val connection = pc_["connectionState"]; - const val ice = pc_["iceConnectionState"]; - const auto is = [](const val& state, const char* name) { - return state.strictlyEquals(val(name)); - }; - if (is(connection, "failed") || is(ice, "failed")) { - return connection_state::failed; - } - if (is(connection, "closed") || is(ice, "closed")) { - return connection_state::closed; - } - if (is(connection, "disconnected") || is(ice, "disconnected")) { - return connection_state::disconnected; - } - if (is(connection, "connected") || is(ice, "connected") || is(ice, "completed")) { - return connection_state::connected; - } - if (is(connection, "connecting") || is(ice, "checking")) { - return connection_state::connecting; - } - return connection_state::fresh; - } - - void on_event(int slot, const val& event) { - const auto h = h_; - if (!h) { - return; - } - if (slot == 0) { - const val candidate = event["candidate"]; - if (candidate.isNull() || candidate.isUndefined() || !h->ice_candidate) { - return; - } - const auto json = - loop_.utf8(val::global("JSON").call("stringify", candidate), memory_); - h->ice_candidate(json); - } else if (slot == 1) { - if (h->data_channel) { - h->data_channel(std::allocate_shared(allocator(), loop_, - event["channel"], memory_)); - } - } else if (h->state) { - h->state(state()); - } - } - - event_loop& loop_; - std::pmr::memory_resource* memory_; - int id_; - val pc_ = val::undefined(); - std::shared_ptr h_; -}; - -/** - * AES-GCM through `crypto.subtle`, under a key imported once, as Trystero's `encrypt` and `decrypt` - * do. - * - * The text is copied into JavaScript during the call; an operation that arrives while the key is - * still being imported waits with a copy of its text, in the room's resource. Without - * `crypto.subtle`, outside a secure context, every operation fails. - * - * @see "The browser backend", in the guide. - */ -class sealer : public backend::sealer, public std::enable_shared_from_this { -public: - /** What a seal or an open completes with: an error, or the text, a view valid for the call. */ - using done_handler = handler; - - /** - * Constructs a sealer under a room's key, which it imports on its first operation. - * - * @param loop The page's loop, which must outlive the sealer's pending promises. - * @param key The raw AES-256 key, `protocol::seal_key`'s. - * @param memory The room's resource, which its texts, its waiting operations and its - * completions are allocated in. - */ - sealer(event_loop& loop, std::array key, std::pmr::memory_resource* memory) - : loop_(loop), raw_key_(key), memory_(memory), waiting_(memory) {} - - /** - * Seals a text under a fresh random IV, with `crypto.subtle.encrypt`. - * - * @param plaintext The text, read during the call. - * @param done Called with the sealed text, or with `error::backend_failure` when the key - * cannot be imported or the encryption fails. - */ - void seal(std::string_view plaintext, done_handler done) override { - if (state_ == key_state::ready) { - encrypt(plaintext, std::move(done)); - return; - } - wait_for_key({std::allocator_arg, allocator(), - [plaintext = std::pmr::string(plaintext, memory_), done = std::move(done)]( - sealer& self, bool ok) mutable { - if (!ok) { - done(make_error_code(error::backend_failure), {}); - return; - } - self.encrypt(plaintext, std::move(done)); - }}); - } - - /** - * Opens a sealed text, with `crypto.subtle.decrypt`. - * - * @param sealed The sealed text, read during the call. - * @param done Called with the plaintext, or with `error::wrong_password` when the text was - * sealed under another key or is not a sealed text, and `error::backend_failure` when the key - * cannot be imported. - */ - void open(std::string_view sealed, done_handler done) override { - if (state_ == key_state::ready) { - decrypt(sealed, std::move(done)); - return; - } - wait_for_key({std::allocator_arg, allocator(), - [sealed = std::pmr::string(sealed, memory_), done = std::move(done)]( - sealer& self, bool ok) mutable { - if (!ok) { - done(make_error_code(error::backend_failure), {}); - return; - } - self.decrypt(sealed, std::move(done)); - }}); - } - -private: - std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } - - /** The page's `crypto.subtle`; undefined outside a secure context, or without `crypto`. */ - static val subtle() { - const val crypto = val::global("crypto"); - return crypto.isUndefined() || crypto.isNull() ? val::undefined() : crypto["subtle"]; - } - - static val algorithm(std::span iv) { - val a = val::object(); - a.set("name", val("AES-GCM")); - a.set("iv", detail::to_js(iv)); - return a; - } - - void encrypt(std::string_view plaintext, done_handler done) { - std::array iv{}; - getentropy(iv.data(), iv.size()); // lint-world: a seal's IV - const auto bytes = - std::span(reinterpret_cast(plaintext.data()), plaintext.size()); - detail::then( - loop_, detail::js_call(subtle(), "encrypt", algorithm(iv), key_, detail::to_js(bytes)), - {std::allocator_arg, allocator(), - [iv, done = std::move(done), memory = memory_](bool ok, const val& cipher) mutable { - if (!ok) { - done(make_error_code(error::backend_failure), {}); - return; - } - const auto sealed = - protocol::format_sealed(iv, detail::from_js(cipher, memory), memory); - done({}, sealed); - }}, - memory_); - } - - void decrypt(std::string_view sealed, done_handler done) { - const auto parts = protocol::parse_sealed(sealed, memory_); - if (!parts || parts->iv.empty()) { - detail::defer(loop_, memory_, [done = std::move(done)]() mutable { - done(make_error_code(error::wrong_password), {}); - }); - return; - } - detail::then( - loop_, - detail::js_call(subtle(), "decrypt", algorithm(parts->iv), key_, - detail::to_js(parts->ciphertext)), - {std::allocator_arg, allocator(), - [done = std::move(done), memory = memory_](bool ok, const val& plain) mutable { - if (!ok) { - done(make_error_code(error::wrong_password), {}); - return; - } - const auto b = detail::from_js(plain, memory); - done({}, std::string_view(reinterpret_cast(b.data()), b.size())); - }}, - memory_); - } - - /** - * Runs `op` once the key is imported, or has failed to be: after the call in every case, so - * that no completion runs inside the operation that started it. - */ - void wait_for_key(handler op) { - const std::weak_ptr weak = shared_from_this(); - if (state_ == key_state::failed) { - detail::defer(loop_, memory_, [weak, op = std::move(op)]() mutable { - if (const auto self = weak.lock()) { - op(*self, false); - } - }); - return; - } - waiting_.push_back(std::move(op)); - if (state_ == key_state::importing) { - return; - } - state_ = key_state::importing; - if (subtle().isUndefined()) { // not a secure context - detail::defer(loop_, memory_, [weak] { - if (const auto self = weak.lock()) { - self->key_imported(false, val::undefined()); - } - }); - return; - } - val usages = val::array(); - usages.call("push", val("encrypt")); - usages.call("push", val("decrypt")); - detail::then(loop_, - detail::js_call(subtle(), "importKey", "raw", detail::to_js(raw_key_), - "AES-GCM", false, usages), - {std::allocator_arg, allocator(), - [weak](bool ok, val key) { - if (const auto self = weak.lock()) { - self->key_imported(ok, std::move(key)); - } - }}, - memory_); - } - - void key_imported(bool ok, val key) { - state_ = ok ? key_state::ready : key_state::failed; - key_ = std::move(key); - for (auto& op : std::exchange(waiting_, {})) { - op(*this, ok); - } - } - - enum class key_state { none, importing, ready, failed }; - - event_loop& loop_; - std::array raw_key_; - std::pmr::memory_resource* memory_; - key_state state_ = key_state::none; - val key_ = val::undefined(); - std::pmr::deque> waiting_; -}; - -/** - * The browser's factory: one per page, beside the page's `event_loop`. - * - * It makes peer connections, data channels and received frames in `app_config::memory`, and - * WebSockets, sealers and room timers in the room's effective `room_options::memory`. Objects, - * handlers and registrations use the resource supplied to their factory method. What - * `emscripten::val` holds is in the JavaScript heap. It needs a secure context, where - * `crypto.subtle` exists. - * - * @see "The browser backend", in the guide. - */ -class backend : public trystero::backend::factory { -public: - /** - * Constructs the page's backend. - * - * @param loop The page's loop, which must outlive the backend and every object it makes. - */ - explicit backend(event_loop& loop) : loop_(loop) {} - - /** - * The most `RTCPeerConnection` objects the page's rooms hold, every backend of the page - * together, counted from their construction until the garbage collector frees them: half of the - * 500 Chromium allows a page, which it counts the same way, so that a closed connection still - * counts until a collection the page cannot ask for. - * - * Tip: a room makes at most 64 connections in any 57 s, so floods of four rooms reach this - * within a minute when no collection runs; the page then makes none until one does, and its - * rooms report each negotiation they cannot start, while the rest of Chromium's count stays - * free for what the page makes without a room. - */ - static constexpr std::size_t max_peer_connections = 256; - - /** - * Opens a WebSocket to a relay, with the page's `WebSocket`. - * - * @param url The relay's URL, read during the call. - * @param h What the WebSocket reports. - * @param memory The room's resource, which the WebSocket, its handlers and its texts are - * allocated in. - * @return The WebSocket. - */ - std::shared_ptr connect( - std::string_view url, trystero::backend::websocket::handlers h, - std::pmr::memory_resource* memory) override { - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), loop_, - url, std::move(h), memory); - } - - /** - * Makes a peer connection, with the page's `RTCPeerConnection`. - * - * @param servers The STUN and TURN servers, read during the call. - * @param memory The app's resource, which the connection, its channels, its handlers and its - * texts are allocated in. - * @return The connection, or null when the page holds `max_peer_connections`, or when the - * browser refuses to make one, as `peer_connection::create` says. - */ - std::shared_ptr make_peer_connection( - std::span servers, - std::pmr::memory_resource* memory) override { - const val census = val::take_ownership(webcpp_trystero_js_census()); - if (census["held"].as() >= static_cast(max_peer_connections)) { - return nullptr; - } - return peer_connection::create(loop_, servers, memory); - } - - /** - * Makes a timer, over `setTimeout`. - * - * @param memory The room's resource, which the timer and its handler are allocated in. - * @return The timer, not started. - */ - std::shared_ptr make_timer( - std::pmr::memory_resource* memory) override { - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), loop_, - memory); - } - - /** - * Makes a sealer, over `crypto.subtle`. - * - * @param key The raw AES-256 key. - * @param memory The room's resource, which the sealer, its texts and its completions are - * allocated in. - * @return The sealer. - */ - std::shared_ptr make_sealer( - std::array key, std::pmr::memory_resource* memory) override { - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), loop_, key, - memory); - } - - /** - * Fills `out` with the page's entropy, which Emscripten draws from `crypto.getRandomValues`. - * - * @param out The bytes to fill. - */ - void random(std::span out) override { - for (std::size_t at = 0; at < out.size(); at += 256) { - // Each call fills at most 256 bytes. - const auto piece = std::min(256, out.size() - at); - getentropy(out.data() + at, piece); // lint-world: Trystero's randomness - } - } - - /** - * Seconds since the Unix epoch, from `Date.now()`. - * - * @return The current time, in whole seconds. - */ - std::int64_t unix_seconds() override { - return static_cast( - std::floor(val::global("Date").call("now") / 1000)); - } - - /** - * Milliseconds from `performance.now()`. - * - * @return The current time, in milliseconds since the page's time origin. - */ - double now_ms() override { return val::global("performance").call("now"); } - -private: - event_loop& loop_; -}; - -} // namespace webcpp::trystero::browser - -#endif diff --git a/include/webcpp/trystero/browser/event_loop.hpp b/include/webcpp/trystero/browser/event_loop.hpp deleted file mode 100644 index a376430..0000000 --- a/include/webcpp/trystero/browser/event_loop.hpp +++ /dev/null @@ -1,495 +0,0 @@ -// 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_BROWSER_EVENT_LOOP_HPP -#define WEBCPP_TRYSTERO_BROWSER_EVENT_LOOP_HPP - -#include - -#include -#include - -#include -#include // lint-world: binds an allocator only -#include // lint-world: posts and polls, never blocks -#include // lint-world: posts and polls, never blocks -#include // lint-world: posts and polls, never blocks -#include // lint-world: posts and polls, never blocks - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::browser { - -class event_loop; - -/** - * An Asio executor over an `event_loop`: what it is given runs on the loop's io_context. - * - * Giving it work while no JavaScript event is being handled schedules one `poll()` in a microtask, - * so posted work runs without a polling loop and without the application calling `poll()`. A room - * in the browser is constructed with it, through `boost::asio::any_io_executor`. - * - * @see "The browser backend", in the guide. - */ -class executor { -public: - /** - * Constructs an executor of `loop`. - * - * @param loop The loop, which must outlive the executor and every copy of it. - */ - explicit executor(event_loop& loop) noexcept : loop_(&loop) {} - - /** - * The execution context, the property Asio queries. - * - * @return The loop's io_context. - */ - [[nodiscard]] boost::asio::execution_context& query( - boost::asio::execution::context_t /*context*/) const noexcept; - - /** - * The blocking property, which Asio queries: `execute` never runs the work inside the call. - * - * @return `blocking.never`. - */ - static constexpr boost::asio::execution::blocking_t::never_t query( - boost::asio::execution::blocking_t /*blocking*/) noexcept { - return {}; - } - - /** - * The executor with `blocking.never` required, which it already is. - * - * @return A copy of this executor. - */ - [[nodiscard]] executor require( - boost::asio::execution::blocking_t::never_t /*never*/) const noexcept { - return executor(*loop_); - } - - /** - * Posts `f` to the loop's io_context, and schedules a poll unless one is coming. - * - * @tparam F A nullary callable. - * @param f The work, allocated as its associated allocator says. - */ - template - void execute(F&& f) const; - - /** - * Whether two executors are of one loop. - * - * @param a An executor. - * @param b Another. - * @return Whether they run work on the same loop. - */ - friend bool operator==(const executor& a, const executor& b) noexcept { - return a.loop_ == b.loop_; - } - - /** - * Whether two executors are of different loops. - * - * @param a An executor. - * @param b Another. - * @return Whether they run work on different loops. - */ - friend bool operator!=(const executor& a, const executor& b) noexcept { - return a.loop_ != b.loop_; - } - -private: - event_loop* loop_; -}; - -/** - * The bridge between the page's JavaScript event loop and an Asio io_context, which never runs on - * its own in a browser: it is polled after every JavaScript event that enters C++, and when work is - * posted from outside one. - * - * JavaScript reaches C++ through `handler(id, slot)`: a function bound to this loop, a registration - * and a slot, passed to `trystero_dispatch` (browser/src.hpp). An object registers a callback with - * `add` and removes it with `remove` when it is destroyed, so a late event for a destroyed object - * finds nothing. A loop must outlive the page's use of it; its destructor marks every handler it - * made as dead. - * - * Tip: a loop serves every room of the page, so the entries of its registrations are in the - * resource it is constructed with; a registered callback stays in its own allocator's resource, a - * room's for a room's object, until it is removed or, for a promise, until the promise settles. - * - * @see "The browser backend", in the guide. - */ -class event_loop { -public: - /** What a registration calls: with the slot the event came through, and the event. */ - using callback = handler; - - /** - * Constructs a loop over `io`, which it keeps from running out of work. - * - * @param io The io_context the loop polls, which must outlive the loop. - * @param memory The resource the entries of the registrations are allocated in; it must - * outlive the loop. - */ - explicit event_loop(boost::asio::io_context& io, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) - : io_(io), - work_(boost::asio::make_work_guard(io)), - token_(emscripten::val::object()), - decoder_(emscripten::val::global("TextDecoder").new_()), - encoder_(emscripten::val::global("TextEncoder").new_()), - callbacks_(memory) { - token_.set("alive", true); - } - - /** - * A JavaScript string of UTF-8 text, decoded by a `TextDecoder` straight from the wasm memory - * the view points into. - * - * No `std::string` is made to carry it across, as `emscripten::val(std::string)` would. - * - * @param utf8 The text, read during the call. - * @return The JavaScript string. - */ - [[nodiscard]] emscripten::val text(std::string_view utf8) const { - return decoder_.call( - "decode", emscripten::val(emscripten::typed_memory_view(utf8.size(), utf8.data()))); - } - - /** - * The UTF-8 bytes of a JavaScript string, encoded by a `TextEncoder` and copied straight into a - * string of `memory`. - * - * No `std::string` is made to carry them across, as `emscripten::val::as()` would. - * - * @param text The JavaScript string. - * @param memory The resource the copy is allocated in. - * @return The text, or an empty one when the string cannot be encoded. - */ - std::pmr::string utf8(const emscripten::val& text, std::pmr::memory_resource* memory) const { - auto out = utf8(text, memory, std::numeric_limits::max()); - return out ? std::move(*out) : std::pmr::string(memory); - } - - /** - * The UTF-8 bytes of a JavaScript string, as the other overload makes them, when they are at - * most `max_bytes`; nothing is copied into WebAssembly otherwise. - * - * The string's length is checked first, in UTF-16 units, each at least one byte, so that a - * longer string is never encoded; then the encoded bytes are. - * - * @param text The JavaScript string. - * @param memory The resource the copy is allocated in. - * @param max_bytes The most bytes the text may hold. - * @return The text, or nothing when it is longer or cannot be encoded. - */ - std::optional utf8(const emscripten::val& text, - std::pmr::memory_resource* memory, - std::size_t max_bytes) const { - if (text["length"].as() > static_cast(max_bytes)) { - return std::nullopt; - } - const auto encoded = detail::js_call(encoder_, "encode", text); - if (!encoded.ok || encoded.value["length"].as() > static_cast(max_bytes)) { - return std::nullopt; - } - std::pmr::string out(encoded.value["length"].as(), '\0', memory); - emscripten::val( - emscripten::typed_memory_view(out.size(), reinterpret_cast(out.data()))) - .call("set", encoded.value); - return out; - } - - /** Not copyable: the page's functions name this loop by its address. */ - event_loop(const event_loop&) = delete; - - /** Not copy-assignable: the page's functions name this loop by its address. */ - event_loop& operator=(const event_loop&) = delete; - - /** Destroys the loop, and marks every handler it made as dead: their events are dropped. */ - ~event_loop() { token_.set("alive", false); } - - /** - * The io_context the loop polls. - * - * @return The io_context it was constructed with. - */ - boost::asio::io_context& io() noexcept { return io_; } - - /** - * An executor of this loop, what a room in the browser is constructed with. - * - * @return The executor. - */ - executor get_executor() noexcept { return executor(*this); } - - /** - * Registers a callback, which JavaScript reaches through @ref handler. - * - * The callback stays in its own allocator's resource (a room's, for a room's object); only the - * registration's entry is the loop's. - * - * @param f The callback. - * @return The registration's id, which @ref handler and @ref remove take. - */ - int add(callback f) { - const int id = next_id_++; - const auto allocator = f.get_allocator(); - callbacks_.emplace(id, std::allocate_shared(allocator, std::move(f))); - return id; - } - - /** - * Removes a registration: an event for it from now on finds nothing. - * - * @param id The registration's id. - */ - void remove(int id) { callbacks_.erase(id); } - - /** - * A JavaScript function of one argument that delivers it to registration `id`, slot `slot`. - * - * An exception that escapes the call, which no operation of trystero raises, is reported to - * the page (`reportError`) and does not stop the loop: the loop recovers, as @ref recover - * says, and the function returns. - * - * @param id The registration's id. - * @param slot A number the callback receives, which tells its events apart. - * @return The function, which calls `trystero_dispatch` with this loop, `id`, `slot` and its - * argument (browser/src.hpp). - */ - [[nodiscard]] emscripten::val handler(int id, int slot) const { - // The loop's address crosses as a pointer, and comes back through trystero_dispatch. - return emscripten::val::take_ownership( - webcpp_trystero_js_handler(token_.as_handle(), this, id, slot)); - } - - /** - * How many calls into C++ are running: 0 between events, 1 inside a callback. - * - * @return The depth. - */ - [[nodiscard]] int depth() const noexcept { return depth_; } - - /** - * Brings the loop back after an exception escaped a call into C++ that entered at `depth`: - * the calls it unwound no longer count, and a poll runs the work that is ready. - * - * Tip: without WebAssembly exceptions no destructor runs while an exception unwinds, so the - * depth a call raised stays raised; the page's function reads the depth before it enters C++ - * and gives it back here, so that a nested entry that escapes leaves the depth of the call - * still running below it, never less. The page's function also puts WebAssembly's stack - * pointer back where it was before the call, which no epilogue of the unwound frames did, but - * what those frames owned on the heap stays allocated: 312 bytes per escape, measured, for a - * frame that held a string of 300. With exceptions, `trystero_dispatch` catches a C++ - * exception itself, which frees it and runs every destructor, and recovers the same way. - * - * @param depth The depth when the call entered, as `depth()` read it; never below 0. - */ - void recover(int depth) { - depth_ = depth > 0 ? depth : 0; - poll_scheduled_ = false; - schedule_poll(); - } - - /** - * Runs a registration's callback for a JavaScript event, then everything that became ready. - * - * An event the page delivers while C++ is already running, inside a call C++ made into - * JavaScript (a WebSocket that fires `close` from inside `close()`, as node's does), is - * posted rather than run, so that a handler never runs inside the call that caused it. - * - * @param id The registration's id; an unknown one runs nothing. - * @param slot The slot the event came through. - * @param event The event. - */ - void dispatch(int id, int slot, emscripten::val event) { - { - const running call(depth_); - if (id == poll_id) { - poll_scheduled_ = false; - } else if (const auto it = callbacks_.find(id); it != callbacks_.end() && depth_ > 1) { - // Delivered when it runs, by id: the registration may be gone by then, and its - // object with it. Ids are never reused. - boost::asio::post(io_, boost::asio::bind_allocator( - it->second->get_allocator(), - [this, id, slot, event = std::move(event)]() mutable { - deliver(id, slot, std::move(event)); - })); - } else { - deliver(id, slot, std::move(event)); - } - } - if (depth_ == 0) { - poll(); - } - } - - /** Runs every ready handler; what they post runs too. */ - void poll() { - const running call(depth_); - if (io_.stopped()) { - io_.restart(); - } - io_.poll(); - } - - /** Schedules a `poll()` in a microtask unless one is pending or a poll is running, which will - * see the work. */ - void schedule_poll() { - if (depth_ > 0 || poll_scheduled_) { - return; - } - poll_scheduled_ = true; - emscripten::val::global("queueMicrotask")(handler(poll_id, 0)); - } - -private: - /** Runs a registration's callback, when it still has one. */ - void deliver(int id, int slot, emscripten::val event) { - if (const auto it = callbacks_.find(id); it != callbacks_.end()) { - const auto f = it->second; // the callback may remove itself - (*f)(slot, std::move(event)); - } - } - - /** - * Counts a call into C++ for as long as it runs, however it ends. - * - * Tip: with WebAssembly exceptions, an exception that unwinds through the call runs this - * destructor, and the depth comes back down; without them nothing runs on the way, and - * `recover` brings the depth back from JavaScript. Neither should be needed: the backend makes - * every call that can throw through browser/js.hpp. - */ - class running { - public: - explicit running(int& depth) noexcept : depth_(depth) { ++depth_; } - - running(const running&) = delete; - running& operator=(const running&) = delete; - - ~running() { --depth_; } - - private: - int& depth_; - }; - - static constexpr int poll_id = 0; - - boost::asio::io_context& io_; - boost::asio::executor_work_guard work_; - emscripten::val token_; - emscripten::val decoder_; - emscripten::val encoder_; - std::pmr::unordered_map> callbacks_; - int next_id_ = 1; - int depth_ = 0; - bool poll_scheduled_ = false; -}; - -inline boost::asio::execution_context& executor::query( - boost::asio::execution::context_t /*context*/) const noexcept { - return loop_->io(); -} - -template -void executor::execute(F&& f) const { - boost::asio::post(loop_->io(), std::forward(f)); - loop_->schedule_poll(); -} - -/** - * The one function JavaScript calls, `trystero_dispatch`, which `browser/src.hpp` exports. - * - * Events for a destroyed loop are dropped. With exceptions, a C++ exception that escapes the - * callback stops here: it is reported to the page, as `event_loop::handler` says, and the loop - * recovers. - * - * @param token The loop's token, whose `alive` is false once the loop is destroyed. - * @param loop The loop's address, as a number. - * @param id The registration's id. - * @param slot The slot the event came through. - * @param event The event. - * @see "The browser backend", in the guide. - */ -inline void dispatch(const emscripten::val& token, std::uintptr_t loop, int id, int slot, - emscripten::val event) { - if (!token["alive"].as()) { - return; - } - // The page holds the loop's address as a number, the one form it passes back through embind. - // NOLINTNEXTLINE(performance-no-int-to-ptr) - auto& target = *reinterpret_cast(loop); -#ifdef __cpp_exceptions - // A C++ exception is caught here, where catching it frees it: one that reached the page's - // function would keep its object, and what the object owns, for good. - const int entered = target.depth(); - try { - target.dispatch(id, slot, std::move(event)); - } catch (const std::exception& e) { - detail::report_escape(emscripten::val::u8string(e.what())); - target.recover(entered); - } catch (...) { - detail::report_escape(emscripten::val("an exception that is not a std::exception")); - target.recover(entered); - } -#else - target.dispatch(id, slot, std::move(event)); -#endif -} - -/** - * The function JavaScript calls, `trystero_recover`, when an exception escaped - * `trystero_dispatch`: the loop recovers, as `event_loop::recover` says. - * - * Calls for a destroyed loop do nothing. - * - * @param token The loop's token, whose `alive` is false once the loop is destroyed. - * @param loop The loop's address, as a number. - * @param depth The loop's depth when the call that escaped entered, as `trystero_depth` read it. - * @see "The browser backend", in the guide. - */ -inline void recover(const emscripten::val& token, std::uintptr_t loop, int depth) { - if (!token["alive"].as()) { - return; - } - // As in dispatch: the page holds the loop's address as a number. - // NOLINTNEXTLINE(performance-no-int-to-ptr) - reinterpret_cast(loop)->recover(depth); -} - -/** - * The function JavaScript calls, `trystero_depth`, before it enters C++ through - * `trystero_dispatch`: the depth `trystero_recover` restores if the call escapes. - * - * @param token The loop's token, whose `alive` is false once the loop is destroyed. - * @param loop The loop's address, as a number. - * @return The loop's depth, or 0 for a destroyed loop. - * @see "The browser backend", in the guide. - */ -inline int depth(const emscripten::val& token, std::uintptr_t loop) { - if (!token["alive"].as()) { - return 0; - } - // As in dispatch: the page holds the loop's address as a number. - // NOLINTNEXTLINE(performance-no-int-to-ptr) - return reinterpret_cast(loop)->depth(); -} - -} // namespace webcpp::trystero::browser - -#endif diff --git a/include/webcpp/trystero/browser/js.hpp b/include/webcpp/trystero/browser/js.hpp deleted file mode 100644 index c7d11c8..0000000 --- a/include/webcpp/trystero/browser/js.hpp +++ /dev/null @@ -1,109 +0,0 @@ -// 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_BROWSER_JS_HPP -#define WEBCPP_TRYSTERO_BROWSER_JS_HPP - -#include - -#include - -#include - -/** - * The browser backend's calls into JavaScript that can throw, made so that no exception enters - * WebAssembly: one JavaScript function, which `browser/src.hpp` defines with `EM_JS`, runs the - * operation inside `try` and returns what it came to, a value or the exception, as a value. - * - * Tip: an exception thrown into WebAssembly unwinds C++ code written to raise none and leaves it - * mid-operation; without WebAssembly exceptions (`exception-handling=off`, or Emscripten's - * JavaScript exceptions), no destructor runs on the way. The same file defines the function every - * event of the page enters C++ through, which catches what still escapes and recovers the loop. - */ - -extern "C" { - -/** - * Runs `target[member](...arguments)`, or `new target(...arguments)` when `member` is undefined, - * and returns `{ok, value}`: what it returned, or, with `ok` false, what it threw. - */ -emscripten::EM_VAL webcpp_trystero_js_try(emscripten::EM_VAL target, emscripten::EM_VAL member, - emscripten::EM_VAL arguments); - -/** - * A function of one argument that calls `trystero_dispatch(token, loop, id, slot, argument)`, and - * on an exception puts WebAssembly's stack pointer back as it was before the call, reports the - * exception, and calls `trystero_recover(token, loop, depth)` with the depth `trystero_depth` gave - * before the call. - */ -emscripten::EM_VAL webcpp_trystero_js_handler(emscripten::EM_VAL token, const void* loop, int id, - int slot); - -/** - * The page's census of its `RTCPeerConnection` objects, one for every program of the page, made on - * the first call: `held`, the connections counted from their construction until the garbage - * collector frees them, as Chromium counts them against its limit; `add(connection)`, which counts - * one; and `onrelease`, a function of the new count called after each release, for a test. Without - * `FinalizationRegistry` nothing is counted. - */ -emscripten::EM_VAL webcpp_trystero_js_census(); -} - -namespace webcpp::trystero::browser::detail { - -/** What a JavaScript operation came to: what it returned, or, with `ok` false, what it threw. */ -struct js_outcome { - /** Whether the operation returned rather than threw. */ - bool ok = false; - /** What it returned, or the exception it threw. */ - emscripten::val value = emscripten::val::undefined(); -}; - -/** The arguments of a JavaScript call, as an array. */ -template -emscripten::val js_arguments(const Args&... arguments) { - emscripten::val array = emscripten::val::array(); - (array.call("push", emscripten::val(arguments)), ...); - return array; -} - -/** Runs the operation `webcpp_trystero_js_try` describes, and reads its outcome. */ -inline js_outcome js_try(const emscripten::val& target, const emscripten::val& member, - const emscripten::val& arguments) { - const emscripten::val outcome = emscripten::val::take_ownership( - webcpp_trystero_js_try(target.as_handle(), member.as_handle(), arguments.as_handle())); - return {.ok = outcome["ok"].as(), .value = outcome["value"]}; -} - -/** Calls `object[method](arguments...)`, catching what it throws. */ -template -js_outcome js_call(const emscripten::val& object, const char* method, const Args&... arguments) { - return js_try(object, emscripten::val(method), js_arguments(arguments...)); -} - -/** Constructs `new constructor(arguments...)`, catching what it throws. */ -template -js_outcome js_new(const emscripten::val& constructor, const Args&... arguments) { - return js_try(constructor, emscripten::val::undefined(), js_arguments(arguments...)); -} - -/** - * Reports an exception that escaped a callback to the page: `reportError` with an `Error` of - * `message`, or `console.error` where there is no `reportError`, as in node. - */ -inline void report_escape(const emscripten::val& message) { - const emscripten::val error = emscripten::val::global("Error").new_(message); - const emscripten::val report = emscripten::val::global("reportError"); - if (report.typeOf().as() == "function") { - report(error); - } else { - emscripten::val::global("console").call("error", error); - } -} - -} // namespace webcpp::trystero::browser::detail - -#endif diff --git a/include/webcpp/trystero/browser/src.hpp b/include/webcpp/trystero/browser/src.hpp deleted file mode 100644 index e7326d2..0000000 --- a/include/webcpp/trystero/browser/src.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// 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_BROWSER_SRC_HPP -#define WEBCPP_TRYSTERO_BROWSER_SRC_HPP - -#include - -/** - * What a browser program compiles once: the exports JavaScript calls (`trystero_dispatch` and - * `trystero_recover`), and the JavaScript functions the backend calls through (browser/js.hpp). - * Include it in exactly one source file of the program. - * - * Tip: Boost.JSON's definitions are not here: a program links them from /webcpp//boost_json, which - * /webcpp/trystero//trystero brings and which builds on emscripten as on every target. - */ -#include -#include - -#include -#include - -// The JavaScript functions of browser/js.hpp. Emval turns the handles C++ passes into values and -// back, and stackSave and stackRestore keep WebAssembly's stack pointer; EM_JS_DEPS has Emscripten -// link them. A native parse (the reference, the lint) has -// no JavaScript to define, nor a section EM_JS can name. -#ifdef __EMSCRIPTEN__ -EM_JS_DEPS(webcpp_trystero, "$Emval,$stackSave,$stackRestore"); - -// clang-format off -EM_JS(emscripten::EM_VAL, webcpp_trystero_js_try, - (emscripten::EM_VAL target, emscripten::EM_VAL member, emscripten::EM_VAL arguments), { - const object = Emval.toValue(target); - const name = Emval.toValue(member); - const values = Emval.toValue(arguments); - try { - const value = - name === undefined ? Reflect.construct(object, values) : object[name](...values); - return Emval.toHandle({ok: true, value}); - } catch (error) { - return Emval.toHandle({ok: false, value: error}); - } -}); - -EM_JS(emscripten::EM_VAL, webcpp_trystero_js_handler, - (emscripten::EM_VAL token, const void* loop, int id, int slot), { - const alive = Emval.toValue(token); - const address = loop >>> 0; - return Emval.toHandle(event => { - // An exception leaves WebAssembly without running its frames' epilogues: the stack - // pointer and the loop's depth are put back as they were before the call. - const top = stackSave(); - const depth = Module['trystero_depth'](alive, address); - try { - Module['trystero_dispatch'](alive, address, id, slot, event); - } catch (error) { - stackRestore(top); - (globalThis.reportError ?? console.error)(error); - Module['trystero_recover'](alive, address, depth); - } - }); -}); - -EM_JS(emscripten::EM_VAL, webcpp_trystero_js_census, (), { - const key = Symbol.for("webcpp.trystero.census"); - if (!globalThis[key]) { - const census = {held: 0, onrelease: null}; - // Without FinalizationRegistry nothing is counted, so that the page never stops making - // connections for a count that never comes down. - const registry = typeof FinalizationRegistry == "function" - ? new FinalizationRegistry(function() { - --census.held; - if (census.onrelease) { - census.onrelease(census.held); - } - }) - : null; - census.add = function(connection) { - if (registry) { - ++census.held; - registry.register(connection, 0); - } - }; - globalThis[key] = census; - } - return Emval.toHandle(globalThis[key]); -}); -// clang-format on -#endif - -EMSCRIPTEN_BINDINGS(trystero_browser) { - emscripten::function("trystero_dispatch", &webcpp::trystero::browser::dispatch); - emscripten::function("trystero_recover", &webcpp::trystero::browser::recover); - emscripten::function("trystero_depth", &webcpp::trystero::browser::depth); -} - -#endif diff --git a/include/webcpp/trystero/config.hpp b/include/webcpp/trystero/config.hpp index b59fd2f..22aabc7 100644 --- a/include/webcpp/trystero/config.hpp +++ b/include/webcpp/trystero/config.hpp @@ -15,7 +15,7 @@ // MrDocs parses trystero as a build with exceptions does, where the macro is // not defined: this definition, undone at once, is the one the reference -// lists, and the parse goes on with every API that needs exceptions in it. +// lists, and the parse goes on as such a build's. #ifdef __MRDOCS__ /** Defined when trystero is built without exceptions: when webcpp has none (the @@ -24,12 +24,12 @@ in a build that has them. trystero raises no exception of its own: every operation that can fail - completes with an error code. The native backend's WebRTC, over - libdatachannel, which reports errors by throwing, needs exceptions: while this - is defined, `native::data_channel`, `native::peer_connection` and - `native::backend` do not exist, and the rest of trystero is unchanged. + completes with an error code, and every part of it, the platform backend + included, works with exceptions and without them. Its WebRTC is + webcpp::webrtc's, which natively calls libdatachannel's C API, where no + exception crosses. - @see "The native backend", in the guide. + @see "The platform backend", in the guide. */ #define WEBCPP_TRYSTERO_NO_EXCEPTIONS #undef WEBCPP_TRYSTERO_NO_EXCEPTIONS diff --git a/include/webcpp/trystero/detail/action_wire.hpp b/include/webcpp/trystero/detail/action_wire.hpp index 93726c1..1de04b7 100644 --- a/include/webcpp/trystero/detail/action_wire.hpp +++ b/include/webcpp/trystero/detail/action_wire.hpp @@ -10,13 +10,12 @@ #include #include +#include #include #include #include #include -#include - #include #include #include @@ -37,8 +36,7 @@ namespace webcpp::trystero::detail { /** * A received action message. It owns one buffer, the data channel frame it arrived in or the * payload a transfer assembled, and names its parts as ranges of it: moving a message moves the - * buffer and copies nothing. It carries the JSON storage of the room that received it, in which a - * JSON payload is decoded. + * buffer and copies nothing. */ struct incoming { // NOLINT(bugprone-exception-escape) @@ -62,8 +60,6 @@ struct incoming { // NOLINT(bugprone-exception-escape) range payload_at = {}; /** Where the metadata, JSON text or empty, is in the buffer. */ range metadata_at = {}; - /** The receiving room's JSON storage, which a JSON payload is parsed into. */ - boost::json::storage_ptr json = {}; /** The action's name, a view into the buffer. */ [[nodiscard]] std::string_view name() const { return text(name_at); } @@ -180,14 +176,11 @@ class action_wire : public std::enable_shared_from_this { handler fail_peer; }; - /** Every allocation goes through `memory`; a received message carries `json`, a storage of that - * resource. */ + /** Every allocation goes through `memory`. */ action_wire(backend::factory& factory, std::string_view room_token, - std::size_t max_receive_bytes, callbacks cb, std::pmr::memory_resource* memory, - boost::json::storage_ptr json) + std::size_t max_receive_bytes, callbacks cb, std::pmr::memory_resource* memory) : factory_(factory), memory_(memory), - json_(std::move(json)), token_(room_token, memory), max_receive_bytes_(max_receive_bytes), cb_(std::move(cb)), @@ -362,7 +355,7 @@ class action_wire : public std::enable_shared_from_this { // reports. struct waiting_inline { // NOLINT(bugprone-exception-escape) incoming message; - double arrived_ms = 0; + time_point arrived{}; }; struct peer_in { @@ -563,7 +556,6 @@ class action_wire : public std::enable_shared_from_this { .name_at = {.offset = offset_of(p.name.data()), .size = p.name.size()}, .payload_at = {.offset = offset_of(p.payload.data()), .size = p.payload.size()}, .metadata_at = {.offset = offset_of(p.metadata.data()), .size = p.metadata.size()}, - .json = json_, }; if (cb_.has_receiver(p.name)) { cb_.deliver(std::move(message)); @@ -573,7 +565,7 @@ class action_wire : public std::enable_shared_from_this { if (in.count() >= max_pending_per_peer) { return; } - in.waiting.push_back({.message = std::move(message), .arrived_ms = factory_.now_ms()}); + in.waiting.push_back({.message = std::move(message), .arrived = steady_now(factory_)}); } peer_in& incoming_for(std::string_view peer) { @@ -608,7 +600,7 @@ class action_wire : public std::enable_shared_from_this { b.name = p.name; b.format = p.format; b.metadata = p.metadata; - b.size = p.size; + b.size = static_cast(p.size); // within max_receive_bytes_, checked above b.timer = factory_.make_timer(memory_); arm(peer, p.id, b); drain(); @@ -677,7 +669,6 @@ class action_wire : public std::enable_shared_from_this { .name_at = name_at, .payload_at = payload_at, .metadata_at = metadata_at, - .json = json_, }; release_bulk(it->second, b); cb_.deliver(std::move(message)); @@ -697,14 +688,14 @@ class action_wire : public std::enable_shared_from_this { /** Delivers inline frames whose action now has a receiver, and accepts the next transfer of * each idle peer. */ void drain() { - const double now = factory_.now_ms(); + const auto now = steady_now(factory_); std::pmr::vector ready(memory_); for (auto& [peer, in] : incoming_) { std::pmr::deque still_waiting(memory_); for (auto& w : in.waiting) { if (cb_.has_receiver(w.message.name())) { ready.push_back(std::move(w.message)); - } else if (now - w.arrived_ms < static_cast(transfer_timeout.count())) { + } else if (now - w.arrived < transfer_timeout) { still_waiting.push_back(std::move(w)); } } @@ -731,7 +722,6 @@ class action_wire : public std::enable_shared_from_this { backend::factory& factory_; std::pmr::memory_resource* memory_; - boost::json::storage_ptr json_; std::pmr::string token_; std::size_t max_receive_bytes_; callbacks cb_; diff --git a/include/webcpp/trystero/detail/app_impl.hpp b/include/webcpp/trystero/detail/app_impl.hpp index f59e6d2..771568b 100644 --- a/include/webcpp/trystero/detail/app_impl.hpp +++ b/include/webcpp/trystero/detail/app_impl.hpp @@ -14,14 +14,17 @@ #include #include #include +#include #include #include #include +#include #include #include #include -#include // lint-world: names the executor only +#include // lint-world: names the executor only + #include #include @@ -81,7 +84,7 @@ class room_endpoint { class app_impl : public std::enable_shared_from_this { public: /** The executor shared by the app and its rooms. */ - using executor_type = boost::asio::any_io_executor; + using executor_type = webcpp::asio::any_io_executor; /** Copies the configuration into its resource, draws the self id unless it names one, and sets * aside what no peer could use, each kept as a report. */ @@ -103,8 +106,14 @@ class app_impl : public std::enable_shared_from_this { self_id_.clear(); set_aside("self_id is longer than any peer accepts, so the app uses a random one"); } + // A signal writes the id as a JSON string, which holds UTF-8 alone, as any JavaScript + // string is once encoded. + if (!protocol::json::quotable(self_id_)) { + self_id_.clear(); + set_aside("self_id is not UTF-8, which no peer reads, so the app uses a random one"); + } if (self_id_.empty()) { - self_id_ = random_id(protocol::peer_id_size); + self_id_ = detail::random_id(factory_, protocol::peer_id_size, memory_); } if (idle_timeout_ < std::chrono::milliseconds::zero()) { idle_timeout_ = std::chrono::milliseconds::zero(); @@ -274,13 +283,14 @@ class app_impl : public std::enable_shared_from_this { } /** The connection a room's negotiation opened becomes the app's, or, when the app already has - * a live one to that peer, is closed and the existing one returned (C/shared-peer.mjs:105-108). + * a live one to that peer, is closed and the existing one returned, as in Trystero's + * dist/shared-peer.mjs:105-108. * * Tip: a stale connection to the peer, one whose channel is closing, ends first, as Trystero - * clears it (C/shared-peer.mjs:142-149): the rooms hear its end before the new connection is - * adopted, and a room may adopt one to the peer from inside that call, which is then the one - * shared, or ends in its turn if it is stale by then. One whose end is - * already under way, further up the stack, is let go: it ends no second time. */ + * clears it (dist/shared-peer.mjs:142-149): the rooms hear its end before the new + * connection is adopted, and a room may adopt one to the peer from inside that call, which is + * then the one shared, or ends in its turn if it is stale by then. One whose end is already + * under way, further up the stack, is let go: it ends no second time. */ std::shared_ptr adopt(std::string_view peer_view, std::shared_ptr pc, std::shared_ptr channel) { @@ -324,7 +334,7 @@ class app_impl : public std::enable_shared_from_this { } const auto weak = weak_from_this(); // The connection whose `ended` this is, set once it exists: its end erases its own entry - // only, never one a room adopted since (Trystero's owns(), C/shared-peer.mjs:210-212). + // only, never one a room adopted since (Trystero's owns(), dist/shared-peer.mjs:210-212). const auto owner = std::allocate_shared>(allocator()); auto c = std::allocate_shared( allocator(), factory_, peer, std::move(pc), std::move(channel), @@ -414,16 +424,6 @@ class app_impl : public std::enable_shared_from_this { setup_reports_.emplace_back(what); } - std::pmr::string random_id(std::size_t n) { - std::array random{}; - factory_.random(std::span(random).first(n)); - std::pmr::string id(n, '0', memory_); - for (std::size_t i = 0; i < n; ++i) { - id[i] = protocol::id_alphabet[random[i] % protocol::id_alphabet.size()]; - } - return id; - } - [[nodiscard]] std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } std::pmr::memory_resource* memory_; diff --git a/include/webcpp/trystero/detail/clock.hpp b/include/webcpp/trystero/detail/clock.hpp new file mode 100644 index 0000000..6c2e70b --- /dev/null +++ b/include/webcpp/trystero/detail/clock.hpp @@ -0,0 +1,40 @@ +// 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_DETAIL_CLOCK_HPP +#define WEBCPP_TRYSTERO_DETAIL_CLOCK_HPP + +#include + +#include + +#include + +namespace webcpp::trystero::detail { + +/** + * A time of the backend's monotonic clock, as the core keeps it: when a relay opened, a ping left + * or a construction was made, which its rate limits and timeouts compare. + * + * Tip: the clock is the backend's, never read here; the memory backend of the tests makes it + * virtual. Its origin is the backend's, which a time point takes as the steady clock's epoch. + */ +using time_point = std::chrono::steady_clock::time_point; // lint-world: names a type only + +/** The time of the backend's monotonic clock, its `steady_now`. */ +inline time_point steady_now(backend::factory& factory) { + return factory.steady_now(); +} + +/** The time of the backend's wall clock, its `unix_now`, in whole seconds since the Unix epoch: + * what a Nostr event's `created_at` and a subscription's `since` say. */ +inline std::chrono::sys_seconds unix_now(backend::factory& factory) { + return factory.unix_now(); +} + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/connection.hpp b/include/webcpp/trystero/detail/connection.hpp index 4325191..7fa01b0 100644 --- a/include/webcpp/trystero/detail/connection.hpp +++ b/include/webcpp/trystero/detail/connection.hpp @@ -62,9 +62,16 @@ class binding; // NOLINT(cppcoreguidelines-virtual-class-destructor) * | presence(1, T), T new | recorded; a 65th distinct token ends the connection | * | presence(0, T) | forgotten; frames kept for T dropped | * | room frame, T bound | to the binding of T | - * | room frame, T kept by the app | kept: 64 per connection, all dropped 10 s after the first | + * | room frame, T kept by the app | T recorded, below 64; kept: 64 per connection, all | + * | | dropped 10 s after the first | * | room frame, any other T | dropped | * + * A room frame the app keeps advertises its token as presence does: only the remote writes to its + * connection, and its presence for a room comes once per connection, which a page can lose, since + * Chrome drops what a page sends on an answering channel as it opens (its log says "Send failed + * INVALID_STATE"). Without it the room would never bind the remote, whose frames of the room keep + * coming. + * * Tip: it holds plain pointers to its bindings, which remove themselves before they go, so that it * keeps nothing of a room's resource after the room has ended. */ @@ -175,7 +182,8 @@ class connection : public std::enable_shared_from_this { /** How many frames are kept for rooms not bound yet. */ [[nodiscard]] std::size_t kept_count() const { return kept_.size(); } - /** Whether the remote advertises the room of `token`. */ + /** Whether the remote advertises the room of `token`: by its presence, or by a room frame of + * the token that the app kept. */ [[nodiscard]] bool advertised(std::string_view token) const { return remote_tokens_.contains(token); } @@ -473,10 +481,10 @@ inline void connection::end(std::string_view reason_view) { channel_->close(); pc_->close(); // The bindings are let go before anyone is told: a room may destroy its binding, or itself, - // from inside `ended` (Trystero's clear, C/shared-peer.mjs:170-180). Every attached binding is - // told, those of the drain order first, then the others in the order they attached: an end - // from inside a drain's turn leaves waiters of that drain in no drain order. A failure may - // detach or destroy another binding, so each is looked up before its turn; one attached + // from inside `ended` (Trystero's clear, dist/shared-peer.mjs:170-180). Every attached + // binding is told, those of the drain order first, then the others in the order they attached: + // an end from inside a drain's turn leaves waiters of that drain in no drain order. A failure + // may detach or destroy another binding, so each is looked up before its turn; one attached // meanwhile finds the connection not live, and fails at once. bound_.clear(); auto order = std::exchange(drain_order_, std::pmr::deque(memory_)); @@ -529,6 +537,11 @@ inline void connection::on_message(backend::bytes&& frame) { return; } if (cb_.keeps(peer_, token) && !ended_) { + // The remote's own advertisement, before its room is told: within the bound on tokens, + // which a frame never ends the connection for. + if (!remote_tokens_.contains(token) && remote_tokens_.size() < max_remote_rooms) { + remote_tokens_.emplace(token); + } keep(token, std::move(frame)); } } @@ -540,7 +553,7 @@ inline void connection::keep(std::string_view token, backend::bytes&& frame) { } kept_.emplace_back(std::pmr::string(token, memory_), std::move(frame)); if (!kept_timer_) { - // All kept frames go 10 s after the first, as Trystero's (C/shared-peer.mjs:425-428). + // All kept frames go 10 s after the first, as in Trystero's dist/shared-peer.mjs:425-428. kept_timer_ = factory_.make_timer(memory_); kept_timer_->start(kept_frames_ttl, {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), @@ -557,7 +570,7 @@ inline void connection::keep(std::string_view token, backend::bytes&& frame) { } /** With nothing kept, the window stops, so that the next kept frame has 10 s of its own, as - * Trystero's syncDataTimers (C/shared-peer.mjs:417-422). */ + * Trystero's syncDataTimers does (dist/shared-peer.mjs:417-422). */ inline void connection::forget_kept_if_empty() { if (!kept_.empty()) { return; diff --git a/include/webcpp/trystero/detail/construction_window.hpp b/include/webcpp/trystero/detail/construction_window.hpp index 0c4c67b..5e20eb8 100644 --- a/include/webcpp/trystero/detail/construction_window.hpp +++ b/include/webcpp/trystero/detail/construction_window.hpp @@ -9,11 +9,13 @@ #include +#include + +#include + #include #include -#include #include -#include namespace webcpp::trystero::detail { @@ -30,24 +32,27 @@ class construction_window { /** No construction yet; the times are allocated in `memory`. */ construction_window(std::size_t limit, std::chrono::milliseconds window, std::pmr::memory_resource* memory) - : times_(limit, -std::numeric_limits::infinity(), memory), - window_ms_(static_cast(window.count())) {} - - /** Takes a construction at `now_ms`, or returns false and takes none when `limit` were - * allowed in the window that ends then. */ - bool take(double now_ms) { - if (times_.empty() || now_ms - times_[next_] < window_ms_) { + : times_(limit, memory), window_(window) {} + + /** Deleted: a boost::circular_buffer moves by swapping its allocator, which std::pmr's + * cannot. */ + construction_window(construction_window&&) = delete; + /** Deleted, as the move constructor is. */ + construction_window& operator=(construction_window&&) = delete; + + /** Takes a construction at `now`, or returns false and takes none when `limit` were allowed in + * the window that ends then. */ + bool take(time_point now) { + if (times_.capacity() == 0 || (times_.full() && now - times_.front() < window_)) { return false; } - times_[next_] = now_ms; - next_ = (next_ + 1) % times_.size(); + times_.push_back(now); // in the oldest's place once full return true; } private: - std::pmr::vector times_; // a ring; times_[next_] is the oldest - std::size_t next_ = 0; - double window_ms_; + boost::circular_buffer> times_; + std::chrono::milliseconds window_; }; } // namespace webcpp::trystero::detail diff --git a/include/webcpp/trystero/detail/nostr_strategy.hpp b/include/webcpp/trystero/detail/nostr_strategy.hpp index 1f01dc1..0fa4443 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -10,29 +10,124 @@ #include #include +#include #include +#include #include #include #include #include -#include +#include + +#include +#include +#include +#include #include #include #include +#include +#include #include #include #include #include +#include #include #include -#include +#include #include #include namespace webcpp::trystero::detail { +/** + * The ids of the newest Nostr events a strategy received, so that it acts on each event once: a + * relay may repeat one, and every relay of the room carries it. + * + * The strategy gives it only an id it checked to be its event's own + * (`protocol::nostr::has_own_id`), so that a relay cannot hide an event behind a forged one under + * its id: an event with any other id is acted on every time, as Trystero, which remembers none, + * acts on every event. Only an id NIP-01 defines, 64 lowercase hexadecimal digits, is remembered, + * so that what a relay makes the room hold is `capacity` ids of 64 bytes. + * + * Tip: an id is whatever a relay sends, so the index hashes it with SipHash under a key drawn when + * the strategy is made. The standard library's hashes are unseeded: ids a relay chose to fall in + * one bucket of a `std::unordered_set` would make each of its lookups walk all of them. + */ +class recent_event_ids { +public: + /** The size of the hash's key, SipHash's 128 bits. */ + static constexpr std::size_t key_size = 16; + + /** The size of an id the index remembers: NIP-01's, the SHA-256 of the event in hexadecimal. */ + static constexpr std::size_t id_size = 64; + + /** SipHash of an id under a key, which Boost.Unordered uses as it is. */ + class keyed_hash { + public: + /** SipHash's output is uniform, so Boost.Unordered takes it without mixing it again. */ + using is_avalanching = std::true_type; + + /** Hashes under `key`. */ + explicit keyed_hash(std::span key) + : hasher_(key.data(), key.size()) {} + + /** The hash of `id`. */ + std::size_t operator()(std::string_view id) const noexcept { + auto h = hasher_; + h.update(id.data(), id.size()); + return boost::hash2::get_integral_result(h); + } + + private: + boost::hash2::siphash_64 hasher_; + }; + + /** The index of the remembered ids, views of the strings the order owns. */ + using index_type = boost::unordered_flat_set, + std::pmr::polymorphic_allocator>; + + /** Remembers nothing yet: up to `capacity` ids, hashed under `key`, allocated in `memory`. */ + recent_event_ids(std::size_t capacity, std::span key, + std::pmr::memory_resource* memory) + : index_(0, keyed_hash(key), std::equal_to<>(), memory), + order_(memory), + capacity_(capacity) {} + + /** Whether `id` is new; a new one is remembered in place of the oldest beyond `capacity`, and + * one that is not NIP-01's is always new and never remembered. */ + bool remember(std::string_view id) { + if (!protocol::nostr::detail::is_nip01_hex(id)) { + return true; + } + if (index_.contains(id)) { + return false; + } + // A deque never moves what it holds, so the view stays valid until pop_front. + const std::string_view stored = order_.emplace_back(id); + index_.insert(stored); + if (order_.size() > capacity_) { + index_.erase(order_.front()); + order_.pop_front(); + } + return true; + } + + /** How many ids are remembered. */ + [[nodiscard]] std::size_t size() const { return order_.size(); } + + /** The index's hash, under its key. */ + [[nodiscard]] keyed_hash hash_function() const { return index_.hash_function(); } + +private: + index_type index_; + std::pmr::deque order_; + std::size_t capacity_; +}; + /** * Trystero's Nostr strategy: one subscription per relay to the room's root and self topics, * announcements on the root topic at Trystero's cadence, and signals published on the relay that @@ -61,15 +156,13 @@ class nostr_strategy : public std::enable_shared_from_this { using message_handler = handler; - /** Every allocation goes through `memory`, the parsed relay messages through `json`, a storage - * of that resource. */ + /** Every allocation goes through `memory`, the parsed relay messages' documents included. */ nostr_strategy(backend::factory& factory, std::span urls, std::pmr::vector topics, std::string_view announce_topic, handler announcement, message_handler on_message, logger log, - std::pmr::memory_resource* memory, boost::json::storage_ptr json) + std::pmr::memory_resource* memory) : factory_(factory), memory_(memory), - json_(std::move(json)), topics_(std::move(topics), memory), announce_topic_(announce_topic, memory), announcement_(std::move(announcement)), @@ -77,8 +170,7 @@ class nostr_strategy : public std::enable_shared_from_this { log_(std::move(log)), signer_(make_signer(factory, memory)), relays_(memory), - seen_(memory), - seen_order_(memory) { + seen_(remembered_events, draw_key(factory), memory) { relays_.reserve(urls.size()); for (const auto& url : urls) { relays_.emplace_back(url, memory); @@ -99,7 +191,7 @@ class nostr_strategy : public std::enable_shared_from_this { return; } const auto& r = relays_[index]; - if (!r.open || backoff_remaining(r) > 0) { + if (!r.open || backoff_remaining(r) > time_point::duration::zero()) { return; } r.socket->send(event_for(topic, content)); @@ -118,6 +210,9 @@ class nostr_strategy : public std::enable_shared_from_this { /** How many relays the strategy uses. */ std::size_t relay_count() const { return relays_.size(); } + /** The ids of the events it acted on, which it remembers to drop their repeats. */ + [[nodiscard]] const recent_event_ids& seen() const { return seen_; } + /** Stops announcing and reconnecting, closes each subscription and each connection. */ void stop() { stopped_ = true; @@ -136,12 +231,28 @@ class nostr_strategy : public std::enable_shared_from_this { } private: - static constexpr std::array warmup_ms{233, 533, 1333, 5333}; - static constexpr int steady_announce_ms = 60'000; - static constexpr double max_backoff_ms = 15 * 60'000; - static constexpr double first_retry_ms = 3333; - static constexpr double max_retry_ms = 60'000; - static constexpr double healthy_ms = 60'000; + /** The delays between the first announcements on a relay, Trystero's. */ + static constexpr std::array warmup{ + std::chrono::milliseconds(233), + std::chrono::milliseconds(533), + std::chrono::milliseconds(1333), + std::chrono::milliseconds(5333), + }; + /** The delay between announcements after the warm-up, and a rate-limited relay's first pause: + * Trystero's `steadyAnnounceIntervalMs`. */ + static constexpr auto steady_announce = std::chrono::milliseconds(60'000); + /** The longest pause of a rate-limited relay, Trystero's `maxRelayBackoffMs`. */ + static constexpr auto max_backoff = std::chrono::milliseconds(15 * 60'000); + /** The first bound of the reconnection delay, Trystero's `defaultRetryMs`. */ + static constexpr auto first_retry = std::chrono::milliseconds(3333); + /** The largest bound of the reconnection delay, Trystero's `maxRetryMs`. */ + static constexpr auto max_retry = std::chrono::milliseconds(60'000); + /** How long a connection stays open before the reconnection bound comes back down. */ + static constexpr auto healthy = std::chrono::milliseconds(60'000); + /** The least delay before a closed subscription is made again, Trystero's + * `subscriptionRetryMs`. */ + static constexpr auto subscription_retry = std::chrono::milliseconds(5333); + static constexpr std::size_t subscription_id_size = 64; struct relay_state { relay_state(std::string_view address, std::pmr::memory_resource* memory) @@ -153,11 +264,14 @@ class nostr_strategy : public std::enable_shared_from_this { bool open = false; bool retired = false; bool opened_before = false; - int announce_attempt = 0; - double backoff_ms = 0; - double backoff_until_ms = 0; - double retry_ms = first_retry_ms; - double opened_ms = 0; + // How many announcements went out since the cadence started, which picks the next delay. + std::size_t announce_attempt = 0; + // The pause of a rate-limited relay, zero when it is not, and when it ends. + std::chrono::milliseconds backoff{}; + time_point backoff_until{}; + // The bound of the next reconnection delay. + std::chrono::milliseconds retry = first_retry; + time_point opened{}; std::shared_ptr announce_timer; std::shared_ptr reconnect_timer; }; @@ -173,27 +287,25 @@ class nostr_strategy : public std::enable_shared_from_this { } } - std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } - - std::pmr::string make_subscription_id() { - std::array random{}; - factory_.random(random); - std::pmr::string id(random.size(), '0', memory_); - for (std::size_t i = 0; i < random.size(); ++i) { - id[i] = protocol::id_alphabet[random[i] % protocol::id_alphabet.size()]; - } - return id; + static std::array draw_key( + backend::factory& factory) { + std::array key{}; + factory.random(key); + return key; } + std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } + std::pmr::string event_for(std::string_view topic, std::string_view content) { std::array aux{}; factory_.random(aux); - return protocol::nostr::event_message(signer_, factory_.unix_seconds(), topic, content, aux, + return protocol::nostr::event_message(signer_, unix_now(factory_), topic, content, aux, memory_); } - double backoff_remaining(const relay_state& r) const { - return std::max(0.0, r.backoff_until_ms - factory_.now_ms()); + /** How long `r` still pauses, being rate-limited; zero when it does not. */ + time_point::duration backoff_remaining(const relay_state& r) const { + return std::max(time_point::duration::zero(), r.backoff_until - steady_now(factory_)); } void connect(std::size_t index) { @@ -242,12 +354,12 @@ class nostr_strategy : public std::enable_shared_from_this { void on_open(std::size_t index) { auto& r = relays_[index]; r.open = true; - r.opened_ms = factory_.now_ms(); + r.opened = steady_now(factory_); if (r.subscription.empty()) { - r.subscription = make_subscription_id(); + r.subscription = random_id(factory_, subscription_id_size, memory_); } r.socket->send(protocol::nostr::subscribe_message(r.subscription, topics_, - factory_.unix_seconds(), memory_)); + unix_now(factory_), memory_)); log_("nostr", r.opened_before ? "reconnected to " : "connected to ", r.url, ", subscribed to the room's topics"); r.opened_before = true; @@ -263,16 +375,19 @@ class nostr_strategy : public std::enable_shared_from_this { if (stopped_ || r.retired) { return; } - if (was_open && factory_.now_ms() - r.opened_ms >= healthy_ms) { - r.retry_ms = first_retry_ms; + if (was_open && steady_now(factory_) - r.opened >= healthy) { + r.retry = first_retry; } log_("nostr", was_open ? "lost " : "could not reach ", r.url, ", next attempt within ", - static_cast(r.retry_ms), " ms"); + r.retry.count(), " ms"); std::array random{}; factory_.random(random); - const double share = ((unsigned{random[0]} << 8U) | random[1]) / 65536.0; - const auto delay = std::chrono::milliseconds(static_cast(share * r.retry_ms)); - r.retry_ms = std::min(r.retry_ms * 2, max_retry_ms); + // A share of the bound in [0, 1), in steps of 1/65536, and the delay in whole + // milliseconds below it. + const std::uint16_t draw = boost::endian::load_big_u16(random.data()); + const double share = draw / 65536.0; + const auto delay = std::chrono::duration_cast(share * r.retry); + r.retry = std::min(r.retry * 2, max_retry); r.reconnect_timer = factory_.make_timer(memory_); const auto weak = weak_from_this(); r.reconnect_timer->start(delay, {std::allocator_arg, allocator(), [weak, index] { @@ -287,36 +402,35 @@ class nostr_strategy : public std::enable_shared_from_this { if (stopped_ || r.retired) { return; } - int next_ms = steady_announce_ms; - if (const double remaining = backoff_remaining(r); !r.open || remaining > 0) { - next_ms = std::max(steady_announce_ms, static_cast(remaining)); + auto next = steady_announce; + if (const auto remaining = backoff_remaining(r); + !r.open || remaining > time_point::duration::zero()) { + next = std::max(steady_announce, + std::chrono::duration_cast(remaining)); } else { r.socket->send(event_for(announce_topic_, announcement_())); - const int attempt = r.announce_attempt++; - if (std::cmp_less(attempt, warmup_ms.size())) { - next_ms = warmup_ms[attempt]; + if (const auto attempt = r.announce_attempt++; attempt < warmup.size()) { + next = warmup[attempt]; } } if (!r.announce_timer) { r.announce_timer = factory_.make_timer(memory_); } const auto weak = weak_from_this(); - r.announce_timer->start(std::chrono::milliseconds(next_ms), - {std::allocator_arg, allocator(), [weak, index] { - if (const auto self = weak.lock()) { - self->announce(index); - } - }}); + r.announce_timer->start(next, {std::allocator_arg, allocator(), [weak, index] { + if (const auto self = weak.lock()) { + self->announce(index); + } + }}); } void back_off(relay_state& r) { - r.backoff_ms = - r.backoff_ms == 0 - ? steady_announce_ms - : std::min(std::max(steady_announce_ms, r.backoff_ms * 2), max_backoff_ms); - r.backoff_until_ms = factory_.now_ms() + r.backoff_ms; + r.backoff = r.backoff == std::chrono::milliseconds::zero() + ? steady_announce + : std::min(std::max(steady_announce, r.backoff * 2), max_backoff); + r.backoff_until = steady_now(factory_) + r.backoff; log_("nostr", r.url, " rate-limits us, pausing it for ", - static_cast(r.backoff_ms / 1000), " s"); + std::chrono::duration_cast(r.backoff).count(), " s"); } static bool terminal(std::string_view reason) { @@ -343,46 +457,35 @@ class nostr_strategy : public std::enable_shared_from_this { } } - /** Whether an event id is new; a relay may repeat one, and several relays carry the same. */ - bool remember(std::string_view id) { - if (id.empty()) { - return true; - } - if (seen_.contains(id)) { - return false; - } - const auto& stored = seen_order_.emplace_back(id); // made in the deque's resource - seen_.insert(stored); - if (seen_order_.size() > remembered_events) { - seen_.erase(seen_order_.front()); - seen_order_.pop_front(); - } - return true; - } - void on_relay_message(std::size_t index, std::string_view text) { - boost::system::error_code ec; - const auto document = protocol::json::parse(text, json_, ec); - if (ec) { + // A text past its bound is dropped as a malformed one is, before it is read. + const auto document = webcpp::document::parse( + text, protocol::json::protocol_limits(protocol::nostr::max_parsed_relay_text_bytes), + std::pmr::polymorphic_allocator(memory_)); + if (!document.has_value()) { return; } - const auto message = protocol::nostr::read_relay_message(document); + const auto message = protocol::nostr::read_relay_message(document->root()); if (!message) { return; } auto& r = relays_[index]; if (const auto* e = std::get_if(&*message)) { - if (e->subscription != r.subscription || e->topic.empty()) { + if (e->subscription != r.subscription || e->topic.empty() || + std::ranges::find(topics_, e->topic) == topics_.end()) { return; } - if (std::ranges::find(topics_, e->topic) == topics_.end() || !remember(e->id)) { + // A repeat is dropped only under an id checked to be its event's own: a relay could + // otherwise send a forged event under a genuine event's id ahead of the relay that + // carries the genuine one, and have the room drop it. + if (protocol::nostr::has_own_id(*e, memory_) && !seen_.remember(e->id)) { return; } on_message_(index, e->topic, e->content); } else if (const auto* o = std::get_if(&*message)) { if (o->accepted) { - if (backoff_remaining(r) == 0) { - r.backoff_ms = 0; + if (backoff_remaining(r) == time_point::duration::zero()) { + r.backoff = std::chrono::milliseconds::zero(); } } else if (o->reason.starts_with("rate-limited:")) { back_off(r); @@ -411,8 +514,9 @@ class nostr_strategy : public std::enable_shared_from_this { if (!r.reconnect_timer) { r.reconnect_timer = factory_.make_timer(memory_); } - const auto delay = std::chrono::milliseconds( - static_cast(std::max(backoff_remaining(r), 5333.0))); + const auto delay = + std::max(subscription_retry, + std::chrono::duration_cast(backoff_remaining(r))); const auto weak = weak_from_this(); r.reconnect_timer->start(delay, {std::allocator_arg, allocator(), [weak, index] { @@ -424,23 +528,13 @@ class nostr_strategy : public std::enable_shared_from_this { if (relay.open) { relay.socket->send(protocol::nostr::subscribe_message( relay.subscription, self->topics_, - self->factory_.unix_seconds(), self->memory_)); + unix_now(self->factory_), self->memory_)); } }}); } - /** Transparent hashing, so an id read as a view is looked up without building a string. */ - struct view_hash { - using is_transparent = void; - - std::size_t operator()(std::string_view s) const noexcept { - return std::hash{}(s); - } - }; - backend::factory& factory_; std::pmr::memory_resource* memory_; - boost::json::storage_ptr json_; std::pmr::vector topics_; std::pmr::string announce_topic_; handler announcement_; @@ -448,10 +542,7 @@ class nostr_strategy : public std::enable_shared_from_this { logger log_; protocol::nostr::signer signer_; std::pmr::vector relays_; - // The ids are owned by `seen_order_`, a deque, which never moves what it holds; `seen_` indexes - // them by view. - std::pmr::unordered_set> seen_; - std::pmr::deque seen_order_; + recent_event_ids seen_; bool stopped_ = false; }; diff --git a/include/webcpp/trystero/detail/post.hpp b/include/webcpp/trystero/detail/post.hpp index d3d1469..59be3c1 100644 --- a/include/webcpp/trystero/detail/post.hpp +++ b/include/webcpp/trystero/detail/post.hpp @@ -9,10 +9,10 @@ #include -#include // lint-world: posts handlers only -#include // lint-world: binds an allocator only -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only +#include // lint-world: posts handlers only +#include // lint-world: binds an allocator only +#include // lint-world: posts handlers only +#include // lint-world: posts handlers only #include #include @@ -28,19 +28,19 @@ namespace webcpp::trystero::detail { * allocator says. So an executor that is an io_context's is posted to directly. */ template -void post_handler(const boost::asio::any_io_executor& ex, Handler&& handler) { - if (const auto* io = ex.target()) { - boost::asio::post(*io, std::forward(handler)); +void post_handler(const webcpp::asio::any_io_executor& ex, Handler&& handler) { + if (const auto* io = ex.target()) { + webcpp::asio::post(*io, std::forward(handler)); return; } - boost::asio::post(ex, std::forward(handler)); + webcpp::asio::post(ex, std::forward(handler)); } /** Posts `f` to `ex`, allocated in `memory`. */ template -void post(const boost::asio::any_io_executor& ex, std::pmr::memory_resource* memory, F&& f) { - post_handler(ex, boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), - std::forward(f))); +void post(const webcpp::asio::any_io_executor& ex, std::pmr::memory_resource* memory, F&& f) { + post_handler(ex, webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), + std::forward(f))); } } // namespace webcpp::trystero::detail diff --git a/include/webcpp/trystero/detail/random_id.hpp b/include/webcpp/trystero/detail/random_id.hpp new file mode 100644 index 0000000..cb982fb --- /dev/null +++ b/include/webcpp/trystero/detail/random_id.hpp @@ -0,0 +1,42 @@ +// 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_DETAIL_RANDOM_ID_HPP +#define WEBCPP_TRYSTERO_DETAIL_RANDOM_ID_HPP + +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** The longest id @ref random_id draws: a Nostr subscription's, 64 characters. */ +inline constexpr std::size_t max_random_id_size = 64; + +/** An id of `n` characters drawn from the backend's randomness, as `protocol::random_id` maps + * them, allocated in `memory`; `n` is at most @ref max_random_id_size. */ +inline std::pmr::string random_id(backend::factory& factory, std::size_t n, + std::pmr::memory_resource* memory) { + BOOST_ASSERT(n <= max_random_id_size); + std::array random{}; + const auto drawn = std::span(random).first(n); + factory.random(drawn); + return protocol::random_id(drawn, memory); +} + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/rebinding.hpp b/include/webcpp/trystero/detail/rebinding.hpp index 9cf527a..48d265f 100644 --- a/include/webcpp/trystero/detail/rebinding.hpp +++ b/include/webcpp/trystero/detail/rebinding.hpp @@ -11,12 +11,12 @@ #include #include +#include #include #include #include #include -#include #include #include #include @@ -30,7 +30,8 @@ class connection; constexpr std::chrono::milliseconds rebinding_step(std::chrono::milliseconds handshake_timeout, std::uint32_t ends) { BOOST_ASSERT(ends >= 1); - constexpr std::chrono::milliseconds keep_time{10'000}; // Trystero's (C/data-limits.mjs:4) + // Trystero's pendingDataTimeoutMs (dist/data-limits.mjs:4). + constexpr std::chrono::milliseconds keep_time{10'000}; constexpr std::chrono::milliseconds margin{1'000}; constexpr std::chrono::milliseconds cap{300'000}; if (handshake_timeout >= cap - margin) { @@ -50,15 +51,16 @@ class recent_challenges { static constexpr std::size_t capacity = 8; /** Keeps the bounded challenge history in the room resource. */ - explicit recent_challenges(std::pmr::polymorphic_allocator<> a) : values_(a) {} + explicit recent_challenges(std::pmr::polymorphic_allocator<> a) : values_(capacity, a) {} - /** Remembers a challenge, dropping the oldest beyond capacity. */ - void push(std::pmr::string challenge) { - values_.push_back(std::move(challenge)); - if (values_.size() > capacity) { - values_.pop_front(); - } - } + /** Deleted: a boost::circular_buffer moves by swapping its allocator, which std::pmr's + * cannot. */ + recent_challenges(recent_challenges&&) = delete; + /** Deleted, as the move constructor is. */ + recent_challenges& operator=(recent_challenges&&) = delete; + + /** Remembers a challenge, in the oldest's place beyond capacity. */ + void push(std::pmr::string challenge) { values_.push_back(std::move(challenge)); } /** Whether any remembered challenge satisfies the response matcher. */ template @@ -70,7 +72,8 @@ class recent_challenges { void clear() { values_.clear(); } private: - std::pmr::deque values_; + boost::circular_buffer> + values_; }; /** One room's history of a peer on a particular shared connection. */ diff --git a/include/webcpp/trystero/detail/replay_cache.hpp b/include/webcpp/trystero/detail/replay_cache.hpp index 89c64af..3053d69 100644 --- a/include/webcpp/trystero/detail/replay_cache.hpp +++ b/include/webcpp/trystero/detail/replay_cache.hpp @@ -11,13 +11,14 @@ #include +#include + #include #include #include #include #include #include -#include namespace webcpp::trystero::detail { @@ -33,9 +34,16 @@ namespace webcpp::trystero::detail { */ class replay_cache { public: - /** Remembers nothing yet; the digests are allocated in `memory`, up to `capacity` of them. */ + /** Remembers nothing yet; the digests are allocated in `memory`, up to `capacity` of them, as + * they come. */ replay_cache(std::size_t capacity, std::pmr::memory_resource* memory) - : digests_(memory), capacity_(capacity) {} + : digests_(capacity, memory) {} + + /** Deleted: a boost::circular_buffer moves by swapping its allocator, which std::pmr's + * cannot. */ + replay_cache(replay_cache&&) = delete; + /** Deleted, as the move constructor is. */ + replay_cache& operator=(replay_cache&&) = delete; /** Whether `opened`, an offer's or an answer's text, is among the last `capacity` used. */ [[nodiscard]] bool contains(std::string_view opened) const { @@ -43,23 +51,14 @@ class replay_cache { } /** Remembers `opened` as used, in place of the oldest once `capacity` are remembered. */ - void insert(std::string_view opened) { - if (capacity_ == 0) { - return; - } - if (digests_.size() < capacity_) { - digests_.push_back(protocol::sha256(opened)); - return; - } - digests_[next_] = protocol::sha256(opened); - next_ = (next_ + 1) % capacity_; - } + void insert(std::string_view opened) { digests_.push_back(protocol::sha256(opened)); } private: - // A ring once full, whose oldest digest is at next_. - std::pmr::vector> digests_; - std::size_t capacity_; - std::size_t next_ = 0; + using digest = std::array; + + // Its storage grows with the digests remembered, up to `capacity`: a quiet room needs a few. + boost::circular_buffer_space_optimized> + digests_; }; } // namespace webcpp::trystero::detail diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index 1bcf781..1f6bd21 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -10,9 +10,11 @@ #include #include +#include #include #include #include +#include #include #include #include @@ -20,7 +22,7 @@ #include #include -#include +#include #include #include @@ -28,14 +30,15 @@ #include #include #include -#include #include #include #include +#include #include #include #include #include +#include #include #include @@ -48,8 +51,9 @@ namespace webcpp::trystero::detail { * | announcement | the lower peer id offers on the relay that carried it; the higher one asks the | * | | other to offer by announcing itself on the other's topic, at most once a | * | | second per peer and once in 5.3 s per relay for the whole room | - * | offer | answers it, unless it already answers one, or offers itself and its id is | - * | | lower | + * | offer | answers it, unless it already answers or opens one, or offers itself and its | + * | | id is lower; the same offer through another relay, while it is opened, has the | + * | | answer sent there too | * | answer | applies it to the matching offer | * | candidate | adds it to the connection its offer id names, or keeps it until that | * | | connection has a remote description | @@ -73,14 +77,15 @@ namespace webcpp::trystero::detail { * for as long as it keeps at it, though it can neither read nor join anything, nor touch joined * peers. Only a wire that seals the offer id and both peer ids closes this. The negotiations under * way are bounded (`max_unconnected_peers`): a negotiation is dropped when its offer and its answer - * expire without a connection, an idle one gives its place to a new peer, and beyond the bound a - * new peer is refused, logged once. The connections made are bounded too - * (`max_connections_per_window`), however soon they end, since a browser counts a closed one until - * its garbage collector runs. Joined peers, memory and connections stay safe under a flood; new - * peers do not: a flooder who keeps sending fresh ids takes each place, and each connection of the - * window, as it frees, and keeps new peers out for as long as the flood lasts. A joined peer whose - * connection drops is a new peer when it comes back, with the same id, and is kept out the same - * way: there is no renegotiation of a joined peer's connection. Trystero bounds none of this. + * expire without a connection, an idle one (no connection, no offer being opened) gives its place + * to a new peer, and beyond the bound a new peer is refused, logged once. The connections made are + * bounded too (`max_connections_per_window`), however soon they end, since a browser counts a + * closed one until its garbage collector runs. Joined peers, memory and connections stay safe + * under a flood; new peers do not: a flooder who keeps sending fresh ids takes each place, and each + * connection of the window, as it frees, and keeps new peers out for as long as the flood lasts. A + * joined peer whose connection drops is a new peer when it comes back, with the same id, and is + * kept out the same way: there is no renegotiation of a joined peer's connection. Trystero bounds + * none of this. * * Tip: a peer id is copied once, into the map's key, and every asynchronous handler captures its * own copy, in the room's resource, because it may outlive the entry. The entry points a handler @@ -91,7 +96,8 @@ class signaling : public std::enable_shared_from_this { public: /** * The most negotiations a room holds at once with peers it is not connected to, each with at - * most two pending connections: a peer beyond it waits for its next announcement. + * most two pending connections: a peer beyond it waits for its next announcement, or its offer + * sent again. It bounds the offers opened at once too, one per negotiation. */ static constexpr std::size_t max_unconnected_peers = 32; @@ -131,18 +137,16 @@ class signaling : public std::enable_shared_from_this { failed; }; - /** Every allocation goes through `memory`, the parsed signals through `json`, a storage of that - * resource, but the peer connections, which are made in `connection_memory`, the app's: the + /** Every allocation goes through `memory`, the parsed signals' documents included, but the + * peer connections, which are made in `connection_memory`, the app's: the * one a negotiation opens becomes the app's connection. */ signaling(backend::factory& factory, std::shared_ptr sealer, std::string_view app_id, std::string_view room_id, std::string_view self_id, std::span ice_servers, callbacks cb, logger log, - std::pmr::memory_resource* memory, std::pmr::memory_resource* connection_memory, - boost::json::storage_ptr json) + std::pmr::memory_resource* memory, std::pmr::memory_resource* connection_memory) : factory_(factory), memory_(memory), connection_memory_(connection_memory), - json_(std::move(json)), sealer_(std::move(sealer)), app_id_(app_id, memory), room_id_(room_id, memory), @@ -157,9 +161,12 @@ class signaling : public std::enable_shared_from_this { if (closed_) { return; } - boost::system::error_code ec; - const auto document = protocol::json::parse(content, json_, ec); - const auto message = ec ? std::nullopt : protocol::read_signal(document); + // A signal past its bound is dropped as a malformed one is, before it is read. + const auto document = webcpp::document::parse( + content, protocol::json::protocol_limits(protocol::max_parsed_signal_bytes), + std::pmr::polymorphic_allocator(memory_)); + const auto message = + document.has_value() ? protocol::read_signal(document->root()) : std::nullopt; if (!message || message->peer_id == self_id_) { return; } @@ -171,14 +178,14 @@ class signaling : public std::enable_shared_from_this { if (!make_room_for(message->peer_id)) { return; } - it = peers_.try_emplace(std::pmr::string(message->peer_id, memory_), allocator()).first; + it = admit(message->peer_id); } const std::string_view peer = it->first; auto& n = it->second; if (n.connected) { return; } - n.last_ms = factory_.now_ms(); + n.last_message = steady_now(factory_); if (message->is_announcement()) { on_announcement(relay, peer, n); } else if (!message->offer.empty()) { @@ -204,7 +211,7 @@ class signaling : public std::enable_shared_from_this { void bound(std::string_view peer) { auto it = peers_.find(peer); if (it == peers_.end()) { - it = peers_.try_emplace(std::pmr::string(peer, memory_), allocator()).first; + it = admit(peer); } reset_offer(it->second); reset_answer(it->second); @@ -229,8 +236,11 @@ class signaling : public std::enable_shared_from_this { static constexpr auto answering_ttl = std::chrono::milliseconds(23'333); static constexpr auto first_offer_retry = std::chrono::milliseconds(2'000); static constexpr auto later_offer_retry = std::chrono::milliseconds(4'800); - static constexpr int max_offer_retries = 2; + static constexpr std::uint32_t max_offer_retries = 2; static constexpr std::size_t max_pending_candidates = 128; + /** The least time between two counter-announcements to one peer on a relay, and between two + * replays of an answer on a relay: Trystero's second, for each. */ + static constexpr auto per_peer_interval = std::chrono::milliseconds(1'000); /** The least time between two counter-announcements of the room on a relay: Trystero's * `announceIntervalMs`, the pace at which it announces. */ static constexpr auto counter_announce_interval = std::chrono::milliseconds(5'333); @@ -250,8 +260,12 @@ class signaling : public std::enable_shared_from_this { }; struct negotiation { - explicit negotiation(pmr_allocator a) - : offer(a), + negotiation(pmr_allocator a, std::uint64_t admitted) + : admitted(admitted), + opening_offer_id(a), + opening_offer(a), + opening_relays(a), + offer(a), offer_id(a), sealed_offer(a), offer_relays(a), @@ -264,12 +278,23 @@ class signaling : public std::enable_shared_from_this { answer_messages(a), answer_relays(a), answer_candidates(a), - answer_replayed_ms(a), - counter_announced_ms(a) {} + answer_replayed(a), + counter_announced(a) {} + // Its place in the order the room took its negotiations in: of two idle as long, the one + // taken first gives its place first, and an opened offer finds by it the very negotiation + // it came to, not a later one with the same peer. + std::uint64_t admitted; bool connected = false; // When the peer last sent a message, for the eviction of an idle negotiation. - double last_ms = 0; + time_point last_message{}; + // The peer's offer the sealer is opening, one at a time, as Trystero answers one at a + // time: its id, its sealed text, empty when none is being opened, and the relays it came + // through, where the answer goes. Until it is opened, the negotiation is not idle, and + // keeps its place. + std::pmr::string opening_offer_id; + std::pmr::string opening_offer; + std::pmr::set opening_relays; // Whether a signal of this negotiation that did not open was reported. bool failed_open_reported = false; // Whether an offer or an answer of this negotiation that the room had used before was @@ -285,7 +310,7 @@ class signaling : public std::enable_shared_from_this { offer_candidates; // plaintext, gathered before the offer went out std::shared_ptr offer_expiry; std::pmr::map> offer_retry; - std::pmr::map offer_retries; + std::pmr::map offer_retries; // Our answer to their offer. side answer; std::pmr::string answered_offer_id; @@ -296,12 +321,14 @@ class signaling : public std::enable_shared_from_this { std::pmr::set answer_relays; std::pmr::vector answer_candidates; // plaintext, gathered before the answer went out - std::pmr::map answer_replayed_ms; + std::pmr::map answer_replayed; std::shared_ptr answer_expiry; // Counter-announcements, per relay. - std::pmr::map counter_announced_ms; + std::pmr::map counter_announced; }; + using negotiations = std::pmr::map>; + pmr_allocator allocator() const { return {memory_}; } std::pmr::string copy(std::string_view text) const { return std::pmr::string(text, memory_); } @@ -316,45 +343,62 @@ class signaling : public std::enable_shared_from_this { return protocol::peer_topic(app_id_, room_id_, peer, memory_); } - std::pmr::string make_id(std::size_t n) { - std::array random{}; - factory_.random(std::span(random).first(n)); - std::pmr::string id(n, '0', memory_); - for (std::size_t i = 0; i < n; ++i) { - id[i] = protocol::id_alphabet[random[i] % protocol::id_alphabet.size()]; - } - return id; - } - negotiation* find(std::string_view peer) { const auto it = peers_.find(peer); return it == peers_.end() ? nullptr : &it->second; } + /** The negotiation with `peer` that the room took in `admitted`-th, if it still holds it. */ + negotiation* find(std::string_view peer, std::uint64_t admitted) { + auto* n = find(peer); + return n != nullptr && n->admitted == admitted ? n : nullptr; + } + + /** Starts a negotiation with `peer`, which has none. */ + negotiations::iterator admit(std::string_view peer) { + return peers_.try_emplace(std::pmr::string(peer, memory_), allocator(), admissions_++) + .first; + } + + /** + * Whether a negotiation waits on nothing: it is not connected, holds no connection, and no + * offer of its peer is being opened. + */ + static bool idle(const negotiation& n) { + return !n.connected && !n.offer.pc && !n.answer.pc && n.opening_offer.empty(); + } + /** * Whether a negotiation may start with a new peer: the room holds fewer than - * `max_unconnected_peers` unconnected negotiations, or one of them holds no connection and is - * dropped, the one idle longest. Otherwise the peer is refused, and logged once. + * `max_unconnected_peers` unconnected negotiations, or one of them is idle and is dropped, the + * one idle longest, and of those idle as long the one taken first. Otherwise the peer is + * refused, and logged once. + * + * Tip: the sealer opens an offer in a step that takes its time (Web Crypto's, in a page), and + * new ids keep arriving meanwhile, at one instant of a page's coarse clock, where no + * negotiation is idle longer than another: an offer being opened holds its negotiation's + * place, so that none of them has the room drop it unopened. */ bool make_room_for(std::string_view peer) { std::size_t unconnected = 0; - auto idle = peers_.end(); + auto evicted = peers_.end(); for (auto it = peers_.begin(); it != peers_.end(); ++it) { const auto& n = it->second; if (n.connected) { continue; } ++unconnected; - if (!n.offer.pc && !n.answer.pc && - (idle == peers_.end() || n.last_ms < idle->second.last_ms)) { - idle = it; + if (idle(n) && (evicted == peers_.end() || + std::tie(n.last_message, n.admitted) < + std::tie(evicted->second.last_message, evicted->second.admitted))) { + evicted = it; } } if (unconnected < max_unconnected_peers) { return true; } - if (idle != peers_.end()) { - peers_.erase(idle); + if (evicted != peers_.end()) { + peers_.erase(evicted); return true; } if (first_refusal(peer)) { @@ -381,7 +425,7 @@ class signaling : public std::enable_shared_from_this { * null beyond it, logged once per peer, or when the backend makes none, reported. */ std::shared_ptr make_connection(std::string_view peer) { - if (!constructions_.take(factory_.now_ms())) { + if (!constructions_.take(steady_now(factory_))) { if (first_refusal(peer)) { log_("signal", "refusing ", peer, ": ", max_connections_per_window, " connections were made in the last ", offer_ttl.count(), @@ -396,10 +440,9 @@ class signaling : public std::enable_shared_from_this { return pc; } - /** Drops a negotiation that holds no connection any more and is not connected. */ + /** Drops a negotiation that is idle: no connection, and no offer being opened. */ void drop_if_done(std::string_view peer) { - if (const auto it = peers_.find(peer); it != peers_.end() && !it->second.connected && - !it->second.offer.pc && !it->second.answer.pc) { + if (const auto it = peers_.find(peer); it != peers_.end() && idle(it->second)) { peers_.erase(it); } } @@ -412,20 +455,19 @@ class signaling : public std::enable_shared_from_this { if (n.offer.pc) { return; } - const double now = factory_.now_ms(); - if (const auto it = n.counter_announced_ms.find(relay); - it != n.counter_announced_ms.end() && now - it->second < 1000) { + const auto now = steady_now(factory_); + if (const auto it = n.counter_announced.find(relay); + it != n.counter_announced.end() && now - it->second < per_peer_interval) { return; } // Room-wide too: a flood of fresh ids below ours must not have the relay rate-limit // the room. A peer not asked offers on our next announcement instead. - if (const auto it = counter_announced_ms_.find(relay); - it != counter_announced_ms_.end() && - now - it->second < static_cast(counter_announce_interval.count())) { + if (const auto it = counter_announced_.find(relay); + it != counter_announced_.end() && now - it->second < counter_announce_interval) { return; } - counter_announced_ms_[relay] = now; - n.counter_announced_ms[relay] = now; + counter_announced_[relay] = now; + n.counter_announced[relay] = now; log_("signal", "announcement from ", peer, ": their id is lower, asking them to offer"); cb_.publish(relay, peer_topic(peer), protocol::write_signal({.peer_id = self_id_}, {}, memory_)); @@ -444,7 +486,7 @@ class signaling : public std::enable_shared_from_this { } void start_offer(std::string_view peer, negotiation& n) { - n.offer_id = make_id(protocol::offer_id_size); + n.offer_id = random_id(factory_, protocol::offer_id_size, memory_); n.offer.pc = make_connection(peer); if (!n.offer.pc) { reset_offer(n); @@ -572,31 +614,56 @@ class signaling : public std::enable_shared_from_this { if (n.offer.pc && self_id_ < peer) { return; // we lead; our offer stands } + // One offer of a peer is opened at a time, as Trystero answers one at a time, ignoring + // another until the first fails (dist/signal-handler.mjs:264-323): so offers sent in one + // name hold one open and one copy. The same offer through another relay has the answer + // sent there too, as Trystero's replay records its relay. + if (!n.opening_offer.empty()) { + if (offer == n.opening_offer && offer_id == n.opening_offer_id) { + n.opening_relays.insert(relay); + } + return; + } // Nothing changes until the offer opens with the room key: a forged one, which anyone who // reads the relays can send in any peer's name, makes no connection and resets no offer. + // Until it opens, the negotiation keeps its place. + n.opening_offer_id = offer_id; + n.opening_offer = offer; + n.opening_relays.insert(relay); const auto weak = weak_from_this(); - sealer_->open( - offer, bind( - [weak, relay, peer = copy(peer), offer_id = copy(offer_id), - offer = copy(offer)](boost::system::error_code ec, std::string_view sdp) { - if (const auto self = weak.lock()) { - self->on_offer_opened(relay, peer, offer_id, offer, ec, sdp); - } - })); + sealer_->open(n.opening_offer, bind( + [weak, peer = copy(peer), admitted = n.admitted]( + boost::system::error_code ec, std::string_view sdp) { + if (const auto self = weak.lock()) { + self->on_offer_opened(peer, admitted, ec, sdp); + } + })); } /** - * Answers an offer the sealer opened: makes the answering connection and applies the offer as - * its remote description. An offer that did not open changes nothing. + * Answers the offer the sealer opened for the negotiation taken in `admitted`-th: makes the + * answering connection and applies the offer as its remote description, and the next offer of + * the peer may be opened. An offer that did not open changes nothing, nor one whose + * negotiation the room no longer holds: the peer left, or the room closed. */ - void on_offer_opened(std::size_t relay, std::string_view peer, std::string_view offer_id, - std::string_view offer, boost::system::error_code ec, - std::string_view sdp) { - auto* found = find(peer); - if (found == nullptr || found->connected) { + void on_offer_opened(std::string_view peer, std::uint64_t admitted, + boost::system::error_code ec, std::string_view sdp) { + auto* found = find(peer, admitted); + if (found == nullptr) { return; } auto& n = *found; + // Taken out of the negotiation, which then opens none: the same resource on both sides, + // so each swap only exchanges what the two hold. + std::pmr::string offer_id(memory_); + std::pmr::string offer(memory_); + std::pmr::set relays(memory_); + offer_id.swap(n.opening_offer_id); + offer.swap(n.opening_offer); + relays.swap(n.opening_relays); + if (n.connected) { + return; + } if (ec) { failed_open(peer, n, "offer"); return; @@ -608,21 +675,35 @@ class signaling : public std::enable_shared_from_this { replayed(peer, n, "offer"); return; } - auto made = make_connection(peer); + const auto made = make_connection(peer); if (!made) { return; } + start_answer(peer, n, made, std::move(offer_id), std::move(offer), relays, sdp); + } + + /** + * Answers the offer `offer_id`, sealed as `offer` and opened as `sdp`, through the connection + * `pc`: it becomes the negotiation's answering one, the offer its remote description, and the + * answer goes through every relay the offer came through. + */ + void start_answer(std::string_view peer, negotiation& n, + const std::shared_ptr& pc, + std::pmr::string offer_id, std::pmr::string offer, + const std::pmr::set& relays, std::string_view sdp) { used_.insert(sdp); if (n.offer.pc) { reset_offer(n); } log_("signal", "offer ", offer_id, " from ", peer); - n.answer.pc = std::move(made); - n.answered_offer_id = offer_id; - n.answered_offer = offer; - n.answer_relays.insert(relay); - n.answer_replayed_ms[relay] = factory_.now_ms(); - const auto pc = n.answer.pc; + n.answer.pc = pc; + n.answered_offer_id = std::move(offer_id); + n.answered_offer = std::move(offer); + const auto now = steady_now(factory_); + for (const auto relay : relays) { + n.answer_relays.insert(relay); + n.answer_replayed[relay] = now; + } const auto weak = weak_from_this(); pc->set_handlers({ .ice_candidate = bind( @@ -672,13 +753,13 @@ class signaling : public std::enable_shared_from_this { /** The same offer again: Trystero replays its answer on that relay, at most once a second. */ void replay_answer(std::size_t relay, std::string_view peer, std::string_view offer_id, std::string_view offer, negotiation& n) { - const double now = factory_.now_ms(); - const auto last = n.answer_replayed_ms.find(relay); + const auto now = steady_now(factory_); + const auto last = n.answer_replayed.find(relay); if (!n.answer.pc || n.answered_offer != offer || n.answered_offer_id != offer_id || - (last != n.answer_replayed_ms.end() && now - last->second < 1000)) { + (last != n.answer_replayed.end() && now - last->second < per_peer_interval)) { return; } - n.answer_replayed_ms[relay] = now; + n.answer_replayed[relay] = now; n.answer_relays.insert(relay); const auto topic = peer_topic(peer); for (const auto& message : n.answer_messages) { @@ -746,6 +827,7 @@ class signaling : public std::enable_shared_from_this { .peer_id = self_id_, .offer_id = m->answered_offer_id, .answer = sealed, + .answering = true, }, {}, memory_)); m->answer_sent = true; @@ -847,10 +929,11 @@ class signaling : public std::enable_shared_from_this { } log_("signal", "could not open the ", what, " from ", peer, ": another password, or forged in its name; ignored"); - const double now = factory_.now_ms(); - const auto interval = static_cast(failed_open_report_interval.count()); - if (unreported_failed_opens_ == 0 && now - failed_open_reported_ms_ >= interval) { - failed_open_reported_ms_ = now; + const auto now = steady_now(factory_); + if (unreported_failed_opens_ == 0 && + (!failed_open_reported_ || + now - *failed_open_reported_ >= failed_open_report_interval)) { + failed_open_reported_ = now; cb_.failed(peer, make_error_code(error::wrong_password), {}); return; } @@ -858,8 +941,11 @@ class signaling : public std::enable_shared_from_this { return; // the report of the interval is already due } failed_open_report_ = factory_.make_timer(memory_); - const auto delay = std::chrono::milliseconds( - static_cast(std::max(0.0, failed_open_reported_ms_ + interval - now))); + // The interval runs from the last report, which there always is by now. + const auto due = failed_open_reported_.value_or(now) + failed_open_report_interval; + const auto delay = + std::max(std::chrono::milliseconds::zero(), + std::chrono::duration_cast(due - now)); failed_open_report_->start(delay, bind([weak = weak_from_this()] { if (const auto self = weak.lock()) { self->report_failed_opens(); @@ -873,11 +959,13 @@ class signaling : public std::enable_shared_from_this { if (closed_ || count == 0) { return; } - failed_open_reported_ms_ = factory_.now_ms(); + failed_open_reported_ = steady_now(factory_); std::pmr::string what(memory_); protocol::json::append_integer(what, static_cast(count)); what += " more peers sent signals that did not open with the room key, in the last "; - protocol::json::append_integer(what, failed_open_report_interval.count() / 1000); + protocol::json::append_integer( + what, + std::chrono::duration_cast(failed_open_report_interval).count()); what += " s: another password, or forged in their names"; cb_.failed({}, make_error_code(error::wrong_password), what); } @@ -1015,6 +1103,7 @@ class signaling : public std::enable_shared_from_this { .peer_id = self->self_id_, .offer_id = m->answered_offer_id, .candidate = sealed, + .answering = true, }, {}, self->memory_)); } @@ -1130,14 +1219,13 @@ class signaling : public std::enable_shared_from_this { n.answer_messages.clear(); n.answer_relays.clear(); n.answer_candidates.clear(); - n.answer_replayed_ms.clear(); + n.answer_replayed.clear(); n.answer_expiry.reset(); } backend::factory& factory_; std::pmr::memory_resource* memory_; std::pmr::memory_resource* connection_memory_; - boost::json::storage_ptr json_; std::shared_ptr sealer_; std::pmr::string app_id_; std::pmr::string room_id_; @@ -1145,16 +1233,17 @@ class signaling : public std::enable_shared_from_this { std::pmr::vector ice_servers_; callbacks cb_; logger log_; - std::pmr::map> peers_; + negotiations peers_; + std::uint64_t admissions_ = 0; // the negotiations the room took in, the next one's place std::pmr::deque refused_{memory_}; construction_window constructions_{max_connections_per_window, offer_ttl, memory_}; - std::pmr::map counter_announced_ms_{memory_}; // per relay + std::pmr::map counter_announced_{memory_}; // per relay replay_cache used_{remembered_descriptions, memory_}; std::size_t failed_opens_ = 0; - // Negotiations whose failed open waits for the next report, when it was last made, and the - // timer of the next. + // Negotiations whose failed open waits for the next report, when it was last made (never + // yet, when empty), and the timer of the next. std::size_t unreported_failed_opens_ = 0; - double failed_open_reported_ms_ = -std::numeric_limits::infinity(); + std::optional failed_open_reported_; std::shared_ptr failed_open_report_; std::size_t replayed_ = 0; bool closed_ = false; diff --git a/include/webcpp/trystero/native/timer.hpp b/include/webcpp/trystero/detail/timer.hpp similarity index 66% rename from include/webcpp/trystero/native/timer.hpp rename to include/webcpp/trystero/detail/timer.hpp index f2095a2..9d51362 100644 --- a/include/webcpp/trystero/native/timer.hpp +++ b/include/webcpp/trystero/detail/timer.hpp @@ -4,16 +4,18 @@ // 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 +#ifndef WEBCPP_TRYSTERO_DETAIL_TIMER_HPP +#define WEBCPP_TRYSTERO_DETAIL_TIMER_HPP #include #include +#include + +#include // lint-world: names the executor only +#include // lint-world: binds an allocator only +#include // lint-world: Trystero's timers -#include // lint-world: Trystero's timers -#include // lint-world: allocates timer waits -#include // lint-world: Trystero's timers #include #include @@ -22,27 +24,27 @@ #include #include -namespace webcpp::trystero::native { +namespace webcpp::trystero::detail { /** - * An Asio timer whose waits are allocated in the room's resource. + * The backend's timer over the steady timer of webcpp::asio, on both targets, whose waits are + * allocated in the resource it is given. * * 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. + * it, by changing the number or freeing it, before its handler runs. On emscripten the wait is in + * the reactor's timer queue, so it fires only while the program runs its io_context. */ -class timer : public trystero::backend::timer { +class timer : public 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. + * @param memory The resource each wait is allocated in, the room's for a room's timer; it must + * outlive the timer's pending waits. */ - timer(const boost::asio::any_io_executor& ex, std::pmr::memory_resource* memory) + timer(const webcpp::asio::any_io_executor& ex, std::pmr::memory_resource* memory) : timer_(ex), memory_(memory), waits_( @@ -58,7 +60,7 @@ class timer : public trystero::backend::timer { 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( + timer_.async_wait(webcpp::asio::bind_allocator( std::pmr::polymorphic_allocator<>(memory_), [waits = std::weak_ptr(waits_), wait, fire = std::move(fire)](boost::system::error_code ec) mutable { @@ -75,12 +77,12 @@ class timer : public trystero::backend::timer { } private: - boost::asio::steady_timer timer_; // lint-world: Trystero's timers + webcpp::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 +} // namespace webcpp::trystero::detail #endif diff --git a/include/webcpp/trystero/error.hpp b/include/webcpp/trystero/error.hpp index 81345a4..dc0f461 100644 --- a/include/webcpp/trystero/error.hpp +++ b/include/webcpp/trystero/error.hpp @@ -60,8 +60,8 @@ enum class error { /** The browser or the native stack refused an operation. */ backend_failure, /** - * The room's configuration names something no backend can use, as an ICE server whose URL - * WebRTC refuses; the room goes on without it, and `room::on_error` reports it with no peer. + * The app's configuration holds something it cannot use, as an ICE server whose URL WebRTC + * refuses; the app goes on without it, and `app::on_error` reports it with no peer. */ invalid_configuration, /** The app already holds a room of that id; a room is joined once per app. */ diff --git a/include/webcpp/trystero/json_resource.hpp b/include/webcpp/trystero/json_resource.hpp deleted file mode 100644 index 7cb8d2f..0000000 --- a/include/webcpp/trystero/json_resource.hpp +++ /dev/null @@ -1,98 +0,0 @@ -// 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_JSON_RESOURCE_HPP -#define WEBCPP_TRYSTERO_JSON_RESOURCE_HPP - -#include - -#include - -#include -#include - -/** - * Boost.JSON's memory resource over a `std::pmr` one: what a room's JSON values allocate through. - * - * Tip: Boost.JSON's `storage_ptr` holds a `boost::container::pmr::memory_resource`, whose base - * class is header-only, while `boost::container::pmr`'s global resources are compiled; the adapter - * needs only the base. - */ -namespace webcpp::trystero { - -/** - * A `boost::container::pmr::memory_resource` that allocates from a `std::pmr::memory_resource`. - * - * A room makes one over `room_options::memory`, or the app's resource when null, as the JSON - * storage every JSON value of the room is - * allocated in: what it parses from a relay, a signal or the handshake, and the - * `boost::json::value` an action's handler receives. The storage is counted, so a value a handler - * keeps keeps it alive; Boost.JSON allocates that count with `operator new`, once per room. - * - * @see "Allocation", in the guide. - */ -class json_resource final : public boost::container::pmr::memory_resource { -public: - /** - * Constructs a resource that allocates from `upstream`. - * - * @param upstream The resource every allocation goes to; it must outlive this resource and - * every value allocated in it. - */ - explicit json_resource(std::pmr::memory_resource* upstream) noexcept : upstream_(upstream) {} - - /** - * The resource this one allocates from. - * - * @return The `upstream` it was constructed with. - */ - [[nodiscard]] std::pmr::memory_resource* upstream() const noexcept { return upstream_; } - -protected: - /** - * Allocates from the upstream resource. - * - * @param bytes The size. - * @param alignment The alignment. - * @return The storage, from the upstream resource. - */ - void* do_allocate(std::size_t bytes, std::size_t alignment) override { - return upstream_->allocate(bytes, alignment); - } - - /** - * Gives storage back to the upstream resource. - * - * @param pointer The storage, which `do_allocate` returned. - * @param bytes The size it was allocated with. - * @param alignment The alignment it was allocated with. - */ - void do_deallocate(void* pointer, std::size_t bytes, std::size_t alignment) override { - upstream_->deallocate(pointer, bytes, alignment); - } - - /** - * Whether `other` is this resource: it is equal to itself alone. - * - * Tip: another adapter over the same upstream would do too, but telling one apart from another - * resource needs RTTI, which a user may build without; an unequal resource costs Boost.JSON a - * copy where it could have moved. - * - * @param other The resource to compare with. - * @return Whether `other` is this resource. - */ - [[nodiscard]] bool do_is_equal( - const boost::container::pmr::memory_resource& other) const noexcept override { - return this == &other; - } - -private: - std::pmr::memory_resource* upstream_; -}; - -} // namespace webcpp::trystero - -#endif diff --git a/include/webcpp/trystero/native/backend.hpp b/include/webcpp/trystero/native/backend.hpp deleted file mode 100644 index e8a42c8..0000000 --- a/include/webcpp/trystero/native/backend.hpp +++ /dev/null @@ -1,220 +0,0 @@ -// 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_BACKEND_HPP -#define WEBCPP_TRYSTERO_NATIVE_BACKEND_HPP - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include // lint-world: posts handlers only -#include // lint-world: the relays' TLS - -#include -#include -#include -#include -#include -#include -#include - -/** - * The native target: the backend interface over libdatachannel for WebRTC, Boost.Beast for the - * relays' WebSockets, OpenSSL for TLS and AES-GCM, and Asio for timers. Everything it reports runs - * on the executor it is given; the application runs that executor's context, blocking on it or - * polling it. - */ -namespace webcpp::trystero::native { - -// 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. -#ifndef WEBCPP_TRYSTERO_NO_EXCEPTIONS - -/** - * What a native backend makes its peer connections with, beside the app's - * `app_config::ice_servers`. - * - * @see "The native backend", in the guide. - */ -struct backend_config { - /** - * The local address every peer connection binds to, as `"127.0.0.1"`; empty means every - * interface but the loopback. - * - * Bound to the loopback, the peers of one machine connect with no other network, which a test - * wants; a peer bound there reaches no other machine. - */ - std::pmr::string bind_address = {}; - - /** - * The most peer connections the backend makes in any minute, for every app and room it serves - * together: beyond, it makes none, and a room reports each negotiation it cannot start. - * - * Tip: a room makes at most 64 in any 57 s however its peers behave, so the default lets four - * rooms do so at once; an application with more rooms raises it. - */ - std::size_t max_peer_connections_per_minute = 256; - - /** What the relays' WebSockets tolerate of a relay that stops reading or answering. */ - websocket_limits relay_limits = {}; -}; - -/** - * The native factory: one per application, beside the executor it runs on. - * - * It makes peer connections, data channels and received frames in `app_config::memory`, and - * WebSockets, sealers and room timers in the room's effective `room_options::memory`. Objects - * and their handlers use the resource supplied to their factory method. What libdatachannel and - * OpenSSL allocate stays theirs. Its peer connections need exceptions: without them - * (`WEBCPP_TRYSTERO_NO_EXCEPTIONS`) it does not exist. - * - * @see "The native backend", in the guide. - */ -class backend : public trystero::backend::factory { -public: - /** - * A backend whose TLS verifies relays against the system's certificate authorities. - * - * @param ex The executor everything the backend reports runs on. - * @param config What its peer connections are made with; the default binds them to no address. - * @throws std::exception A `boost::system::system_error` when OpenSSL cannot make the TLS - * context or load the system's certificate authorities. - */ - explicit backend(boost::asio::any_io_executor ex, backend_config config = {}) - : ex_(std::move(ex)), - config_(std::move(config)), - constructions_(config_.max_peer_connections_per_minute, std::chrono::minutes(1), - std::pmr::get_default_resource()), - tls_(boost::asio::ssl::context::tls_client) { - tls_.set_default_verify_paths(); - tls_.set_verify_mode(boost::asio::ssl::verify_peer); - } - - /** - * The TLS configuration of the relays' connections, for an application with authorities of its - * own. - * - * @return The context every `wss://` connection of the backend is made with. - */ - boost::asio::ssl::context& tls_context() { return tls_; } - - /** - * Opens a WebSocket to a relay over Boost.Beast, with @ref connect_websocket. - * - * @param url The relay's `ws://` or `wss://` URL, read during the call. - * @param h What the WebSocket reports. - * @param memory The room's resource, which the WebSocket, its handlers and its queued texts are - * allocated in. - * @return The WebSocket. - */ - std::shared_ptr connect( - std::string_view url, trystero::backend::websocket::handlers h, - std::pmr::memory_resource* memory) override { - return connect_websocket(ex_, tls_, url, std::move(h), memory, config_.relay_limits); - } - - /** - * Makes a peer connection of libdatachannel, bound to `backend_config::bind_address`. - * - * @param servers The STUN and TURN servers, read during the call. - * @param memory The app's resource, which the connection, its channels, its handlers and its - * texts are allocated in. - * @return The connection, or null when the backend made - * `backend_config::max_peer_connections_per_minute` in the last minute, or when libdatachannel - * refuses to make one, by throwing. - */ - std::shared_ptr make_peer_connection( - std::span servers, - std::pmr::memory_resource* memory) override { - if (!constructions_.take(now_ms())) { - return nullptr; - } - try { - return peer_connection::create(ex_, servers, config_.bind_address, memory); - } catch (...) { - return nullptr; - } - } - - /** - * Makes an Asio timer on the backend's executor. - * - * @param memory The room's resource, which the timer and its waits are allocated in. - * @return The timer, not started. - */ - std::shared_ptr make_timer( - std::pmr::memory_resource* memory) override { - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), ex_, memory); - } - - /** - * Makes a sealer over OpenSSL's AES-256-GCM. - * - * @param key The raw AES-256 key. - * @param memory The room's resource, which the sealer, its texts and its completions are - * allocated in. - * @return The sealer. - */ - std::shared_ptr make_sealer( - std::array key, std::pmr::memory_resource* memory) override { - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), ex_, key, - memory); - } - - /** - * Fills `out` from OpenSSL's random generator; the program aborts when it has no secure - * randomness. - * - * @param out The bytes to fill. - */ - void random(std::span out) override { - const auto size = static_cast(out.size()); - if (RAND_bytes(out.data(), size) != 1) { // lint-world: Trystero's randomness - std::abort(); // no secure randomness: nothing is safe - } - } - - /** - * Seconds since the Unix epoch, from the system's wall clock. - * - * @return The current time, in whole seconds. - */ - std::int64_t unix_seconds() override { - const auto now = std::chrono::system_clock::now(); // lint-world: Nostr's created_at - return std::chrono::duration_cast(now.time_since_epoch()).count(); - } - - /** - * Milliseconds from the standard library's steady clock. - * - * @return The current time, in milliseconds since the clock's epoch. - */ - double now_ms() override { - const auto now = std::chrono::steady_clock::now(); // lint-world: Trystero's timing - return std::chrono::duration(now.time_since_epoch()).count(); - } - -private: - boost::asio::any_io_executor ex_; - backend_config config_; - trystero::detail::construction_window constructions_; - boost::asio::ssl::context tls_; -}; - -#endif // WEBCPP_TRYSTERO_NO_EXCEPTIONS - -} // namespace webcpp::trystero::native - -#endif diff --git a/include/webcpp/trystero/native/data_channel.hpp b/include/webcpp/trystero/native/data_channel.hpp deleted file mode 100644 index b4f521c..0000000 --- a/include/webcpp/trystero/native/data_channel.hpp +++ /dev/null @@ -1,302 +0,0 @@ -// 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_DATA_CHANNEL_HPP -#define WEBCPP_TRYSTERO_NATIVE_DATA_CHANNEL_HPP - -#include - -// libdatachannel reports errors by throwing, and the data channel over it catches them: it exists -// only with exceptions, and without them (WEBCPP_TRYSTERO_NO_EXCEPTIONS) this header declares -// nothing. -#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 -#include - -namespace webcpp::trystero::native { - -/** - * A data channel of libdatachannel, the native `RTCDataChannel`. - * - * Its events arrive on libdatachannel's threads; each is posted to the executor and handled there, - * through a weak reference, so a late event for a destroyed channel does nothing. It exists only - * with exceptions: libdatachannel reports errors by throwing. - * - * 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. 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 - * touches no resource of the room, and its posts carry Asio's default allocator. - */ -class data_channel : public backend::data_channel, - public std::enable_shared_from_this { - struct private_tag { - explicit private_tag() = default; - }; - -public: - /** - * Wraps a channel of libdatachannel, and takes over its events. - * - * @param ex The executor every handler of the channel runs on. - * @param channel libdatachannel's channel. - * @param memory The resource the wrapper, its handlers and its frames are allocated in. - * @return The channel. - */ - // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - static std::shared_ptr create(boost::asio::any_io_executor ex, - std::shared_ptr channel, - std::pmr::memory_resource* memory) { - // NOLINTEND(performance-unnecessary-value-param) - auto self = std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), - private_tag{}, std::move(ex), - std::move(channel), memory); - self->start(); - return self; - } - - /** - * Constructs the wrapper; only `create` can, which then takes over the channel's events. - * - * @param ex The executor every handler of the channel runs on. - * @param channel libdatachannel's channel. - * @param memory The resource its handlers and its frames are allocated in. - */ - 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), - pending_(memory), - pending_timer_(ex_, memory) {} - - /** Destroys the wrapper, which closes the channel without reporting the close. */ - ~data_channel() override { - channel_->resetCallbacks(); - // A channel whose connection is gone may refuse to close, which leaves nothing to do. - try { - channel_->close(); - } catch (...) { // NOLINT(bugprone-empty-catch) - } - } - - /** - * Replaces the handlers, kept in a shared object so that one replacing them during its own call - * outlives the call. - * - * @param h The new handlers, kept in the channel's resource. - */ - 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 Whether this wrapper has not closed and libdatachannel's channel is open. - */ - 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 - * event reports the close. - * - * @param frame The message, read during the call. - */ - void send(std::span frame) override { - // A channel closed in between refuses the frame, and its close event reports it. - try { - if (is_open()) { - channel_->send(reinterpret_cast(frame.data()), frame.size()); - } - } catch (...) { // NOLINT(bugprone-empty-catch) - } - } - - /** - * The bytes queued to send. - * - * @return libdatachannel's `bufferedAmount()`. - */ - std::size_t buffered_amount() const override { return channel_->bufferedAmount(); } - - /** 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(); - } catch (...) { // NOLINT(bugprone-empty-catch) - } - } - -private: - /** Posts `f` from one of libdatachannel's threads to the executor, where it runs on this - * channel if the channel still exists then. */ - template - static void post_to(const boost::asio::any_io_executor& ex, - const std::weak_ptr& weak, F f) { - boost::asio::post(ex, [weak, f = std::move(f)]() mutable { - if (const auto self = weak.lock()) { - f(*self); - } - }); - } - - void start() { - const std::weak_ptr weak = shared_from_this(); - const auto ex = ex_; - channel_->setBufferedAmountLowThreshold(low_threshold); - channel_->onOpen( - [weak, ex] { post_to(ex, weak, [](data_channel& self) { self.on_open(); }); }); - channel_->onMessage([weak, ex](rtc::message_variant message) { - auto* binary = std::get_if(&message); - // Trystero frames are binary, and none is larger than the largest room frame. - if (binary == nullptr || binary->size() > protocol::max_room_frame_bytes) { - return; - } - post_to(ex, weak, - [binary = std::move(*binary)](data_channel& self) { self.on_message(binary); }); - }); - channel_->onClosed( - [weak, ex] { post_to(ex, weak, [](data_channel& self) { self.on_closed(); }); }); - channel_->onBufferedAmountLow( - [weak, ex] { post_to(ex, weak, [](data_channel& self) { self.on_drained(); }); }); - } - - // The handlers run from a copy of the shared object, which a handler may replace. - - void on_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 || !pending_.empty()) && pending_.size() >= max_pending_frames) { - close(); - return; - } - backend::bytes frame(binary.size(), memory_); - std::memcpy(frame.data(), binary.data(), binary.size()); - 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(); - } - } - } - - void on_drained() { - if (const auto h = h_; h && h->buffered_amount_low) { - h->buffered_amount_low(); - } - } - - boost::asio::any_io_executor ex_; - 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 - -#endif // WEBCPP_TRYSTERO_NO_EXCEPTIONS - -#endif diff --git a/include/webcpp/trystero/native/peer_connection.hpp b/include/webcpp/trystero/native/peer_connection.hpp deleted file mode 100644 index 0ee5723..0000000 --- a/include/webcpp/trystero/native/peer_connection.hpp +++ /dev/null @@ -1,384 +0,0 @@ -// 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_PEER_CONNECTION_HPP -#define WEBCPP_TRYSTERO_NATIVE_PEER_CONNECTION_HPP - -#include - -// libdatachannel reports errors by throwing, and the peer connection over it catches them: it -// exists only with exceptions, and without them (WEBCPP_TRYSTERO_NO_EXCEPTIONS) this header -// declares nothing. -#ifndef WEBCPP_TRYSTERO_NO_EXCEPTIONS - -#include -#include -#include -#include -#include -#include -#include - -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::native { - -/** - * A peer connection of libdatachannel, the native `RTCPeerConnection`, with its negotiation driven - * by the signaling. - * - * Automatic negotiation is off, so an offer or an answer exists only when `set_local_description` - * asks for one, as in the browser. It exists only with exceptions: libdatachannel reports errors - * by throwing. - * - * | libdatachannel | Here | - * | events, on its own threads | posted to the executor, through a weak reference | - * | exceptions on refused input | `error::backend_failure` | - * | `Candidate` | the JSON of an `RTCIceCandidateInit`, as the browser writes it | - * - * Tip: the connection, its handlers and the texts it hands to the app are in the app's resource, - * and so are the `rtc::PeerConnection` object and its control block, which `create` makes with - * `std::allocate_shared`; what that object allocates inside libdatachannel, the data channels it - * creates, and the `std::string` and `rtc::Description` its API takes and returns, are - * libdatachannel's. - * - * @see "The native backend", in the guide. - */ -class peer_connection : public backend::peer_connection, - public std::enable_shared_from_this { - struct private_tag { - explicit private_tag() = default; - }; - -public: - /** What `set_local_description` completes with: an error, or the type and the SDP. */ - using description_handler = - handler; - - /** - * Makes a peer connection that gathers through `servers`, bound to `bind_address` when it is - * not empty. - * - * A connection that is not bound gathers a host candidate on each interface but the loopback, - * which ICE never offers (RFC 8445, 5.1.1.1); one bound to an address, as `"127.0.0.1"`, - * gathers on that address alone, which lets two peers of one machine connect with no other - * network. - * - * @param ex The executor every handler of the connection runs on. - * @param servers The STUN and TURN servers it gathers through. - * @param bind_address The local address it binds to, as `"127.0.0.1"`; empty means every - * interface but the loopback. - * @param memory The resource the connection, its handlers and its texts are allocated in. - * @return The new connection. - * @throws std::exception What libdatachannel throws when it cannot make the connection. - */ - // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - static std::shared_ptr create(boost::asio::any_io_executor ex, - std::span servers, - std::string_view bind_address, - std::pmr::memory_resource* memory) { - // NOLINTEND(performance-unnecessary-value-param) - rtc::Configuration config; - config.disableAutoNegotiation = true; - if (!bind_address.empty()) { - config.bindAddress = std::string(bind_address); - } - for (const auto& server : servers) { - for (const auto& url : server.urls) { - // A room has dropped every server WebRTC refuses when it joined; a URL - // libdatachannel still cannot parse is skipped here, where a browser would throw. - try { - config.iceServers.emplace_back( - with_credentials(url, server.username, server.credential)); - } catch (...) { // NOLINT(bugprone-empty-catch) - } - } - } - const std::pmr::polymorphic_allocator<> allocator(memory); - auto self = std::allocate_shared( - allocator, private_tag{}, std::move(ex), - std::allocate_shared(allocator, config), memory); - self->start(); - return self; - } - - /** - * Constructs the wrapper; only `create` can, which then takes over the connection's events. - * - * @param ex The executor every handler of the connection runs on. - * @param pc libdatachannel's connection. - * @param memory The resource its handlers and its texts are allocated in. - */ - peer_connection(private_tag /*tag*/, boost::asio::any_io_executor ex, - std::shared_ptr pc, std::pmr::memory_resource* memory) - : ex_(std::move(ex)), - pc_(std::move(pc)), - memory_(memory), - json_(memory), - pending_local_(memory) {} - - /** Destroys the wrapper, which closes the connection without reporting the close. */ - ~peer_connection() override { - pc_->resetCallbacks(); - pc_->close(); - } - - /** - * Replaces the handlers, kept in a shared object so that one replacing them during its own call - * outlives the call. - * - * @param h The new handlers, kept in the connection's resource. - */ - void set_handlers(handlers h) override { - h_ = std::allocate_shared(allocator(), std::move(h)); - } - - /** - * Opens a data channel. - * - * @param label The channel's label, read during the call. - * @return The channel, made in the connection's resource, or null when libdatachannel refuses - * to open one, as on a closed connection. - */ - std::shared_ptr create_data_channel(std::string_view label) override { - // libdatachannel refuses a channel by throwing, as on a closed connection. - try { - return data_channel::create(ex_, pc_->createDataChannel(std::string(label)), memory_); - } catch (...) { - return nullptr; - } - } - - /** - * Creates the offer or the answer the signaling state calls for and applies it. - * - * @param done Called on the executor with the description's type and SDP, or with - * `error::backend_failure` when libdatachannel refuses. - */ - void set_local_description(description_handler done) override { - pending_local_.push_back(std::move(done)); - try { - pc_->setLocalDescription(); - } catch (...) { - auto failed = std::move(pending_local_.back()); - pending_local_.pop_back(); - post([failed = std::move(failed)]() mutable { - failed(make_error_code(error::backend_failure), {}, {}); - }); - } - } - - /** - * Applies the remote peer's offer or answer. - * - * @param type "offer" or "answer", read during the call. - * @param sdp The description's SDP, read during the call. - * @param done Called on the executor once it is applied, or with `error::backend_failure` when - * libdatachannel refuses it. - */ - void set_remote_description(std::string_view type, std::string_view sdp, - handler done) override { - backend::error_code ec; - try { - pc_->setRemoteDescription(rtc::Description(std::string(sdp), std::string(type))); - } catch (...) { - ec = make_error_code(error::backend_failure); - } - post([done = std::move(done), ec]() mutable { done(ec); }); - } - - /** - * Adds a remote ICE candidate; the empty candidate that ends the remote gathering adds none. - * - * @param candidate_json The JSON of an `RTCIceCandidateInit`, read during the call. - * @param done Called on the executor once it is added, or with `error::backend_failure` when - * the JSON has no candidate or libdatachannel refuses it. - */ - void add_ice_candidate(std::string_view candidate_json, - handler done) override { - backend::error_code ec; - boost::system::error_code parse_error; - const auto document = - protocol::json::parse(candidate_json, boost::json::storage_ptr(&json_), parse_error); - const auto* object = parse_error ? nullptr : document.if_object(); - const auto* candidate = object != nullptr ? object->if_contains("candidate") : nullptr; - const auto* mid = object != nullptr ? object->if_contains("sdpMid") : nullptr; - if (candidate == nullptr || !candidate->is_string()) { - ec = make_error_code(error::backend_failure); - } else if (!candidate->get_string() - .empty()) { // an empty candidate marks the end of gathering - try { - const std::string text(candidate->get_string()); - const std::string mid_text = mid != nullptr && mid->is_string() - ? std::string(mid->get_string()) - : std::string("0"); - pc_->addRemoteCandidate(rtc::Candidate(text, mid_text)); - } catch (...) { - ec = make_error_code(error::backend_failure); - } - } - post([done = std::move(done), ec]() mutable { done(ec); }); - } - - /** - * Whether a remote description was applied. - * - * @return Whether libdatachannel's connection has a remote description. - */ - bool has_remote_description() const override { return pc_->remoteDescription().has_value(); } - - /** Closes the connection and its channels. */ - void close() override { pc_->close(); } - - /** - * libdatachannel's own `rtc::PeerConnection`, what media will be added to. - * - * The object and its control block are in the app's resource: no copy of the pointer may - * outlive `app_config::memory`. - * - * @return The connection. - * @see "Roadmap", in the guide. - */ - const std::shared_ptr& native_handle() const { return pc_; } - -private: - std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } - - /** "turn:host" with a username and credential becomes "turn:user:credential\@host", the form - * libdatachannel parses. */ - static std::string with_credentials(std::string_view url, std::string_view username, - std::string_view credential) { - if (username.empty()) { - return std::string(url); - } - const auto colon = url.find(':'); - if (colon == std::string_view::npos) { - return std::string(url); - } - std::string out(url.substr(0, colon + 1)); - out += username; - out += ':'; - out += credential; - out += '@'; - out += url.substr(colon + 1); - return out; - } - - /** Posts a completion from the executor, in the app's resource. */ - template - void post(F&& f) { - trystero::detail::post(ex_, memory_, std::forward(f)); - } - - /** Posts `f` from one of libdatachannel's threads to the executor, where it runs on this - * connection if the connection still exists then. */ - template - static void post_to(const boost::asio::any_io_executor& ex, - const std::weak_ptr& weak, F f) { - boost::asio::post(ex, [weak, f = std::move(f)]() mutable { - if (const auto self = weak.lock()) { - f(*self); - } - }); - } - - void start() { - const std::weak_ptr weak = shared_from_this(); - const auto ex = ex_; - pc_->onLocalDescription([weak, ex](rtc::Description description) { - post_to(ex, weak, [description = std::move(description)](peer_connection& self) { - self.on_local_description(description); - }); - }); - pc_->onLocalCandidate([weak, ex](rtc::Candidate candidate) { - post_to(ex, weak, [candidate = std::move(candidate)](peer_connection& self) { - self.on_local_candidate(candidate); - }); - }); - pc_->onDataChannel([weak, ex](std::shared_ptr channel) { - post_to(ex, weak, [channel = std::move(channel)](peer_connection& self) mutable { - self.on_data_channel(std::move(channel)); - }); - }); - pc_->onStateChange([weak, ex](rtc::PeerConnection::State state) { - post_to(ex, weak, [state](peer_connection& self) { self.on_state_change(state); }); - }); - } - - // The handlers run from a copy of the shared object, which a handler may replace. - - void on_local_description(const rtc::Description& description) { - if (pending_local_.empty()) { - return; - } - auto done = std::move(pending_local_.front()); - pending_local_.pop_front(); - done({}, description.typeString(), std::string(description)); - } - - void on_local_candidate(const rtc::Candidate& candidate) { - const auto h = h_; - if (!h || !h->ice_candidate) { - return; - } - std::pmr::string json(R"({"candidate":)", memory_); - protocol::json::append_string(json, candidate.candidate()); - json += R"(,"sdpMid":)"; - protocol::json::append_string(json, candidate.mid()); - json += R"(,"sdpMLineIndex":0})"; - h->ice_candidate(json); - } - - void on_data_channel(std::shared_ptr channel) { - auto wrapped = data_channel::create(ex_, std::move(channel), memory_); - if (const auto h = h_; h && h->data_channel) { - h->data_channel(std::move(wrapped)); - } - } - - void on_state_change(rtc::PeerConnection::State state) { - if (const auto h = h_; h && h->state) { - h->state(map(state)); - } - } - - static backend::connection_state map(rtc::PeerConnection::State state) { - using backend::connection_state; - switch (state) { - case rtc::PeerConnection::State::New: return connection_state::fresh; - case rtc::PeerConnection::State::Connecting: return connection_state::connecting; - case rtc::PeerConnection::State::Connected: return connection_state::connected; - case rtc::PeerConnection::State::Disconnected: return connection_state::disconnected; - case rtc::PeerConnection::State::Failed: return connection_state::failed; - case rtc::PeerConnection::State::Closed: return connection_state::closed; - } - return connection_state::fresh; - } - - boost::asio::any_io_executor ex_; - std::shared_ptr pc_; - std::pmr::memory_resource* memory_; - json_resource json_; - std::shared_ptr h_; - std::pmr::deque pending_local_; -}; - -} // namespace webcpp::trystero::native - -#endif // WEBCPP_TRYSTERO_NO_EXCEPTIONS - -#endif diff --git a/include/webcpp/trystero/native/sealer.hpp b/include/webcpp/trystero/native/sealer.hpp deleted file mode 100644 index e61fd6d..0000000 --- a/include/webcpp/trystero/native/sealer.hpp +++ /dev/null @@ -1,178 +0,0 @@ -// 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_SEALER_HPP -#define WEBCPP_TRYSTERO_NATIVE_SEALER_HPP - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only - -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::native { - -namespace detail { - -/** Frees an OpenSSL cipher context. */ -struct cipher_context_deleter { - /** Frees `c`. */ - void operator()(EVP_CIPHER_CTX* c) const { EVP_CIPHER_CTX_free(c); } -}; - -/** An OpenSSL cipher context, freed with its owner. */ -using cipher_context = std::unique_ptr; - -/** The size of AES-GCM's authentication tag, which WebCrypto appends to the ciphertext. */ -inline constexpr std::size_t gcm_tag_size = 16; - -/** AES-256-GCM with a 16-byte IV, the ciphertext followed by its 16-byte tag: what WebCrypto's - * encrypt returns. */ -inline std::optional aes_gcm(bool encrypt, const std::array& key, - std::span iv, - std::span input, - std::pmr::memory_resource* memory) { - if (!encrypt && input.size() < gcm_tag_size) { - return std::nullopt; - } - const cipher_context context(EVP_CIPHER_CTX_new()); - if (!context) { - return std::nullopt; - } - const auto body = encrypt ? input : input.first(input.size() - gcm_tag_size); - backend::bytes out(body.size() + (encrypt ? gcm_tag_size : 0), memory); - int length = 0; - int final_length = 0; - // OpenSSL's functions return 0 when they fail. - bool ok = EVP_CipherInit_ex(context.get(), EVP_aes_256_gcm(), nullptr, nullptr, nullptr, - encrypt ? 1 : 0) != 0 && - EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_SET_IVLEN, - static_cast(iv.size()), nullptr) != 0 && - EVP_CipherInit_ex(context.get(), nullptr, nullptr, key.data(), iv.data(), -1) != 0 && - EVP_CipherUpdate(context.get(), out.data(), &length, body.data(), - static_cast(body.size())) != 0; - if (ok && !encrypt) { - // OpenSSL takes the expected tag through a pointer to mutable bytes, and only reads it. - auto* tag = const_cast(input.data() + body.size()); - ok = EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_SET_TAG, - static_cast(gcm_tag_size), tag) != 0; - } - ok = ok && EVP_CipherFinal_ex(context.get(), out.data() + length, &final_length) != 0; - if (ok && encrypt) { - ok = EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_GET_TAG, - static_cast(gcm_tag_size), out.data() + body.size()) != 0; - } - if (!ok) { - return std::nullopt; - } - return out; -} - -} // namespace detail - -/** - * AES-GCM under one room key, through OpenSSL, in Trystero's sealed text form, what Trystero's - * `encrypt` and `decrypt` do with `crypto.subtle`. - * - * It works synchronously and posts each completion to the executor, as the backend interface asks: - * a handler never runs inside the call that started it. Its texts and completions are in the - * room's resource; OpenSSL's cipher context is OpenSSL's. It needs no exceptions. - * - * @see "The native backend", in the guide. - */ -class sealer : public backend::sealer { -public: - /** What a seal or an open completes with: an error, or the text, a view valid for the call. */ - using done_handler = handler; - - /** - * Constructs a sealer under a room's key. - * - * @param ex The executor its completions are posted to. - * @param key The raw AES-256 key, `protocol::seal_key`'s. - * @param memory The room's resource, which its texts and its completions are allocated in; it - * must outlive the completions it posts. - */ - sealer(boost::asio::any_io_executor ex, std::array key, - std::pmr::memory_resource* memory) - : ex_(std::move(ex)), key_(key), memory_(memory) {} - - /** - * Seals a text under a fresh IV from OpenSSL's random generator. - * - * @param plaintext The text, read during the call. - * @param done Called on the executor with the sealed text, or with `error::backend_failure` - * when OpenSSL fails. - */ - void seal(std::string_view plaintext, done_handler done) override { - std::array iv{}; - if (RAND_bytes(iv.data(), static_cast(iv.size())) != 1) { // lint-world: a seal's IV - complete(std::move(done), error::backend_failure); - return; - } - const auto cipher = detail::aes_gcm( - true, key_, iv, - std::span(reinterpret_cast(plaintext.data()), plaintext.size()), - memory_); - if (!cipher) { - complete(std::move(done), error::backend_failure); - return; - } - complete(std::move(done), {}, protocol::format_sealed(iv, *cipher, memory_)); - } - - /** - * Opens a sealed text. - * - * @param sealed The sealed text, read during the call. - * @param done Called on the executor with the plaintext, or with `error::wrong_password` when - * the text was sealed under another key or is not a sealed text. - */ - void open(std::string_view sealed, done_handler done) override { - const auto parts = protocol::parse_sealed(sealed, memory_); - const auto plain = parts && !parts->iv.empty() - ? detail::aes_gcm(false, key_, parts->iv, parts->ciphertext, memory_) - : std::nullopt; - if (!plain) { - complete(std::move(done), error::wrong_password); - return; - } - complete(std::move(done), {}, std::pmr::string(plain->begin(), plain->end(), memory_)); - } - -private: - void complete(done_handler done, backend::error_code ec, std::pmr::string text) { - trystero::detail::post( - ex_, memory_, - [done = std::move(done), ec, text = std::move(text)]() mutable { done(ec, text); }); - } - - void complete(done_handler done, error e) { - complete(std::move(done), make_error_code(e), std::pmr::string(memory_)); - } - - boost::asio::any_io_executor ex_; - std::array key_; - std::pmr::memory_resource* memory_; -}; - -} // namespace webcpp::trystero::native - -#endif diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp deleted file mode 100644 index 2189f6d..0000000 --- a/include/webcpp/trystero/native/websocket.hpp +++ /dev/null @@ -1,415 +0,0 @@ -// 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_WEBSOCKET_HPP -#define WEBCPP_TRYSTERO_NATIVE_WEBSOCKET_HPP - -#include - -#include -#include -#include - -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets -#include // lint-world: the relays' WebSockets - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::native { - -/** - * What a native WebSocket tolerates of a relay that stops reading or answering. - * - * @see "The native backend", in the guide. - */ -struct websocket_limits { - /** - * The most bytes of text queued to write: a relay that stops reading lets them pile up, and a - * text beyond this drops the connection, which reports a close, so that the room reconnects - * with its backoff. - */ - std::size_t max_queued_bytes = protocol::max_queued_relay_bytes; - - /** - * How long the connection may stay silent: half of it, a keep-alive ping is sent, and a relay - * that answers nothing within the whole of it is closed, which reports a close. - * - * It counts the bytes received, and a ping waits for the write in flight. Native only: a page's - * `WebSocket` cannot ping, so the browser backend has no idle timeout. - */ - std::chrono::seconds idle_timeout = std::chrono::seconds(30); -}; - -namespace detail { - -// Its implicit move assignment may allocate: a std::pmr member copies when the two resources -// differ, which bugprone-exception-escape, expecting every move assignment not to throw, reports. -/** A WebSocket URL's parts, in the memory resource it was parsed into. */ -struct url_parts { // NOLINT(bugprone-exception-escape) - /** Whether the scheme is `wss`. */ - bool secure = false; - /** The host, a name or an address. */ - std::pmr::string host; - /** The port, the scheme's default when the URL names none. */ - std::pmr::string port; - /** The path and the query, `/` when the URL has neither. */ - std::pmr::string target; -}; - -/** The parts of a `ws://` or `wss://` URL, in `memory`; nothing for any other scheme or without a - * host. */ -inline std::optional parse_url( - std::string_view url, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - url_parts out{ - .secure = false, - .host = std::pmr::string(memory), - .port = std::pmr::string(memory), - .target = std::pmr::string(memory), - }; - if (url.starts_with("wss://")) { - out.secure = true; - url.remove_prefix(6); - } else if (url.starts_with("ws://")) { - url.remove_prefix(5); - } else { - return std::nullopt; - } - const auto slash = url.find_first_of("/?"); - const auto authority = url.substr(0, slash); - out.target = slash == std::string_view::npos ? std::string_view("/") : url.substr(slash); - if (out.target.front() == '?') { - out.target.insert(out.target.begin(), '/'); - } - const auto colon = authority.rfind(':'); - const bool has_port = - colon != std::string_view::npos && authority.find(']', colon) == std::string_view::npos; - out.host = authority.substr(0, has_port ? colon : authority.size()); - out.port = has_port ? authority.substr(colon + 1) : std::string_view(out.secure ? "443" : "80"); - if (out.host.empty() || out.port.empty()) { - return std::nullopt; - } - return out; -} - -/** - * One WebSocket connection, run by a coroutine that owns it until the connection ends: connect, TLS - * for `wss`, the handshake, then a read loop handing each message to the handler as a view of the - * read buffer. Writes are queued, one in flight at a time, as Beast requires. - * - * Tip: the session, its handlers and its queued texts are in the room's resource; Boost.Beast's - * stream state, the resolver's results and the coroutines' frames are Beast's and Asio's. - */ -template -class websocket_session : public std::enable_shared_from_this> { -public: - /** Asio's TCP. */ - using tcp = boost::asio::ip::tcp; - /** The stream the WebSocket runs over: TLS over TCP for `wss`, TCP for `ws`. */ - using next_layer = - std::conditional_t, - boost::beast::tcp_stream>; - /** Beast's WebSocket stream. */ - using stream_type = boost::beast::websocket::stream; - - /** A session, not started, for a parsed URL, in `memory`. */ - websocket_session(const boost::asio::any_io_executor& ex, boost::asio::ssl::context& tls, - url_parts url, backend::websocket::handlers h, - std::pmr::memory_resource* memory, websocket_limits limits) - : ex_(ex), - resolver_(ex), - ws_(make_stream(ex, tls)), - url_(std::move(url)), - memory_(memory), - limits_(limits), - h_(std::allocate_shared( - std::pmr::polymorphic_allocator<>(memory), std::move(h))), - queue_(memory) {} - - /** Starts the coroutine that connects, shakes hands and reads. */ - void start() { - boost::asio::co_spawn( - ex_, [self = this->shared_from_this()] { return self->run(); }, boost::asio::detached); - } - - /** - * Queues a text to write, when open and not closing; one write is in flight at a time. A text - * that would take the queue beyond `websocket_limits::max_queued_bytes` drops the connection. - */ - void send(std::string_view text) { - if (!open_ || closing_) { - return; - } - if (queued_bytes_ + text.size() > limits_.max_queued_bytes) { - // The relay stopped reading: no close frame could reach it, so the socket is closed, - // the read fails, and end() reports the close. - closing_ = true; - boost::beast::get_lowest_layer(ws_).close(); - return; - } - queued_bytes_ += text.size(); - queue_.emplace_back(text); // a write outlives the call, so the text is copied once, here - if (std::exchange(writing_, true)) { - return; // marked now: the writer only starts once the executor runs it - } - boost::asio::co_spawn( - ex_, [self = this->shared_from_this()] { return self->write_queue(); }, - boost::asio::detached); - } - - /** Closes with a WebSocket close frame, or drops a connection still being made. */ - void close() { - if (closing_ || ended_) { - return; - } - closing_ = true; - if (!open_) { - boost::beast::get_lowest_layer(ws_) - .close(); // still connecting: the run ends with an error and reports - return; - } - boost::asio::co_spawn( - ex_, - [self = this->shared_from_this()]() -> boost::asio::awaitable { - co_await self->ws_.async_close(boost::beast::websocket::close_code::normal, - boost::asio::as_tuple(boost::asio::use_awaitable)); - boost::beast::get_lowest_layer(self->ws_).close(); - }, - boost::asio::detached); - } - - /** The owner let go: nothing is reported any more, and the connection is dropped. */ - void abandon() { - h_.reset(); - closing_ = true; - boost::beast::get_lowest_layer(ws_).close(); - } - -private: - static stream_type make_stream(const boost::asio::any_io_executor& ex, - boost::asio::ssl::context& tls) { - if constexpr (Secure) { - return stream_type(ex, tls); - } else { - (void)tls; - return stream_type(ex); - } - } - - boost::asio::awaitable run() { - using boost::asio::as_tuple; - using boost::asio::use_awaitable; - 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(); - } - auto& lowest = boost::beast::get_lowest_layer(ws_); - lowest.expires_after(std::chrono::seconds(30)); - auto [connect_error, endpoint] = - co_await lowest.async_connect(endpoints, as_tuple(use_awaitable)); - if (connect_error || closing_) { - co_return end(); - } - if constexpr (Secure) { - auto& tls = ws_.next_layer(); - if (SSL_set_tlsext_host_name(tls.native_handle(), url_.host.c_str()) != 1) { - co_return end(); // SNI - } - tls.set_verify_callback(boost::asio::ssl::host_name_verification( - std::string(url_.host))); // Asio's, a std::string - auto [tls_error] = co_await tls.async_handshake(boost::asio::ssl::stream_base::client, - as_tuple(use_awaitable)); - if (tls_error || closing_) { - co_return end(); - } - } - lowest.expires_never(); - auto timeouts = boost::beast::websocket::stream_base::timeout::suggested( - boost::beast::role_type::client); - timeouts.idle_timeout = limits_.idle_timeout; - timeouts.keep_alive_pings = true; // a relay that reads nothing answers no ping - ws_.set_option(timeouts); - const bool default_port = url_.port == (Secure ? "443" : "80"); - std::pmr::string host(url_.host, memory_); - if (!default_port) { - host.append(":").append(url_.port); - } - auto [handshake_error] = - co_await ws_.async_handshake(host, url_.target, as_tuple(use_awaitable)); - if (handshake_error || closing_) { - co_return end(); - } - open_ = true; - if (const auto h = h_; h && h->open) { - h->open(); - } - // A longer message fails the read, which closes the connection, as the browser backend - // does. - ws_.read_message_max(protocol::max_relay_message_bytes); - boost::beast::flat_buffer buffer; - while (!closing_) { - auto [read_error, size] = co_await ws_.async_read(buffer, as_tuple(use_awaitable)); - if (read_error) { - break; - } - if (const auto h = h_; h && h->message) { - const auto data = buffer.cdata(); - h->message(std::string_view(static_cast(data.data()), size)); - } - buffer.consume(buffer.size()); - } - end(); - } - - /** - * Writes the queued texts in turn, each moved out of the queue into this frame before its - * write starts. - * - * Tip: the connection can end while a write is in flight, and `end` then clears the queue; the - * text being written is no longer in it, so the write reads a text it owns, and its completion - * touches only that text. - */ - boost::asio::awaitable write_queue() { - while (!queue_.empty() && open_ && !ended_) { - const std::pmr::string text = std::move(queue_.front()); - queue_.pop_front(); - queued_bytes_ -= text.size(); - ws_.text(true); - auto [ec, size] = co_await ws_.async_write( - boost::asio::buffer(text), boost::asio::as_tuple(boost::asio::use_awaitable)); - if (ec) { - break; - } - } - writing_ = false; - } - - void end() { - if (std::exchange(ended_, true)) { - return; - } - open_ = false; - queue_.clear(); - queued_bytes_ = 0; - if (const auto h = h_) { - if (auto f = std::exchange(h->close, {})) { - f(); - } - } - } - - boost::asio::any_io_executor ex_; - tcp::resolver resolver_; - stream_type ws_; - url_parts url_; - std::pmr::memory_resource* memory_; - websocket_limits limits_; - // Shared so that a handler that destroys the connection's owner during its own call outlives - // the call. - std::shared_ptr h_; - std::pmr::deque queue_; - std::size_t queued_bytes_ = 0; // of the texts in queue_ - bool open_ = false; - bool writing_ = false; - bool closing_ = false; - bool ended_ = false; -}; - -/** What the caller holds: dropping it abandons the session, which may still be finishing an - * operation. */ -template -class websocket_handle : public backend::websocket { -public: - /** A handle of a started session. */ - explicit websocket_handle(std::shared_ptr> session) - : session_(std::move(session)) {} - - /** Abandons the session. */ - ~websocket_handle() override { session_->abandon(); } - - /** Sends a text through the session. */ - void send(std::string_view text) override { session_->send(text); } - - /** Closes the session. */ - void close() override { session_->close(); } - -private: - std::shared_ptr> session_; -}; - -} // namespace detail - -/** - * Connects to a Nostr relay over Boost.Beast: `ws://` in the clear, `wss://` over TLS with `tls`. - * - * Writes are queued, one in flight at a time; a received message is handed over as a view of the - * read buffer, and one longer than `protocol::max_relay_message_bytes` closes the connection. A - * relay that stops reading is dropped once the queue would pass `limits.max_queued_bytes`, and one - * that stops answering once `limits.idle_timeout` passes with its keep-alive ping unanswered; both - * report a close. A URL it cannot parse reports a close, as an unreachable relay does. It needs no - * exceptions. - * - * @param ex The executor every handler runs on. - * @param tls The TLS context of `wss://`, which must outlive the connection and should verify - * peers. - * @param url The relay's URL, read during the call. - * @param h What the WebSocket reports. - * @param memory The room's resource, which the connection, its handlers and its queued texts are - * allocated in; Beast's stream state and the coroutines' frames are Asio's. - * @param limits What it tolerates of a relay that stops reading or answering. - * @return The WebSocket; destroying it drops the connection without reporting it. - * @see "The native backend", in the guide. - */ -inline std::shared_ptr connect_websocket(const boost::asio::any_io_executor& ex, - boost::asio::ssl::context& tls, - std::string_view url, - backend::websocket::handlers h, - std::pmr::memory_resource* memory, - websocket_limits limits = {}) { - auto parts = detail::parse_url(url, memory); - if (!parts) { - parts = detail::url_parts{ - .secure = false, - .host = std::pmr::string(memory), - .port = std::pmr::string(memory), - .target = std::pmr::string(memory), - }; - } - const std::pmr::polymorphic_allocator<> allocator(memory); - if (parts->secure) { - const auto session = std::allocate_shared>( - allocator, ex, tls, std::move(*parts), std::move(h), memory, limits); - session->start(); - return std::allocate_shared>(allocator, session); - } - const auto session = std::allocate_shared>( - allocator, ex, tls, std::move(*parts), std::move(h), memory, limits); - session->start(); - return std::allocate_shared>(allocator, session); -} - -} // namespace webcpp::trystero::native - -#endif diff --git a/include/webcpp/trystero/options.hpp b/include/webcpp/trystero/options.hpp index 2177bb5..c607aa2 100644 --- a/include/webcpp/trystero/options.hpp +++ b/include/webcpp/trystero/options.hpp @@ -12,8 +12,11 @@ #include #include +#include + #include #include +#include #include #include #include @@ -117,6 +120,17 @@ struct room_options { * Trystero's `maxReceiveBytes`. */ std::size_t max_receive_bytes = std::size_t{256} * 1024 * 1024; + /** + * The largest image a received JSON payload's document may take in the room, webcpp::document's + * own default, 64 MiB, which Trystero JS, reading with `JSON.parse`, does not have. + * + * A payload's document grows to at most 96 times its text and 64 KiB, which every valid text + * fits, and this bounds it whatever the text: each value is a node of 192 bytes, so a payload + * of one-character values past some 350,000 of them is not delivered with the default. + * + * @see "JSON texts", in the guide. + */ + std::uint64_t max_json_document_bytes = webcpp::document::parse_options().max_document_bytes; /** * The resource every allocation of the room goes through: its state, bindings, negotiations, * relays, actions, sent frames, transfers and JSON. diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp new file mode 100644 index 0000000..d2f38a8 --- /dev/null +++ b/include/webcpp/trystero/platform/backend.hpp @@ -0,0 +1,413 @@ +// 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_PLATFORM_BACKEND_HPP +#define WEBCPP_TRYSTERO_PLATFORM_BACKEND_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include // lint-world: names the executor only +#include // lint-world: the relays' TLS + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * The platform: one implementation of the backend interface for both targets, over webcpp::webrtc + * for WebRTC, webcpp::beast for the relays' WebSockets and webcpp::asio for timers; natively + * libdatachannel's WebRTC, Boost.Beast's WebSockets and OpenSSL's TLS, AES-GCM and randomness, in a + * page its own `RTCPeerConnection`, `WebSocket` and `crypto.subtle`. Everything it reports runs on + * the executor it is given, whose io_context the program runs. + */ +namespace webcpp::trystero::platform { + +/** + * What a backend makes its peer connections, its relays' WebSockets and its own state with, beside + * the app's `app_config::ice_servers`. + * + * @see "The platform backend", in the guide. + */ +struct backend_config { + /** + * The local address every peer connection binds to, as `"127.0.0.1"`; empty means every + * interface but the loopback. + * + * Bound to the loopback, the peers of one machine connect with no other network, which a test + * wants; a peer bound there reaches no other machine. Natively only: a page's + * `RTCPeerConnection` cannot bind, and webcpp::webrtc refuses every connection a page asks it + * to bind, so a page leaves it empty. + */ + std::pmr::string bind_address = {}; + + /** + * The most peer connections the backend makes in any minute, for every app and room it serves + * together: beyond, it makes none, and a room reports each negotiation it cannot start. + * + * Tip: a room makes at most 64 in any 57 s however its peers behave, so the default lets four + * rooms do so at once; an application with more rooms raises it. + */ + std::size_t max_peer_connections_per_minute = 256; + + /** + * What the backend's own webcpp::webrtc runtime is made with: the most peer connections alive + * at once, 256 by default, and, natively, libdatachannel's threads. + * + * A backend given the program's runtime does not use it. In a page the runtime's cap counts + * every `RTCPeerConnection` of the page, every program of it together, from its construction + * until the garbage collector frees it, as Chromium counts them against its 500: the default is + * half of that, so that a closed connection still counts until a collection the page cannot ask + * for, while the rest of Chromium's count stays free for what the page makes without a room. + */ + ::webcpp::webrtc::runtime_options runtime = {}; + + /** What the relays' WebSockets tolerate of a relay that stops reading or answering. */ + websocket_limits relay_limits = {}; + + /** + * The resource of the backend's own state: its copy of `bind_address`, its window of + * constructions and its own runtime. + * + * It must not be null, and must outlive the backend and every connection of its runtime. + * + * What the backend makes for a room or an app uses the resource given with each call instead. + */ + std::pmr::memory_resource* memory = std::pmr::get_default_resource(); +}; + +/** + * The platform's factory: one per application, beside the executor it runs on, natively or in a + * page. + * + * It makes peer connections, data channels and received frames in `app_config::memory`, and + * WebSockets, sealers and room timers in the room's effective `room_options::memory`; its own state + * is in `backend_config::memory`. Objects and their handlers use the resource supplied to their + * factory method. What libdatachannel and OpenSSL allocate stays theirs, and what + * `emscripten::val` holds is in the JavaScript heap. + * + * Its peer connections are webcpp::webrtc's, counted by a `webcpp::webrtc::runtime`: its own, or + * the program's. Each of its connections and channels keeps its own runtime alive, so that one + * which outlives the backend, in a handler the io_context still holds, does not outlive the + * runtime. Natively a process holds one runtime at a time, since libdatachannel's state is the + * process's: a program with several backends at once, or that uses webcpp::webrtc beside + * trystero, makes one runtime and gives it to each; in a page the census counts the connections of + * every runtime alike. + * + * Tip: in a page, every object it makes runs on its executor, whose io_context the program runs + * from `main`, under a work guard, for as long as the page lives: the page's events, the timers and + * the promises it awaits post to that io_context, and run only while it runs. A page needs a + * secure context (https, or http on localhost), where `crypto.subtle` exists, for its sealer. + * + * @see "The platform backend", in the guide. + */ +class backend : public trystero::backend::factory { +public: + /** + * A backend with a runtime of its own, made with `backend_config::runtime`, whose TLS context + * is @ref make_tls_context's, which natively verifies relays against the system's certificate + * authorities; in a page the browser verifies them against its own. + * + * It throws nothing: when OpenSSL cannot make the TLS context natively, `tls_context()` holds + * the error, and every `wss://` relay reports a close, as an unreachable relay does. + * + * @param ex The executor everything the backend reports runs on, in a page an io_context's of + * webcpp::asio, which must outlive the backend and every object it makes. + * @param config What its peer connections, its relays and its own state are made with. + */ + explicit backend(webcpp::asio::any_io_executor ex, const backend_config& config = {}) + : backend(std::move(ex), make_tls_context(), nullptr, config) {} + + /** + * A backend with a runtime of its own whose relays' TLS is the program's: another set of + * certificate authorities, as webcpp's embedded Mozilla roots, which + * `webcpp::asio::make_tls_client_context()` trusts natively, or a private one. + * + * Each relay is verified whatever the context's verify mode, natively against the context's + * authorities and in a page against the browser's; in a page a context that asks for what the + * page cannot honour (authorities added, a client certificate or key, options, a method other + * than `tls_client` or `sslv23_client`, or a verify callback of its own) has every `wss://` + * relay report a close. + * + * @param ex The executor everything the backend reports runs on. + * @param tls The TLS context of every `wss://` connection, or the error that kept the program + * from making it, which `tls_context()` then holds, every `wss://` relay reporting a close. + * @param config What its peer connections, its relays and its own state are made with. + */ + backend(webcpp::asio::any_io_executor ex, boost::system::result tls, + const backend_config& config = {}) + : backend(std::move(ex), std::move(tls), nullptr, config) {} + + /** + * A backend whose peer connections the program's runtime counts, and whose TLS context is + * @ref make_tls_context's, as the first constructor's is. + * + * @param ex The executor everything the backend reports runs on. + * @param runtime The program's runtime, which must outlive every connection of the backend, + * and so the io_context that may hold one in a handler. + * @param config What its peer connections, its relays and its own state are made with; its + * `runtime` is not used. + */ + backend(webcpp::asio::any_io_executor ex, ::webcpp::webrtc::runtime& runtime, + const backend_config& config = {}) + : backend(std::move(ex), make_tls_context(), runtime, config) {} + + /** + * A backend whose peer connections the program's runtime counts, and whose relays' TLS is the + * program's. + * + * @param ex The executor everything the backend reports runs on. + * @param tls The TLS context of every `wss://` connection, or the error that kept the program + * from making it, as the second constructor takes it. + * @param runtime The program's runtime, which must outlive every connection of the backend, + * and so the io_context that may hold one in a handler. + * @param config What its peer connections, its relays and its own state are made with; its + * `runtime` is not used. + */ + backend(webcpp::asio::any_io_executor ex, boost::system::result tls, + ::webcpp::webrtc::runtime& runtime, const backend_config& config = {}) + // An empty owner: the pointer does not own the program's runtime. + : backend(std::move(ex), std::move(tls), + std::shared_ptr<::webcpp::webrtc::runtime>( + std::shared_ptr<::webcpp::webrtc::runtime>(), &runtime), + config) {} + + /** + * The executor everything the backend reports runs on. + * + * @return The executor it was constructed with. + */ + [[nodiscard]] const webcpp::asio::any_io_executor& get_executor() const noexcept { return ex_; } + + /** + * The TLS context of the relays' connections, which an application may still configure before + * the backend connects to a relay. + * + * Natively its authorities, its client certificate, its options and its protocol versions hold, + * and its verify mode and verify callback do not: each connection verifies its relay, against + * the URL's host. In a page the browser verifies each relay against its own authorities, and + * what the context asks for that a page cannot honour (authorities added, a client certificate + * or key, options, a verify callback of its own) has every `wss://` relay report a close. + * + * @return The context every `wss://` connection of the backend is made with, or the error that + * kept it from being made. + */ + [[nodiscard]] boost::system::result tls_context() { + if (!tls_) { + return tls_.error(); + } + return *tls_; + } + + /** + * The runtime that counts the backend's peer connections. + * + * @return Its own, or the program's. + */ + [[nodiscard]] ::webcpp::webrtc::runtime& runtime() const { return *runtime_; } + + /** + * Opens a WebSocket to a relay over webcpp::beast, with @ref connect_websocket. + * + * @param url The relay's `ws://` or `wss://` URL, read during the call. + * @param h What the WebSocket reports. + * @param memory The room's resource, which the WebSocket, its handlers, its queued texts and + * its operations are allocated in. + * @return The WebSocket; one of a `wss://` URL reports a close when the backend has no TLS + * context. + */ + std::shared_ptr connect( + std::string_view url, trystero::backend::websocket::handlers h, + std::pmr::memory_resource* memory) override { + return connect_websocket(ex_, tls_ ? &*tls_ : nullptr, url, std::move(h), memory, + config_.relay_limits); + } + + /** + * Makes a peer connection of webcpp::webrtc, bound to `backend_config::bind_address`. + * + * A room has dropped every server WebRTC refuses when it joined. Natively a URL libdatachannel + * still cannot parse, as a `stuns:` one, a scheme it does not know, is left out here; a page's + * `RTCPeerConnection` refuses the connection for a server it cannot use. + * + * @param servers The STUN and TURN servers, read during the call. + * @param memory The app's resource, which the connection, its channels, its handlers and its + * texts are allocated in. + * @return The connection, or null when the backend made + * `backend_config::max_peer_connections_per_minute` in the last minute, when its runtime holds + * as many connections as it allows, or when the platform refuses to make one. + */ + std::shared_ptr make_peer_connection( + std::span servers, + std::pmr::memory_resource* memory) override { + if (!constructions_.take(steady_now())) { + return nullptr; + } + auto made = webrtc::peer_connection::make(runtime_, ex_, servers, config_.bind_address, + *this, memory); +#ifndef WEBCPP_TARGET_EMSCRIPTEN + if (!made && made.error() == ::webcpp::webrtc::error::syntax_error) { + made = webrtc::peer_connection::make(runtime_, ex_, parsed(servers, memory), + config_.bind_address, *this, memory); + } +#endif + return made ? *made : nullptr; + } + + /** + * Makes a timer over webcpp::asio's steady timer, on the backend's executor. + * + * @param memory The room's resource, which the timer and its waits are allocated in. + * @return The timer, not started. + */ + std::shared_ptr make_timer( + std::pmr::memory_resource* memory) override { + return std::allocate_shared( + std::pmr::polymorphic_allocator<>(memory), ex_, memory); + } + + /** + * Makes a sealer: natively over OpenSSL's AES-256-GCM, in a page over `crypto.subtle`. + * + * @param key The raw AES-256 key. + * @param memory The room's resource, which the sealer, its texts and its completions are + * allocated in. + * @return The sealer. + */ + std::shared_ptr make_sealer( + std::array key, std::pmr::memory_resource* memory) override { + return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), ex_, key, + memory); + } + + /** + * Fills `out` from the platform's secure source of randomness, natively OpenSSL's generator, + * in a page its `crypto.getRandomValues`; the program aborts when it has none. + * + * @param out The bytes to fill. + */ + void random(std::span out) override { + if (!detail::fill_random(out)) { + std::abort(); // no secure randomness: nothing is safe + } + } + + /** + * The standard library's wall clock, which a page reads from `Date.now()`, in whole seconds. + * + * @return The current time, in whole seconds since the Unix epoch. + */ + std::chrono::sys_seconds unix_now() override { + const auto now = std::chrono::system_clock::now(); // lint-world: Nostr's created_at + return std::chrono::floor(now); + } + + /** + * The standard library's steady clock, which a page reads from `performance.now()`. + * + * @return The current time, from the steady clock's epoch. + */ + std::chrono::steady_clock::time_point steady_now() override { // lint-world: a type only + return std::chrono::steady_clock::now(); // lint-world: Trystero's timing + } + +private: + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + backend(webcpp::asio::any_io_executor ex, boost::system::result tls, + std::shared_ptr<::webcpp::webrtc::runtime> runtime, const backend_config& config) + // NOLINTEND(performance-unnecessary-value-param) + : ex_(std::move(ex)), + config_(kept(config)), + runtime_(runtime ? std::move(runtime) : own_runtime(config_)), + constructions_(config_.max_peer_connections_per_minute, std::chrono::minutes(1), + config_.memory), + tls_(std::move(tls)) {} + + /** The configuration the backend keeps, its bind address copied into its own memory. */ + static backend_config kept(const backend_config& config) { + return { + .bind_address = std::pmr::string(config.bind_address, config.memory), + .max_peer_connections_per_minute = config.max_peer_connections_per_minute, + .runtime = config.runtime, + .relay_limits = config.relay_limits, + .memory = config.memory, + }; + } + + /** A runtime of the backend's own, in its memory, which its connections share with it. */ + static std::shared_ptr<::webcpp::webrtc::runtime> own_runtime(const backend_config& config) { + return std::allocate_shared<::webcpp::webrtc::runtime>( + std::pmr::polymorphic_allocator<>(config.memory), config.runtime); + } + +#ifndef WEBCPP_TARGET_EMSCRIPTEN + /** + * The servers of `servers` without the URLs libdatachannel cannot parse, in `memory`: each URL + * is tried alone, so that one refused leaves the others. + */ + std::pmr::vector parsed( + std::span servers, std::pmr::memory_resource* memory) { + std::pmr::vector out(memory); + for (const auto& server : servers) { + trystero::backend::ice_server kept{ + .urls = std::pmr::vector(memory), + .username = std::pmr::string(server.username, memory), + .credential = std::pmr::string(server.credential, memory), + }; + for (const auto& url : server.urls) { + const trystero::backend::ice_server one{ + .urls = std::pmr::vector(1, url, memory), + .username = std::pmr::string(server.username, memory), + .credential = std::pmr::string(server.credential, memory), + }; + // A URL it parses makes a connection, given up at once. + const auto probe = webrtc::peer_connection::make_connection( + *runtime_, ex_, std::span(&one, 1), config_.bind_address, memory); + if (probe || probe.error() != ::webcpp::webrtc::error::syntax_error) { + kept.urls.push_back(url); + } + } + if (!kept.urls.empty()) { + out.push_back(std::move(kept)); + } + } + return out; + } +#endif + + webcpp::asio::any_io_executor ex_; + backend_config config_; + std::shared_ptr<::webcpp::webrtc::runtime> runtime_; + trystero::detail::construction_window constructions_; + boost::system::result tls_; +}; + +} // namespace webcpp::trystero::platform + +#endif diff --git a/include/webcpp/trystero/platform/entropy.hpp b/include/webcpp/trystero/platform/entropy.hpp new file mode 100644 index 0000000..7962403 --- /dev/null +++ b/include/webcpp/trystero/platform/entropy.hpp @@ -0,0 +1,92 @@ +// 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_PLATFORM_ENTROPY_HPP +#define WEBCPP_TRYSTERO_PLATFORM_ENTROPY_HPP + +#include + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#include +#else +#include +#endif + +#include +#include +#include +#include + +namespace webcpp::trystero::platform::detail { + +#ifdef WEBCPP_TARGET_EMSCRIPTEN + +// clang-format off +/** + * Fills the `size` bytes at `data` from the page's `crypto.getRandomValues`: 0 when it filled + * them, -1 when the page has no such function or it threw, caught here, so that no JavaScript + * exception enters WebAssembly, as one does through the C library's entropy call, Emscripten's, + * which lets the page's exception through. + */ +// NOLINTNEXTLINE(misc-const-correctness): JavaScript writes to the pointed WebAssembly storage +inline int js_fill_random(void* data, std::size_t size) { + return EM_ASM_INT(({ + const data = $0 >>> 0; + const size = $1 >>> 0; + + try { + const view = HEAPU8.subarray(data, data + size); + /* Web Crypto fills no view of a SharedArrayBuffer, which a threaded build's memory is. */ + if (view.buffer instanceof ArrayBuffer) { + crypto.getRandomValues(view); + } else { + view.set(crypto.getRandomValues(new Uint8Array(size))); + } + return 0; + } catch (_) { + return -1; + } + }), data, size); +} +// clang-format on + +#endif + +/** + * Fills `out` from the platform's one secure source of randomness, its result checked: natively + * OpenSSL's generator; on emscripten the page's `crypto.getRandomValues`, whose absence or + * exception is a failure, not an exception in WebAssembly. + * + * @param out The bytes to fill. + * @return Whether every byte was filled; on false, the bytes must not be used. + */ +inline bool fill_random(std::span out) noexcept { +#ifdef WEBCPP_TARGET_EMSCRIPTEN + // Web Crypto fills at most 65536 bytes a call, and throws for more. + constexpr std::size_t most = std::size_t{1} << 16U; +#else + // OpenSSL's generator takes its count as an int. + constexpr std::size_t most = std::size_t{1} << 30U; +#endif + for (std::size_t at = 0; at < out.size(); at += most) { + const auto piece = std::min(most, out.size() - at); +#ifdef WEBCPP_TARGET_EMSCRIPTEN + if (js_fill_random(out.data() + at, piece) != 0) { // lint-world: Trystero's randomness + return false; + } +#else + const auto count = static_cast(piece); // at most 2^30, in an int's range + if (RAND_bytes(out.data() + at, count) != 1) { // lint-world: Trystero's randomness + return false; + } +#endif + } + return true; +} + +} // namespace webcpp::trystero::platform::detail + +#endif diff --git a/include/webcpp/trystero/platform/page.hpp b/include/webcpp/trystero/platform/page.hpp new file mode 100644 index 0000000..2a57a20 --- /dev/null +++ b/include/webcpp/trystero/platform/page.hpp @@ -0,0 +1,165 @@ +// 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_PLATFORM_PAGE_HPP +#define WEBCPP_TRYSTERO_PLATFORM_PAGE_HPP + +#include + +#ifndef WEBCPP_TARGET_EMSCRIPTEN +#error " is a page's: it builds on emscripten only" +#endif + +#include + +#include // lint-world: names the executor only +#include // lint-world: the page's calls +#include // lint-world: the bridge of the executor's context +#include // lint-world: the bridge of the executor's context + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::platform { + +namespace detail { + +// clang-format off +/** The JavaScript string of `size` bytes of UTF-8 at `data`, its NUL characters included. */ +inline emscripten::EM_VAL js_text(const char* data, std::size_t size) { + return reinterpret_cast(EM_ASM_PTR(({ + const data = $0 >>> 0; + const size = $1 >>> 0; + + return Emval.toHandle(UTF8ToString(data, size, true)); + }), data, size)); +} +// clang-format on + +/** The bridge of the io_context an executor runs on, which delivers the page's calls to it. */ +inline webcpp::asio::browser::bridge& bridge_of(const webcpp::asio::any_io_executor& ex) { + return webcpp::asio::use_service( + webcpp::asio::query(ex, webcpp::asio::execution::context)); +} + +} // namespace detail + +/** + * A JavaScript string of UTF-8 text, decoded straight from the WebAssembly memory the view points + * into. + * + * No `std::string` is made to carry it across, as `emscripten::val(std::string)` would; a NUL + * character is kept, and a byte that is not UTF-8 becomes U+FFFD, as `TextDecoder` makes it. + * + * @param utf8 The text, read during the call. + * @return The JavaScript string. + */ +inline emscripten::val js_string(std::string_view utf8) { + return emscripten::val::take_ownership(detail::js_text(utf8.data(), utf8.size())); +} + +/** + * A function the page calls into C++ with, made by webcpp::asio's bridge, each call of which posts + * `f` with the value the page passed to the executor's io_context. + * + * It is how a page reaches a program whose `main` runs its io_context: the call returns at once, + * having run nothing, and `f` runs when the run family does, never inside the page's event, in + * either suspension variant. An embind function would run its work inside the event, and under + * Asyncify, while `main` is suspended in its run, returns a promise that never settles, and aborts + * a debug build at its second call (measured with Emscripten 6.0.11). A call made once the + * page_call is destroyed, or once its work is posted and the page_call destroyed before it runs, + * reaches nothing; so does one made once the io_context is destroyed. + * + * `f` is a handler of the run, and lets no JavaScript error out, webcpp::asio's rule for every + * handler: an error that leaves `f` leaves `run` with it, and the program's run never resumes + * (measured with Emscripten 6.0.11 under node: the process ends with the error, in either + * suspension variant). A page may pass any value, so `f` checks its type before it converts it, + * with `isString()`, `isNumber()` or `typeOf()`, and reads a field only of what is neither null + * nor undefined: embind's `as()` of a number throws a `BindingError`, and a field of + * undefined a `TypeError`. A number is read as a `double`, with `as()`, and its range + * checked before it becomes an integer: in a build with assertions, as a debug build is, embind's + * `as()` of a number beyond the type's range, as `1e10`, throws a `TypeError`. `f` + * is given the page's value as it is when `f` runs, not when the page called: a JavaScript object + * the page changes meanwhile is seen changed. + * + * @tparam F A callable of one `const emscripten::val&`, the value the page passed. + * @see "The program runs its io_context", in the guide, and webcpp::asio's guide, "A JavaScript + * error that a handler lets escape". + */ +template +// The bridge indexes the call by its registration, a private base: its one owner is the call. +class page_call final : private webcpp::asio::browser::intrusive_registration { +public: + /** + * Makes the function, registered with the bridge of the io_context of `ex`. + * + * @param ex The executor `f` is posted to, an io_context's of webcpp::asio, which must outlive + * the page_call or be destroyed first, which ends it. + * @param f What each call runs, on the executor; it lets no JavaScript error out. + * @param memory The resource `f` and each posted call are allocated in. It holds each call the + * page made until the io_context runs it or is destroyed, so it must outlive the io_context, as + * well as the page_call. + */ + page_call(webcpp::asio::any_io_executor ex, F f, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) + : ex_(std::move(ex)), + memory_(memory), + f_(std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), std::move(f))), + bridge_(&detail::bridge_of(ex_)), + key_(bridge_->add(*this)) {} + + /** Not copyable: the bridge delivers to it by its address. */ + page_call(const page_call&) = delete; + + /** Not copy-assignable: the bridge delivers to it by its address. */ + page_call& operator=(const page_call&) = delete; + + /** Destroys the function: a call from now on, or one posted and not yet run, reaches nothing. + */ + ~page_call() { + if (bridge_ != nullptr) { + bridge_->remove(key_); + } + } + + /** + * The JavaScript function, of one argument, which the program hands to the page. + * + * @return The function; undefined once the io_context is destroyed. + */ + [[nodiscard]] emscripten::val function() const { + return bridge_ != nullptr ? bridge_->function(key_) : emscripten::val::undefined(); + } + +private: + bool deliver(const emscripten::val& argument) override { + trystero::detail::post(ex_, memory_, [weak = std::weak_ptr(f_), argument] { + if (const auto f = weak.lock()) { + (*f)(argument); + } + }); + return false; + } + + void shutdown() noexcept override { bridge_ = nullptr; } + + webcpp::asio::any_io_executor ex_; + std::pmr::memory_resource* memory_; + std::shared_ptr f_; + webcpp::asio::browser::bridge* bridge_; + std::uint64_t key_; +}; + +} // namespace webcpp::trystero::platform + +#endif diff --git a/include/webcpp/trystero/platform/sealer.hpp b/include/webcpp/trystero/platform/sealer.hpp new file mode 100644 index 0000000..7bd9852 --- /dev/null +++ b/include/webcpp/trystero/platform/sealer.hpp @@ -0,0 +1,488 @@ +// 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_PLATFORM_SEALER_HPP +#define WEBCPP_TRYSTERO_PLATFORM_SEALER_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include // lint-world: posts handlers only + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#include // lint-world: binds an allocator only +#include // lint-world: awaits the page's promises +#include // lint-world: names its executor only + +#include +#include +#include + +#include +#else +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::platform { + +namespace detail { + +#ifdef WEBCPP_TARGET_EMSCRIPTEN + +// The page's Web Crypto, called from C++. Each function is an EM_ASM block in an inline function, +// which Emscripten allows in several translation units, as webcpp::webrtc's and webcpp::beast's +// browser imports are. A Web Crypto call is made inside an async function, so that what it throws +// becomes the rejection of the promise it returns, and no JavaScript exception reaches a +// WebAssembly frame. The functions use Emval and HEAPU8, which webcpp::asio's browser runtime has +// Emscripten link, in every program on /webcpp/asio//asio. + +// clang-format off +/** Copies the first `size` bytes of `bytes`, a `Uint8Array`, to `data`. */ +// NOLINTNEXTLINE(misc-const-correctness): JavaScript writes to the pointed WebAssembly storage +inline void js_copy(emscripten::EM_VAL bytes, void* data, std::size_t size) { + EM_ASM(({ + const bytes = Emval.toValue($0); + const data = $1 >>> 0; + const size = $2 >>> 0; + + HEAPU8.set(bytes.subarray(0, size), data); + }), bytes, data, size); +} + +/** + * A promise of the AES-GCM key of the `size` raw bytes at `key`, from `crypto.subtle.importKey`, + * rejected where there is no `crypto.subtle`. + */ +inline emscripten::EM_VAL js_import_key(const std::uint8_t* key, std::size_t size) { + return reinterpret_cast(EM_ASM_PTR(({ + const key = $0 >>> 0; + const size = $1 >>> 0; + + const raw = HEAPU8.slice(key, key + size); + return Emval.toHandle((async () => crypto.subtle.importKey('raw', raw, 'AES-GCM', false, + ['encrypt', 'decrypt']))()); + }), key, size)); +} + +/** + * A promise of `crypto.subtle.encrypt`, or `decrypt`, of the `size` bytes at `data` under `key` + * and the IV at `iv`, rejected for what the call throws as for what it rejects. + */ +inline emscripten::EM_VAL js_crypt(bool decrypt, emscripten::EM_VAL key, const std::uint8_t* iv, + std::size_t iv_size, const void* data, std::size_t size) { + return reinterpret_cast(EM_ASM_PTR(({ + const decrypt = $0; + const key = Emval.toValue($1); + const iv = HEAPU8.slice($2 >>> 0, ($2 >>> 0) + ($3 >>> 0)); + const data = HEAPU8.slice($4 >>> 0, ($4 >>> 0) + ($5 >>> 0)); + + const algorithm = {name: 'AES-GCM', iv}; + return Emval.toHandle((async () => decrypt ? crypto.subtle.decrypt(algorithm, key, data) + : crypto.subtle.encrypt(algorithm, key, data))()); + }), decrypt, key, iv, iv_size, data, size)); +} +// clang-format on + +/** Takes ownership of a handle an import returned. */ +inline emscripten::val take(emscripten::EM_VAL handle) { + return emscripten::val::take_ownership(handle); +} + +/** + * A copy of the bytes of a Web Crypto settlement, in `memory`; nothing when it is no `ArrayBuffer`, + * which a page whose `crypto.subtle` was replaced can settle with, and whose reading as one could + * throw (`new Uint8Array(-1)`) or read what it is not. + */ +inline std::optional from_js(const emscripten::val& buffer, + std::pmr::memory_resource* memory) { + if (!buffer.instanceof(emscripten::val::global("ArrayBuffer"))) { + return std::nullopt; + } + const emscripten::val view = emscripten::val::global("Uint8Array").new_(buffer); + backend::bytes out(view["length"].as(), memory); + js_copy(view.as_handle(), out.data(), out.size()); + return out; +} + +#else + +/** Frees an OpenSSL cipher context. */ +struct cipher_context_deleter { + /** Frees `c`. */ + void operator()(EVP_CIPHER_CTX* c) const { EVP_CIPHER_CTX_free(c); } +}; + +/** An OpenSSL cipher context, freed with its owner. */ +using cipher_context = std::unique_ptr; + +/** The size of AES-GCM's authentication tag, which WebCrypto appends to the ciphertext. */ +inline constexpr std::size_t gcm_tag_size = 16; + +/** AES-256-GCM with a 16-byte IV, the ciphertext followed by its 16-byte tag: what WebCrypto's + * encrypt returns. */ +inline std::optional aes_gcm(bool encrypt, const std::array& key, + std::span iv, + std::span input, + std::pmr::memory_resource* memory) { + if (!encrypt && input.size() < gcm_tag_size) { + return std::nullopt; + } + const cipher_context context(EVP_CIPHER_CTX_new()); + if (!context) { + return std::nullopt; + } + const auto body = encrypt ? input : input.first(input.size() - gcm_tag_size); + backend::bytes out(body.size() + (encrypt ? gcm_tag_size : 0), memory); + int length = 0; + int final_length = 0; + // OpenSSL's functions return 0 when they fail. + bool ok = EVP_CipherInit_ex(context.get(), EVP_aes_256_gcm(), nullptr, nullptr, nullptr, + encrypt ? 1 : 0) != 0 && + EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_SET_IVLEN, + static_cast(iv.size()), nullptr) != 0 && + EVP_CipherInit_ex(context.get(), nullptr, nullptr, key.data(), iv.data(), -1) != 0 && + EVP_CipherUpdate(context.get(), out.data(), &length, body.data(), + static_cast(body.size())) != 0; + if (ok && !encrypt) { + // OpenSSL takes the expected tag through a pointer to mutable bytes, and only reads it. + auto* tag = const_cast(input.data() + body.size()); + ok = EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_SET_TAG, + static_cast(gcm_tag_size), tag) != 0; + } + ok = ok && EVP_CipherFinal_ex(context.get(), out.data() + length, &final_length) != 0; + if (ok && encrypt) { + ok = EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_GET_TAG, + static_cast(gcm_tag_size), out.data() + body.size()) != 0; + } + if (!ok) { + return std::nullopt; + } + return out; +} + +#endif + +} // namespace detail + +#ifdef WEBCPP_TARGET_EMSCRIPTEN + +/** + * AES-GCM under one room key, in Trystero's sealed text form: on emscripten through the page's + * `crypto.subtle`, under a key imported once, as Trystero's `encrypt` and `decrypt` do. + * + * Each Web Crypto promise is awaited with webcpp::asio's `browser::async_await`, which posts its + * settlement to the executor, through the io_context's own executor when the executor is one, so + * that the wait and the settlement's post are both in the room's resource. The text is copied into + * JavaScript during the call; an operation that arrives while the key is still being imported waits + * with a copy of its text, in the room's resource. Without `crypto.subtle`, outside a secure + * context, every operation fails. A seal's IV comes from the platform's one source of randomness, + * the page's `crypto.getRandomValues` there. + * + * @see "The platform backend", in the guide. + */ +class sealer : public backend::sealer, public std::enable_shared_from_this { +public: + /** What a seal or an open completes with: an error, or the text, a view valid for the call. */ + using done_handler = handler; + + /** + * Constructs a sealer under a room's key, which it imports on its first operation. + * + * @param ex The executor its completions run on, an io_context's of webcpp::asio, which must + * outlive the sealer's pending promises. + * @param key The raw AES-256 key, `protocol::seal_key`'s. + * @param memory The room's resource, which its texts, its waiting operations and its + * completions are allocated in. + */ + sealer(webcpp::asio::any_io_executor ex, std::array key, + std::pmr::memory_resource* memory) + : ex_(std::move(ex)), raw_key_(key), memory_(memory), waiting_(memory) {} + + /** + * Seals a text under a fresh random IV, with `crypto.subtle.encrypt`. + * + * @param plaintext The text, read during the call. + * @param done Called with the sealed text, or with `error::backend_failure` when the key + * cannot be imported, the page has no entropy for the IV, or the encryption fails. + */ + void seal(std::string_view plaintext, done_handler done) override { + if (state_ == key_state::ready) { + encrypt(plaintext, std::move(done)); + return; + } + wait_for_key({std::allocator_arg, allocator(), + [plaintext = std::pmr::string(plaintext, memory_), done = std::move(done)]( + sealer& self, bool ok) mutable { + if (!ok) { + done(make_error_code(error::backend_failure), {}); + return; + } + self.encrypt(plaintext, std::move(done)); + }}); + } + + /** + * Opens a sealed text, with `crypto.subtle.decrypt`. + * + * @param sealed The sealed text, read during the call. + * @param done Called with the plaintext, or with `error::wrong_password` when the text was + * sealed under another key or is not a sealed text, and `error::backend_failure` when the key + * cannot be imported. + */ + void open(std::string_view sealed, done_handler done) override { + if (state_ == key_state::ready) { + decrypt(sealed, std::move(done)); + return; + } + wait_for_key({std::allocator_arg, allocator(), + [sealed = std::pmr::string(sealed, memory_), done = std::move(done)]( + sealer& self, bool ok) mutable { + if (!ok) { + done(make_error_code(error::backend_failure), {}); + return; + } + self.decrypt(sealed, std::move(done)); + }}); + } + +private: + using waiting_operation = handler; + + [[nodiscard]] std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } + + /** Calls `done` with `failure` after the call, on the executor. */ + void fail(done_handler done, trystero::error failure) { + trystero::detail::post(ex_, memory_, [done = std::move(done), failure]() mutable { + done(make_error_code(failure), {}); + }); + } + + /** + * Awaits `promise`, its settlement posted to `handler` through the io_context's own executor + * when `ex_` is one. + * + * Tip: as `trystero::detail::post` does. Asio posts what it posts through an `any_io_executor` + * in a function object and an operation of `std::allocator`, which it takes from the C library + * when its cache has none (measured: two for each seal and each open); through the io_context's + * own executor the operation is allocated as the handler's allocator says, in the room's + * resource. + */ + template + void await(emscripten::val promise, Handler&& handler) { + if (const auto* io = ex_.target()) { + webcpp::asio::browser::async_await(*io, std::move(promise), + std::forward(handler)); + return; + } + webcpp::asio::browser::async_await(ex_, std::move(promise), std::forward(handler)); + } + + void encrypt(std::string_view plaintext, done_handler done) { + std::array iv{}; + if (!detail::fill_random(iv)) { + fail(std::move(done), error::backend_failure); + return; + } + await(detail::take(detail::js_crypt(false, key_.as_handle(), iv.data(), iv.size(), + plaintext.data(), plaintext.size())), + webcpp::asio::bind_allocator( + allocator(), + [iv, done = std::move(done), memory = memory_]( + boost::system::error_code ec, const emscripten::val& cipher) mutable { + const auto bytes = ec ? std::nullopt : detail::from_js(cipher, memory); + if (!bytes) { + done(make_error_code(error::backend_failure), {}); + return; + } + const auto sealed = protocol::format_sealed(iv, *bytes, memory); + done({}, sealed); + })); + } + + void decrypt(std::string_view sealed, done_handler done) { + const auto parts = protocol::parse_sealed(sealed, memory_); + if (!parts || parts->iv.empty()) { + fail(std::move(done), error::wrong_password); + return; + } + await(detail::take(detail::js_crypt(true, key_.as_handle(), parts->iv.data(), + parts->iv.size(), parts->ciphertext.data(), + parts->ciphertext.size())), + webcpp::asio::bind_allocator(allocator(), [done = std::move(done), memory = memory_]( + boost::system::error_code ec, + const emscripten::val& plain) mutable { + if (ec) { + done(make_error_code(error::wrong_password), {}); + return; + } + const auto b = detail::from_js(plain, memory); + if (!b) { + done(make_error_code(error::backend_failure), {}); + return; + } + done({}, std::string_view(reinterpret_cast(b->data()), b->size())); + })); + } + + /** + * Runs `op` once the key is imported, or has failed to be: after the call in every case, so + * that no completion runs inside the operation that started it. + */ + void wait_for_key(waiting_operation op) { + const std::weak_ptr weak = weak_from_this(); + if (state_ == key_state::failed) { + trystero::detail::post(ex_, memory_, [weak, op = std::move(op)]() mutable { + if (const auto self = weak.lock()) { + op(*self, false); + } + }); + return; + } + waiting_.push_back(std::move(op)); + if (state_ == key_state::importing) { + return; + } + state_ = key_state::importing; + await(detail::take(detail::js_import_key(raw_key_.data(), raw_key_.size())), + webcpp::asio::bind_allocator( + allocator(), [weak](boost::system::error_code ec, const emscripten::val& key) { + if (const auto self = weak.lock()) { + self->key_imported(!ec, key); + } + })); + } + + void key_imported(bool ok, const emscripten::val& key) { + state_ = ok ? key_state::ready : key_state::failed; + key_ = key; + std::pmr::deque ready(allocator()); + ready.swap(waiting_); + for (auto& op : ready) { + op(*this, ok); + } + } + + enum class key_state : std::uint8_t { none, importing, ready, failed }; + + webcpp::asio::any_io_executor ex_; + std::array raw_key_; + std::pmr::memory_resource* memory_; + key_state state_ = key_state::none; + emscripten::val key_ = emscripten::val::undefined(); + std::pmr::deque waiting_; +}; + +#else + +/** + * AES-GCM under one room key, in Trystero's sealed text form: natively through OpenSSL, what + * Trystero's `encrypt` and `decrypt` do with `crypto.subtle`. + * + * It works synchronously and posts each completion to the executor, as the backend interface asks: + * a handler never runs inside the call that started it. Its texts and completions are in the + * room's resource; OpenSSL's cipher context is OpenSSL's. A seal's IV comes from the platform's one + * source of randomness, OpenSSL's generator there. It needs no exceptions. + * + * @see "The platform backend", in the guide. + */ +class sealer : public backend::sealer { +public: + /** What a seal or an open completes with: an error, or the text, a view valid for the call. */ + using done_handler = handler; + + /** + * Constructs a sealer under a room's key. + * + * @param ex The executor its completions are posted to. + * @param key The raw AES-256 key, `protocol::seal_key`'s. + * @param memory The room's resource, which its texts and its completions are allocated in; it + * must outlive the completions it posts. + */ + sealer(webcpp::asio::any_io_executor ex, std::array key, + std::pmr::memory_resource* memory) + : ex_(std::move(ex)), key_(key), memory_(memory) {} + + /** + * Seals a text under a fresh random IV. + * + * @param plaintext The text, read during the call. + * @param done Called on the executor with the sealed text, or with `error::backend_failure` + * when there is no randomness for the IV or OpenSSL fails. + */ + void seal(std::string_view plaintext, done_handler done) override { + std::array iv{}; + if (!detail::fill_random(iv)) { + complete(std::move(done), error::backend_failure); + return; + } + const auto cipher = detail::aes_gcm( + true, key_, iv, + std::span(reinterpret_cast(plaintext.data()), plaintext.size()), + memory_); + if (!cipher) { + complete(std::move(done), error::backend_failure); + return; + } + complete(std::move(done), {}, protocol::format_sealed(iv, *cipher, memory_)); + } + + /** + * Opens a sealed text. + * + * @param sealed The sealed text, read during the call. + * @param done Called on the executor with the plaintext, or with `error::wrong_password` when + * the text was sealed under another key or is not a sealed text. + */ + void open(std::string_view sealed, done_handler done) override { + const auto parts = protocol::parse_sealed(sealed, memory_); + const auto plain = parts && !parts->iv.empty() + ? detail::aes_gcm(false, key_, parts->iv, parts->ciphertext, memory_) + : std::nullopt; + if (!plain) { + complete(std::move(done), error::wrong_password); + return; + } + complete(std::move(done), {}, std::pmr::string(plain->begin(), plain->end(), memory_)); + } + +private: + void complete(done_handler done, backend::error_code ec, std::pmr::string text) { + trystero::detail::post( + ex_, memory_, + [done = std::move(done), ec, text = std::move(text)]() mutable { done(ec, text); }); + } + + void complete(done_handler done, error e) { + complete(std::move(done), make_error_code(e), std::pmr::string(memory_)); + } + + webcpp::asio::any_io_executor ex_; + std::array key_; + std::pmr::memory_resource* memory_; +}; + +#endif + +} // namespace webcpp::trystero::platform + +#endif diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp new file mode 100644 index 0000000..81d5cda --- /dev/null +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -0,0 +1,837 @@ +// 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_PLATFORM_WEBSOCKET_HPP +#define WEBCPP_TRYSTERO_PLATFORM_WEBSOCKET_HPP + +#include + +#include +#include +#include +#include + +#include // lint-world: the relays' WebSockets +#include // lint-world: binds an allocator only +#include // lint-world: a text's buffer only +#include // lint-world: the relays' WebSockets +#include // lint-world: the relays' TLS +#include // lint-world: the relays' WebSockets +#include // lint-world: the relays' TLS +#include // lint-world: the relays' WebSockets +#include // lint-world: the relays' WebSockets + +#ifndef WEBCPP_TARGET_EMSCRIPTEN +#include // lint-world: the relays' WebSockets + +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::platform { + +/** + * What a relay's WebSocket tolerates of a relay that stops reading or answering. + * + * @see "The platform backend", in the guide. + */ +struct websocket_limits { + /** + * The most bytes of text queued to write: a relay that stops reading lets them pile up, and a + * text beyond this drops the connection, which reports a close, so that the room reconnects + * with its backoff. + * + * It bounds the session's own queue on both targets, and in a page also what the page's + * `WebSocket` holds unsent, its `bufferedAmount`, through webcpp::beast's `queue_limits::send`. + */ + std::size_t max_queued_bytes = protocol::max_queued_relay_bytes; + + /** + * How long the connection may stay silent: half of it, a keep-alive ping is sent, and a relay + * that answers nothing within the whole of it is closed, which reports a close. + * + * It counts the bytes received, and a ping waits for the write in flight. Native only: a page's + * `WebSocket` cannot ping, so a page's relay socket has no idle timeout. + */ + std::chrono::seconds idle_timeout = std::chrono::seconds(30); +}; + +namespace detail { + +/** The error OpenSSL queued last, or `not_enough_memory` when none; the queue is emptied. */ +inline boost::system::error_code openssl_error() { +#ifndef WEBCPP_TARGET_EMSCRIPTEN + // The queue's first error may be one an earlier call left behind; the last is the failure's. + const auto code = ERR_peek_last_error(); + ERR_clear_error(); + // Asio's own TLS errors are OpenSSL's codes, in its category, as an int. + if (code != 0) { + return {static_cast(code), webcpp::asio::error::get_ssl_category()}; + } +#endif + // OpenSSL queues no reason when it cannot allocate a context. + return boost::system::errc::make_error_code(boost::system::errc::not_enough_memory); +} + +} // namespace detail + +/** + * Makes the TLS context of the relays' `wss://` connections, a client of TLS 1.2 or newer that + * verifies each relay against the system's certificate authorities. + * + * Natively the authorities are those OpenSSL's default verify paths name, the system's own; a + * relay whose certificate does not verify is unreachable. On Windows those paths are in OpenSSL's + * build-time directory, which neither Windows nor webcpp fills, and OpenSSL reads no Windows + * certificate store by default, so there are none there unless `SSL_CERT_FILE` or `SSL_CERT_DIR` + * names some: a Windows program gives the backend its own context. A program that trusts other + * authorities, as webcpp's embedded Mozilla roots (`webcpp::asio::make_tls_client_context()`) or a + * private one, makes its context itself and gives it to the backend. In the browser the page's + * `WebSocket` verifies the relay against the browser's authorities, and the context records only + * the policy its stream asks for: a client that verifies its peer. + * + * @return The context, or the error that kept OpenSSL from making it or from finding the system's + * authorities. + * @see "The relays", in the guide. + */ +[[nodiscard]] inline boost::system::result make_tls_context() { +#ifndef WEBCPP_TARGET_EMSCRIPTEN + // What an earlier call left in OpenSSL's queue is not this one's error. + ERR_clear_error(); + std::unique_ptr raw(SSL_CTX_new(TLS_client_method()), + &SSL_CTX_free); + if (!raw) { + return detail::openssl_error(); + } + if (SSL_CTX_set_min_proto_version(raw.get(), TLS1_2_VERSION) != 1) { + return detail::openssl_error(); + } + SSL_CTX_set_options(raw.get(), SSL_OP_NO_COMPRESSION); + SSL_CTX_set_verify(raw.get(), SSL_VERIFY_PEER, nullptr); + // The system's certificate authorities: the files of OpenSSL's default verify paths, read as + // Asio's set_default_verify_paths(ec) reads them, which also returns a copy of its error. + if (SSL_CTX_set_default_verify_paths(raw.get()) != 1) { // lint-world: the system's authorities + return detail::openssl_error(); + } + // The context owns the handle from here, and throws only for a null one. + return webcpp::asio::ssl::context(raw.release()); +#else + webcpp::asio::ssl::context context(webcpp::asio::ssl::context::tls_client); + boost::system::error_code ec; + context.set_verify_mode(webcpp::asio::ssl::verify_peer, ec); + if (ec) { + return ec; + } + return context; +#endif +} + +namespace detail { + +// Its implicit move assignment may allocate: a std::pmr member copies when the two resources +// differ, which bugprone-exception-escape, expecting every move assignment not to throw, reports. +/** A WebSocket URL's parts, in the memory resource it was parsed into. */ +struct url_parts { // NOLINT(bugprone-exception-escape) + /** Whether the scheme is `wss`. */ + bool secure = false; + /** Whether the host is a name, not an address: TLS names only a name to the server (SNI). */ + bool named = false; + /** + * The host the resolver looks up: a name in lower case, or an address, IPv6 without brackets. + */ + std::pmr::string host; + /** The port, in decimal, the scheme's default when the URL names none. */ + std::pmr::string port; + /** + * The host the handshake names, as a page's `WebSocket` does: an IPv6 address in brackets, and + * the port unless it is the scheme's default. + */ + std::pmr::string handshake_host; + /** The path and the query, `/` when the URL has neither. */ + std::pmr::string target; +}; + +/** + * Whether a decoded host name holds a byte that a page's URL parser refuses in a host, or a byte + * beyond ASCII, of an international name that a page turns into its A-label and this parser does + * not. + */ +inline bool forbidden_in_host(std::string_view name) { + constexpr std::string_view forbidden = "#%/:<>?@[\\]^|"; + return std::ranges::any_of(name, [forbidden](char c) { + const auto byte = static_cast(c); + return byte <= 0x20U || byte >= 0x7FU || forbidden.find(c) != std::string_view::npos; + }); +} + +/** + * Whether a decoded host name in lower case ends in a number, as a page's URL parser asks before it + * reads the host as an IPv4 address: its last label, a final empty one left out, is decimal digits, + * or `0x` and hexadecimal digits. + */ +inline bool ends_in_a_number(std::string_view name) { + if (name.ends_with('.')) { + name.remove_suffix(1); + } + const auto dot = name.rfind('.'); + const auto last = dot == std::string_view::npos ? name : name.substr(dot + 1); + if (last.starts_with("0x")) { + return std::ranges::all_of(last.substr(2), boost::urls::grammar::hexdig_chars); + } + return !last.empty() && std::ranges::all_of(last, boost::urls::grammar::digit_chars); +} + +/** + * The parts of a `ws://` or `wss://` URL, in `memory`, read with Boost.URL; nothing for another + * scheme, for a URL without a host, with userinfo or a fragment, which a page's `WebSocket` refuses + * too, with a port beyond 65535, or with a host that a page's URL parser refuses or reads + * otherwise. + */ +inline std::optional parse_url( + std::string_view url, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + const auto parsed = boost::urls::parse_uri(url); + if (!parsed) { + return std::nullopt; + } + const boost::urls::url_view& view = *parsed; + const auto scheme = view.scheme_id(); + if ((scheme != boost::urls::scheme::ws && scheme != boost::urls::scheme::wss) || + !view.has_authority() || view.has_userinfo() || view.has_fragment()) { + return std::nullopt; + } + const bool secure = scheme == boost::urls::scheme::wss; + const std::uint16_t default_port = secure ? 443 : 80; + std::uint16_t port = default_port; + if (const auto text = view.port(); view.has_port() && !text.empty()) { + const auto* const end = text.data() + text.size(); + const auto [last, error] = std::from_chars(text.data(), end, port); + if (error != std::errc{} || last != end) { + return std::nullopt; + } + } + url_parts out{ + .secure = secure, + .named = false, + .host = std::pmr::string(memory), + .port = std::pmr::string(memory), + .handshake_host = std::pmr::string(memory), + .target = std::pmr::string(memory), + }; + const auto address = view.encoded_host_address(); + switch (view.host_type()) { + case boost::urls::host_type::name: { + const auto decoded = *address; + out.host.assign(decoded.begin(), decoded.end()); + // A host name is case-insensitive; a page's URL parser writes it in lower case. + std::ranges::transform(out.host, out.host.begin(), [](char c) { + return c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c; + }); + if (out.host.empty() || forbidden_in_host(out.host)) { + return std::nullopt; + } + // Escaped digits make Boost.URL read an address as a name; decoded, it is an address, + // as a page reads it, and TLS names no address to the server. A decoded name holds no + // ':', refused above, so it is never an IPv6 address. + out.named = !boost::urls::parse_ipv4_address(out.host).has_value(); + // A page reads a host that ends in a number as an IPv4 address in any of its forms + // (127.1, octal and hexadecimal parts, a single number), or refuses it: a form other + // than a dotted quad is refused here, never resolved as a name. + if (out.named && ends_in_a_number(out.host)) { + return std::nullopt; + } + out.handshake_host = out.host; + break; + } + case boost::urls::host_type::ipv4: + out.host.assign(address.data(), address.size()); + out.handshake_host = out.host; + break; + case boost::urls::host_type::ipv6: + out.host.assign(address.data(), address.size()); + out.handshake_host.push_back('['); + out.handshake_host += out.host; + out.handshake_host.push_back(']'); + break; + default: // none, or an IPvFuture address, which no resolver knows + return std::nullopt; + } + std::array digits{}; + const auto written = std::to_chars(digits.data(), digits.data() + digits.size(), port); + out.port.assign(digits.data(), written.ptr); + if (port != default_port) { + out.handshake_host.push_back(':'); + out.handshake_host += out.port; + } + const auto target = view.encoded_target(); + if (target.empty() || target.front() != '/') { + out.target.assign("/"); + } + out.target.append(target.data(), target.size()); + return out; +} + +/** + * One WebSocket connection over webcpp::beast, on both targets, composed of Asio operations on the + * room's executor, each a callback that holds the session until it completes: resolve, connect, TLS + * for `wss`, the handshake, then a read loop handing each message to the handler as a view of the + * read buffer. Writes are queued, one in flight at a time, as Beast requires; a write that fails + * ends the connection, which reports its close once. + * + * Tip: every operation's handler carries the room's allocator, so that what Asio and Beast + * allocate for it, and the read buffer, are in the room's resource beside the session, its + * handlers and its queued texts; the reads' and the writes' handlers have no executor of their own + * (`transfer_handler`), so that Asio wraps none of their completions. Natively what Beast, Asio + * and OpenSSL allocate of their own takes no allocator and stays outside the room's resource, for + * each connection: the WebSocket stream's state and the TCP stream's, the WebSocket's write buffer + * and, over TLS, Asio's two TLS buffers and OpenSSL's state; the resolver's state and results; the + * handshake's request and response and the header fields of both, the response's header at most + * 8 KiB, which webcpp::beast's bounded handshake layer reads through Beast's own parser, keeping a + * header line split between two reads in the room's resource, and reading no byte of the body of a + * response that refuses the upgrade; the verify callback Asio's `set_verify_callback` makes with + * `new`, with its copy of the host; each wait of Beast's timers, from Asio's per-thread recycling + * cache (the TCP stream's deadline over the connection and the TLS handshake, the WebSocket's + * handshake, idle and close timeouts, the idle one started again at each read); and each + * keep-alive ping's frame. On Emscripten the page's stream keeps its state in the room's resource + * too, and its `WebSocket` makes the handshake; what stays outside is, for each connection, the + * results webcpp::asio's page resolver makes with `new` (Asio's list of one entry, its shared count + * and the entry's storage, and two copies of the host when it is longer than a short string holds, + * 10 bytes in a page), and, for each event of the page's `WebSocket` (its open, each message and + * its close), the C library's allocation embind makes for the `std::string` into which + * webcpp::beast's page stream reads the event's type, and for a message a second, for the type of + * its data, each freed before the call that made it returns. + */ +template +class websocket_session : public std::enable_shared_from_this> { +public: + /** The executor every handler runs on. */ + using executor_type = webcpp::asio::any_io_executor; + /** Asio's TCP. */ + using tcp = webcpp::asio::ip::tcp; + /** The transport the WebSocket runs over: TLS over TCP for `wss`, TCP for `ws`. */ + using transport = + std::conditional_t, + webcpp::beast::tcp_stream>; +#ifdef WEBCPP_TARGET_EMSCRIPTEN + /** The stream the WebSocket runs over: in a page the transport, whose WebSocket reads its own + * handshake response. */ + using next_layer = transport; +#else + /** + * The stream the WebSocket runs over: natively the transport under webcpp::beast's bounded + * handshake layer, which reads a refusal's header alone, a split header line kept in the room's + * resource. + */ + using next_layer = + webcpp::beast::websocket::bounded_handshake_stream>; +#endif + /** Beast's WebSocket stream. */ + using stream_type = webcpp::beast::websocket::stream; + + /** A session, not started, for a parsed URL, in `memory`; `tls` is read for `wss` only. */ + websocket_session(const executor_type& ex, webcpp::asio::ssl::context* tls, url_parts url, + backend::websocket::handlers h, std::pmr::memory_resource* memory, + websocket_limits limits) + : ex_(ex), + resolver_(ex), + ws_(make_stream(ex, tls, memory)), + url_(std::move(url)), + memory_(memory), + limits_(limits), + h_(std::allocate_shared( + std::pmr::polymorphic_allocator<>(memory), std::move(h))), + buffer_(std::pmr::polymorphic_allocator(memory)), + queue_(memory), + writing_text_(memory) {} + + /** + * Starts to resolve the relay's host; a session without a host, whose URL did not parse, + * reports its close from the executor instead. + */ + void start() { + if (url_.host.empty()) { + trystero::detail::post(ex_, memory_, + [self = this->shared_from_this()] { self->end(); }); + return; + } + resolver_.async_resolve( + url_.host, url_.port, + bound([self = this->shared_from_this()](const boost::system::error_code& ec, + const tcp::resolver::results_type& results) { + self->on_resolve(ec, results); + })); + } + + /** + * Queues a text to write, when open and not closing; one write is in flight at a time. A text + * that would take the queue beyond `websocket_limits::max_queued_bytes` drops the connection. + */ + void send(std::string_view text) { + if (!open_ || closing_) { + return; + } + if (queued_bytes_ + text.size() > limits_.max_queued_bytes) { + // The relay stopped reading: no close frame could reach it, so the socket is closed, + // the read fails, and end() reports the close. + closing_ = true; + webcpp::beast::get_lowest_layer(ws_).close(); + return; + } + queued_bytes_ += text.size(); + queue_.emplace_back(text); // a write outlives the call, so the text is copied once, here + if (std::exchange(writing_, true)) { + return; + } + write_next(); + } + + /** Closes with a WebSocket close frame, or drops a connection still being made. */ + void close() { + if (closing_ || ended_) { + return; + } + closing_ = true; + if (!open_) { + // Still connecting: the operation under way ends with an error, and reports. + resolver_.cancel(); + webcpp::beast::get_lowest_layer(ws_).close(); + return; + } + ws_.async_close(webcpp::beast::websocket::close_code::normal, + bound([self = this->shared_from_this()](const boost::system::error_code&) { + webcpp::beast::get_lowest_layer(self->ws_).close(); + })); + } + + /** The owner let go: nothing is reported any more, and the connection is dropped. */ + void abandon() { + h_.reset(); + closing_ = true; + // A resolution under way is not cancelled: `on_resolve` drops its result, as closing, and + // Asio's cancel allocates a new cancellation token, which a destructor, the caller here, + // must not risk. + webcpp::beast::get_lowest_layer(ws_).close(); + } + +private: + /** The stream, natively Boost.Beast's own; on Emscripten its state is in `memory`. */ + static stream_type make_stream(const executor_type& ex, webcpp::asio::ssl::context* tls, + std::pmr::memory_resource* memory) { +#ifdef WEBCPP_TARGET_EMSCRIPTEN + const std::pmr::polymorphic_allocator allocator(memory); + if constexpr (Secure) { + return stream_type(std::allocator_arg, allocator, ex, *tls); + } else { + (void)tls; + return stream_type(std::allocator_arg, allocator, ex); + } +#else + const std::pmr::polymorphic_allocator allocator(memory); + if constexpr (Secure) { + return stream_type(std::allocator_arg, allocator, ex, *tls); + } else { + (void)tls; + return stream_type(std::allocator_arg, allocator, ex); + } +#endif + } + + /** The TLS stream, natively under the bounded handshake layer, in a page the next layer. */ + transport& tls_stream() { +#ifdef WEBCPP_TARGET_EMSCRIPTEN + return ws_.next_layer(); +#else + return ws_.next_layer().next_layer(); +#endif + } + + /** `f` with the room's allocator, which Asio and Beast allocate its operation with. */ + template + auto bound(F&& f) const { + return webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory_), + std::forward(f)); + } + + void on_resolve(const boost::system::error_code& ec, + const tcp::resolver::results_type& results) { + if (ec || closing_) { + end(); + return; + } + auto& lowest = webcpp::beast::get_lowest_layer(ws_); + lowest.expires_after(std::chrono::seconds(30)); // the connection and the TLS handshake + lowest.async_connect( + results, bound([self = this->shared_from_this()](const boost::system::error_code& error, + const tcp::endpoint&) { + self->on_connect(error); + })); + } + + void on_connect(const boost::system::error_code& ec) { + if (ec || closing_) { + end(); + return; + } + if constexpr (Secure) { + auto& tls = tls_stream(); + // The relay is verified whatever the context's own mode, which a program's context + // made as Asio makes a client's leaves at verify_none: natively a certificate that does + // not verify fails the handshake; a page's WebSocket always verifies, and its stream + // refuses a mode other than verify_peer, which it reads from the stream before the + // context. + boost::system::error_code verify; + tls.set_verify_mode(webcpp::asio::ssl::verify_peer, verify); + if (verify) { + end(); + return; + } +#ifndef WEBCPP_TARGET_EMSCRIPTEN + // SNI names a host name only, never an address (RFC 6066). + if (url_.named && !webcpp::beast::set_server_name(tls, url_.host)) { + end(); + return; + } + // Asio's verification takes a std::string, and reads an address as one. + tls.set_verify_callback( + webcpp::asio::ssl::host_name_verification(std::string(url_.host))); +#endif + // In a page its WebSocket sends the name and checks the certificate against the host. + tls.async_handshake( + webcpp::asio::ssl::stream_base::client, + bound([self = this->shared_from_this()](const boost::system::error_code& error) { + self->on_tls(error); + })); + } else { + handshake(); + } + } + + void on_tls(const boost::system::error_code& ec) { + if (ec || closing_) { + end(); + return; + } + handshake(); + } + + void handshake() { + webcpp::beast::get_lowest_layer(ws_).expires_never(); + // NOLINTNEXTLINE(misc-const-correctness): changed natively only + auto timeouts = webcpp::beast::websocket::stream_base::timeout::suggested( + webcpp::beast::role_type::client); +#ifndef WEBCPP_TARGET_EMSCRIPTEN + timeouts.idle_timeout = limits_.idle_timeout; + timeouts.keep_alive_pings = true; // a relay that reads nothing answers no ping +#endif + // A page's WebSocket cannot ping, and its stream refuses keep-alive pings: no idle timeout. + ws_.set_option(timeouts); +#ifdef WEBCPP_TARGET_EMSCRIPTEN + // The page's WebSocket writes at once: what a relay does not read piles up in its + // bufferedAmount, which the stream bounds as the session bounds its queue, and closes past. + ws_.set_option(webcpp::beast::websocket::queue_limits{ + .send = limits_.max_queued_bytes, + .receive = webcpp::beast::websocket::queue_limits{}.receive, + }); +#endif + ws_.text(true); + // A longer message fails the read, which closes the connection. It is set before the + // handshake: a page's stream checks each message as its event arrives, and a relay's first + // ones can arrive in the same task of the page as its open, before the handshake's + // completion runs on the executor. + ws_.read_message_max(protocol::max_relay_message_bytes); +#ifndef WEBCPP_TARGET_EMSCRIPTEN + // A relay that refuses the upgrade has its response's header read, at most 8 KiB, and no + // byte of its body: Beast's own parser would read a body of up to 8 MiB outside the room's + // resource. A page's WebSocket reads its own response. + ws_.next_layer().limits({.body = 0}); +#endif + ws_.async_handshake( + url_.handshake_host, url_.target, + bound([self = this->shared_from_this()](const boost::system::error_code& ec) { + self->on_handshake(ec); + })); + } + + void on_handshake(const boost::system::error_code& ec) { + if (ec || closing_) { + end(); + return; + } + open_ = true; + if (const auto h = h_; h && h->open) { + h->open(); + } + read(); + } + + /** + * A read's or a write's completion: the session, and the member it calls, through a pointer. + * + * Tip: the reads, and the writes, are a loop of asynchronous operations, not a recursion: each + * handler runs from the executor once the call that started its operation has returned, so the + * stack never grows. The member is called through a pointer, so that the analysis of calls + * (misc-no-recursion) sees no cycle through Asio's post on either target, natively in Boost's + * headers and on Emscripten in webcpp::asio's and webcpp::beast's own, where the reports would + * land. Its allocator is the room's, and it has no executor of its own, so that Asio completes + * it on the stream's executor, which it finds is an io_context's. Asio's type-erased handler, + * `any_completion_handler`, which the session used before, has an executor of another type, + * `any_completion_executor`: Asio made one around the stream's with `new` for each operation, + * and dispatched each completion through it in a function object of its own (measured natively: + * six `operator new` and four of Asio's recycled blocks for a text sent and its echo received). + */ + struct transfer_handler { + /** The room's allocator, which Asio and Beast allocate the operation with. */ + using allocator_type = std::pmr::polymorphic_allocator<>; + + /** The session, held until the operation completes. */ + std::shared_ptr self; + /** What the completion calls. */ + void (websocket_session::*member)(const boost::system::error_code&, std::size_t); + + /** The room's allocator. */ + [[nodiscard]] allocator_type get_allocator() const noexcept { + return allocator_type(self->memory_); + } + + /** Calls the member with the operation's result. */ + void operator()(const boost::system::error_code& ec, std::size_t size) const { + ((*self).*member)(ec, size); + } + }; + + void read() { + ws_.async_read(buffer_, transfer_handler{ + .self = this->shared_from_this(), + .member = &websocket_session::on_read, + }); + } + + void on_read(const boost::system::error_code& ec, std::size_t size) { + if (ec || ended_) { // a failed write ended it: nothing is reported after its close + end(); + return; + } + // A relay's messages are texts (NIP-01): a binary one is dropped, as the room would drop a + // text that is no Nostr message. + if (const auto h = h_; h && h->message && ws_.got_text()) { + const auto data = buffer_.cdata(); + h->message(std::string_view(static_cast(data.data()), size)); + } + buffer_.consume(buffer_.size()); + if (closing_) { + end(); + return; + } + read(); + } + + /** + * Writes the next queued text, moved out of the queue into `writing_text_` before its write + * starts; the completion writes the one after it. + * + * Tip: the connection can end while a write is in flight, and `end` then clears the queue; the + * text being written is no longer in it, so the write reads a text the session owns, and its + * completion touches only that text. Its completion calls it again from the executor, a loop + * and not a recursion, as the reads' (`transfer_handler`). + */ + void write_next() { + if (queue_.empty() || !open_ || ended_) { + writing_ = false; + return; + } + writing_text_ = std::move(queue_.front()); + queue_.pop_front(); + queued_bytes_ -= writing_text_.size(); + ws_.async_write(webcpp::asio::buffer(writing_text_), + transfer_handler{ + .self = this->shared_from_this(), + .member = &websocket_session::on_write, + }); + } + + void on_write(const boost::system::error_code& ec, std::size_t /*size*/) { + if (ec) { + fail(); + return; + } + write_next(); + } + + /** + * A write failed: the relay is unreachable, or, in a page, its `WebSocket` held more than the + * bound unsent, whose close event may never come. The connection is dropped and its close + * reported at once, without waiting for the read to fail; one already closing, whose writes + * fail as it closes, ends as its read does. + */ + void fail() { + writing_ = false; + if (std::exchange(closing_, true)) { + return; + } + webcpp::beast::get_lowest_layer(ws_).close(); + end(); + } + + void end() { + if (std::exchange(ended_, true)) { + return; + } + open_ = false; + queue_.clear(); + queued_bytes_ = 0; + if (const auto h = h_) { + if (auto f = std::exchange(h->close, {})) { + f(); + } + } + } + + executor_type ex_; + tcp::resolver resolver_; + stream_type ws_; + url_parts url_; + std::pmr::memory_resource* memory_; + websocket_limits limits_; + // Shared so that a handler that destroys the connection's owner during its own call outlives + // the call. + std::shared_ptr h_; + webcpp::beast::basic_flat_buffer> buffer_; + std::pmr::deque queue_; + std::size_t queued_bytes_ = 0; // of the texts in queue_ + std::pmr::string writing_text_; // the text whose write is in flight, out of queue_ + bool open_ = false; + bool writing_ = false; + bool closing_ = false; + bool ended_ = false; +}; + +/** What the caller holds: dropping it abandons the session, which may still be finishing an + * operation. */ +template +class websocket_handle : public backend::websocket { +public: + /** A handle of a started session. */ + explicit websocket_handle(std::shared_ptr> session) + : session_(std::move(session)) {} + + /** Abandons the session. */ + ~websocket_handle() override { session_->abandon(); } + + /** Sends a text through the session. */ + void send(std::string_view text) override { session_->send(text); } + + /** Closes the session. */ + void close() override { session_->close(); } + +private: + std::shared_ptr> session_; +}; + +} // namespace detail + +/** + * Connects to a Nostr relay over webcpp::beast, on both targets: `ws://` in the clear, `wss://` + * over TLS with `tls`; natively over Boost.Beast's own stream, in a page over its `WebSocket`. + * + * Writes are queued, one in flight at a time; a received text is handed over as a view of the + * read buffer, a binary message is dropped, and a message longer than + * `protocol::max_relay_message_bytes` closes the connection, a page's before it is copied into + * WebAssembly, the relay's first ones too. A relay that stops reading is dropped once the + * queue, or a page's `bufferedAmount`, would pass `limits.max_queued_bytes`, and, natively, one + * that stops answering once `limits.idle_timeout` passes with its keep-alive ping unanswered; each + * reports one close. The URL is read with Boost.URL: `ws://` or `wss://` in any case, a host name + * with its escapes decoded, an IPv4 address as a dotted quad or an IPv6 address in brackets, and a + * port up to 65535. A URL it refuses, which includes what a page's URL parser reads otherwise (an + * IPv4 shorthand such as `127.1`, an international name, a tab or a backslash), and a `wss://` URL + * without `tls`, report a close, as an unreachable relay does. A `wss://` connection asks for the + * relay's verification whatever the verify mode of `tls`, on both targets. Natively it names the + * host to the server (SNI) when it is a name, verifies the relay's certificate against the + * authorities of `tls`, and checks it against the URL's host, a name or an address; in a page the + * browser does all three, against its own authorities, and the connection reports a close, making + * no `WebSocket`, when `tls` asks for what a page cannot honour: authorities added, a client + * certificate or key, options, a method other than `tls_client` or `sslv23_client`, or a verify + * callback other than `host_name_verification` of the relay's host. It needs no exceptions. + * + * The connection, its handlers, its queued texts, its read buffer and its operations are in + * `memory`. What stays outside it, for each connection: natively what Boost.Beast, Asio and OpenSSL + * allocate of their own, their streams' state, the resolver's, the handshake's request and + * response, the verify callback, their timers' waits, the idle timer's again at each read, and + * each keep-alive ping's frame; a relay that answers the handshake with a status other than 101 + * has its response's header read, at most 8 KiB, and no byte of its body, through webcpp::beast's + * bounded handshake layer, before the connection reports its close. In a page, the page + * resolver's results, made with `new`, and, for each event of the page's `WebSocket`, the open, + * each message and the close, the C library's allocation embind makes for its type, and for a + * message a second, for the type of its data, each freed before the call that made it returns. + * + * @param ex The executor every handler runs on. + * @param tls The TLS context of `wss://`, which must outlive the connection, or null when the + * program has none; the connection verifies the relay even when its verify mode is `verify_none`, + * as Asio makes a client's context, natively against its authorities and in a page against the + * browser's. + * @param url The relay's URL, read during the call. + * @param h What the WebSocket reports. + * @param memory The room's resource, which the connection's own allocations are in. + * @param limits What it tolerates of a relay that stops reading or answering. + * @return The WebSocket; destroying it drops the connection without reporting it. + * @see "The platform backend", in the guide. + * @see "What stays outside the resource", in the guide. + */ +inline std::shared_ptr connect_websocket( + const webcpp::asio::any_io_executor& ex, webcpp::asio::ssl::context* tls, std::string_view url, + backend::websocket::handlers h, std::pmr::memory_resource* memory, + websocket_limits limits = {}) { + auto parts = detail::parse_url(url, memory); + if (!parts || (parts->secure && tls == nullptr)) { + // A session without a host reports its close once started. + parts = detail::url_parts{ + .secure = false, + .named = false, + .host = std::pmr::string(memory), + .port = std::pmr::string(memory), + .handshake_host = std::pmr::string(memory), + .target = std::pmr::string(memory), + }; + } + const std::pmr::polymorphic_allocator<> allocator(memory); + if (parts->secure) { + const auto session = std::allocate_shared>( + allocator, ex, tls, std::move(*parts), std::move(h), memory, limits); + session->start(); + return std::allocate_shared>(allocator, session); + } + const auto session = std::allocate_shared>( + allocator, ex, tls, std::move(*parts), std::move(h), memory, limits); + session->start(); + return std::allocate_shared>(allocator, session); +} + +} // namespace webcpp::trystero::platform + +#endif diff --git a/include/webcpp/trystero/protocol/action_wire.hpp b/include/webcpp/trystero/protocol/action_wire.hpp index 687baa0..0085905 100644 --- a/include/webcpp/trystero/protocol/action_wire.hpp +++ b/include/webcpp/trystero/protocol/action_wire.hpp @@ -11,6 +11,9 @@ #include +#include +#include + #include #include #include @@ -90,25 +93,45 @@ inline constexpr std::size_t chunk_size = max_action_frame_bytes - chunk_header_ inline constexpr std::size_t max_action_name_bytes = 32; /** The longest reason a rejected frame carries, in UTF-8 bytes. */ inline constexpr std::size_t max_reject_reason_bytes = 200; +/** The largest size an offer may announce, JavaScript's `Number.MAX_SAFE_INTEGER`, 2^53 - 1. */ +inline constexpr std::uint64_t max_offer_size = 9007199254740991; namespace detail { -/** Reads a big-endian uint32 at `at`. */ +/** Reads the big-endian uint16 at `at`, as `DataView`'s `getUint16`. */ +inline std::uint16_t get_u16(std::span in, std::size_t at) { + BOOST_ASSERT(at + 2 <= in.size()); + return boost::endian::load_big_u16(in.data() + at); +} + +/** Reads the big-endian uint32 at `at`, as `DataView`'s `getUint32`. */ inline std::uint32_t get_u32(std::span in, std::size_t at) { - std::uint32_t v = 0; - for (int i = 0; i < 4; ++i) { - v = (v << 8U) | in[at + i]; - } - return v; + BOOST_ASSERT(at + 4 <= in.size()); + return boost::endian::load_big_u32(in.data() + at); } -/** Reads a big-endian float64 at `at`. */ +/** Reads the big-endian float64 at `at`, as `DataView`'s `getFloat64`. */ inline double get_f64(std::span in, std::size_t at) { - std::uint64_t bits = 0; - for (int i = 0; i < 8; ++i) { - bits = (bits << 8U) | in[at + i]; - } - return std::bit_cast(bits); + BOOST_ASSERT(at + 8 <= in.size()); + return std::bit_cast(boost::endian::load_big_u64(in.data() + at)); +} + +/** Writes `value` as a big-endian uint16 at `at`, as `DataView`'s `setUint16`. */ +inline void set_u16(bytes& out, std::size_t at, std::uint16_t value) { + BOOST_ASSERT(at + 2 <= out.size()); + boost::endian::store_big_u16(out.data() + at, value); +} + +/** Writes `value` as a big-endian uint32 at `at`, as `DataView`'s `setUint32`. */ +inline void set_u32(bytes& out, std::size_t at, std::uint32_t value) { + BOOST_ASSERT(at + 4 <= out.size()); + boost::endian::store_big_u32(out.data() + at, value); +} + +/** Writes `value` as a big-endian float64 at `at`, as `DataView`'s `setFloat64`. */ +inline void set_f64(bytes& out, std::size_t at, double value) { + BOOST_ASSERT(at + 8 <= out.size()); + boost::endian::store_big_u64(out.data() + at, std::bit_cast(value)); } } // namespace detail @@ -145,19 +168,18 @@ inline void append_header(bytes& out, frame_kind kind, std::string_view name, pa out.resize(at + header_size, 0); out[at] = action_wire_version; out[at + 1] = static_cast(static_cast(kind) | - (static_cast(format) << 4U)); + (static_cast(format) << 4U)); std::memcpy(out.data() + at + 2, name.data(), name.size()); - out[at + 34] = static_cast(metadata.size() >> 8U); - out[at + 35] = static_cast(metadata.size() & 0xffU); + set_u16(out, at + 34, static_cast(metadata.size())); } /** Appends the header of a chunk or a transfer's answer: version, kind, transfer id. */ inline void append_control(bytes& out, frame_kind kind, std::uint32_t id) { - out.push_back(action_wire_version); - out.push_back(static_cast(kind)); - for (int i = 0; i < 4; ++i) { - out.push_back(static_cast(id >> (24U - (8 * i)))); - } + const auto at = out.size(); + out.resize(at + control_header_size); + out[at] = action_wire_version; + out[at + 1] = static_cast(kind); + set_u32(out, at + 2, id); } } // namespace detail @@ -197,13 +219,8 @@ inline void append_offer(bytes& out, std::string_view name, payload_format forma out.reserve(out.size() + offer_header_size + metadata.size()); const auto at = out.size(); detail::append_header(out, frame_kind::offer, name, format, metadata, offer_header_size); - for (int i = 0; i < 4; ++i) { - out[at + 36 + i] = static_cast(id >> (24U - (8 * i))); - } - const auto bits = std::bit_cast(static_cast(size)); - for (int i = 0; i < 8; ++i) { - out[at + 40 + i] = static_cast(bits >> (56U - (8 * i))); - } + detail::set_u32(out, at + 36, id); + detail::set_f64(out, at + 40, static_cast(size)); out.insert(out.end(), metadata.begin(), metadata.end()); } @@ -219,10 +236,9 @@ inline void append_chunk(bytes& out, std::uint32_t id, std::size_t offset, std::span data) { out.reserve(out.size() + chunk_header_size + data.size()); detail::append_control(out, frame_kind::chunk, id); - const auto bits = std::bit_cast(static_cast(offset)); - for (int i = 0; i < 8; ++i) { - out.push_back(static_cast(bits >> (56U - (8 * i)))); - } + const auto at = out.size(); + out.resize(at + chunk_header_size - control_header_size); + detail::set_f64(out, at, static_cast(offset)); out.insert(out.end(), data.begin(), data.end()); } @@ -373,8 +389,13 @@ struct proposal { std::string_view metadata; /** The transfer's id; offers only. */ std::uint32_t id = 0; - /** The payload's size; for an inline frame, the bytes that follow the metadata. */ - std::size_t size = 0; + /** + * The payload's size; for an inline frame, the bytes that follow the metadata. + * + * An offer's is a float64 on the wire, up to @ref max_offer_size, so it is 64 bits wide even + * where `std::size_t` is 32: a receiver compares it with its bound before it allocates. + */ + std::uint64_t size = 0; /** The payload; inline frames only. */ std::span payload; }; @@ -477,7 +498,7 @@ inline decode_result decode_proposal(std::span bytes_in, fra const auto* name = reinterpret_cast(bytes_in.data() + 2); p.name = std::string_view( name, static_cast(std::find(name, name + max_action_name_bytes, '\0') - name)); - const std::size_t metadata_size = (std::size_t{bytes_in[34]} << 8U) | bytes_in[35]; + const std::size_t metadata_size = get_u16(bytes_in, 34); const std::size_t payload_index = header_size + metadata_size; if (p.name.empty() || payload_index > bytes_in.size()) { result.error = wire_error::invalid_proposal; @@ -488,13 +509,13 @@ inline decode_result decode_proposal(std::span bytes_in, fra p.payload = bytes_in.subspan(payload_index); } else { const double size = get_f64(bytes_in, 40); - if (size < 1 || size > 9007199254740991.0 || std::floor(size) != size || + if (size < 1 || size > static_cast(max_offer_size) || std::floor(size) != size || payload_index != bytes_in.size()) { result.error = wire_error::invalid_proposal; return result; } p.id = get_u32(bytes_in, 36); - p.size = static_cast(size); + p.size = static_cast(size); } p.metadata = std::string_view(reinterpret_cast(bytes_in.data() + header_size), metadata_size); diff --git a/include/webcpp/trystero/protocol/envelope.hpp b/include/webcpp/trystero/protocol/envelope.hpp index 1d0c801..37c4211 100644 --- a/include/webcpp/trystero/protocol/envelope.hpp +++ b/include/webcpp/trystero/protocol/envelope.hpp @@ -11,6 +11,8 @@ #include +#include + #include #include #include @@ -44,9 +46,9 @@ inline bytes begin_room_frame( std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { bytes out(memory); out.reserve(3 + token.size() + payload_size); - out.push_back(1); - out.push_back(static_cast((token.size() >> 8U) & 0xffU)); - out.push_back(static_cast(token.size() & 0xffU)); + out.resize(3); + out[0] = 1; + boost::endian::store_big_u16(out.data() + 1, static_cast(token.size())); out.insert(out.end(), token.begin(), token.end()); return out; } @@ -78,10 +80,10 @@ inline bytes presence_frame(std::string_view token, bool present, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { bytes out(memory); out.reserve(4 + token.size()); - out.push_back(2); - out.push_back(present ? 1 : 0); - out.push_back(static_cast((token.size() >> 8U) & 0xffU)); - out.push_back(static_cast(token.size() & 0xffU)); + out.resize(4); + out[0] = 2; + out[1] = present ? 1 : 0; + boost::endian::store_big_u16(out.data() + 2, static_cast(token.size())); out.insert(out.end(), token.begin(), token.end()); return out; } @@ -129,7 +131,7 @@ inline std::optional decode_envelope(std::span fra if (offset == 0 || frame.size() < offset + 2) { return std::nullopt; } - const std::size_t token_size = (std::size_t{frame[offset]} << 8U) | frame[offset + 1]; + const std::size_t token_size = boost::endian::load_big_u16(frame.data() + offset); const std::size_t header_size = offset + 2 + token_size; if (token_size == 0 || token_size > max_room_token_bytes || frame.size() < header_size) { return std::nullopt; diff --git a/include/webcpp/trystero/protocol/json.hpp b/include/webcpp/trystero/protocol/json.hpp index 7c54cb2..d837342 100644 --- a/include/webcpp/trystero/protocol/json.hpp +++ b/include/webcpp/trystero/protocol/json.hpp @@ -9,72 +9,172 @@ #include -#include +#include +#include +#include +#include +#include +#include +#include +#include -#include -#include -#include -#include +#include #include #include +#include #include #include #include #include +#include /** - * Reading and writing the protocol's JSON texts, with every allocation in the resource the caller - * gives. A text the protocol writes is a fixed shape of a few strings and numbers, so it is - * appended field by field rather than built as a boost::json::value, which would copy every string - * into a node of its own before serializing it again. - * - * Tip: strings are escaped by Boost.JSON's serializer, so the bytes match what - * `boost::json::serialize` and JavaScript's `JSON.stringify` write; a Nostr event id is a hash over - * exactly these bytes. + * Reading and writing the protocol's JSON texts on webcpp::document, with every value in the + * resource the caller gives. A text is read by `webcpp::document::parse` into a + * `webcpp::document::pmr::document` of that resource, whose image and working state are allocated + * there; a text the protocol writes is a fixed shape of a few strings and numbers, so it is + * appended field by field, its strings quoted as `JSON.stringify` quotes them, rather than built as + * a document, which would copy every string into a node of its own before writing it again. */ namespace webcpp::trystero::protocol::json { -namespace detail { +/** The traits of every document trystero reads and writes: document's defaults, UTF-8. */ +using traits = webcpp::document::default_traits; -/** Drains a serializer into `out`, in pieces of a buffer on the stack. */ -inline void drain(boost::json::serializer& serializer, std::pmr::string& out) { - std::array buffer{}; - while (!serializer.done()) { - const auto piece = serializer.read(buffer.data(), buffer.size()); - out.append(piece.data(), piece.size()); - } +/** The read-only handle of a value of a `webcpp::document::pmr::document`. */ +using const_value = webcpp::document::basic_const_value; + +/** The handle of a value of a `webcpp::document::pmr::document`, which reads and writes. */ +using value = webcpp::document::basic_value; + +/** The deepest a protocol text nests: Trystero's nest 4 deep at most, a relay's event and its tags. + */ +inline constexpr std::uint64_t max_protocol_depth = 16; + +/** + * The limits of a protocol text's parse: at most `max_bytes` of text, nested at most + * @ref max_protocol_depth deep, into an image that grows to at most twice that and 64 KiB more. + * + * Tip: a text Trystero writes holds a few dozen values at most, each node some 200 bytes of image + * beside its string, so the image of the longest is under its text and 16 KiB. A text that needs + * more holds thousands of values, which no Trystero message has; it is refused once its image has + * grown to the bound, so that no text costs a room more than a multiple of its bound to read. The + * depth bounds what the parse's recursion takes of the stack, far below document's 256. + * + * @param max_bytes The longest text the caller reads. + * @return The options. + */ +constexpr webcpp::document::parse_options protocol_limits(std::uint64_t max_bytes) noexcept { + webcpp::document::parse_options o; + o.max_bytes = max_bytes; + o.max_depth = max_protocol_depth; + o.max_document_bytes = (2 * max_bytes) + (std::uint64_t{64} << 10U); + return o; +} + +/** + * The most image a byte of JSON text takes in a document: a value of one character with its comma + * or bracket, two bytes, is a node of 192 bytes, and no text takes more (measured on every shape: + * numbers, literals, empty strings, arrays and objects, nested to 255). + */ +inline constexpr std::uint64_t image_bytes_per_text_byte = 96; + +/** + * The limits of a JSON payload's parse: its own length, nested as deep as document's default, + * into an image that grows to at most 96 times the text and 64 KiB, which every valid text of that + * length fits, or `most`, the smaller. + * + * @param text_bytes The payload's length. + * @param most The largest image a payload may take, `room_options::max_json_document_bytes`. + * @return The options. + */ +constexpr webcpp::document::parse_options payload_limits(std::uint64_t text_bytes, + std::uint64_t most) noexcept { + constexpr std::uint64_t spare = std::uint64_t{64} << 10U; + webcpp::document::parse_options o; + o.max_bytes = text_bytes; + o.max_document_bytes = most <= spare || text_bytes >= (most - spare) / image_bytes_per_text_byte + ? most + : (image_bytes_per_text_byte * text_bytes) + spare; + return o; +} + +/** + * The text a value holds. + * + * @param v The value. + * @return The text, valid while its document is unchanged; empty when it holds no string. + */ +inline std::string_view text_of(const const_value& v) noexcept { + return v.value_or(std::string_view()); } +namespace detail { + +/** An output of `webcpp::document::quote` that keeps nothing: what checks that a text quotes. */ +struct discard { + /** Takes a piece of the literal, and drops it. */ + void append(const char* /*data*/, std::size_t /*size*/) noexcept {} +}; + } // namespace detail /** - * Appends `text` as a JSON string literal, quotes included, as `JSON.stringify` writes it. + * Whether `text` can be written as a JSON string: whether it is UTF-8, as every JavaScript string + * is once encoded. * - * Tip: the serializer keeps where it stopped on a stack of its own when the text outgrows its - * buffer; that stack is in `out`'s resource. + * @param text The text. + * @return Whether @ref append_string writes it. + */ +inline bool quotable(std::string_view text) { + detail::discard nothing; + return webcpp::document::quote(text, nothing).has_value(); +} + +/** + * Appends `text` as a JSON string literal, quotes included, as `JSON.stringify` writes it, with + * webcpp::document's quoting, which allocates only through `out`. * - * @param out The text to append to. - * @param text The string, in UTF-8. + * @param out The text to append to, unchanged when `text` is refused. + * @param text The string. + * @return Nothing, or `errc::type` when `text` is not UTF-8 (@ref quotable), which no JSON string + * holds: a local candidate whose text is refused is not sent. */ -inline void append_string(std::pmr::string& out, std::string_view text) { - json_resource resource(out.get_allocator().resource()); - boost::json::serializer serializer{boost::json::storage_ptr(&resource)}; - serializer.reset(boost::json::string_view(text.data(), text.size())); - detail::drain(serializer, out); +[[nodiscard]] inline webcpp::document::result append_string(std::pmr::string& out, + std::string_view text) { + return webcpp::document::quote(text, out); } +namespace detail { + /** - * Appends `value` serialized, as `boost::json::serialize` writes it. + * Appends `text`, UTF-8 by the caller's precondition, as a JSON string: an id, a topic, a key, a + * nonce or a sealed text, all ASCII, a text read from JSON, or the self id, checked when the app + * is made. + */ +inline void append_utf8(std::pmr::string& out, std::string_view text) { + // Quoting fails only on a text that is not UTF-8, which the precondition rules out. + static_cast(append_string(out, text)); +} + +} // namespace detail + +/** + * Appends a value as `JSON.stringify` writes it. * - * @param out The text to append to; the serializer's state is in its resource. - * @param value The value. + * @tparam Storage The storage of the value's document. + * @param out The text to append to. The writer hands it pieces of at most 8 bytes, which no + * standard library's string holds outside its own object, so that only `out` allocates the text. + * @param v The value; `undefined` writes nothing. */ -inline void append_value(std::pmr::string& out, const boost::json::value& value) { - json_resource resource(out.get_allocator().resource()); - boost::json::serializer serializer{boost::json::storage_ptr(&resource)}; - serializer.reset(&value); - detail::drain(serializer, out); +template +// A handle is taken by value, as document passes every handle, and moved on. +void append_value(std::pmr::string& out, webcpp::document::basic_const_value v) { + constexpr std::uint64_t piece = 8; + // A sink that returns nothing never fails, so neither does the writing. + static_cast(webcpp::document::stringify_to( + std::move(v), [&out](std::string_view text) { out.append(text); }, 0, piece)); } /** @@ -94,37 +194,16 @@ inline void append_integer(std::pmr::string& out, std::int64_t value) { * * @param out The text of an object being written, which ends with its `{` or a member's value. * @param key The member's name. + * @pre `key` is UTF-8, as every name the protocol writes is. */ inline void append_key(std::pmr::string& out, std::string_view key) { if (out.back() != '{') { out += ','; } - append_string(out, key); + detail::append_utf8(out, key); out += ':'; } -/** - * Parses `text` into a value of `storage`, or sets `ec`. - * - * Tip: `boost::json::parse` keeps its temporaries in the default resource once they outgrow a - * buffer on the stack; this parser keeps them in `storage` too. - * - * @param text The JSON text. - * @param storage The storage the value and the parser's temporaries are allocated in. - * @param ec Set when the text is not one JSON value. - * @return The value, or a null value of `storage` when `ec` is set. - */ -inline boost::json::value parse(std::string_view text, const boost::json::storage_ptr& storage, - boost::system::error_code& ec) { - boost::json::parser parser(storage); - parser.reset(storage); - parser.write(text.data(), text.size(), ec); - if (ec) { - return boost::json::value(storage); - } - return parser.release(); -} - } // namespace webcpp::trystero::protocol::json #endif diff --git a/include/webcpp/trystero/protocol/nostr.hpp b/include/webcpp/trystero/protocol/nostr.hpp index 4d4f4a1..9c91349 100644 --- a/include/webcpp/trystero/protocol/nostr.hpp +++ b/include/webcpp/trystero/protocol/nostr.hpp @@ -10,6 +10,8 @@ #include #include +#include +#include #include #include @@ -17,11 +19,11 @@ #include #include #include -#include #include #include #include +#include #include #include #include @@ -36,6 +38,19 @@ namespace webcpp::trystero::protocol::nostr { +/** + * The longest text of a relay a room reads, in bytes: a longer one is dropped before it is read, + * and the connection goes on; one longer than @ref max_relay_message_bytes closes the connection + * instead. + * + * The longest text measured is an event that carries an answer, 1,244 bytes, among Trystero JS in + * Chrome and both backends. The bound is an event that carries the longest signal a room reads + * (@ref max_parsed_signal_bytes), with 2 KiB for the event's other fields, the subscription id and + * the escaping of the signal's quotes, which take some 600 bytes. + */ +inline constexpr std::size_t max_parsed_relay_text_bytes = max_parsed_signal_bytes + 2048; +static_assert(max_parsed_relay_text_bytes < max_relay_message_bytes); + /** The tag a Trystero event carries its topic in, its `tag`: "x". */ inline constexpr std::string_view topic_tag = "x"; @@ -44,10 +59,10 @@ inline constexpr std::string_view topic_tag = "x"; * forward the events and keep none. * * @param topic The topic's name. - * @return 20000 plus `str_to_num(topic, 10000)`. + * @return 20000 plus `str_to_num(topic, 10000)`, below 30000. */ -inline int topic_kind(std::string_view topic) { - return static_cast(str_to_num(topic, 10000)) + 20000; +inline std::uint32_t topic_kind(std::string_view topic) { + return static_cast(str_to_num(topic, 10000)) + 20000; } namespace detail { @@ -57,11 +72,13 @@ namespace detail { * canonical * `[0,"",,,[["x",]],]`, fed to the hash piece by piece. */ -inline std::array event_id(std::string_view pubkey, std::int64_t created_at, - int kind, std::string_view quoted_topic, +inline std::array event_id(std::string_view pubkey, + std::chrono::sys_seconds created_at, + std::uint32_t kind, std::string_view quoted_topic, std::string_view quoted_content) { std::array buffer{}; - char* end = std::to_chars(buffer.data(), buffer.data() + 24, created_at).ptr; + const auto seconds = created_at.time_since_epoch().count(); + char* end = std::to_chars(buffer.data(), buffer.data() + 24, seconds).ptr; *end++ = ','; end = std::to_chars(end, buffer.data() + buffer.size(), kind).ptr; const std::string_view numbers(buffer.data(), static_cast(end - buffer.data())); @@ -89,10 +106,32 @@ inline std::array event_id(std::string_view pubkey, std::int64 inline std::pmr::string quoted(std::string_view text, std::pmr::memory_resource* memory) { std::pmr::string out(memory); out.reserve(text.size() + 8); - json::append_string(out, text); + json::detail::append_utf8(out, text); return out; } +/** Whether `text` is 32 bytes as NIP-01 writes an id or a public key: 64 lowercase hexadecimal + * digits. */ +inline bool is_nip01_hex(std::string_view text) { + return text.size() == 64 && std::ranges::all_of(text, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }); +} + +/** Whether `text` is the lowercase hexadecimal of `data`, as `append_hex` writes it. */ +inline bool is_hex_of(std::string_view text, std::span data) { + constexpr std::string_view digits = "0123456789abcdef"; + if (text.size() != data.size() * 2) { + return false; + } + for (std::size_t i = 0; i < data.size(); ++i) { + if (text[2 * i] != digits[data[i] >> 4U] || text[(2 * i) + 1] != digits[data[i] & 15U]) { + return false; + } + } + return true; +} + } // namespace detail /** @@ -100,7 +139,7 @@ inline std::pmr::string quoted(std::string_view text, std::pmr::memory_resource* * `[0, pubkey, created_at, kind, [["x", topic]], content]`. * * @param pubkey The signer's x-only public key, in hexadecimal. - * @param created_at The event's time, in seconds since the Unix epoch. + * @param created_at The event's time, in whole seconds since the Unix epoch. * @param kind The event's kind, @ref topic_kind of its topic. * @param topic The topic, the value of its tag "x". * @param content The content. @@ -108,8 +147,8 @@ inline std::pmr::string quoted(std::string_view text, std::pmr::memory_resource* * @return The id. */ inline std::array event_id( - std::string_view pubkey, std::int64_t created_at, int kind, std::string_view topic, - std::string_view content, + std::string_view pubkey, std::chrono::sys_seconds created_at, std::uint32_t kind, + std::string_view topic, std::string_view content, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { return detail::event_id(pubkey, created_at, kind, detail::quoted(topic, memory), detail::quoted(content, memory)); @@ -228,18 +267,20 @@ inline bool verify(std::span sig, std::span aux, + const signer& key, std::chrono::sys_seconds created_at, std::string_view topic, + std::string_view content, std::span aux, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - const int kind = topic_kind(topic); + const auto kind = topic_kind(topic); const auto quoted_topic = detail::quoted(topic, memory); const auto quoted_content = detail::quoted(content, memory); const auto id = detail::event_id(key.pubkey(), created_at, kind, quoted_topic, quoted_content); @@ -251,7 +292,7 @@ inline std::pmr::string event_message( out += R"(,"tags":[["x",)"; out += quoted_topic; out += R"(]],"created_at":)"; - json::append_integer(out, created_at); + json::append_integer(out, created_at.time_since_epoch().count()); out += R"(,"content":)"; out += quoted_content; out += R"(,"pubkey":")"; @@ -270,36 +311,39 @@ inline std::pmr::string event_message( * * @param subscription The subscription's id. * @param topics The topics, whose kinds the filter lists once each, in increasing order. - * @param since The earliest `created_at` of the events wanted. + * @param since The earliest `created_at` of the events wanted, in whole seconds since the Unix + * epoch. * @param memory The resource the message is allocated in. * @return The message's JSON text. + * @pre `subscription` and the topics are UTF-8, as a room's, which are ASCII, are. */ inline std::pmr::string subscribe_message( - std::string_view subscription, std::span topics, std::int64_t since, + std::string_view subscription, std::span topics, + std::chrono::sys_seconds since, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - std::pmr::set kinds(memory); + std::pmr::set kinds(memory); for (const auto& t : topics) { kinds.insert(topic_kind(t)); } std::pmr::string out(memory); out.reserve(96 + subscription.size() + (topics.size() * 48)); out += R"(["REQ",)"; - json::append_string(out, subscription); + json::detail::append_utf8(out, subscription); out += R"(,{"kinds":[)"; - for (const int k : kinds) { + for (const std::uint32_t k : kinds) { if (out.back() != '[') { out += ','; } json::append_integer(out, k); } out += R"(],"since":)"; - json::append_integer(out, since); + json::append_integer(out, since.time_since_epoch().count()); out += R"(,"#x":[)"; for (std::size_t i = 0; i < topics.size(); ++i) { if (i != 0) { out += ','; } - json::append_string(out, topics[i]); + json::detail::append_utf8(out, topics[i]); } out += "]}]"; return out; @@ -311,12 +355,13 @@ inline std::pmr::string subscribe_message( * @param subscription The subscription's id. * @param memory The resource the message is allocated in. * @return The message's JSON text. + * @pre `subscription` is UTF-8, as a room's, which is ASCII, is. */ inline std::pmr::string close_message( std::string_view subscription, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { std::pmr::string out(R"(["CLOSE",)", memory); - json::append_string(out, subscription); + json::detail::append_utf8(out, subscription); out += ']'; return out; } @@ -331,8 +376,40 @@ struct event { std::string_view topic; /** The event's content. */ std::string_view content; + /** The signer's public key, as the event holds it; empty when it holds no string. */ + std::string_view pubkey{}; + /** The event's `created_at`, in whole seconds since the Unix epoch; nothing when it is not an + * integer of 64 bits. */ + std::optional created_at{}; + /** The event's kind; nothing when it is not an integer of 32 bits. */ + std::optional kind{}; + /** Whether the event's one tag is its topic's, `["x", ]`, as Trystero writes it. */ + bool only_topic_tag = false; }; +/** + * Whether an event's id is its own, the SHA-256 of NIP-01's serialization of the event + * `[0,,,,,]`, which @ref event_id computes. + * + * A relay sends whatever id it chooses, so an id that is not its event's own may be another + * event's. Only an event whose one tag is its topic's and whose public key is 64 lowercase + * hexadecimal digits is checked, as Trystero writes every event; any other has no id of its own + * here, whatever it says. + * + * @param e The event, as @ref read_relay_message reads it. + * @param memory The resource the escaped topic and content are allocated in, during the call. + * @return Whether the id is the hexadecimal of the SHA-256 of the event's serialization. + */ +inline bool has_own_id(const event& e, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + if (!e.only_topic_tag || !e.created_at.has_value() || !e.kind.has_value() || + !detail::is_nip01_hex(e.pubkey) || !detail::is_nip01_hex(e.id)) { + return false; + } + return detail::is_hex_of( + e.id, event_id(e.pubkey, *e.created_at, *e.kind, e.topic, e.content, memory)); +} + /** A relay's `["OK", , , ]`: whether it took a published event, as views. */ struct ok { /** The event's id. */ @@ -372,64 +449,66 @@ using relay_message = std::variant; namespace detail { -/** The text a JSON value holds, or an empty view when it holds none. */ -inline std::string_view text_of(const boost::json::value& v) { - const auto* s = v.if_string(); - return s != nullptr ? std::string_view(s->data(), s->size()) : std::string_view(); -} - -/** The event of a relay's `["EVENT", , ]`, as views into `array`. */ -inline std::optional read_event(const boost::json::array& array) { - if (array.size() < 3 || !array.at(2).is_object()) { +/** The event of a relay's `["EVENT", , ]`, as views into its document. */ +inline std::optional read_event(const json::const_value& array) { + const json::const_value o = array[2]; + if (!o.is_object()) { return std::nullopt; } - const auto& o = array.at(2).get_object(); event e; - e.subscription = text_of(array.at(1)); - if (const auto* id = o.if_contains("id")) { - e.id = text_of(*id); + e.subscription = json::text_of(array[1]); + e.id = json::text_of(o["id"]); + e.content = json::text_of(o["content"]); + e.pubkey = json::text_of(o["pubkey"]); + if (const auto created_at = o["created_at"].get(); created_at.has_value()) { + e.created_at = std::chrono::sys_seconds(std::chrono::seconds(*created_at)); } - if (const auto* c = o.if_contains("content")) { - e.content = text_of(*c); + if (const auto kind = o["kind"].get(); kind.has_value()) { + e.kind = *kind; } - if (const auto* tags = o.if_contains("tags"); tags != nullptr && tags->is_array()) { - for (const auto& tag : tags->get_array()) { - const auto* pair = tag.if_array(); - if (pair != nullptr && pair->size() >= 2 && text_of(pair->at(0)) == topic_tag && - pair->at(1).is_string()) { - e.topic = text_of(pair->at(1)); - break; - } + // An array is its own range of elements, which the handle, outliving the loop, keeps. + const json::const_value tags = o["tags"]; + const auto is_topic_tag = [](const json::const_value& tag) { + return tag.is_array() && tag.size() >= 2 && json::text_of(tag[0]) == topic_tag && + tag[1].is_string(); + }; + for (const json::const_value tag : tags) { + if (is_topic_tag(tag)) { + e.topic = json::text_of(tag[1]); + break; } } + // NIP-01 hashes the tags whole, so an id is checked only over tags event_id writes. + e.only_topic_tag = + tags.is_array() && tags.size() == 1 && is_topic_tag(tags[0]) && tags[0].size() == 2; return e; } } // namespace detail /** - * The message a parsed relay text holds, as views into `document`. + * The message a parsed relay text holds, as views into its document. + * + * A key written twice is read as JavaScript reads it, the last value, which the parse keeps. * - * @param document The parsed text, which the caller keeps alive while it reads the views. + * @param document The root of the parsed text, whose document the caller keeps alive and unchanged + * while it reads the views. * @return The message, or nothing when Trystero would ignore it: not an array, or not one of the * messages of @ref relay_message. */ -inline std::optional read_relay_message(const boost::json::value& document) { - const auto* array = document.if_array(); - if (array == nullptr || array->empty() || !array->at(0).is_string()) { +inline std::optional read_relay_message(const json::const_value& document) { + if (!document.is_array() || !document[0].is_string()) { return std::nullopt; } - const auto text_at = [array](std::size_t i) { - return i < array->size() ? detail::text_of(array->at(i)) : std::string_view(); - }; + const auto text_at = [&document](std::uint64_t i) { return json::text_of(document[i]); }; const std::string_view type = text_at(0); if (type == "EVENT") { - return detail::read_event(*array); + return detail::read_event(document); } if (type == "OK") { return ok{ .id = text_at(1), - .accepted = array->size() > 2 && array->at(2).is_bool() && array->at(2).get_bool(), + .accepted = document[2].value_or(false), .reason = text_at(3), }; } diff --git a/include/webcpp/trystero/protocol/relays.hpp b/include/webcpp/trystero/protocol/relays.hpp index 01ac535..246a880 100644 --- a/include/webcpp/trystero/protocol/relays.hpp +++ b/include/webcpp/trystero/protocol/relays.hpp @@ -26,8 +26,9 @@ namespace webcpp::trystero::protocol { * protocol (an event's content is a signal, whose SDP is a few KiB) and of what public relays * accept (their events are capped at 64 to 512 KiB). * - * Both backends close a relay's connection that sends a longer one, before copying it, and the - * room reconnects as it does to a relay that went away. + * The platform backend closes, on both targets, a relay's connection that sends a longer one, + * before copying it, in a page before it enters WebAssembly, and the room reconnects as it does to + * a relay that went away. */ inline constexpr std::size_t max_relay_message_bytes = std::size_t{1} << 20U; @@ -35,8 +36,8 @@ inline constexpr std::size_t max_relay_message_bytes = std::size_t{1} << 20U; * The most text a room holds unsent for one relay, in UTF-8 bytes: 4 MiB, a thousand signals and * more. * - * A relay that stops reading lets the texts pile up; beyond this, both backends drop its - * connection, which reports a close, and the room reconnects with its backoff. + * A relay that stops reading lets the texts pile up; beyond this, the platform backend drops its + * connection on both targets, which reports a close, and the room reconnects with its backoff. */ inline constexpr std::size_t max_queued_relay_bytes = std::size_t{4} << 20U; @@ -80,7 +81,8 @@ inline constexpr std::array default_nostr_relays{ * Trystero's `shuffle`: Fisher-Yates driven by `sin(seed++) * 10000`, so every peer of an app picks * the same order. * - * Tip: `std::sin` and V8's `Math.sin` agree on these inputs; the oracle's fixtures check it. + * Tip: the seed and the draws are doubles, JavaScript's Numbers, as in Trystero; `std::sin` and + * V8's `Math.sin` agree on these inputs; the oracle's fixtures check it. * * @tparam Sequence A sequence with `size()` and random access, as `std::pmr::vector`. * @param items The items, shuffled in the copy returned. diff --git a/include/webcpp/trystero/protocol/signal.hpp b/include/webcpp/trystero/protocol/signal.hpp index 3565cfa..8accea9 100644 --- a/include/webcpp/trystero/protocol/signal.hpp +++ b/include/webcpp/trystero/protocol/signal.hpp @@ -13,8 +13,6 @@ #include #include -#include - #include #include #include @@ -69,6 +67,29 @@ inline constexpr std::size_t max_sealed_description_bytes = std::size_t{64} * 10 inline constexpr std::size_t max_sealed_candidate_bytes = std::size_t{16} * 1024; static_assert(sealed_size(8192) <= max_sealed_candidate_bytes); +/** + * The longest signal a room reads, in bytes: a longer one is dropped before it is read. + * + * The longest signal measured is an answer, 762 bytes, among Trystero JS in Chrome and both + * backends, which trickle their candidates. The bound is the longest signal the bounds of its + * fields admit, a sealed offer or answer of @ref max_sealed_description_bytes with the longest ids, + * and 1 KiB to spare, so that it refuses no signal they accept. + */ +inline constexpr std::size_t max_parsed_signal_bytes = max_sealed_description_bytes + 1024; +// The 64 bytes hold the 53 of the keys and the punctuation of an answer from a passive room. +static_assert(max_sealed_description_bytes + max_peer_id_bytes + max_offer_id_bytes + 64 <= + max_parsed_signal_bytes, + "the longest signal the bounds of its fields admit is read"); + +/** + * The longest message of the password handshake a room reads, in bytes: a longer one fails the + * handshake, as a message of the wrong shape does. + * + * Trystero's are at most 99 bytes, `{"__trystero_pw":"response","h":"<64 hexadecimal digits>"}`; + * the bound is ten times that. + */ +inline constexpr std::size_t max_handshake_bytes = 1024; + /** * The raw AES-GCM key of a room, what Trystero's `genKey` imports: the SHA-256 of * "::". @@ -134,12 +155,13 @@ inline std::optional parse_sealed( for (std::string_view ivs = text.substr(0, dollar); !ivs.empty();) { const auto comma = ivs.find(','); const auto item = ivs.substr(0, comma); - unsigned value = 0; + // A byte: from_chars refuses a number above 255 as out of range. + std::uint8_t value = 0; const auto [end, ec] = std::from_chars(item.data(), item.data() + item.size(), value); - if (ec != std::errc{} || end != item.data() + item.size() || value > 255) { + if (ec != std::errc{} || end != item.data() + item.size()) { return std::nullopt; } - out.iv.push_back(static_cast(value)); + out.iv.push_back(value); ivs = comma == std::string_view::npos ? std::string_view{} : ivs.substr(comma + 1); } auto ciphertext = base64_decode(text.substr(dollar + 1), memory); @@ -175,6 +197,14 @@ struct signal_message { * announces only once it has seen a peer that is not passive. */ bool passive = false; + /** + * Whether the sender answers the offer, which places `offerId` in the text. + * + * Trystero's answerer writes `offerId` after its answer or candidate, its offerer before its + * offer or candidate. Written only; a reader leaves it false, the order being no part of the + * meaning. + */ + bool answering = false; /** * Whether the message is an announcement. @@ -187,32 +217,35 @@ struct signal_message { }; /** - * The message a parsed signaling payload holds, as views into `document`. + * The message a parsed signaling payload holds, as views into its document. * - * @param document The parsed payload, which the caller keeps alive while it reads the views. - * @return The message, or nothing when Trystero would ignore it (not an object, no peer id, or an - * offer, answer or candidate that is not a non-empty string), or when a field is longer than its - * bound: the peer id than @ref max_peer_id_bytes, the offer id than @ref max_offer_id_bytes, an - * offer or answer than @ref max_sealed_description_bytes, a candidate than - * @ref max_sealed_candidate_bytes. + * A key written twice is read as JavaScript reads it, the last value, which the parse keeps. + * + * @param document The root of the parsed payload, whose document the caller keeps alive and + * unchanged while it reads the views. + * @return The message, or nothing when Trystero would ignore it (not an object, one with a member + * `peer`, no peer id, or an offer, answer or candidate that is not a non-empty string), or when a + * field is longer than its bound: the peer id than @ref max_peer_id_bytes, the offer id than + * @ref max_offer_id_bytes, an offer or answer than @ref max_sealed_description_bytes, a candidate + * than @ref max_sealed_candidate_bytes. */ -inline std::optional read_signal(const boost::json::value& document) { - const auto* object = document.if_object(); - if (object == nullptr) { +inline std::optional read_signal(const json::const_value& document) { + // Trystero ignores a text that names a member `peer`, which its own rooms keep for a peer + // object no text can hold. + if (!document.is_object() || document.contains("peer")) { return std::nullopt; } signal_message out; - const auto text = [object](std::string_view key, std::string_view& into, - bool must_be_nonempty) { - const auto* v = object->if_contains(key); - if (v == nullptr) { + const auto text = [&document](std::string_view key, std::string_view& into, + bool must_be_nonempty) { + const json::const_value v = document[key]; + if (v.is_undefined()) { return true; } - const auto* s = v->if_string(); - if (s == nullptr || (must_be_nonempty && s->empty())) { + if (!v.is_string() || (must_be_nonempty && json::text_of(v).empty())) { return !must_be_nonempty; } - into = std::string_view(s->data(), s->size()); + into = json::text_of(v); return true; }; if (!text("offer", out.offer, true) || !text("answer", out.answer, true) || @@ -221,9 +254,7 @@ inline std::optional read_signal(const boost::json::value& docum } text("peerId", out.peer_id, false); text("offerId", out.offer_id, false); - if (const auto* v = object->if_contains("passive"); v != nullptr && v->is_bool()) { - out.passive = v->get_bool(); - } + out.passive = document["passive"].value_or(false); if (out.peer_id.empty() || out.peer_id.size() > max_peer_id_bytes || out.offer_id.size() > max_offer_id_bytes || out.offer.size() > max_sealed_description_bytes || @@ -241,6 +272,9 @@ inline std::optional read_signal(const boost::json::value& docum * @param nonce A random text, which makes repeated announcements distinct events; empty for none. * @param memory The resource the text is allocated in. * @return The text. + * @pre Every string is UTF-8, as every one a room writes is: the ids, the nonce and the sealed + * texts are ASCII, an answered offer's id was read from JSON, and the self id is checked when the + * app is made. */ inline std::pmr::string write_signal( const signal_message& m, std::string_view nonce = {}, @@ -254,13 +288,18 @@ inline std::pmr::string write_signal( return; } json::append_key(out, key); - json::append_string(out, value); + json::detail::append_utf8(out, value); }; field("peerId", m.peer_id); - field("offerId", m.offer_id); + if (!m.answering) { + field("offerId", m.offer_id); + } field("offer", m.offer); field("answer", m.answer); field("candidate", m.candidate); + if (m.answering) { + field("offerId", m.offer_id); + } if (m.passive) { json::append_key(out, "passive"); out += "true"; diff --git a/include/webcpp/trystero/protocol/text.hpp b/include/webcpp/trystero/protocol/text.hpp index 9ecb70b..21c5ba6 100644 --- a/include/webcpp/trystero/protocol/text.hpp +++ b/include/webcpp/trystero/protocol/text.hpp @@ -65,28 +65,29 @@ inline std::optional from_hex( if (text.size() % 2 != 0) { return std::nullopt; } - const auto nibble = [](char c) -> int { + // A digit's value, or `not_hex` for a character that is none. + constexpr std::uint32_t not_hex = 16; + const auto nibble = [](char c) -> std::uint32_t { if (c >= '0' && c <= '9') { - return c - '0'; + return static_cast(c - '0'); } if (c >= 'a' && c <= 'f') { - return c - 'a' + 10; + return static_cast(c - 'a' + 10); } if (c >= 'A' && c <= 'F') { - return c - 'A' + 10; + return static_cast(c - 'A' + 10); } - return -1; + return not_hex; }; bytes out(memory); out.reserve(text.size() / 2); for (std::size_t i = 0; i < text.size(); i += 2) { - const int high = nibble(text[i]); - const int low = nibble(text[i + 1]); - if (high < 0 || low < 0) { + const std::uint32_t high = nibble(text[i]); + const std::uint32_t low = nibble(text[i + 1]); + if (high == not_hex || low == not_hex) { return std::nullopt; } - out.push_back(static_cast((static_cast(high) << 4U) | - static_cast(low))); + out.push_back(static_cast((high << 4U) | low)); } return out; } @@ -148,15 +149,17 @@ inline std::pmr::string base64_encode( */ inline std::optional base64_decode( std::string_view in, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - const auto value = [](char c) -> int { + // A digit's value, or `not_base64` for a character that is none. + constexpr std::uint32_t not_base64 = 64; + const auto value = [](char c) -> std::uint32_t { if (c >= 'A' && c <= 'Z') { - return c - 'A'; + return static_cast(c - 'A'); } if (c >= 'a' && c <= 'z') { - return c - 'a' + 26; + return static_cast(c - 'a' + 26); } if (c >= '0' && c <= '9') { - return c - '0' + 52; + return static_cast(c - '0' + 52); } if (c == '+') { return 62; @@ -164,7 +167,7 @@ inline std::optional base64_decode( if (c == '/') { return 63; } - return -1; + return not_base64; }; while (!in.empty() && in.back() == '=') { in.remove_suffix(1); @@ -175,13 +178,13 @@ inline std::optional base64_decode( bytes out(memory); out.reserve(in.size() * 3 / 4); std::uint32_t buffer = 0; - unsigned bits = 0; + std::uint32_t bits = 0; for (const char c : in) { - const int v = value(c); - if (v < 0) { + const std::uint32_t v = value(c); + if (v == not_base64) { return std::nullopt; } - buffer = (buffer << 6U) | static_cast(v); + buffer = (buffer << 6U) | v; bits += 6U; if (bits >= 8U) { bits -= 8U; @@ -195,7 +198,8 @@ inline std::optional base64_decode( * The sum of the UTF-16 code units of a UTF-8 text, what JavaScript's `charCodeAt` sees. * * Tip: Trystero derives Nostr kinds and the relay shuffle seed from it, so non-ASCII ids must count - * as in JS. + * as in JS. The sum is a double, JavaScript's Number, as Trystero's is; the oracle's fixtures pin + * it. * * @param utf8 The text, in UTF-8. * @return The sum of the code units of its UTF-16 form, a character above U+FFFF counting as its @@ -206,7 +210,7 @@ inline double utf16_code_unit_sum(std::string_view utf8) { for (std::size_t i = 0; i < utf8.size();) { // The bytes as unsigned values: a char may be signed. const auto byte = [utf8](std::size_t at) -> std::uint32_t { - return static_cast(utf8[at]); + return static_cast(utf8[at]); }; const std::uint32_t c = byte(i); std::uint32_t point = c; diff --git a/include/webcpp/trystero/protocol/topics.hpp b/include/webcpp/trystero/protocol/topics.hpp index 1c2b804..c2ad80d 100644 --- a/include/webcpp/trystero/protocol/topics.hpp +++ b/include/webcpp/trystero/protocol/topics.hpp @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include #include @@ -38,25 +38,25 @@ inline constexpr std::size_t offer_id_size = 12; inline constexpr std::size_t nonce_size = 8; /** - * A random id of `n` characters of `id_alphabet`, Trystero's `genId`. + * An id of one character of `id_alphabet` for each random byte, Trystero's `genId`. * - * @tparam Generator A uniform random bit generator. - * @param n The id's length. - * @param generator The source of randomness. + * Each byte picks the character at its remainder in 62, as Trystero picks one character of its + * `charSet` for each draw, so an id of `n` characters takes `n` random bytes. + * + * Tip: 256 is not a multiple of 62, so each of the first eight characters comes from 5 of the 256 + * bytes and each other from 4, where Trystero draws each of the 62 alike: a character carries + * about 5.95 bits of its byte's 8, a little less than log2(62). + * + * @param random The random bytes, one for each character. * @param memory The resource the id is allocated in. - * @return The id. + * @return The id, as long as `random`. */ -template -std::pmr::string make_id(std::size_t n, Generator& generator, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - // A distribution draws through a non-const operator(), which misc-const-correctness does not - // see through the dependent generator. - // NOLINTNEXTLINE(misc-const-correctness) - std::uniform_int_distribution pick(0, id_alphabet.size() - 1); - std::pmr::string out(n, '0', memory); - for (auto& c : out) { - c = id_alphabet[pick(generator)]; - } +inline std::pmr::string random_id( + std::span random, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + std::pmr::string out(random.size(), '0', memory); + std::ranges::transform(random, out.begin(), + [](std::uint8_t b) { return id_alphabet[b % id_alphabet.size()]; }); return out; } @@ -184,6 +184,9 @@ inline std::pmr::string room_token( /** * Trystero's `strToNum`: the sum of the text's UTF-16 code units, modulo `limit`. * + * Tip: it computes in doubles, JavaScript's Numbers, as `strToNum` does, so that every peer derives + * the same kinds and relays; the oracle's fixtures pin it. + * * @param text The text, in UTF-8. * @param limit The modulus; the default is JavaScript's `Number.MAX_SAFE_INTEGER`. * @return The number, in [0, `limit`). diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 9c2f8a9..c83c85f 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -17,11 +17,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -29,16 +29,20 @@ #include #include -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only -#include // lint-world: posts handlers only +#include // lint-world: posts handlers only +#include // lint-world: posts handlers only +#include // lint-world: posts handlers only +#include // lint-world: posts handlers only +#include // lint-world: posts handlers only +#include // lint-world: posts handlers only +#include // lint-world: posts handlers only + +#include +#include +#include +#include + #include -#include -#include #include #include @@ -91,9 +95,13 @@ using pmr_bytes = std::pmr::vector; * What an action carries when its type is not fixed: Trystero's text, JSON or binary payload. * * A message received as `payload` holds the alternative of its format: a `std::string` for text, - * a `boost::json::value` for JSON, in the room's JSON storage, and `bytes` for binary data. + * a `webcpp::document::document` for JSON, and `bytes` for binary data, each with the standard + * allocator. + * + * Tip: a handle of the document's values refers to the document object, as every handle of + * webcpp::document does: moving the document, or the variant that holds it, invalidates it. */ -using payload = std::variant; +using payload = std::variant; /** * Who sent a message, and the metadata it carried, the second and third arguments of Trystero's @@ -151,24 +159,39 @@ inline std::string_view as_text(std::span data) { return {reinterpret_cast(data.data()), data.size()}; } +/** + * What a room decodes a received payload with: its resource, and its bound on a JSON payload's + * image. + */ +struct decoding { + /** The room's resource, which the `std::pmr` types are built in. */ + std::pmr::memory_resource* memory = nullptr; + /** The largest image a JSON payload may take, `room_options::max_json_document_bytes`. */ + std::uint64_t max_json_document_bytes = 0; +}; + /** * How an action's type travels. `encode` takes the value at the call and keeps it alive without * copying it when the type owns its storage; a view is copied once, there, into the room's - * resource. `decode` reads a received message: a view type refers to the message's buffer and is - * valid for the duration of the handler, so only owning types can be awaited. The `std::pmr` types - * are built in the receiving room's resource, and JSON in its JSON storage; the standard types - * allocate with `std::allocator`, as the user chose. + * resource. `decode` reads a received message with the room's @ref decoding. A view type refers to + * the message's buffer and is valid for the duration of the handler, so only owning types can be + * awaited. The `std::pmr` types are built in the receiving room's resource, + * `webcpp::document::pmr::document` too; the standard types allocate with `std::allocator`, as the + * user chose, and so does `webcpp::document::document`. A JSON text is parsed + * within @ref json_payload_limits. * - * | Type | Trystero format | Receiving | - * | std::string | text | a copy of the bytes | - * | std::pmr::string | text | a copy of the bytes, in the room's resource | - * | std::string_view | text | a view of the frame, in a handler | - * | boost::json::value | JSON | parsed, in the room's JSON storage | - * | trystero::bytes | binary | a copy of the bytes | - * | trystero::pmr_bytes | binary | moved or copied once into the room's | - * | | | resource | - * | std::span | binary | a view of the frame, in a handler | - * | trystero::payload | any | by format | + * | Type | Trystero format | Receiving | + * | std::string | text | a copy of the bytes | + * | std::pmr::string | text | a copy of the bytes, in the room's | + * | | | resource | + * | std::string_view | text | a view of the frame, in a handler | + * | webcpp::document::document | JSON | parsed, with `std::allocator` | + * | webcpp::document::pmr::document | JSON | parsed, in the room's resource | + * | trystero::bytes | binary | a copy of the bytes | + * | trystero::pmr_bytes | binary | moved or copied once into the room's | + * | | | resource | + * | std::span | binary | a view of the frame, in a handler | + * | trystero::payload | any | by format | */ template struct payload_traits; @@ -190,7 +213,7 @@ struct payload_traits { * The message's payload as this type: a copy of the text, allocated with `std::allocator`; * nothing for another format. */ - static std::optional decode(incoming& m, std::pmr::memory_resource* /*memory*/) { + static std::optional decode(incoming& m, const decoding& /*to*/) { if (m.format != protocol::payload_format::text) { return std::nullopt; } @@ -215,11 +238,11 @@ struct payload_traits { * The message's payload as this type: a copy of the text, in the room's resource; nothing for * another format. */ - static std::optional decode(incoming& m, std::pmr::memory_resource* memory) { + static std::optional decode(incoming& m, const decoding& to) { if (m.format != protocol::payload_format::text) { return std::nullopt; } - return std::pmr::string(as_text(m.payload()), memory); + return std::pmr::string(as_text(m.payload()), to.memory); } }; @@ -238,8 +261,7 @@ struct payload_traits { * The message's payload as this type: a view of the message, valid for the handler's call; * nothing for another format. */ - static std::optional decode(incoming& m, - std::pmr::memory_resource* /*memory*/) { + static std::optional decode(incoming& m, const decoding& /*to*/) { if (m.format != protocol::payload_format::text) { return std::nullopt; } @@ -247,34 +269,80 @@ struct payload_traits { } }; -/** How an action of `boost::json::value`, Trystero's JSON payload, travels. */ +/** + * The limits of a received JSON payload's parse: its own length, and an image that grows to at + * most 96 times that and 64 KiB, which every valid text fits, or the room's bound, the smaller + * (@ref protocol::json::payload_limits). + */ +inline webcpp::document::parse_options json_payload_limits(std::string_view text, + const decoding& to) noexcept { + return protocol::json::payload_limits(text.size(), to.max_json_document_bytes); +} + +/** How an action of `webcpp::document::document`, Trystero's JSON payload, travels. */ template <> -struct payload_traits { +struct payload_traits { /** Whether a decoded value owns its storage, so that it may be awaited. */ static constexpr bool owning = true; - /** Serializes the value once, into a shared string of the room's resource. */ - static encoded_payload encode(const boost::json::value& v, std::pmr::memory_resource* memory) { + /** Writes the value once, as `JSON.stringify` writes what JavaScript can hold, into a shared + * string of the room's resource. */ + static encoded_payload encode(const webcpp::document::document& v, + std::pmr::memory_resource* memory) { std::pmr::string text(memory); - protocol::json::append_value(text, v); + protocol::json::append_value(text, v.root()); return own(protocol::payload_format::json, keep(memory, std::move(text))); } /** - * The message's payload as this type: the parsed text, in the room's JSON storage; nothing for - * another format or a text that does not parse. + * The message's payload as this type: the parsed text, an owned document in `std::allocator`, + * as the user chose (@ref json_payload_limits); nothing for another format or a text that does + * not parse within them. */ - static std::optional decode(incoming& m, - std::pmr::memory_resource* /*memory*/) { + static std::optional decode(incoming& m, const decoding& to) { if (m.format != protocol::payload_format::json) { return std::nullopt; } - boost::system::error_code ec; - auto v = protocol::json::parse(as_text(m.payload()), m.json, ec); - if (ec) { + const std::string_view text = as_text(m.payload()); + auto v = webcpp::document::parse(text, json_payload_limits(text, to)); + if (!v.has_value()) { return std::nullopt; } - return v; + return std::move(v).unsafe_value(); + } +}; + +/** How an action of `webcpp::document::pmr::document`, Trystero's JSON payload, travels. */ +template <> +struct payload_traits { + /** Whether a decoded value owns its storage, so that it may be awaited. */ + static constexpr bool owning = true; + + /** Writes the value once, as `JSON.stringify` writes what JavaScript can hold, into a shared + * string of the room's resource. */ + static encoded_payload encode(const webcpp::document::pmr::document& v, + std::pmr::memory_resource* memory) { + std::pmr::string text(memory); + protocol::json::append_value(text, v.root()); + return own(protocol::payload_format::json, keep(memory, std::move(text))); + } + + /** + * The message's payload as this type: the parsed text, its image and the parse's working state + * in the room's resource (@ref json_payload_limits); nothing for another format or a text that + * does not parse within them. + */ + static std::optional decode(incoming& m, const decoding& to) { + if (m.format != protocol::payload_format::json) { + return std::nullopt; + } + const std::string_view text = as_text(m.payload()); + auto v = webcpp::document::parse(text, json_payload_limits(text, to), + std::pmr::polymorphic_allocator(to.memory)); + if (!v.has_value()) { + return std::nullopt; + } + return std::move(v).unsafe_value(); } }; @@ -295,7 +363,7 @@ struct payload_traits { * The message's payload as this type: a copy of the bytes, allocated with `std::allocator`; * nothing for another format. */ - static std::optional decode(incoming& m, std::pmr::memory_resource* /*memory*/) { + static std::optional decode(incoming& m, const decoding& /*to*/) { if (m.format != protocol::payload_format::binary) { return std::nullopt; } @@ -321,15 +389,15 @@ struct payload_traits { * The message's payload as this type: the message's buffer, moved when the payload starts it, * in the room's resource; nothing for another format. */ - static std::optional decode(incoming& m, std::pmr::memory_resource* memory) { + static std::optional decode(incoming& m, const decoding& to) { if (m.format != protocol::payload_format::binary) { return std::nullopt; } - if (m.buffer.get_allocator().resource() != memory) { + if (m.buffer.get_allocator().resource() != to.memory) { const auto payload = m.payload(); - return pmr_bytes(payload.begin(), payload.end(), memory); + return pmr_bytes(payload.begin(), payload.end(), to.memory); } - return pmr_bytes(std::move(m).take_payload(), memory); + return pmr_bytes(std::move(m).take_payload(), to.memory); } }; @@ -349,8 +417,8 @@ struct payload_traits> { * The message's payload as this type: a view of the message, valid for the handler's call; * nothing for another format. */ - static std::optional> decode( - incoming& m, std::pmr::memory_resource* /*memory*/) { + static std::optional> decode(incoming& m, + const decoding& /*to*/) { if (m.format != protocol::payload_format::binary) { return std::nullopt; } @@ -378,20 +446,20 @@ struct payload_traits { * The message's payload as this type: the alternative of the message's format; nothing for * another format. */ - static std::optional decode(incoming& m, std::pmr::memory_resource* memory) { + static std::optional decode(incoming& m, const decoding& to) { switch (m.format) { case protocol::payload_format::text: - if (auto v = payload_traits::decode(m, memory)) { + if (auto v = payload_traits::decode(m, to)) { return payload(std::move(*v)); } return std::nullopt; case protocol::payload_format::json: - if (auto v = payload_traits::decode(m, memory)) { + if (auto v = payload_traits::decode(m, to)) { return payload(std::move(*v)); } return std::nullopt; case protocol::payload_format::binary: - if (auto v = payload_traits::decode(m, memory)) { + if (auto v = payload_traits::decode(m, to)) { return payload(std::move(*v)); } return std::nullopt; @@ -400,6 +468,26 @@ struct payload_traits { } }; +/** + * The value `async_receive` completes with when it decodes no message, which neither allocates nor + * raises: an empty container in the room's resource for a `std::pmr` type, and for a JSON document + * one that holds nothing, whose root reads `undefined`, `webcpp::document::pmr::document`'s in the + * room's resource. + */ +template +T empty_payload(std::pmr::memory_resource* memory) noexcept { + if constexpr (std::is_same_v) { + return T::nothing(std::pmr::polymorphic_allocator(memory)); + } else if constexpr (std::is_same_v) { + return T::nothing(); + } else if constexpr (std::is_same_v || std::is_same_v) { + // An empty std::pmr container allocates nothing. + return T(memory); + } else { + return T{}; + } +} + /** * A user's completion handler, type-erased, and whether its associated executor is the room's, * which only its concrete type tells cheaply: a type-erased executor is compared through objects @@ -408,17 +496,17 @@ struct payload_traits { template struct completion { /** The user's handler. */ - boost::asio::any_completion_handler handler; + webcpp::asio::any_completion_handler handler; /** Whether the handler's associated executor is the room's. */ bool on_room_executor = false; /** The handler's associated allocator type. */ using allocator_type = - boost::asio::associated_allocator_t>; + webcpp::asio::associated_allocator_t>; /** The handler's associated allocator, which Asio allocates what carries it with. */ [[nodiscard]] allocator_type get_allocator() const noexcept { - return boost::asio::get_associated_allocator(handler); + return webcpp::asio::get_associated_allocator(handler); } /** Calls the handler once, with the completion's arguments. */ @@ -443,21 +531,14 @@ struct completion { class room_impl final : public std::enable_shared_from_this, public room_endpoint { public: /** The executor every handler and completion of the room runs on. */ - using executor_type = boost::asio::any_io_executor; + using executor_type = webcpp::asio::any_io_executor; /** What an action's `on_message` becomes: a handler of each received message. */ using message_handler = handler; - /** - * A room of `app`, with its own options copied into `memory`, where it makes its JSON storage - * too. - * - * Tip: the storage is counted, since a value a handler keeps may outlive the room; Boost.JSON - * allocates its counter with `operator new`, once, here. - */ + /** A room of `app`, with its own options copied into `memory`. */ room_impl(std::shared_ptr app, room_options options, std::string_view room_id, std::pmr::memory_resource* memory) : memory_(memory), - json_(boost::json::make_shared_resource(memory_)), app_(std::move(app)), ex_(app_->get_executor()), factory_(app_->factory()), @@ -465,6 +546,7 @@ class room_impl final : public std::enable_shared_from_this, public r options_{ .handshake_timeout = options.handshake_timeout, .max_receive_bytes = options.max_receive_bytes, + .max_json_document_bytes = options.max_json_document_bytes, .memory = memory_, }, room_id_(room_id, memory_), @@ -543,7 +625,7 @@ class room_impl final : public std::enable_shared_from_this, public r } }), }, - memory_, json_); + memory_); signaling_ = std::allocate_shared( allocator(), factory_, sealer_, app_->app_id(), room_id_, app_->self_id(), app_->ice_servers(), @@ -577,7 +659,7 @@ class room_impl final : public std::enable_shared_from_this, public r } }), }, - log_, memory_, app_->memory(), json_); + log_, memory_, app_->memory()); std::pmr::vector topics(memory_); topics.push_back(root_topic_); topics.push_back(self_topic_); @@ -585,8 +667,10 @@ class room_impl final : public std::enable_shared_from_this, public r allocator(), factory_, app_->relay_urls(), std::move(topics), root_topic_, bind([weak, memory = memory_] { const auto self = weak.lock(); - return self ? protocol::write_signal({.peer_id = self->app_->self_id()}, - self->random_id(protocol::nonce_size), memory) + return self ? protocol::write_signal( + {.peer_id = self->app_->self_id()}, + detail::random_id(self->factory_, protocol::nonce_size, memory), + memory) : std::pmr::string(memory); }), bind( @@ -595,7 +679,7 @@ class room_impl final : public std::enable_shared_from_this, public r self->signaling_->handle(relay, content); } }), - log_, memory_, json_); + log_, memory_); register_and_advertise(); } @@ -627,6 +711,11 @@ class room_impl final : public std::enable_shared_from_this, public r /** The room's resource. */ std::pmr::memory_resource* memory() const { return memory_; } + /** What the room decodes a received payload with. */ + detail::decoding decoding() const { + return {.memory = memory_, .max_json_document_bytes = options_.max_json_document_bytes}; + } + /** An allocator of the room's resource. */ std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } @@ -681,7 +770,7 @@ class room_impl final : public std::enable_shared_from_this, public r return it == rebinds_.end() || !it->second.dropping; } - /** Tries to bind a peer after its frame for this room was kept. */ + /** Tries to bind a peer after its frame for this room was kept, which advertised the room. */ void frame_kept(std::string_view peer) override { try_bind(peer, bind_event::frame); } /** Forgets history and removes only the binding belonging to the ended connection. */ @@ -770,7 +859,7 @@ class room_impl final : public std::enable_shared_from_this, public r return; } it->second.pings.push_back( - {.started_ms = factory_.now_ms(), .handler = std::move(handler)}); + {.started = steady_now(factory_), .handler = std::move(handler)}); send_internal("@_ping", it->first); } @@ -841,8 +930,8 @@ class room_impl final : public std::enable_shared_from_this, public r template void complete(Handler&& handler, Args&&... args) { if (on_room_executor(handler)) { - const auto allocator = boost::asio::get_associated_allocator(handler); - post_handler(ex_, boost::asio::bind_allocator( + const auto allocator = webcpp::asio::get_associated_allocator(handler); + post_handler(ex_, webcpp::asio::bind_allocator( allocator, [handler = std::forward(handler), ... args = std::forward(args)]() mutable { std::move(handler)(std::move(args)...); @@ -850,11 +939,11 @@ class room_impl final : public std::enable_shared_from_this, public r return; } if constexpr (is_completion>) { - boost::asio::post( - ex_, boost::asio::append(std::move(handler.handler), std::forward(args)...)); + webcpp::asio::post( + ex_, webcpp::asio::append(std::move(handler.handler), std::forward(args)...)); } else { - boost::asio::post(ex_, boost::asio::append(std::forward(handler), - std::forward(args)...)); + webcpp::asio::post(ex_, webcpp::asio::append(std::forward(handler), + std::forward(args)...)); } } @@ -863,7 +952,7 @@ class room_impl final : public std::enable_shared_from_this, public r completion erase(Handler&& handler) const { const bool here = on_room_executor(handler); return { - boost::asio::any_completion_handler(std::forward(handler)), + webcpp::asio::any_completion_handler(std::forward(handler)), here, }; } @@ -886,9 +975,9 @@ class room_impl final : public std::enable_shared_from_this, public r if constexpr (is_completion) { return handler.on_room_executor; } else if constexpr (std::is_same_v< - boost::asio::associated_executor_t, + webcpp::asio::associated_executor_t, executor_type>) { - return boost::asio::get_associated_executor(handler, ex_) == ex_; + return webcpp::asio::get_associated_executor(handler, ex_) == ex_; } else { return false; } @@ -899,7 +988,7 @@ class room_impl final : public std::enable_shared_from_this, public r enum class end_kind { peer_left, withdrawn, kick, connection_end, room_end }; struct pending_ping { - double started_ms = 0; + detail::time_point started{}; completion handler; }; @@ -940,16 +1029,6 @@ class room_impl final : public std::enable_shared_from_this, public r detail::post(ex_, memory_, std::forward(f)); } - std::pmr::string random_id(std::size_t n) { - std::array random{}; - factory_.random(std::span(random).first(n)); - std::pmr::string id(n, '0', memory_); - for (std::size_t i = 0; i < n; ++i) { - id[i] = protocol::id_alphabet[random[i] % protocol::id_alphabet.size()]; - } - return id; - } - action_slot& slot_for(std::string_view name) { auto it = actions_.find(name); if (it == actions_.end()) { @@ -1038,8 +1117,9 @@ class room_impl final : public std::enable_shared_from_this, public r * itself advertised this room's token on that connection, this room is not leaving, no backoff * of this room runs for the peer, and the peer is not bound already. Whether it bound. * - * Tip: the advertisement is the peer's own, on a connection only it can write to, so that an - * announcement or a signal anyone publishes in its name binds nothing. */ + * Tip: the advertisement is the peer's own, its presence or a room frame of the token, on a + * connection only it can write to, so that an announcement or a signal anyone publishes in its + * name binds nothing. */ bool try_bind(std::string_view peer, bind_event event) { if (left_ || peers_.contains(peer)) { return false; @@ -1197,12 +1277,12 @@ class room_impl final : public std::enable_shared_from_this, public r return; } if (app_->self_id() < peer) { - state.challenge = random_id(36); + state.challenge = detail::random_id(factory_, 36, memory_); // Trystero's genId(36) if (const auto history = rebinds_.find(peer); history != rebinds_.end()) { history->second.challenges.push(std::pmr::string(state.challenge, memory_)); } std::pmr::string text(R"({"__trystero_pw":"challenge","c":)", memory_); - protocol::json::append_string(text, state.challenge); + protocol::json::detail::append_utf8(text, state.challenge); // drawn from id_alphabet text += '}'; send_internal("@_hsdata", peer, protocol::payload_format::json, text); state.challenge_sent = true; @@ -1214,14 +1294,14 @@ class room_impl final : public std::enable_shared_from_this, public r if (it == peers_.end() || it->second.active || it->second.local_passed) { return; } - boost::system::error_code ec; - const auto value = protocol::json::parse(data, json_, ec); - const auto* o = ec ? nullptr : value.if_object(); - const auto field = [o](std::string_view key) -> std::string_view { - const auto* v = o != nullptr ? o->if_contains(key) : nullptr; - const auto* s = v != nullptr ? v->if_string() : nullptr; - return s != nullptr ? std::string_view(s->data(), s->size()) : std::string_view(); - }; + // A message past its bound fails the handshake as one of the wrong shape does. + const auto value = webcpp::document::parse( + data, protocol::json::protocol_limits(protocol::max_handshake_bytes), + std::pmr::polymorphic_allocator(memory_)); + const protocol::json::const_value o = value.has_value() && value->root().is_object() + ? value->root() + : protocol::json::const_value(); + const auto field = [&o](std::string_view key) { return protocol::json::text_of(o[key]); }; if (app_->self_id() < peer) { const auto h = field("h"); const auto r = rebinds_.find(peer); @@ -1241,14 +1321,12 @@ class room_impl final : public std::enable_shared_from_this, public r fail_handshake(peer); return; } - const auto* challenge = o != nullptr ? o->if_contains("c") : nullptr; - if (field("__trystero_pw") != "challenge" || challenge == nullptr || - !challenge->is_string()) { + if (field("__trystero_pw") != "challenge" || !o["c"].is_string()) { fail_handshake(peer); return; } std::pmr::string text(R"({"__trystero_pw":"response","h":)", memory_); - protocol::json::append_string( + protocol::json::detail::append_utf8( text, protocol::handshake_proof(field("c"), app_->password(), app_->app_id(), room_id_, memory_)); text += '}'; @@ -1316,8 +1394,8 @@ class room_impl final : public std::enable_shared_from_this, public r if (it_peer != peers_.end() && !it_peer->second.pings.empty()) { auto ping = std::move(it_peer->second.pings.front()); it_peer->second.pings.pop_front(); - const auto elapsed = std::chrono::milliseconds( - static_cast(factory_.now_ms() - ping.started_ms)); + const auto elapsed = std::chrono::duration_cast( + steady_now(factory_) - ping.started); complete(std::move(ping.handler), boost::system::error_code{}, elapsed); } } else if (name == "@_leave") { @@ -1488,7 +1566,6 @@ class room_impl final : public std::enable_shared_from_this, public r } std::pmr::memory_resource* memory_; - boost::json::storage_ptr json_; std::shared_ptr app_; executor_type ex_; backend::factory& factory_; @@ -1546,7 +1623,7 @@ class action; class room { public: /** The executor every handler and completion of the room runs on. */ - using executor_type = boost::asio::any_io_executor; + using executor_type = webcpp::asio::any_io_executor; /** Not copyable: a room is one membership. */ room(const room&) = delete; @@ -1681,8 +1758,8 @@ class room { * per peer, for 120 s), are delivered to it. * * @tparam T The type of its messages: `std::string`, `std::pmr::string`, `std::string_view`, - * `boost::json::value`, @ref bytes, @ref pmr_bytes, `std::span`, or - * @ref payload for any of Trystero's formats. + * `webcpp::document::document`, `webcpp::document::pmr::document`, @ref bytes, @ref pmr_bytes, + * `std::span`, or @ref payload for any of Trystero's formats. * @param name The action's name, 1 to 32 UTF-8 bytes without NUL; with another, every send * fails with `error::invalid_action_name`. * @return The action. @@ -1705,8 +1782,8 @@ class room { */ template auto async_ping(std::string_view peer, CompletionToken&& token) { - return boost::asio::async_initiate( + return webcpp::asio::async_initiate( [impl = impl_](auto handler, const peer_id& peer) { impl->ping(peer, impl->template erase( @@ -1729,7 +1806,7 @@ class room { */ template auto async_leave(CompletionToken&& token) { - return boost::asio::async_initiate( + return webcpp::asio::async_initiate( [impl = impl_](auto handler) { impl->leave( impl->template erase(std::move(handler))); @@ -1774,7 +1851,9 @@ class action { * Messages that queued while the action had no handler are delivered to it first. * * @tparam F A callable with a `T` and a `const message_info&`; with a view type, the view is - * valid for the duration of the call. + * valid for the duration of the call. A JSON document is the handler's to keep: a handle of its + * values refers to the document object, as every handle of webcpp::document does, so moving the + * document invalidates it. * @param f The handler, kept in the room's resource; it replaces the one set before. */ template @@ -1783,21 +1862,21 @@ class action { impl_->set_action_handler( name_, impl_->bind( - [f = std::forward(f), memory = impl_->memory()](detail::incoming& m) mutable { + [f = std::forward(f), to = impl_->decoding()](detail::incoming& m) mutable { // The metadata is read before decoding: a binary payload takes the buffer the // metadata lives in. const message_info info{ .from = std::move(m.peer), - .metadata = std::pmr::string(m.metadata(), memory), + .metadata = std::pmr::string(m.metadata(), to.memory), }; - if (auto value = detail::payload_traits::decode(m, memory)) { + if (auto value = detail::payload_traits::decode(m, to)) { f(std::move(*value), info); } })); } // T is the action's type, taken by value and moved into its encoding, which keeps a value - // that owns its storage; a boost::json::value is serialized there at once, from a reference. + // that owns its storage; a JSON document is written there at once, from a reference. /** * Sends a message to `options.targets`, or every active peer, Trystero's `send`. * @@ -1812,7 +1891,7 @@ class action { * @tparam CompletionToken An Asio completion token for `void(error_code)`. * @param value The message, taken at the call: moved when `T` owns its storage, copied once * into the room's resource when it is a view, and serialized at once into the room's resource - * when it is a `boost::json::value`, or a @ref payload that holds one. + * when it is a JSON document, or a @ref payload that holds one. * @param options The targets and the metadata. * @param token The completion token. * @return What the token's initiation returns. @@ -1820,7 +1899,7 @@ class action { template auto async_send(T value, send_options options, // NOLINT(performance-unnecessary-value-param) CompletionToken&& token) { - return boost::asio::async_initiate( + return webcpp::asio::async_initiate( [impl = impl_, name = std::pmr::string(name_, impl_->memory())]( auto handler, detail::encoded_payload payload, const send_options& options) { impl->send( @@ -1848,8 +1927,12 @@ class action { * Receives the next message, when no handler is set: the oldest queued, or the next to arrive. * * Completes with `(error_code, T, message_info)`; a message of another payload format than - * `T`'s completes with `error::transfer_rejected` and an empty value, and leaving the room - * with `error::room_left`. `T` must own its storage: a view would outlive the message. + * `T`'s, or a JSON text that does not parse, completes with `error::transfer_rejected` and an + * empty value, which allocates nothing (a JSON document that holds nothing, whose root reads + * `undefined`), and leaving the room with `error::room_left`. + * `T` must own its storage: a view would outlive the message. A JSON document is the + * handler's: a handle of its values refers to the document object, so moving the document + * invalidates it. * * @tparam CompletionToken An Asio completion token for `void(error_code, T, message_info)`. * @param token The completion token. @@ -1859,30 +1942,32 @@ class action { auto async_receive(CompletionToken&& token) { static_assert(detail::payload_traits::owning, "a received view would outlive the message: await an owning type"); - return boost::asio::async_initiate( + return webcpp::asio::async_initiate( [impl = impl_, name = std::pmr::string(name_, impl_->memory())](auto handler) { // The decoding step is allocated as the user's handler is, which it carries. - const auto allocator = boost::asio::get_associated_allocator(handler); + const auto allocator = webcpp::asio::get_associated_allocator(handler); impl->receive( - name, - impl->template erase( - boost::asio::bind_allocator(allocator, [impl, handler = std::move(handler)]( - boost::system::error_code ec, - detail::incoming m) mutable { - auto* const memory = impl->memory(); - message_info info{ - .from = std::move(m.peer), - .metadata = std::pmr::string(m.metadata(), memory), - }; - auto value = - ec ? std::nullopt : detail::payload_traits::decode(m, memory); - if (!ec && !value) { - ec = make_error_code(error::transfer_rejected); - } - impl->complete(std::move(handler), ec, value ? std::move(*value) : T{}, - std::move(info)); - }))); + name, impl->template erase( + webcpp::asio::bind_allocator( + allocator, + [impl, handler = std::move(handler)](boost::system::error_code ec, + detail::incoming m) mutable { + const detail::decoding to = impl->decoding(); + message_info info{ + .from = std::move(m.peer), + .metadata = std::pmr::string(m.metadata(), to.memory), + }; + auto value = ec ? std::nullopt + : detail::payload_traits::decode(m, to); + if (!ec && !value) { + ec = make_error_code(error::transfer_rejected); + } + impl->complete(std::move(handler), ec, + value ? std::move(*value) + : detail::empty_payload(to.memory), + std::move(info)); + }))); }, token); } diff --git a/include/webcpp/trystero/webrtc/data_channel.hpp b/include/webcpp/trystero/webrtc/data_channel.hpp new file mode 100644 index 0000000..465246c --- /dev/null +++ b/include/webcpp/trystero/webrtc/data_channel.hpp @@ -0,0 +1,395 @@ +// 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_WEBRTC_DATA_CHANNEL_HPP +#define WEBCPP_TRYSTERO_WEBRTC_DATA_CHANNEL_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include // lint-world: names the executor only +#include // lint-world: binds an allocator only +#include // lint-world: a frame's buffer only +#include // lint-world: Asio's codes only +#include // lint-world: posts handlers only + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * The backend's WebRTC over webcpp::webrtc, the same on both targets: natively libdatachannel's, + * in the browser the page's own. The platform backend makes its peer connections here, and what + * remains of the platform is webcpp::webrtc's. + */ +namespace webcpp::trystero::webrtc { + +/** The executor of the backend's WebRTC objects: the app's. */ +using executor_type = webcpp::asio::any_io_executor; + +/** The allocator of their state, their queues and their texts: the app's resource. */ +using allocator_type = std::pmr::polymorphic_allocator; + +/** + * A data channel over webcpp::webrtc's, the backend's `RTCDataChannel`, which carries a peer's + * frames. + * + * It reads every message as it comes, with `async_receive`, on the executor. A text message, as a + * peer can send, or a binary one larger than any room frame (`protocol::max_room_frame_bytes`), is + * then dropped: neither can be a frame. Frames received while no message handler is installed wait + * in the app's resource, in order, up to `max_pending_frames` for `pending_frames_ttl` from the + * first, Trystero's pending-data bounds; exceeding either closes the channel. Installing a receiver + * posts their delivery, so that `set_handlers` never calls it inline. In the browser, a message + * larger than webcpp::webrtc's `options::max_message_size`, or past its receive budget, closes the + * channel too. + * + * Tip: a received frame is read once, by webcpp::webrtc, into a vector of the app's resource, + * which the message handler then owns; what the platform holds before is the platform's. + * + * @see "The backend's WebRTC", in the guide. + */ +class data_channel : public backend::data_channel, + public std::enable_shared_from_this { + struct private_tag { + explicit private_tag() = default; + }; + +public: + /** webcpp::webrtc's data channel it holds. */ + using channel_type = ::webcpp::webrtc::basic_data_channel; + + /** The most frames kept while no message handler is installed: more close the channel. */ + static constexpr std::size_t max_pending_frames = 64; + + /** How long after the first kept frame the channel closes, if no handler took them. */ + static constexpr std::chrono::milliseconds pending_frames_ttl{10'000}; + + /** + * Takes over a channel of webcpp::webrtc: its threshold, and its events. + * + * @param runtime The runtime of the channel's connection, which the channel keeps alive. + * @param channel The channel, made or accepted by a connection of the same executor and + * allocator. + * @param factory The backend, which makes the timer of the pending frames, in `memory`. + * @param memory The app's resource, the channel's: the wrapper, its handlers and its frames + * are allocated in it. + * @return The channel. + */ + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + static std::shared_ptr make(std::shared_ptr<::webcpp::webrtc::runtime> runtime, + channel_type channel, backend::factory& factory, + std::pmr::memory_resource* memory) { + // NOLINTEND(performance-unnecessary-value-param) + auto self = std::allocate_shared( + std::pmr::polymorphic_allocator<>(memory), private_tag{}, std::move(runtime), + std::move(channel), factory.make_timer(memory), memory); + self->start(); + return self; + } + + /** + * Constructs the wrapper; only `make` can, which then takes over the channel's events. + * + * @param runtime The runtime of the channel's connection. + * @param channel The channel. + * @param timer The timer of the pending frames. + * @param memory The resource its handlers and its frames are allocated in. + */ + data_channel(private_tag /*tag*/, std::shared_ptr<::webcpp::webrtc::runtime> runtime, + channel_type channel, std::shared_ptr timer, + std::pmr::memory_resource* memory) + : runtime_(std::move(runtime)), + memory_(memory), + pending_(memory), + pending_timer_(std::move(timer)), + frame_(memory), + channel_(std::move(channel)) {} + + /** Not copyable: its operations reach it by its address. */ + data_channel(const data_channel&) = delete; + /** Not copy-assignable: its operations reach it by its address. */ + data_channel& operator=(const data_channel&) = delete; + + /** + * Destroys the wrapper, which closes the channel without reporting the close: webcpp::webrtc + * aborts its pending operations, whose handlers find the wrapper gone. + */ + ~data_channel() override = default; + + /** + * Replaces the handlers, kept in a shared object so that one replacing them during its own call + * outlives the call. + * + * A message handler installed while frames wait posts their delivery. + * + * @param h The new handlers, kept in the channel's resource. + */ + void set_handlers(handlers h) override { + h_ = std::allocate_shared(allocator(), std::move(h)); + if (!pending_.empty() && h_->message && !flush_posted_) { + flush_posted_ = true; + webcpp::asio::post(channel_.get_executor(), + webcpp::asio::bind_allocator(allocator(), [weak = weak_from_this()] { + if (const auto self = weak.lock()) { + self->flush_posted_ = false; + self->flush_pending(); + } + })); + } + } + + /** + * Whether the channel is open. + * + * @return Whether this wrapper has not closed it and its `readyState` is "open". + */ + [[nodiscard]] bool is_open() const override { + return !closed_ && channel_.ready_state() == ::webcpp::webrtc::data_channel_state::open; + } + + /** + * Sends a binary message when the channel is open; one the channel refuses, as one that would + * pass webcpp::webrtc's bound on what it buffers, is dropped. + * + * @param frame The message, read during the call. + */ + void send(std::span frame) override { + if (!is_open()) { + return; + } + // A channel closed in between refuses the frame, and its close event reports it; a frame + // refused leaves nothing to drain. + if (channel_.send(webcpp::asio::buffer(frame.data(), frame.size()))) { + return; + } + watch_drain(); + } + + /** + * The bytes queued to send. + * + * @return Its `bufferedAmount`. + */ + [[nodiscard]] std::size_t buffered_amount() const override { + return channel_.buffered_amount(); + } + + /** Closes the channel, which the handler `close` reports, and discards the frames kept. */ + void close() override { + closed_ = true; + clear_pending(); + channel_.close(); + } + + /** + * The frames received while no message handler is installed, which wait for one. + * + * @return Their number, at most `max_pending_frames`. + */ + [[nodiscard]] std::size_t pending_frames() const noexcept { return pending_.size(); } + +private: + using buffer_type = + webcpp::asio::dynamic_vector_buffer>; + + [[nodiscard]] std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } + + /** Binds `f` to the channel's resource, which webcpp::webrtc allocates its operation in. */ + template + auto bound(F&& f) const { + return webcpp::asio::bind_allocator(allocator(), std::forward(f)); + } + + void start() { + const auto weak = weak_from_this(); + channel_.set_buffered_amount_low_threshold(low_threshold); + channel_.async_wait_open(bound([weak](boost::system::error_code ec) { + if (const auto self = weak.lock(); self && !ec) { + self->on_open(); + } + })); + channel_.async_wait_close(bound([weak](boost::system::error_code ec) { + if (const auto self = weak.lock(); self && !ec) { + self->on_closed(); + } + })); + receive(); + } + + /** Reads the next message into a fresh frame of the channel's resource. */ + void receive() { + // A frame no larger than the largest message webcpp::webrtc accepts, so that none stays + // queued: natively libdatachannel cuts a longer one to it, and in the browser a longer one + // closes the channel. + frame_.clear(); + buffer_.emplace(frame_, ::webcpp::webrtc::options{}.max_message_size); + channel_.async_receive(*buffer_, + bound([weak = weak_from_this()](boost::system::error_code ec, + std::size_t /*size*/, bool text) { + if (const auto self = weak.lock()) { + self->on_received(ec, text); + } + })); + } + + void on_received(boost::system::error_code ec, bool text) { + buffer_.reset(); + // Closed or destroyed, or closing: in the browser a message past max_message_size, or + // past the receive budget, closes the channel. Its close event reports it. + if (ec == webcpp::asio::error::operation_aborted || ec == ::webcpp::webrtc::error::closed || + ec == ::webcpp::webrtc::error::message_too_large || + ec == ::webcpp::webrtc::error::receive_overflow) { + return; + } + if (ec) { + // A message no buffer can take stays queued, and the platform's failure stays too: the + // channel cannot go on. + close(); + return; + } + auto frame = std::exchange(frame_, backend::bytes(memory_)); + if (!closed_) { + receive(); + } + // Trystero frames are binary, and none is larger than the largest room frame. + if (text || frame.size() > protocol::max_room_frame_bytes) { + return; + } + on_message(std::move(frame)); + } + + // The handlers run from a copy of the shared object, which a handler may replace. + + void on_open() { + if (const auto h = h_; !closed_ && h && h->open) { + h->open(); + } + } + + void on_message(backend::bytes frame) { + if (!is_open()) { + return; + } + // A delivery posted by set_handlers may still be ahead: a receiver now exists, so the + // frames kept go first, before the new one counts against the bound. + if (!pending_.empty() && h_ && h_->message) { + flush_pending(); + if (!is_open()) { + return; + } + } + const auto h = h_; + if ((!h || !h->message || !pending_.empty()) && pending_.size() >= max_pending_frames) { + close(); + return; + } + if (h && h->message && pending_.empty()) { + h->message(std::move(frame)); + return; + } + if (pending_.empty()) { + pending_timer_->start(pending_frames_ttl, + {std::allocator_arg, allocator(), [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(); + } + } + } + + /** + * Waits for the buffered amount to fall to `low_threshold` once a send left it above: the + * handler `buffered_amount_low` reports the fall, as `onbufferedamountlow` does. + */ + void watch_drain() { + if (draining_ || channel_.buffered_amount() <= low_threshold) { + return; + } + draining_ = true; + channel_.async_wait_buffered_amount_low( + bound([weak = weak_from_this()](boost::system::error_code ec) { + const auto self = weak.lock(); + if (!self) { + return; + } + self->draining_ = false; + if (const auto h = self->h_; !ec && h && h->buffered_amount_low) { + h->buffered_amount_low(); + } + })); + } + + // The runtime outlives the channel, and the channel goes first, before the frame it reads into. + std::shared_ptr<::webcpp::webrtc::runtime> runtime_; + std::pmr::memory_resource* memory_; + std::shared_ptr h_; + std::pmr::deque pending_; + std::shared_ptr pending_timer_; + backend::bytes frame_; + std::optional buffer_; + bool flush_posted_ = false; + bool draining_ = false; + bool closed_ = false; + channel_type channel_; +}; + +} // namespace webcpp::trystero::webrtc + +#endif diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp new file mode 100644 index 0000000..b6f2c3d --- /dev/null +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -0,0 +1,518 @@ +// 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_WEBRTC_PEER_CONNECTION_HPP +#define WEBCPP_TRYSTERO_WEBRTC_PEER_CONNECTION_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include // lint-world: binds an allocator only +#include // lint-world: posts handlers only + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::webrtc { + +namespace detail { + +/** + * The JSON of an `RTCIceCandidateInit`, as a browser's `RTCIceCandidate` gives it to + * `JSON.stringify`: `candidate`, `sdpMid`, null when empty, `sdpMLineIndex`, null when unknown, + * then `usernameFragment` when there is one; `errc::type` when a text is not UTF-8, which no + * browser's is and JSON cannot carry. + */ +inline webcpp::document::result candidate_json( + std::string_view candidate, std::string_view sdp_mid, + std::optional sdp_m_line_index, std::string_view username_fragment, + std::pmr::memory_resource* memory) { + std::pmr::string json(R"({"candidate":)", memory); + if (const auto quoted = protocol::json::append_string(json, candidate); !quoted) { + return quoted.error(); + } + json += R"(,"sdpMid":)"; + if (sdp_mid.empty()) { + json += "null"; + } else if (const auto quoted = protocol::json::append_string(json, sdp_mid); !quoted) { + return quoted.error(); + } + json += R"(,"sdpMLineIndex":)"; + if (sdp_m_line_index) { + protocol::json::append_integer(json, *sdp_m_line_index); + } else { + json += "null"; + } + if (!username_fragment.empty()) { + json += R"(,"usernameFragment":)"; + if (const auto quoted = protocol::json::append_string(json, username_fragment); !quoted) { + return quoted.error(); + } + } + json += '}'; + return json; +} + +} // namespace detail + +/** + * A peer connection over webcpp::webrtc's, the backend's `RTCPeerConnection`, with its + * negotiation driven by the signaling: an offer or an answer exists only when + * `set_local_description` asks for one. + * + * It keeps a wait of each kind pending on its connection, re-armed on the executor, and reports + * through the handlers what each completes with: + * + * | webcpp::webrtc | Reported | + * | `async_wait_ice_candidate` | the JSON of an `RTCIceCandidateInit` | + * | `async_wait_state_change`, and the ICE state's wait | one state, merging both | + * | `async_accept_data_channel` | the channel, as a `data_channel` | + * + * The merged state is the browser's view of both: failed when either failed, then closed, + * disconnected, connected (or ICE completed), connecting (or ICE checking), and new. + * + * Tip: the connection, its channels, its handlers, its operations and the texts it hands to the + * app are in the app's resource; what the platform holds (libdatachannel's objects, or the page's) + * is the platform's. + * + * @see "The backend's WebRTC", in the guide. + */ +class peer_connection : public backend::peer_connection, + public std::enable_shared_from_this { + struct private_tag { + explicit private_tag() = default; + }; + + [[nodiscard]] std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } + + /** Binds `f` to the connection's resource, which webcpp::webrtc allocates its operation in. */ + template + auto bound(F&& f) const { + return webcpp::asio::bind_allocator(allocator(), std::forward(f)); + } + + /** Posts a completion from the executor, in the connection's resource. */ + template + void post(F&& f) { + webcpp::asio::post(pc_.get_executor(), bound(std::forward(f))); + } + +public: + /** webcpp::webrtc's peer connection it holds. */ + using connection_type = ::webcpp::webrtc::basic_peer_connection; + + /** What `set_local_description` completes with: an error, or the type and the SDP. */ + using description_handler = + handler; + + /** + * Makes a peer connection that gathers through `servers`, bound to `bind_address` when it is + * not empty. + * + * A connection that is not bound gathers a host candidate on each interface but the loopback, + * which ICE never offers (RFC 8445, 5.1.1.1); natively, one bound to an address, as + * `"127.0.0.1"`, gathers on that address alone, which lets two peers of one machine connect + * with no other network. The browser cannot honour it. + * + * @param runtime The runtime that counts the connection, which it keeps alive. + * @param ex The executor every handler of the connection runs on. + * @param servers The STUN and TURN servers it gathers through, read during the call. + * @param bind_address The local address it binds to, natively; empty for every interface. + * @param factory The backend, which makes its channels' timers, and which outlives every + * operation of the connection. + * @param memory The app's resource: the connection, its channels, its handlers and its texts + * are allocated in it. + * @return The connection, or webcpp::webrtc's error: `too_many_peer_connections` past the + * runtime's cap, `syntax_error` for an ICE server URL the platform cannot parse, + * `operation_error` for another refusal. + */ + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + [[nodiscard]] static boost::system::result> make( + std::shared_ptr<::webcpp::webrtc::runtime> runtime, const executor_type& ex, + std::span servers, std::string_view bind_address, + backend::factory& factory, std::pmr::memory_resource* memory) { + // NOLINTEND(performance-unnecessary-value-param) + auto made = make_connection(*runtime, ex, servers, bind_address, memory); + if (!made) { + return made.error(); + } + auto self = std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), + private_tag{}, std::move(runtime), + std::move(*made), factory, memory); + self->start(); + return self; + } + + /** + * Makes webcpp::webrtc's connection alone, with the configuration `make` gives it. + * + * @param runtime The runtime that counts the connection. + * @param ex The executor of the connection. + * @param servers The STUN and TURN servers, read during the call. + * @param bind_address The local address it binds to, natively. + * @param memory The resource of the connection, and of the call's own lists. + * @return The connection, or webcpp::webrtc's error, as `make` says. + */ + [[nodiscard]] static boost::system::result make_connection( + ::webcpp::webrtc::runtime& runtime, const executor_type& ex, + std::span servers, std::string_view bind_address, + std::pmr::memory_resource* memory) { + std::size_t count = 0; + for (const auto& server : servers) { + count += server.urls.size(); + } + // Views of every URL, then the servers as webcpp::webrtc reads them, over those views. + std::pmr::vector urls(memory); + urls.reserve(count); + for (const auto& server : servers) { + urls.insert(urls.end(), server.urls.begin(), server.urls.end()); + } + std::pmr::vector<::webcpp::webrtc::ice_server> list(memory); + list.reserve(servers.size()); + std::size_t at = 0; + for (const auto& server : servers) { + list.push_back({ + .urls = std::span(urls).subspan(at, server.urls.size()), + .username = server.username, + .credential = server.credential, + }); + at += server.urls.size(); + } + const ::webcpp::webrtc::configuration config{ + .ice_servers = list, + .policy = ::webcpp::webrtc::ice_transport_policy::all, + .bind_address = bind_address, + }; + const ::webcpp::webrtc::options bounds; + return connection_type::make(runtime, ex, config, bounds, allocator_type(memory)); + } + + /** + * Constructs the wrapper; only `make` can, which then takes over the connection's events. + * + * @param runtime The runtime that counts the connection. + * @param pc webcpp::webrtc's connection. + * @param factory The backend, which makes its channels' timers. + * @param memory The resource its handlers and its texts are allocated in. + */ + peer_connection(private_tag /*tag*/, std::shared_ptr<::webcpp::webrtc::runtime> runtime, + connection_type pc, backend::factory& factory, + std::pmr::memory_resource* memory) + : runtime_(std::move(runtime)), factory_(factory), memory_(memory), pc_(std::move(pc)) {} + + /** Not copyable: its operations reach it by its address. */ + peer_connection(const peer_connection&) = delete; + /** Not copy-assignable: its operations reach it by its address. */ + peer_connection& operator=(const peer_connection&) = delete; + + /** + * Destroys the wrapper, which closes the connection without reporting the close: + * webcpp::webrtc aborts its pending operations, whose handlers find the wrapper gone. + */ + ~peer_connection() override = default; + + /** + * Replaces the handlers, kept in a shared object so that one replacing them during its own call + * outlives the call. + * + * @param h The new handlers, kept in the connection's resource. + */ + void set_handlers(handlers h) override { + h_ = std::allocate_shared(allocator(), std::move(h)); + } + + /** + * Opens a data channel, with webcpp::webrtc's `create_data_channel`. + * + * @param label The channel's label, read during the call. + * @return The channel, made in the connection's resource, or null when the platform refuses + * to open one, as on a closed connection. + */ + std::shared_ptr create_data_channel(std::string_view label) override { + auto made = pc_.create_data_channel(label); + if (!made) { + return nullptr; + } + return data_channel::make(runtime_, std::move(*made), factory_, memory_); + } + + /** + * Creates the offer or the answer the signaling state calls for and applies it. + * + * @param done Called on the executor with the description's type and SDP, or with + * `error::backend_failure` when the platform refuses, or when the connection goes first. + */ + void set_local_description(description_handler done) override { + pc_.async_set_local_description( + bound([done = std::move(done)](boost::system::error_code ec, + const connection_type::session_description& d) mutable { + if (ec) { + done(make_error_code(error::backend_failure), {}, {}); + return; + } + done({}, type_name(d.type), d.sdp); + })); + } + + /** + * Applies the remote peer's offer or answer. + * + * @param type "offer" or "answer", read during the call. + * @param sdp The description's SDP, read during the call. + * @param done Called on the executor once it is applied, or with `error::backend_failure` when + * the platform refuses it, or when `type` is no description's. + */ + void set_remote_description(std::string_view type, std::string_view sdp, + handler done) override { + const auto kind = type_of(type); + if (!kind) { + post([done = std::move(done)]() mutable { + done(make_error_code(error::backend_failure)); + }); + return; + } + pc_.async_set_remote_description( + {.type = *kind, .sdp = sdp}, + bound([done = std::move(done)](boost::system::error_code ec) mutable { + done(ec ? make_error_code(error::backend_failure) : backend::error_code{}); + })); + } + + /** + * Adds a remote ICE candidate; the empty candidate that ends the remote gathering adds none. + * + * @param candidate_json The JSON of an `RTCIceCandidateInit`, read during the call, at most + * `protocol::max_sealed_candidate_bytes`, the bound of a sealed candidate, which its opened + * JSON never passes. + * @param done Called on the executor once it is added, or with `error::backend_failure` when + * the JSON has no candidate or the platform refuses it. + */ + void add_ice_candidate(std::string_view candidate_json, + handler done) override { + // The document lives in the app's resource for the call: the platform copies the views. + const auto document = webcpp::document::parse( + candidate_json, protocol::json::protocol_limits(protocol::max_sealed_candidate_bytes), + std::pmr::polymorphic_allocator(memory_)); + const protocol::json::const_value object = + document.has_value() ? document->root() : protocol::json::const_value(); + const protocol::json::const_value text = object["candidate"]; + if (!object.is_object() || !text.is_string()) { + post([done = std::move(done)]() mutable { + done(make_error_code(error::backend_failure)); + }); + return; + } + ::webcpp::webrtc::ice_candidate_view candidate{.candidate = protocol::json::text_of(text)}; + if (const protocol::json::const_value mid = object["sdpMid"]; mid.is_string()) { + candidate.sdp_mid = protocol::json::text_of(mid); + } + if (const auto index = object["sdpMLineIndex"].get(); + index.has_value() && *index >= 0 && *index <= 65535) { + candidate.sdp_m_line_index = static_cast(*index); + } + if (const protocol::json::const_value fragment = object["usernameFragment"]; + fragment.is_string()) { + candidate.username_fragment = protocol::json::text_of(fragment); + } + pc_.async_add_ice_candidate( + candidate, bound([done = std::move(done)](boost::system::error_code ec) mutable { + done(ec ? make_error_code(error::backend_failure) : backend::error_code{}); + })); + } + + /** + * Whether a remote description was applied. + * + * @return Whether the connection has a `remoteDescription`. + */ + [[nodiscard]] bool has_remote_description() const override { + return pc_.has_remote_description(); + } + + /** Closes the connection and its channels, as the W3C's `close()`: no state is reported. */ + void close() override { pc_.close(); } + +private: + using state = ::webcpp::webrtc::peer_connection_state; + using ice_state = ::webcpp::webrtc::ice_connection_state; + + static std::string_view type_name(::webcpp::webrtc::sdp_type type) { + switch (type) { + case ::webcpp::webrtc::sdp_type::offer: return "offer"; + case ::webcpp::webrtc::sdp_type::answer: return "answer"; + case ::webcpp::webrtc::sdp_type::pranswer: return "pranswer"; + case ::webcpp::webrtc::sdp_type::rollback: return "rollback"; + } + return "offer"; + } + + static std::optional<::webcpp::webrtc::sdp_type> type_of(std::string_view name) { + if (name == "offer") { + return ::webcpp::webrtc::sdp_type::offer; + } + if (name == "answer") { + return ::webcpp::webrtc::sdp_type::answer; + } + if (name == "pranswer") { + return ::webcpp::webrtc::sdp_type::pranswer; + } + if (name == "rollback") { + return ::webcpp::webrtc::sdp_type::rollback; + } + return std::nullopt; + } + + void start() { + watch_candidates(); + watch_state(); + watch_ice_state(); + accept_channels(); + } + + // Each wait re-arms itself before it reports, on the executor, while the wrapper lives; the + // wrapper's end, or the connection's close, ends them with an error. + + void watch_candidates() { + pc_.async_wait_ice_candidate( + bound([weak = weak_from_this()](boost::system::error_code ec, + const connection_type::ice_candidate& candidate) { + if (const auto self = weak.lock(); self && !ec) { + // The end of gathering, an empty candidate, ends the candidates: none follows. + if (candidate.candidate.empty()) { + return; + } + self->watch_candidates(); + self->on_candidate(candidate); + } + })); + } + + void watch_state() { + pc_.async_wait_state_change( + bound([weak = weak_from_this()](boost::system::error_code ec, state s) { + if (const auto self = weak.lock(); self && !ec) { + self->watch_state(); + self->state_ = s; + self->report(); + } + })); + } + + void watch_ice_state() { + pc_.async_wait_ice_connection_state_change( + bound([weak = weak_from_this()](boost::system::error_code ec, ice_state s) { + if (const auto self = weak.lock(); self && !ec) { + self->watch_ice_state(); + self->ice_state_ = s; + self->report(); + } + })); + } + + void accept_channels() { + pc_.async_accept_data_channel( + bound([weak = weak_from_this()](boost::system::error_code ec, + data_channel::channel_type channel) { + if (const auto self = weak.lock(); self && !ec) { + self->accept_channels(); + self->on_channel(std::move(channel)); + } + })); + } + + // The handlers run from a copy of the shared object, which a handler may replace. + + /** + * Reports `candidate` as the JSON of an `RTCIceCandidateInit`, as the browser writes it; one + * whose text is not UTF-8, which no browser's is and JSON cannot carry, is not reported. + */ + void on_candidate(const connection_type::ice_candidate& candidate) { + const auto h = h_; + if (!h || !h->ice_candidate) { + return; + } + const auto json = detail::candidate_json(candidate.candidate, candidate.sdp_mid, + candidate.sdp_m_line_index, + candidate.username_fragment, memory_); + if (!json.has_value()) { + return; + } + h->ice_candidate(*json); + } + + void on_channel(data_channel::channel_type channel) { + auto wrapped = data_channel::make(runtime_, std::move(channel), factory_, memory_); + if (const auto h = h_; h && h->data_channel) { + h->data_channel(std::move(wrapped)); + } + } + + void report() { + if (const auto h = h_; h && h->state) { + h->state(merged()); + } + } + + /** The connection's state and its ICE state as one, as a page sees them together. */ + [[nodiscard]] backend::connection_state merged() const { + using backend::connection_state; + if (state_ == state::failed || ice_state_ == ice_state::failed) { + return connection_state::failed; + } + if (state_ == state::closed || ice_state_ == ice_state::closed) { + return connection_state::closed; + } + if (state_ == state::disconnected || ice_state_ == ice_state::disconnected) { + return connection_state::disconnected; + } + if (state_ == state::connected || ice_state_ == ice_state::connected || + ice_state_ == ice_state::completed) { + return connection_state::connected; + } + if (state_ == state::connecting || ice_state_ == ice_state::checking) { + return connection_state::connecting; + } + return connection_state::fresh; + } + + // The runtime outlives the connection, which goes first. + std::shared_ptr<::webcpp::webrtc::runtime> runtime_; + backend::factory& factory_; + std::pmr::memory_resource* memory_; + std::shared_ptr h_; + state state_ = state::new_; + ice_state ice_state_ = ice_state::new_; + connection_type pc_; +}; + +} // namespace webcpp::trystero::webrtc + +#endif diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 32fe954..4bdb541 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -8,13 +8,14 @@ "include/webcpp/trystero/detail/*.hpp" ], "must-not-include": [ - "webcpp/trystero/native", - "webcpp/trystero/browser", + "webcpp/trystero/platform", + "webcpp/trystero/webrtc", + "webcpp/webrtc", "rtc/", "emscripten/", "openssl/" ], - "why": "the core builds on both targets, without libdatachannel, OpenSSL or Emscripten" + "why": "the core builds on both targets, without the platform backend, its WebRTC (webcpp::webrtc, natively libdatachannel), OpenSSL or Emscripten" } ] } diff --git a/meta/libraries.json b/meta/libraries.json index f27d25c..be4fd56 100644 --- a/meta/libraries.json +++ b/meta/libraries.json @@ -2,7 +2,7 @@ "key": "trystero", "name": "trystero", "authors": ["R"], - "description": "Serverless WebRTC rooms for C++20, wire compatible with Trystero.", + "description": "Serverless WebRTC rooms for C++20 over webcpp::webrtc, wire compatible with Trystero.", "category": ["Concurrent", "IO"], "maintainers": ["R "], "cxxstd": "20", diff --git a/test/CONVERSION.md b/test/CONVERSION.md index 1296def..a1f115e 100644 --- a/test/CONVERSION.md +++ b/test/CONVERSION.md @@ -35,6 +35,20 @@ build has exceptions is the user's choice and a library supports both (owner dec 2026-10-10). The lint analyses each test a second time without exceptions, except the two that declare them. +Since the backends' WebRTC moved to webcpp::webrtc (2026-11-14), which natively calls +libdatachannel's C API, `native_peer_connection` and `native_room` declare no exceptions: they +run as the build asks and once more without them (`native_peer_connection_no_exceptions`, +`native_room_no_exceptions`). `native_peer_connection` tests the backend's WebRTC +(`webrtc::peer_connection`, `webrtc::data_channel`) in place of `native::peer_connection` and +`native::data_channel`, which are gone, with each old assertion kept. + +Since one platform backend replaced `native::backend` and `browser::backend` (2026-11-14), the +four native programs are `platform_sealer_test.cpp`, `platform_websocket_test.cpp`, +`platform_peer_connection_test.cpp` and `platform_room_test.cpp`, the targets `platform_sealer`, +`platform_websocket`, `platform_peer_connection` and `platform_room`. The sealer's runs on both +targets, its steps chained through the `io_context` rather than one `poll()` each, with the cases +of the browser's sealer test folded in. The tables below keep the names of the conversion. + ## How each form was converted | Old | New | Why | @@ -163,6 +177,16 @@ assertion are not listed. | helper `run` | same | 1 | 1 | in its callers | in its callers | | **3 cases** | **3 functions** | **12** | **12** | **16** | **16** | +The "New function" column is the conversion's. `platform_sealer_test.cpp`, which this file +became, holds none of these functions: its steps are chained through the `io_context`, each +started from the completion of the one before, and `verdict` checks what each recorded, so a case +is now a step and its assertions are in `verdict`. `opens_what_trystero_js_sealed` is +`open_what_js_sealed`, its assertions `opened_js`'s; `seals_in_trystero_form_and_opens_it_back` +is `seal` and `open_sealed`, its assertions `sealed`'s and `opened`'s; +`another_key_is_a_wrong_password` is `refuse`, its assertion `wrong_key`'s; the helper +`sealed_fixture` is `load` and `state::sealed_by_js`, and the helper `run` is gone, `main` +running the `io_context` once with `run_for`. + ### native_websocket_test.cpp | Old case | New function | Static, old | Static, new | Run, old | Run, new | @@ -258,6 +282,6 @@ was built from scratch (`b2 -a`, native clang) and run, the headers then restore | --- | --- | --- | --- | --- | | (1) the root topic built from `"Trystero:"` instead of `"Trystero@"` | `protocol/topics.hpp`, `root_topic` | `protocol`: `topics`, 4 failed assertions of 119, the four root topics of the fixture | `protocol`: `topics`, the same 4 failed assertions, at the same values | every test passes | | (2) a room that does not answer the password challenge | `room.hpp`, `on_handshake_data`: the responder never sends `"__trystero_pw":"response"` | `room`: `the_same_password_joins_and_another_does_not`, 2 failed assertions (the join, then `a.peers().size() == 1`); `native_room`: `native_rooms_join_and_exchange_every_format`, its required join, which ends the case | `room`: the same case, the same 2 assertions; `native_room`: the same case, the same required join, which returns | every test passes | -| (3) a sealer whose `open` skips the GCM tag check | `native/sealer.hpp`, `aes_gcm`: no `EVP_CTRL_GCM_SET_TAG` on decryption, and `EVP_CipherFinal_ex`'s result ignored | `native_sealer`: `another_key_is_a_wrong_password`, 1 failed assertion (the intruder's key opens the text); `native_room`: `another_password_never_joins`, 1 failed assertion (`!errors.empty()`) | `native_sealer`: the same case and assertion; `native_room`: the same case and assertion | every test passes | +| (3) a sealer whose `open` skips the GCM tag check | `native/sealer.hpp`, `aes_gcm` (now `platform/sealer.hpp`, natively): no `EVP_CTRL_GCM_SET_TAG` on decryption, and `EVP_CipherFinal_ex`'s result ignored | `native_sealer`: `another_key_is_a_wrong_password`, 1 failed assertion (the intruder's key opens the text); `native_room`: `another_password_never_joins`, 1 failed assertion (`!errors.empty()`) | `native_sealer`: the same case and assertion (now `platform_sealer`: the step `refuse`, whose `wrong_key` `verdict` checks); `native_room`: the same case and assertion (now `platform_room`) | every test passes | In every planted run, every other test passed, in both suites. diff --git a/test/Jamfile b/test/Jamfile index 849bc69..88e0536 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -7,8 +7,9 @@ # MSVC deprecates std::getenv, which room_test.cpp reads, for a getenv_s of # its own (C4996), an error under /WX: the tests keep the standard's. A test # of rooms over Asio holds more sections than MSVC's object format allows by -# default (C1128, measured in room, native_websocket, native_peer_connection -# and native_room): /bigobj. +# default (C1128, measured in room, and in platform_websocket, +# platform_peer_connection and platform_room when they were native_*): +# /bigobj. project : requirements /webcpp/trystero//trystero msvc:_CRT_SECURE_NO_WARNINGS msvc:/bigobj ; @@ -16,23 +17,38 @@ import webcpp ; webcpp.targets native emscripten ; -# The headers that build on both targets, the native backend's, against -# libdatachannel and OpenSSL, and the browser backend's, on emscripten. The -# native timer (backend.hpp), sealer and WebSockets compile without -# exceptions, so the lint analyses them so too. data_channel.hpp and -# peer_connection.hpp declare nothing without exceptions, so they are -# compiled with them whatever the build asks: libdatachannel reports errors -# by throwing. +# Natively the platform backend needs worker threads, libdatachannel's; a +# page has none. +rule native-threads ( properties * ) +{ + if ! emscripten in $(properties) + { + return multi ; + } +} +local platform = /webcpp/trystero//platform @native-threads ; +# A test of a part that parses no JSON, the timer, a relay's URL, a page's +# calls or the sealer, links parts or platform-parts in place of the rooms: +# they leave out the rooms' Asyncify list, whose pattern names Boost.JSON's +# parser, of which such a program has no function, and Binaryen warns of a +# pattern that names none (build.jam). +local part = -/webcpp/trystero//trystero /webcpp/trystero//parts ; +local platform-part = -/webcpp/trystero//trystero + /webcpp/trystero//platform-parts @native-threads ; + +# The headers that build on both targets: the core, and the platform backend +# with its WebRTC over webcpp::webrtc, natively against libdatachannel and +# OpenSSL, in a page over its own objects; and a page's own header, which +# builds only on emscripten. Every one compiles with exceptions and without +# them, as the build asks, so the lint analyses them so too. 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/timer.hpp - trystero/native/websocket.hpp - : /webcpp/trystero//native multi : native ; -webcpp.headers-alone trystero : ../include - : trystero/native/data_channel.hpp trystero/native/peer_connection.hpp - : /webcpp/trystero//native multi on : native ; -webcpp.headers-alone trystero : ../include : trystero/browser/*.hpp : : emscripten ; + : trystero/platform/backend.hpp trystero/platform/entropy.hpp + trystero/platform/sealer.hpp trystero/platform/websocket.hpp trystero/webrtc/*.hpp + : $(platform) ; +webcpp.headers-alone trystero : ../include : trystero/platform/page.hpp + : $(platform) : emscripten ; # config.hpp defines WEBCPP_TRYSTERO_NO_EXCEPTIONS exactly when webcpp has no # exceptions, and keeps it when a developer defines it in a build that has @@ -47,13 +63,13 @@ webcpp.compile config_all_off : config_test.cpp # The protocol against what Trystero JS computed, which the original's oracle # wrote into fixtures/expected/expected.json, and whole rooms over the memory -# backend of support/memory_backend.hpp: on both targets. The native -# backend's tests, over libdatachannel and OpenSSL, run natively only. Two -# need exceptions whatever the build asks: the types of data_channel.hpp, -# peer_connection.hpp and backend.hpp exist only with them, since -# libdatachannel reports errors by throwing. +# backend of support/memory_backend.hpp: on both targets. # tag::both-targets[] webcpp.run protocol : protocol_test.cpp : fixtures/expected/expected.json ; +# The signaling and the Nostr strategy alone: an answerer's signals against +# Trystero's, and the bounds of the texts they read. +webcpp.run signaling : signaling_test.cpp + : fixtures/expected/expected.json ; webcpp.run room : room_test.cpp ; # Rooms of one app that share one connection per remote peer; once as the # build asks, once without exceptions, on both targets; and, natively, once @@ -71,62 +87,168 @@ webcpp.run memory_backend : memory_backend_test.cpp ; webcpp.run connection : connection_test.cpp ; # The state an app and its rooms share, alone, over the memory backend. webcpp.run app_impl : app_impl_test.cpp ; +# The timer over webcpp::asio's steady_timer, which the platform backend +# makes: a wait cancelled, restarted or destroyed never fires. +webcpp.run timer : timer_test.cpp : $(part) ; # end::both-targets[] -webcpp.run native_sealer : native_sealer_test.cpp - : /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 multi - _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE + +# The platform backend's own tests, on each target that builds them. On both: +# the backend itself (its own state in backend_config::memory, its clocks, +# its randomness, its TLS context); its sealer, natively OpenSSL's AES-GCM, in +# a page Web Crypto under node, against what Trystero JS sealed; relays it +# cannot reach; and how a relay's URL is read. Natively, against +# libdatachannel and in-process servers: the relays' WebSocket, 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; what a relay's message +# allocates outside the room's resource, none; the backend's WebRTC; and whole +# rooms over it. Each as the build asks and, +# but the WebSocket's, which runs once with those checks, without exceptions +# too: webcpp::webrtc calls libdatachannel's C API, which catches what +# libdatachannel throws, so the backend needs none. +# tag::platform[] +webcpp.run platform_backend : platform_backend_test.cpp : $(platform) ; +webcpp.run platform_sealer : platform_sealer_test.cpp + : $(platform) fixtures/expected/expected.json ; +webcpp.run platform_websocket_unreachable : platform_websocket_unreachable_test.cpp + : $(platform) ; +webcpp.run platform_websocket_url : platform_websocket_url_test.cpp : $(platform-part) ; +webcpp.run platform_websocket : platform_websocket_test.cpp + : $(platform) _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS : 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 multi on : native ; -webcpp.run native_room : native_room_test.cpp - : /webcpp/trystero//native multi on : native ; -# end::native[] +webcpp.run platform_websocket_allocation : platform_websocket_allocation_test.cpp + : $(platform) : native ; +webcpp.run platform_peer_connection : platform_peer_connection_test.cpp + : $(platform) : native ; +webcpp.run platform_room : platform_room_test.cpp : $(platform) : native ; +webcpp.run platform_backend_no_exceptions : platform_backend_test.cpp + : $(platform) off ; +webcpp.run platform_sealer_no_exceptions : platform_sealer_test.cpp + : $(platform) fixtures/expected/expected.json off ; +webcpp.run platform_websocket_unreachable_no_exceptions : platform_websocket_unreachable_test.cpp + : $(platform) off ; +webcpp.run platform_websocket_url_no_exceptions : platform_websocket_url_test.cpp + : $(platform-part) off ; +webcpp.run platform_websocket_allocation_no_exceptions : platform_websocket_allocation_test.cpp + : $(platform) off : native ; +webcpp.run platform_peer_connection_no_exceptions : platform_peer_connection_test.cpp + : $(platform) off : native ; +webcpp.run platform_room_no_exceptions : platform_room_test.cpp + : $(platform) off : native ; +# end::platform[] # Every allocation of two rooms that exchange a payload goes through the -# resources of their configurations, and the global operator new and the C -# library's allocation functions see none. Its two counting resources hold -# 64 MiB each, beyond Emscripten's 16 MiB unless the memory grows. +# resources of their configurations, webcpp::document's images and working +# state included: neither the global operator new nor the C library's +# allocation functions see one. Its two counting resources hold 64 MiB each, +# beyond Emscripten's 16 MiB unless the memory grows. # tag::allocation[] webcpp.run allocation : allocation_test.cpp : emscripten:-sALLOW_MEMORY_GROWTH ; # end::allocation[] -# The browser backend's own tests, under node, which has the page's -# WebSocket, Web Crypto and microtasks but no WebRTC. -# tag::browser[] -webcpp.run browser_event_loop : browser_event_loop_test.cpp : : emscripten ; -webcpp.run browser_websocket : browser_websocket_test.cpp : : emscripten ; -webcpp.run browser_websocket_bound : browser_websocket_bound_test.cpp : : emscripten ; -webcpp.run browser_websocket_late_events : browser_websocket_late_events_test.cpp : : emscripten ; -webcpp.run browser_sealer : browser_sealer_test.cpp : : emscripten ; -webcpp.run browser_data_channel : browser_data_channel_test.cpp : : emscripten ; -webcpp.run browser_peer_connection : browser_peer_connection_test.cpp : : emscripten ; -# end::browser[] +# The room, app_impl and allocation tests, whose cases hold whole apps, run +# once more under Asyncify in a release build, as a page ships them, in the +# own lane asyncify: the CI's emscripten lane builds JSPI, and a target that +# names asyncify is declared only in a lane of emscripten's, +# as asio's and cobalt's are, since asyncify composes +# js, a feature only the emscripten toolset +# defines, and a build with no emscripten configured cannot expand it. A +# test whose cases suspend runs each in a frame of its +# own (cases.hpp), whatever the link: -O3 inlines a case that main alone +# calls into main, and linked without optimization, as b2 linked release +# until 2026-11-15 and as -O0 still links it, the room test's +# first suspension then wrote 33,580 bytes, main's frame most of them, and +# stopped it. Linked at -O3 an inlined main fits, so these runs no longer +# catch one. The deepest suspension, as the bytes its unwind wrote, measured +# on 2026-11-15 with Emscripten 6.0.11: in release, linked at -O3, room 564, +# app_impl 440 and allocation 408 (616, 496 and 400 with every case inlined +# into main); in debug, now the deepest build, 2,344, 2,068 and 2,020. +# tag::asyncify-release[] +webcpp.run room_asyncify_release : room_test.cpp + : asyncify release : emscripten ; +webcpp.run app_impl_asyncify_release : app_impl_test.cpp + : asyncify release : emscripten ; +webcpp.run allocation_asyncify_release : allocation_test.cpp + : asyncify release -sALLOW_MEMORY_GROWTH + : emscripten ; +webcpp.lane asyncify : room_asyncify_release app_impl_asyncify_release + allocation_asyncify_release : emscripten ; +# end::asyncify-release[] + +# The platform backend in a page, under node, which has the page's WebSocket +# and Web Crypto but no WebRTC: stand-ins for the page's objects where a test +# needs them. Each main runs its io_context, as a page's program does, and +# suspends in it in either variant. +# tag::page[] +webcpp.run platform_page_websocket_bound : platform_page_websocket_bound_test.cpp + : $(platform) : emscripten ; +webcpp.run platform_page_websocket_late_events : platform_page_websocket_late_events_test.cpp + : $(platform) : emscripten ; +# What a relay sends: a text past the bound in the task of its open is +# refused, and a binary message dropped; and the TLS contexts a page honours, +# and those it refuses. +webcpp.run platform_page_websocket_ingress : platform_page_websocket_ingress_test.cpp + : $(platform) : emscripten ; +webcpp.run platform_page_websocket_tls : platform_page_websocket_tls_test.cpp + : $(platform) : emscripten ; +webcpp.run platform_page_data_channel : platform_page_data_channel_test.cpp + : $(platform) : emscripten ; +webcpp.run platform_page_peer_connection : platform_page_peer_connection_test.cpp + : $(platform) : emscripten ; +# A page's program: main runs the io_context under a work guard, and the +# page's calls into C++ only post to it. +webcpp.run platform_page : platform_page_test.cpp : $(platform) : emscripten ; +# A page's sealer allocates nothing outside the room's resource from the +# start of a seal or an open to its completion: the global operator new and +# the C library's allocation functions, replaced, count none. +webcpp.run platform_page_sealer_allocation : platform_page_sealer_allocation_test.cpp + : $(platform-part) : emscripten ; +# A relay's connection and each of its messages allocate outside the room's +# resource exactly what the guide lists, no more and no fewer. +webcpp.run platform_page_relay_allocation : platform_page_relay_allocation_test.cpp + : $(platform) : emscripten ; +# A page whose crypto misbehaves: its randomness and its sealer fail with +# their errors, and no JavaScript exception enters WebAssembly. +webcpp.run platform_page_sealer : platform_page_sealer_test.cpp : $(platform-part) : emscripten ; +# A page_call's handler sees the page's value as it is when it runs; a +# function the page kept reaches nothing once its page_call, or its +# io_context, is destroyed; and a page_call outlives its io_context harmlessly. +webcpp.run platform_page_call : platform_page_call_test.cpp : $(platform-part) : emscripten ; +# A relay socket's handlers and a sealer's completions run outside the page's +# events. +webcpp.run platform_page_handlers : platform_page_handlers_test.cpp : $(platform) : emscripten ; +# end::page[] -# The same, built without exceptions, as a program that uses the browser -# backend may be: no exception may enter WebAssembly there either. +# The same, built without exceptions, as a page's program may be: no +# exception may enter WebAssembly there either. # tag::no-exceptions[] -webcpp.run browser_event_loop_no_exceptions : browser_event_loop_test.cpp - : off : emscripten ; -webcpp.run browser_websocket_no_exceptions : browser_websocket_test.cpp - : off : emscripten ; -webcpp.run browser_websocket_bound_no_exceptions : browser_websocket_bound_test.cpp - : off : emscripten ; -webcpp.run browser_websocket_late_events_no_exceptions : browser_websocket_late_events_test.cpp - : off : emscripten ; -webcpp.run browser_sealer_no_exceptions : browser_sealer_test.cpp - : off : emscripten ; -webcpp.run browser_data_channel_no_exceptions : browser_data_channel_test.cpp - : off : emscripten ; -webcpp.run browser_peer_connection_no_exceptions : browser_peer_connection_test.cpp - : off : emscripten ; +webcpp.run platform_page_websocket_bound_no_exceptions : platform_page_websocket_bound_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_websocket_late_events_no_exceptions + : platform_page_websocket_late_events_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_websocket_ingress_no_exceptions : platform_page_websocket_ingress_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_websocket_tls_no_exceptions : platform_page_websocket_tls_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_data_channel_no_exceptions : platform_page_data_channel_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_peer_connection_no_exceptions : platform_page_peer_connection_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_no_exceptions : platform_page_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_sealer_allocation_no_exceptions + : platform_page_sealer_allocation_test.cpp + : $(platform-part) off : emscripten ; +webcpp.run platform_page_sealer_no_exceptions : platform_page_sealer_test.cpp + : $(platform-part) off : emscripten ; +webcpp.run platform_page_relay_allocation_no_exceptions : platform_page_relay_allocation_test.cpp + : $(platform) off : emscripten ; +webcpp.run platform_page_call_no_exceptions : platform_page_call_test.cpp + : $(platform-part) off : emscripten ; +webcpp.run platform_page_handlers_no_exceptions : platform_page_handlers_test.cpp + : $(platform) off : emscripten ; # end::no-exceptions[] # The combined Asio/Beast/Trystero provider has its own recurring native lane. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 57f3ddb..b3b4645 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -12,17 +12,24 @@ #include +#include "cases.hpp" #include "require.hpp" #include "support/memory_backend.hpp" -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + #include -#include -#include #include +#include #include #include @@ -43,7 +50,8 @@ #else #include #endif -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#include #include #include #include @@ -52,6 +60,8 @@ #endif namespace trystero = webcpp::trystero; +namespace tp = webcpp::trystero::protocol; +using namespace std::chrono_literals; namespace { @@ -68,10 +78,32 @@ std::array global_sizes{}; std::size_t c_allocations = 0; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool counting = false; + +// The global allocations counted and not freed yet, by address, in a table of a fixed size that +// allocates nothing: open addressing, linear probing, and deletion by shifting back. +constexpr std::size_t live_slots = std::size_t{1} << 16U; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::array live{}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t live_count = 0; +// Set when the table was full: an allocation then went untracked, which fails the test. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +bool live_overflow = false; // Set while operator new takes its memory from the C library, which then // counts nothing: that allocation is operator new's, counted once. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool inside_operator_new = false; +#ifdef WEBCPP_TARGET_EMSCRIPTEN +// Set, from JavaScript, while Asyncify allocates the unwind data of a call that suspends, on +// emscripten under Asyncify: webcpp::asio's run family suspends there, and that allocation is the +// platform's (webcpp::asio's page "Allocation"), counted apart. A char, which JavaScript writes +// through HEAPU8. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::uint8_t inside_runtime = 0; +// The C library's allocations made while inside_runtime is set. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t runtime_allocations = 0; +#endif #ifdef _MSC_VER /** Whether the calling thread is the one the test counts on: MSVC counts every thread. */ @@ -117,7 +149,7 @@ void count_this_thread() noexcept { // any under AddressSanitizer. #ifdef WEBCPP_TEST_TRYSTERO_ADDRESS_SANITIZER // Nothing of the C library is counted. -#elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) +#elif defined(__GLIBC__) || defined(WEBCPP_TARGET_EMSCRIPTEN) #define WEBCPP_TEST_TRYSTERO_COUNTS_C_ALLOCATIONS 1 #ifdef __GLIBC__ extern "C" { @@ -144,7 +176,11 @@ namespace { void* counted(void* pointer) { if (on_counted_thread() && counting && !inside_operator_new) { +#ifdef WEBCPP_TARGET_EMSCRIPTEN + ++(inside_runtime != 0 ? runtime_allocations : c_allocations); +#else ++c_allocations; +#endif } return pointer; } @@ -187,60 +223,69 @@ int posix_memalign(void** out, std::size_t alignment, std::size_t size) { } // NOLINTEND(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN // Emscripten's select() is a poll() over an array of pollfd it callocs on every // call (system/lib/libc/musl/src/select/select.c), and Asio's reactor calls it on // every wait of the io_context the test drives: measured, thousands of calls // while two rooms exchange one payload. This one keeps the array on the stack, so // that the count sees the rooms' allocations rather than the C library's wait. +namespace { + +/** The poll() event `event` when `set` holds `fd`, else none. */ +std::uint32_t requested_event(int fd, const fd_set* set, std::uint32_t event) { + return set != nullptr && FD_ISSET(fd, set) ? event : 0U; +} + +void clear_set(fd_set* set) { + if (set != nullptr) { + FD_ZERO(set); + } +} + +/** Adds the descriptor to `set` when poll() reported one of `events` on it; 1 when it did. */ +int ready_event(const pollfd& descriptor, fd_set* set, std::uint32_t events) { + if (set != nullptr && (static_cast(descriptor.revents) & events) != 0) { + FD_SET(descriptor.fd, set); + return 1; + } + return 0; +} + +} // namespace + +// select's C declaration requires a mutable timeval pointer, although this implementation +// does not change it. extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, - timeval* timeout) { + timeval* timeout) { // NOLINT(misc-const-correctness) if (nfds < 0 || nfds > FD_SETSIZE) { errno = EINVAL; return -1; } std::array fds{}; - int n = 0; + std::size_t n = 0; for (int fd = 0; fd < nfds; ++fd) { - short events = 0; - events |= readfds != nullptr && FD_ISSET(fd, readfds) ? POLLIN : 0; - events |= writefds != nullptr && FD_ISSET(fd, writefds) ? POLLOUT : 0; - events |= exceptfds != nullptr && FD_ISSET(fd, exceptfds) ? POLLPRI : 0; + const std::uint32_t events = requested_event(fd, readfds, POLLIN) | + requested_event(fd, writefds, POLLOUT) | + requested_event(fd, exceptfds, POLLPRI); if (events != 0) { - fds[n++] = pollfd{fd, events, 0}; + fds[n++] = pollfd{.fd = fd, .events = static_cast(events), .revents = 0}; } } const int milliseconds = timeout == nullptr ? -1 - : static_cast(timeout->tv_sec * 1000 + timeout->tv_usec / 1000); + : static_cast((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000)); const int ready = poll(fds.data(), static_cast(n), milliseconds); if (ready < 0) { return ready; } - if (readfds != nullptr) { - FD_ZERO(readfds); - } - if (writefds != nullptr) { - FD_ZERO(writefds); - } - if (exceptfds != nullptr) { - FD_ZERO(exceptfds); - } + clear_set(readfds); + clear_set(writefds); + clear_set(exceptfds); int count = 0; - for (int i = 0; i < n && ready > 0; ++i) { - const short got = fds[i].revents; - if (readfds != nullptr && (got & (POLLIN | POLLHUP | POLLERR)) != 0) { - FD_SET(fds[i].fd, readfds); - ++count; - } - if (writefds != nullptr && (got & (POLLOUT | POLLERR)) != 0) { - FD_SET(fds[i].fd, writefds); - ++count; - } - if (exceptfds != nullptr && (got & POLLPRI) != 0) { - FD_SET(fds[i].fd, exceptfds); - ++count; - } + for (std::size_t i = 0; i < n && ready > 0; ++i) { + count += ready_event(fds[i], readfds, POLLIN | POLLHUP | POLLERR); + count += ready_event(fds[i], writefds, POLLOUT | POLLERR); + count += ready_event(fds[i], exceptfds, POLLPRI); } return count; } @@ -276,6 +321,54 @@ void count_c_allocation(std::uint32_t type, std::uintptr_t /*zone*/, std::uintpt namespace { +/** The slot an address is first looked for in. */ +std::size_t home_of(const void* pointer) noexcept { + const auto bits = static_cast(reinterpret_cast(pointer)); + return static_cast(((bits >> 4U) * 0x9E3779B97F4A7C15ULL) >> 48U) & + (live_slots - 1); +} + +/** Records a counted allocation as live. */ +void track(void* pointer) noexcept { + if (live_count + 1 >= live_slots) { + live_overflow = true; + return; + } + std::size_t i = home_of(pointer); + while (live[i] != nullptr) { + i = (i + 1) & (live_slots - 1); + } + live[i] = pointer; + ++live_count; +} + +/** Forgets a live allocation when it is freed; one never counted is not in the table. */ +void untrack(const void* pointer) noexcept { + if (pointer == nullptr || live_count == 0) { + return; + } + std::size_t i = home_of(pointer); + while (live[i] != pointer) { + if (live[i] == nullptr) { + return; + } + i = (i + 1) & (live_slots - 1); + } + live[i] = nullptr; + --live_count; + // Every entry after it in its run moves back unless its own slot lies between them. + for (std::size_t j = (i + 1) & (live_slots - 1); live[j] != nullptr; + j = (j + 1) & (live_slots - 1)) { + const std::size_t k = home_of(live[j]); + const bool stays = i < j ? (i < k && k <= j) : (i < k || k <= j); + if (!stays) { + live[i] = live[j]; + live[j] = nullptr; + i = j; + } + } +} + /** Memory for operator new, from the C library, uncounted there. */ void* take(std::size_t size, std::size_t alignment) { #ifdef _MSC_VER @@ -291,6 +384,9 @@ void* take(std::size_t size, std::size_t alignment) { } void release(void* pointer) noexcept { + if (on_counted_thread()) { + untrack(pointer); + } #ifdef _MSC_VER _aligned_free(pointer); #elif defined(WEBCPP_TEST_C_FREE) @@ -324,6 +420,9 @@ void* allocate(std::size_t size, std::size_t alignment) { if (pointer == nullptr) { boost::throw_exception(std::bad_alloc()); } + if (on_counted_thread() && counting) { + track(pointer); + } return pointer; } @@ -362,8 +461,15 @@ class counting_resource final : public std::pmr::memory_resource { std::size_t sized = 0; private: - std::vector storage_ = std::vector(std::size_t{64} << 20U); - std::pmr::monotonic_buffer_resource buffer_{storage_.data(), storage_.size(), + static constexpr std::size_t capacity = std::size_t{64} << 20U; + + // Left uninitialized: a std::vector would set its bytes one at a time and destroy them one at + // a time, a call each in a debug build, and under Asyncify, built with Emscripten's exceptions + // in JavaScript, each call inside a try crosses into JavaScript and back: 96 s of the test's + // 118 (measured with node's profiler). + using arena = std::array; + std::unique_ptr storage_ = std::make_unique_for_overwrite(); + std::pmr::monotonic_buffer_resource buffer_{storage_->data(), storage_->size(), std::pmr::null_memory_resource()}; void* do_allocate(std::size_t bytes, std::size_t alignment) override { @@ -375,7 +481,7 @@ class counting_resource final : public std::pmr::memory_resource { void do_deallocate(void* pointer, std::size_t bytes, std::size_t /*alignment*/) override { const auto* at = static_cast(pointer); - if (at < storage_.data() || at >= storage_.data() + storage_.size()) { + if (at < storage_->data() || at >= storage_->data() + storage_->size()) { ++foreign; return; } @@ -387,12 +493,15 @@ class counting_resource final : public std::pmr::memory_resource { } }; +/** How long each run of the io_context the test drives lasts. */ +constexpr std::chrono::milliseconds slice = 10ms; + /** Runs io in slices of 10 ms until done holds, for 5 s at most. */ template -bool run_until(boost::asio::io_context& io, Predicate done) { - for (int slice = 0; slice < 500 && !done(); ++slice) { +bool run_until(webcpp::asio::io_context& io, Predicate done) { + for (auto ran = 0ms; ran < 5s && !done(); ran += slice) { io.restart(); - io.run_for(std::chrono::milliseconds(10)); // lint-run: the memory relays post to it + io.run_for(slice); // lint-run: the memory relays post to it } return done(); } @@ -420,13 +529,16 @@ void the_replaced_operators_serve_every_alignment() { /** * What the counts can see, so that a zero below means something: a counted - * operator new, and a counted call of the C library where it is counted. + * operator new, kept live until it is freed, and a counted call of the C + * library where it is counted. */ void the_counts_see_an_allocation() { counting = true; void* pointer = ::operator new(40); counting = false; + BOOST_TEST_EQ(live_count, 1U); ::operator delete(pointer); + BOOST_TEST_EQ(live_count, 0U); explain_global_allocations(1U); BOOST_TEST_EQ(global_allocations, 1U); #ifdef WEBCPP_TEST_TRYSTERO_COUNTS_C_ALLOCATIONS @@ -460,20 +572,51 @@ trystero::room join(trystero::app& a, std::string_view room_id, return std::move(*r); } -/** Two rooms exchange two payloads that make builds; the second is counted. */ +/** What the global counts saw in a window: operator new's, the C library's, and what is still out. + */ +struct seen { + std::size_t global = 0; + std::size_t c = 0; + std::size_t live = 0; +}; + +// The operator new `plant` leaves out, which `free_planted` frees once the window is closed. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +void* planted = nullptr; + +/** + * Allocates outside every resource, as a room must not, from a handler the io_context runs: an + * operator new it leaves out, and a call of the C library, freed at once. + */ +void plant() { + planted = ::operator new(24); + // The C library's allocation, on purpose. + void* volatile memory = std::malloc(40); + std::free(memory); +} + +/** Frees what `plant` left out. */ +void free_planted() { + ::operator delete(planted); + planted = nullptr; +} + +/** + * Two rooms exchange two payloads that make builds; the second is counted, and the global counts + * seen in its window returned. With `planting`, the receiving handler plants allocations outside + * the resources, which the window must see (doc: #trystero-allocation). + */ template -void exchange_allocates_through_the_rooms_resources(Make make) { +seen exchange_through_the_rooms_resources(Make make, bool planting = false) { // The resources outlive the io_context, whose pending operations they hold. counting_resource a_memory; counting_resource z_memory; - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::test::memory_network network{io}; // The rooms meet on a relay the memory network has: one that names none // derives Trystero's public relays, which it refuses. constexpr std::string_view relay = "wss://relay.test"; network.relay(relay); - const boost::json::storage_ptr json_storage = - boost::json::make_shared_resource(&a_memory); trystero::app a_app(io.get_executor(), network, { .app_id = "allocation", @@ -491,44 +634,174 @@ void exchange_allocates_through_the_rooms_resources(Make make) { auto a = join(a_app, "room"); auto z = join(z_app, "room"); std::size_t received = 0; + bool plant_next = false; auto from_a = a.make_action("chat"); z.make_action("chat").on_message( - [&](const Payload& /*payload*/, const trystero::message_info& /*info*/) { ++received; }); + [&](const Payload& /*payload*/, const trystero::message_info& /*info*/) { + ++received; + if (std::exchange(plant_next, false)) { + plant(); + } + }); const auto send = [&] { - from_a.async_send(make(&a_memory, json_storage), - boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_memory), - [](boost::system::error_code /*ec*/) {})); + from_a.async_send(make(&a_memory), + webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_memory), + [](boost::system::error_code /*ec*/) {})); }; // Joined, connected and one payload through, before the window opens: a // payload sent before the peers meet reaches nobody. if (!BOOST_TEST( run_until(io, [&] { return a.peers().size() == 1 && z.peers().size() == 1; }))) { - return; + return {}; } send(); if (!BOOST_TEST(run_until(io, [&] { return received == 1; }))) { - return; + return {}; } const std::size_t before = a_memory.allocations + z_memory.allocations; + global_allocations = 0; + c_allocations = 0; + plant_next = planting; counting = true; send(); const bool arrived = run_until(io, [&] { return received == 2; }); counting = false; BOOST_TEST(arrived); - explain_global_allocations(0U); - BOOST_TEST_EQ(global_allocations, 0U); - BOOST_TEST_EQ(c_allocations, 0U); + explain_global_allocations(planting ? 1U : 0U); + const seen window{ + .global = std::exchange(global_allocations, 0), + .c = std::exchange(c_allocations, 0), + .live = live_count, + }; + if (planted != nullptr) { + free_planted(); + } BOOST_TEST_GT(a_memory.allocations + z_memory.allocations, before); BOOST_TEST_EQ(a_memory.foreign + z_memory.foreign, 0U); - global_allocations = 0; - c_allocations = 0; + return window; +} + +/** Checks that a window saw no global allocation. */ +void nothing_global(const seen& window) { + BOOST_TEST_EQ(window.global, 0U); + BOOST_TEST_EQ(window.c, 0U); + BOOST_TEST_EQ(window.live, 0U); +} + +/** + * Exchanging each payload type that receives in the room's resource sees no global allocation, a + * JSON document's write and parse included; and a window in which the receiving handler allocates + * outside the resources sees it, so that the zeros are not vacuous (doc: #trystero-allocation). + */ +void exchanges_allocate_through_the_rooms_resources() { + nothing_global(exchange_through_the_rooms_resources( + [](std::pmr::memory_resource* memory) { + return std::pmr::string("a text that no small string holds", memory); + })); + nothing_global(exchange_through_the_rooms_resources( + [](std::pmr::memory_resource* memory) { return trystero::pmr_bytes(4096, 7, memory); })); + nothing_global(exchange_through_the_rooms_resources( + [](std::pmr::memory_resource* memory) { + auto made = webcpp::document::parse( + R"({"drink":"a text that no small string holds","ice":[1,2.5,true,null]})", + webcpp::document::parse_options(), + std::pmr::polymorphic_allocator(memory)); + webcpp::test::require(BOOST_TEST(made.has_value())); + return std::move(made).unsafe_value(); + })); + // A planted operator new and C library call, seen, and the operator new seen still out. + const seen planted_window = exchange_through_the_rooms_resources( + [](std::pmr::memory_resource* memory) { + return std::pmr::string("a text that no small string holds", memory); + }, + true); + BOOST_TEST_EQ(planted_window.global, 1U); +#ifdef WEBCPP_TEST_TRYSTERO_COUNTS_C_ALLOCATIONS + BOOST_TEST_EQ(planted_window.c, 1U); +#endif + BOOST_TEST_EQ(planted_window.live, 1U); + BOOST_TEST_EQ(live_count, 0U); +} + +/** + * Each text a room reads is parsed into a document of the room's resource without a global + * allocation: its image and the parse's working state are the resource's, and the image goes back + * with the document (doc: #trystero-allocation). + */ +void reading_a_text_allocates_through_its_resource() { + counting_resource memory; + std::array secret{}; + secret.fill(7); + const auto key = tp::nostr::signer::from_secret(secret, &memory); + webcpp::test::require(BOOST_TEST(key.has_value())); + const std::array aux{}; + const std::pmr::string sealed(1100, 'A', &memory); + const auto signal = tp::write_signal( + {.peer_id = "AAAAAAAAAAAAAAAAAAAA", .offer_id = "BBBBBBBBBBBBBBBBBBBB", .offer = sealed}, + {}, &memory); + const auto message = tp::nostr::event_message( + *key, std::chrono::sys_seconds(std::chrono::seconds(1'759'700'000)), "topic", signal, aux, + &memory); + // A relay's text of that event: `["EVENT","",]`. + const std::string_view written = message; + std::pmr::string relayed(R"(["EVENT","CCCCCCCCCCCCCCCCCCCC",)", &memory); + relayed += written.substr(9, written.size() - 10); + relayed += ']'; + const std::pmr::string ok( + R"(["OK","0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",true,""])", + &memory); + const std::pmr::string handshake( + R"({"__trystero_pw":"response","h":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"})", + &memory); + const std::pmr::string candidate( + R"({"candidate":"candidate:1 1 UDP 2122317823 192.168.1.10 54321 typ host","sdpMid":"0","sdpMLineIndex":0,"usernameFragment":"abcd"})", + &memory); + + struct text { + std::string_view what; + std::string_view json; + std::size_t bound; + }; + + constexpr std::size_t relay_bound = tp::nostr::max_parsed_relay_text_bytes; + const std::array texts{ + text{.what = "relay event", .json = relayed, .bound = relay_bound}, + text{.what = "relay OK", .json = ok, .bound = relay_bound}, + text{.what = "signal", .json = signal, .bound = tp::max_parsed_signal_bytes}, + text{.what = "handshake", .json = handshake, .bound = tp::max_handshake_bytes}, + text{.what = "candidate", .json = candidate, .bound = tp::max_sealed_candidate_bytes}, + }; + for (const text& t : texts) { + const std::size_t outstanding = memory.outstanding; + global_allocations = 0; + c_allocations = 0; + counting = true; + { + const auto document = + webcpp::document::parse(t.json, tp::json::protocol_limits(t.bound), + std::pmr::polymorphic_allocator(&memory)); + // The image is the resource's, and goes back with the document. + BOOST_TEST(document.has_value()); + BOOST_TEST_GT(memory.outstanding, outstanding); + } + counting = false; + BOOST_TEST_EQ(memory.outstanding, outstanding); + if (global_allocations != 0) { + std::cerr << t.what << ": "; + } + explain_global_allocations(0U); + nothing_global({.global = global_allocations, .c = c_allocations, .live = live_count}); + global_allocations = 0; + c_allocations = 0; + } + BOOST_TEST_EQ(memory.foreign, 0U); } -/** Runs io for about `milliseconds`, whatever happens. */ -void run_for(boost::asio::io_context& io, int milliseconds) { - for (int slice = 0; slice < milliseconds / 10; ++slice) { +/** Runs io for about `duration`, whatever happens, in slices of 10 ms. */ +void run_for(webcpp::asio::io_context& io, std::chrono::milliseconds duration) { + for (auto ran = 0ms; ran + slice <= duration; ran += slice) { io.restart(); - io.run_for(std::chrono::milliseconds(10)); // lint-run: the memory relays post to it + io.run_for(slice); // lint-run: the memory relays post to it } } @@ -537,17 +810,17 @@ void run_for(boost::asio::io_context& io, int milliseconds) { * the timer service and the reactor, the scheduler's first operation, and room * in the timer queue for more waits at once than two rooms keep. */ -void warm(boost::asio::io_context& io) { - std::vector> timers; - for (int i = 0; i < 256; ++i) { - timers.push_back(std::make_unique(io, std::chrono::hours(1))); +void warm(webcpp::asio::io_context& io) { + std::vector> timers; + for (std::size_t i = 0; i < 256; ++i) { + timers.push_back(std::make_unique(io, std::chrono::hours(1))); timers.back()->async_wait([](boost::system::error_code /*ec*/) {}); } for (auto& timer : timers) { timer->cancel(); } - boost::asio::post(io, [] {}); - run_for(io, 20); + webcpp::asio::post(io, [] {}); + run_for(io, 20ms); } // tag::config[] @@ -582,15 +855,15 @@ trystero::room_options options_in(counting_resource& memory) { * Two apps, each with a log and a relay of its own, are made one after the other * and join a room with a password, whose two sides exchange a payload that travels * in chunks, measure a round trip, and one says goodbye; both are destroyed and the - * io_context drained. From the first construction to the drain, operator new sees - * the two rooms' JSON storage counters alone, which Boost.JSON allocates once per - * room, and the C library nothing (doc: #trystero-allocation). + * io_context drained. From the first construction to the drain, while the rooms and + * the relay read and write their JSON texts, neither operator new nor the C library + * sees an allocation (doc: #trystero-allocation). */ void a_room_allocates_through_its_resource_from_join_to_destruction() { counting_resource network_memory; counting_resource a_memory; counting_resource z_memory; - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::test::memory_network network{io, 1, &network_memory}; constexpr std::string_view relay = "wss://relay.test"; network.relay(relay); @@ -619,7 +892,7 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { trystero::app z_app(io.get_executor(), network, app_config_in(z_memory, "zzzzzzzzzzzzzzzzzzzz", relay, z_lines)); auto z = join(z_app, "room", options_in(z_memory)); - run_for(io, 100); + run_for(io, 100ms); { trystero::app a_app(io.get_executor(), network, app_config_in(a_memory, "AAAAAAAAAAAAAAAAAAAA", relay, a_lines)); @@ -633,16 +906,17 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { // tag::bind-allocator[] a.make_action("file").async_send( trystero::pmr_bytes(100'000, 7, &a_memory), - boost::asio::bind_allocator(in(a_memory), [](boost::system::error_code /*ec*/) {})); + webcpp::asio::bind_allocator(in(a_memory), + [](boost::system::error_code /*ec*/) {})); a.async_ping(z.self_id(), - boost::asio::bind_allocator( + webcpp::asio::bind_allocator( in(a_memory), [&pings](boost::system::error_code ec, std::chrono::milliseconds /*rtt*/) { pings += ec ? 0 : 1; })); // end::bind-allocator[] exchanged = run_until(io, [&] { return files == 1 && pings == 1; }); bool gone = false; - z.async_leave(boost::asio::bind_allocator( + z.async_leave(webcpp::asio::bind_allocator( in(z_memory), [&gone](boost::system::error_code /*ec*/) { gone = true; })); farewell = run_until(io, [&] { return gone && left == 1; }); } @@ -652,7 +926,7 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { // #trystero-allocation). The order that holds: // // std::pmr::unsynchronized_pool_resource memory; // first: destroyed last - // boost::asio::io_context io; // destroyed before the resource + // webcpp::asio::io_context io; // destroyed before the resource // { // trystero::app app(io.get_executor(), factory, {.memory = &memory}); // auto room = app.join("id"); @@ -660,7 +934,7 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { // } // io.run(); // lint-run: the program's I/O; or destroy io: pending operations free const std::size_t left_behind = a_memory.outstanding + z_memory.outstanding; - run_for(io, 300); + run_for(io, 300ms); counting = false; BOOST_TEST_GT(left_behind, 0U); BOOST_TEST_EQ(a_memory.outstanding, 0U); @@ -671,8 +945,10 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { BOOST_TEST(farewell); BOOST_TEST_GT(a_lines, 0U); BOOST_TEST_GT(z_lines, 0U); - explain_global_allocations(2U); - BOOST_TEST_EQ(global_allocations, 2U); + explain_global_allocations(0U); + BOOST_TEST_EQ(global_allocations, 0U); + BOOST_TEST_EQ(live_count, 0U); + BOOST_TEST(!live_overflow); BOOST_TEST_EQ(c_allocations, 0U); BOOST_TEST_GT(network_memory.allocations, 0U); global_allocations = 0; @@ -681,11 +957,10 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { /** * Two apps, each with two rooms, one room in the app's resource and one in a resource of its own, - * exchange binary payloads: from construction until the io_context drains, operator new sees only - * the rooms' JSON storage counters and the C library nothing. A payload received by the room with - * its own resource is copied into that resource once, the received frame staying the app's; by the - * room in the app's resource, the payload taken out of the frame is moved into the value (doc: - * #trystero-allocation). + * exchange binary payloads: from construction until the io_context drains, neither operator new nor + * the C library sees an allocation. A payload received by the room with its own resource is copied + * into that resource once, the received frame staying the app's; by the room in the app's resource, + * the payload taken out of the frame is moved into the value (doc: #trystero-allocation). */ void rooms_of_one_app_allocate_through_their_resources() { counting_resource network_memory; @@ -708,7 +983,7 @@ void rooms_of_one_app_allocate_through_their_resources() { const trystero::pmr_bytes to_shared(payload_size, std::uint8_t{1}, &a_memory); const trystero::pmr_bytes to_own(payload_size, std::uint8_t{2}, &a_room_memory); { - boost::asio::io_context io; // after the resources: destroyed before them + webcpp::asio::io_context io; // after the resources: destroyed before them trystero::test::memory_network network{io, 1, &network_memory}; network.relay("wss://relay.test"); warm(io); @@ -741,25 +1016,27 @@ void rooms_of_one_app_allocate_through_their_resources() { } a2.make_action("b").async_send( trystero::pmr_bytes(to_own, &a_room_memory), - boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_room_memory), - [](boost::system::error_code) {})); + webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_room_memory), + [](boost::system::error_code) {})); BOOST_TEST(run_until(io, [&] { return got == 1; })); BOOST_TEST_EQ(z_room_memory.sized, 1U); // copied once, out of the frame BOOST_TEST_EQ(z_memory.sized, 1U); // the received frame, and nothing more z_memory.sized = 0; a1.make_action("b").async_send( trystero::pmr_bytes(to_shared, &a_memory), - boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_memory), - [](boost::system::error_code) {})); + webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_memory), + [](boost::system::error_code) {})); BOOST_TEST(run_until(io, [&] { return got == 2; })); BOOST_TEST_EQ(z_memory.sized, 2U); // the frame, the payload taken out and moved on } - run_for(io, 300); // the io_context runs out of the rooms' work + run_for(io, 300ms); // the io_context runs out of the rooms' work } counting = false; } - explain_global_allocations(4U); - BOOST_TEST_EQ(global_allocations, 4U); // the four rooms' JSON storage counters + explain_global_allocations(0U); + BOOST_TEST_EQ(global_allocations, 0U); + BOOST_TEST_EQ(live_count, 0U); + BOOST_TEST(!live_overflow); BOOST_TEST_EQ(c_allocations, 0U); for (const auto* m : {&a_memory, &a_room_memory, &z_memory, &z_room_memory}) { BOOST_TEST_EQ(m->outstanding, 0U); @@ -804,28 +1081,52 @@ void operator delete(void* pointer, std::size_t /*size*/, std::align_val_t /*ali release(pointer); } +namespace { + +/** + * Marks Asyncify's allocation of a suspension's unwind data, on emscripten under Asyncify, as + * webcpp::asio's own allocation test does: the C library's allocations made during it are counted + * apart, since a suspension of webcpp::asio's run family makes one, which is no room's. + */ +void mark_the_runtime_allocations() { +#ifdef WEBCPP_TARGET_EMSCRIPTEN + // clang-format off + EM_ASM({ + if (typeof Asyncify !== 'object' || typeof Asyncify.allocateData !== 'function') { + return; + } + const flag = $0; + const allocate = Asyncify.allocateData; + Asyncify.allocateData = function(...values) { + const previous = HEAPU8[flag]; + HEAPU8[flag] = 1; + try { + return allocate.apply(this, values); + } finally { + HEAPU8[flag] = previous; + } + }; + }, &inside_runtime); + // clang-format on +#endif +} + +} // namespace + int main() { count_this_thread(); + mark_the_runtime_allocations(); #if defined(WEBCPP_TEST_TRYSTERO_COUNTS_C_ALLOCATIONS) && defined(__APPLE__) && \ - !defined(__EMSCRIPTEN__) + !defined(WEBCPP_TARGET_EMSCRIPTEN) malloc_logger = &count_c_allocation; #endif - the_replaced_operators_serve_every_alignment(); - the_counts_see_an_allocation(); - exchange_allocates_through_the_rooms_resources( - [](std::pmr::memory_resource* memory, const boost::json::storage_ptr& /*storage*/) { - return std::pmr::string("a text that no small string holds", memory); - }); - exchange_allocates_through_the_rooms_resources>( - [](std::pmr::memory_resource* memory, const boost::json::storage_ptr& /*storage*/) { - return std::pmr::vector(4096, 7, memory); - }); - exchange_allocates_through_the_rooms_resources( - [](std::pmr::memory_resource* /*memory*/, const boost::json::storage_ptr& storage) { - return boost::json::value(std::string_view("a text that no small string holds"), - storage); - }); - a_room_allocates_through_its_resource_from_join_to_destruction(); - rooms_of_one_app_allocate_through_their_resources(); - return boost::report_errors(); + // Each case in a frame of its own, which main's never holds (cases.hpp). + using webcpp::test::run_case; + run_case(the_replaced_operators_serve_every_alignment); + run_case(the_counts_see_an_allocation); + run_case(exchanges_allocate_through_the_rooms_resources); + run_case(reading_a_text_allocates_through_its_resource); + run_case(a_room_allocates_through_its_resource_from_join_to_destruction); + run_case(rooms_of_one_app_allocate_through_their_resources); + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/app_impl_test.cpp b/test/app_impl_test.cpp index ac32574..8d9b84d 100644 --- a/test/app_impl_test.cpp +++ b/test/app_impl_test.cpp @@ -17,8 +17,10 @@ #include "support/memory_backend.hpp" -#include +#include + #include +#include #include #include @@ -33,9 +35,10 @@ #include #include +#include "cases.hpp" #include "require.hpp" -namespace asio = boost::asio; +namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; namespace detail = webcpp::trystero::detail; using namespace std::chrono_literals; @@ -276,6 +279,33 @@ void what_no_peer_could_use_is_set_aside() { BOOST_TEST(log == logged); } +// A self id that is not UTF-8, which a signal could not write as a JSON string, is set aside for a +// random one, reported and logged; one in UTF-8 past ASCII is kept as it is. +void a_self_id_that_is_not_utf8_is_set_aside() { + asio::io_context io; + trystero::test::memory_network net(io); + for (const std::string_view id : + {std::string_view("peer\xff"), std::string_view("\xc3\xa9t\xc3\xa9")}) { + lines log; + const auto app = make_app(io, net, log, [&](trystero::app_config& c) { c.self_id = id; }); + const auto reports = app->setup_reports(); + if (id == "peer\xff") { + BOOST_TEST_EQ(app->self_id().size(), trystero::protocol::peer_id_size); + BOOST_TEST_EQ(app->self_id().find_first_not_of(trystero::protocol::id_alphabet), + std::string_view::npos); + const std::vector expected{ + "self_id is not UTF-8, which no peer reads, so the app uses a random one", + }; + BOOST_TEST(std::vector(reports.begin(), reports.end()) == expected); + BOOST_TEST(log == lines{"app: " + expected[0]}); + } else { + BOOST_TEST_EQ(app->self_id(), id); + BOOST_TEST(reports.empty()); + BOOST_TEST(log.empty()); + } + } +} + // Every allocation of the app's construction, of its registry, of an adoption, of a stale // connection's replacement and end, of the list of live connections and of the last user's release // goes through its resource: the default resource refuses every request meanwhile. @@ -454,7 +484,7 @@ void the_last_user_ends_every_connection() { } // A connection whose channel is closing is not reused; the connection that replaces it ends it -// first, as Trystero clears a stale peer (C/shared-peer.mjs:142-149), so the rooms hear its end +// first, as Trystero clears a stale peer (dist/shared-peer.mjs:142-149), so the rooms hear its end // before the new one is adopted, and its later close event ends nothing. void a_stale_connection_ends_before_its_replacement() { asio::io_context io; @@ -481,7 +511,7 @@ void a_stale_connection_ends_before_its_replacement() { // A room that adopts a connection to the peer from inside the stale connection's end: the // replacement the outer adoption brought is closed, and the room's is the one kept, so the peer -// has one connection, whose end leaves none (Trystero's owns(), C/shared-peer.mjs:210-212). +// has one connection, whose end leaves none (Trystero's owns(), dist/shared-peer.mjs:210-212). void an_adoption_from_inside_a_stale_end_is_the_one_kept() { asio::io_context io; trystero::test::memory_network net(io); @@ -575,7 +605,7 @@ void an_adoption_from_inside_an_end_under_way() { m); net.channel_capacity = 1; const std::vector payload(16'000, 0); - for (int i = 0; i < 5; ++i) { + for (std::size_t i = 0; i < 5; ++i) { webcpp::test::require( BOOST_TEST(b->send(trystero::protocol::room_frame("T9", payload, m)))); } @@ -677,20 +707,24 @@ void the_apps_destruction_is_quiet() { } // namespace int main() { - the_configuration_is_copied_and_completed(); - what_the_configuration_names_is_kept(); - what_no_peer_could_use_is_set_aside(); - every_allocation_goes_through_the_apps_resource(); - the_registry_holds_rooms_by_a_weak_reference(); - adopt_starts_one_connection_per_peer(); - the_connections_events_reach_the_rooms(); - the_last_user_ends_every_connection(); - a_stale_connection_ends_before_its_replacement(); - an_adoption_from_inside_a_stale_end_is_the_one_kept(); - a_nested_adoption_gone_stale_ends_before_the_outer_one(); - an_adoption_from_inside_an_end_under_way(); - an_end_takes_only_its_own_entry(); - a_view_into_the_stale_connection_names_its_replacement(); - the_apps_destruction_is_quiet(); - return boost::report_errors(); + // Each case in a frame of its own, which main's never holds (cases.hpp). + using webcpp::test::run_case; + run_case(the_configuration_is_copied_and_completed); + run_case(what_the_configuration_names_is_kept); + run_case(what_no_peer_could_use_is_set_aside); + run_case(a_self_id_that_is_not_utf8_is_set_aside); + run_case(every_allocation_goes_through_the_apps_resource); + run_case(the_registry_holds_rooms_by_a_weak_reference); + run_case(adopt_starts_one_connection_per_peer); + run_case(the_connections_events_reach_the_rooms); + run_case(the_last_user_ends_every_connection); + run_case(a_stale_connection_ends_before_its_replacement); + run_case(an_adoption_from_inside_a_stale_end_is_the_one_kept); + run_case(a_nested_adoption_gone_stale_ends_before_the_outer_one); + run_case(an_adoption_from_inside_an_end_under_way); + run_case(an_end_takes_only_its_own_entry); + run_case(a_view_into_the_stale_connection_names_its_replacement); + run_case(the_apps_destruction_is_quiet); + // Under Asyncify, a main that suspended loses what it returns: the status goes first. + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/bookkeeping.hpp b/test/bookkeeping.hpp new file mode 100644 index 0000000..543765f --- /dev/null +++ b/test/bookkeeping.hpp @@ -0,0 +1,75 @@ +// 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 standard container allocates for itself through its allocator, rebound, whatever it +// holds: the MSVC STL's checked iterators (_ITERATOR_DEBUG_LEVEL above 0, the default of a debug +// build) allocate a proxy for each container when it is constructed and when it is moved; the +// other standard libraries allocate nothing so. A test that counts allocations exactly leaves such +// a block out, as document's tests do: it is no state of what the test measures. Measured once, on +// an empty std::pmr::vector. + +#ifndef WEBCPP_TEST_TRYSTERO_BOOKKEEPING_HPP +#define WEBCPP_TEST_TRYSTERO_BOOKKEEPING_HPP + +#include +#include +#include + +namespace webcpp::test { + +/** The block one standard container allocates for itself; its size is 0 when there is none. */ +struct container_bookkeeping { + /** The size of the block, or 0. */ + std::size_t bytes = 0; + /** The alignment of the block, or 0. */ + std::size_t alignment = 0; +}; + +/** What a standard container allocates for itself on this standard library. */ +inline const container_bookkeeping& bookkeeping() { + /** A resource that records the first block asked of it. */ + class measuring final : public std::pmr::memory_resource { + public: + container_bookkeeping seen; + + private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + if (seen.bytes == 0) { + seen = {.bytes = bytes, .alignment = alignment}; + } + 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; + } + }; + + static const container_bookkeeping measured = [] { + measuring resource; + { + [[maybe_unused]] const std::pmr::vector empty(&resource); + } + return resource.seen; + }(); + return measured; +} + +/** Whether a block of `bytes` at `alignment` may be a standard container's own; never on a + * standard library that allocates none. */ +inline bool is_bookkeeping(std::size_t bytes, std::size_t alignment) { + const container_bookkeeping& own = bookkeeping(); + return own.bytes != 0 && bytes == own.bytes && alignment == own.alignment; +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_TRYSTERO_BOOKKEEPING_HPP diff --git a/test/browser_data_channel_test.cpp b/test/browser_data_channel_test.cpp deleted file mode 100644 index a39dc47..0000000 --- a/test/browser_data_channel_test.cpp +++ /dev/null @@ -1,114 +0,0 @@ -// 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) - -// Tests the browser backend's data channels, under node, over a plain object in place of the -// page's RTCDataChannel: what a peer can send that is no frame is dropped before it is read. A text -// message "1e300" once threw a RangeError out of `new Uint8Array`, and "300000000" made a 300 MB -// frame; a binary message larger than any room frame is dropped too. Only the frame sent last -// reaches the handler, and nothing larger than it is allocated. -// -// main sets the test up and returns with node's exit code at 1; the verdict comes when the last -// frame arrives, or from a deadline that fails by name, and node exits once nothing is pending. - -#include -#include // once per program: the JavaScript export - -#include -#include -#include - -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -namespace { - -/** A resource that remembers the largest allocation it made. */ -class watching_resource final : public std::pmr::memory_resource { -public: - std::size_t largest = 0; - -private: - void* do_allocate(std::size_t bytes, std::size_t alignment) override { - largest = std::max(largest, bytes); - 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; - } -}; - -struct state { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - watching_resource memory; - val channel = val::object(); - std::shared_ptr wrapper; - int messages = 0; - std::size_t last_size = 0; - val deadline = val::undefined(); -}; - -state& the_state() { - static state s; - return s; -} - -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -/** Delivers `data` to the channel's `onmessage` from a timer, as the page delivers a message. */ -void deliver(const val& data) { - val event = val::object(); - event.set("data", data); - val::global("setTimeout")(the_state().channel["onmessage"], val(0), event); -} - -} // namespace - -int main() { - auto& s = the_state(); - s.channel.set("readyState", val("open")); - s.wrapper = std::make_shared(s.loop, s.channel, &s.memory); - s.wrapper->set_handlers({ - .open = {}, - .message = - [](const trystero::backend::bytes& frame) { - auto& s = the_state(); - ++s.messages; - s.last_size = frame.size(); - BOOST_TEST_EQ(s.messages, 1); - BOOST_TEST_EQ(s.last_size, 3U); - BOOST_TEST_LT(s.memory.largest, std::size_t{1024}); - val::global("clearTimeout")(s.deadline); - set_exit_code(boost::report_errors()); - }, - .close = {}, - .buffered_amount_low = {}, - }); - - deliver(val("1e300")); - deliver(val("300000000")); - deliver(val::global("ArrayBuffer").new_(val(20'000))); - deliver(val::global("ArrayBuffer").new_(val(3))); - - const int id = s.loop.add([](int /*slot*/, const val& /*event*/) { - BOOST_ERROR("the frame sent last never arrived"); - set_exit_code(boost::report_errors()); - }); - s.deadline = val::global("setTimeout")(s.loop.handler(id, 0), val(10'000), val::undefined()); - set_exit_code(1); // until the verdict - return 0; -} diff --git a/test/browser_event_loop_test.cpp b/test/browser_event_loop_test.cpp deleted file mode 100644 index 1cfa284..0000000 --- a/test/browser_event_loop_test.cpp +++ /dev/null @@ -1,250 +0,0 @@ -// 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) - -// Tests the browser's event loop, under node, against exceptions that escape a callback, with -// WebAssembly exceptions and without them (exception-handling=off): -// -// - a callback that posts work, then throws, from an event of the page: the exception is reported -// and stops at the function the page called, and the posted work still runs; -// - 3000 such events in a row: WebAssembly's stack pointer is where it was before them, and the -// loop still serves an event and runs posted work after them. Before the fix each escape left -// the frames' stack behind (128 bytes without exceptions), the stack ran past its end after -// about 500, and the loop silently stopped; -// - a recovery from a nested entry, which the page's function makes with the depth it found -// there, keeps the depth of the call still running, and the loop goes on polling; -// - with WebAssembly exceptions, 20,000 C++ exceptions in a row that escape a callback, each from -// an event of the page: each is reported with its what(), and the heap in use is the same after -// them as before. Before the fix each one reached the page's function, which kept the exception -// and the string it owned: 332 bytes per escape, measured. -// -// main starts the first step and returns with node's exit code at 1; each step starts from the -// previous one's posted work, the last sets the exit code to `boost::report_errors()`, and a -// deadline fails by name if the chain stops. Node exits once nothing is pending. - -#include -#include // once per program: the JavaScript exports - -#include -#include -#include -#include -#include // lint-world: posts handlers only -#include - -#include - -#include -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -namespace { - -constexpr int escapes = 3000; - -struct state { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - val deadline = val::undefined(); - std::uintptr_t stack_before = 0; - std::uintptr_t stack_after = 0; - int served_after = 0; - bool heap_measured = false; - std::size_t heap_before = 0; - std::size_t heap_after = 0; -}; - -state& the_state() { - static state s; - return s; -} - -/** Calls `setTimeout` with a function that runs `f` through the loop, as the page's events do. */ -val after(int milliseconds, trystero::browser::event_loop::callback f) { - auto& loop = the_state().loop; - const int id = loop.add(std::move(f)); - return val::global("setTimeout")(loop.handler(id, 0), val(milliseconds), val::undefined()); -} - -/** Sets the code node exits with once nothing is pending. */ -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -/** Ends the test. */ -void verdict() { - val::global("clearTimeout")(the_state().deadline); - set_exit_code(boost::report_errors()); -} - -#ifdef __cpp_exceptions -constexpr int cpp_escapes = 20'000; - -/** - * 20,000 C++ exceptions that escape a callback, each from an event of the page; the heap in use is - * measured from the same callback before and after them, after a first escape, which may allocate - * what every later one reuses. - */ -void cpp_escapes_free_their_exceptions() { - auto& loop = the_state().loop; - const int throwing = loop.add([](int /*slot*/, const val& /*event*/) { - throw std::runtime_error(std::string(200, 'x')); - }); - const int measure = loop.add([](int /*slot*/, const val& /*event*/) { - auto& s = the_state(); - const auto in_use = static_cast(mallinfo().uordblks); - if (!s.heap_measured) { - s.heap_measured = true; - s.heap_before = in_use; - return; - } - s.heap_after = in_use; - boost::asio::post(s.loop.get_executor(), [] { - const auto& s = the_state(); - BOOST_TEST_EQ(s.heap_after, s.heap_before); - BOOST_TEST_EQ(val::global("trysteroTestReported").as(), cpp_escapes); - verdict(); - }); - }); - val::global().set("trysteroTestThrowing", loop.handler(throwing, 0)); - val::global().set("trysteroTestMeasure", loop.handler(measure, 0)); - // Each escape is reported with reportError, where its message is the exception's what(). - // clang-format off - EM_ASM({ - const escapes = $0; - setTimeout(function() { - const report = globalThis.reportError; - let reported = 0; - globalThis.reportError = function(error) { - if (error.message == "x".repeat(200)) { - ++reported; - } - }; - globalThis.trysteroTestThrowing(null); - globalThis.trysteroTestMeasure(null); - reported = 0; - for (let i = 0; i < escapes; ++i) { - globalThis.trysteroTestThrowing(null); - } - globalThis.trysteroTestReported = reported; - if (report) { - globalThis.reportError = report; - } else { - delete globalThis.reportError; - } - globalThis.trysteroTestMeasure(null); - }, 0); - }, cpp_escapes); - // clang-format on -} -#endif - -/** The step after the nested recovery: C++ escapes with exceptions, else the verdict. */ -void after_nested_recovery() { -#ifdef __cpp_exceptions - cpp_escapes_free_their_exceptions(); -#else - verdict(); -#endif -} - -/** - * A recovery from a nested entry: inside a callback, the depth is the callback's own, and - * recovering to it, as the page's function does when a nested call escapes, leaves the depth the - * running call brings back down when it returns. - */ -void nested_recovery() { - after(0, [](int /*slot*/, const val& /*event*/) { - auto& loop = the_state().loop; - BOOST_TEST_EQ(loop.depth(), 1); - loop.recover(loop.depth()); - BOOST_TEST_EQ(loop.depth(), 1); - boost::asio::post(loop.get_executor(), [] { - BOOST_TEST_EQ(the_state().loop.depth(), 1); // the poll that runs it - after_nested_recovery(); - }); - }); -} - -/** A callback with a frame of 4 KiB, which throws from inside it. */ -__attribute__((noinline)) void throw_from_deep(char* sink) { - std::array buffer{}; - std::memset(buffer.data(), 1, buffer.size()); - sink[0] = buffer[100]; - val::global("JSON").call("parse", val("not JSON at all")); - sink[1] = buffer[200]; -} - -/** - * 3000 escapes in a row, each from an event of the page; the stack pointer is measured from the - * same depth before and after them, and the loop must still serve an event and run posted work. - */ -void many_escapes() { - auto& loop = the_state().loop; - static std::array sink{}; - const int throwing = - loop.add([](int /*slot*/, const val& /*event*/) { throw_from_deep(sink.data()); }); - // One registration measures before and after, so that both measures come from one frame. - const int measure = loop.add([](int /*slot*/, const val& /*event*/) { - auto& s = the_state(); - if (s.stack_before == 0) { - s.stack_before = emscripten_stack_get_current(); - return; - } - s.stack_after = emscripten_stack_get_current(); - ++s.served_after; - boost::asio::post(s.loop.get_executor(), [] { - const auto& s = the_state(); - BOOST_TEST_EQ(s.served_after, 1); - BOOST_TEST_EQ(s.stack_after, s.stack_before); - nested_recovery(); - }); - }); - val::global().set("trysteroTestThrowing", loop.handler(throwing, 0)); - val::global().set("trysteroTestMeasure", loop.handler(measure, 0)); - // The escapes are reported with console.error in node; counted here rather than printed. - // EM_ASM spaces its tokens apart: no arrow function, no strict comparison. - // clang-format off - EM_ASM({ - const escapes = $0; - setTimeout(function() { - let reported = 0; - const error = console.error; - console.error = function() { ++reported; }; - globalThis.trysteroTestMeasure(null); - for (let i = 0; i < escapes; ++i) { - globalThis.trysteroTestThrowing(null); - } - console.error = error; - if (reported != escapes) { - console.log("reported " + reported + " of " + escapes + " escapes"); - } - globalThis.trysteroTestMeasure(null); - }, 0); - }, escapes); - // clang-format on -} - -} // namespace - -int main() { - // An event whose callback posts work, then throws: JSON.parse of a text that is not JSON, as - // the backend once did with a peer's candidate. - after(0, [](int /*slot*/, const val& /*event*/) { - boost::asio::post(the_state().loop.get_executor(), many_escapes); - val::global("JSON").call("parse", val("not JSON at all")); - }); - the_state().deadline = after(10'000, [](int /*slot*/, const val& /*event*/) { - BOOST_ERROR("the steps stopped before the verdict"); - set_exit_code(boost::report_errors()); - }); - set_exit_code(1); // until the verdict - return 0; -} diff --git a/test/browser_peer_connection_test.cpp b/test/browser_peer_connection_test.cpp deleted file mode 100644 index 64f54a0..0000000 --- a/test/browser_peer_connection_test.cpp +++ /dev/null @@ -1,143 +0,0 @@ -// 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) - -// Tests the browser backend's peer connections, under node, which has no WebRTC of its own: when -// the page makes no `RTCPeerConnection` (none exists, or its constructor throws, as for a server it -// cannot use or with as many connections as the browser allows), the backend makes none and says -// so with a null connection, which the room reports, rather than letting the exception through; -// a connection whose `createDataChannel` throws, as a closed one's does, opens no channel. -// -// The page holds at most `backend::max_peer_connections` of them, counted from their construction -// until the garbage collector frees them, as Chromium counts them: beyond, the backend makes none, -// closed or dropped connections still count, and once a collection frees them it makes one again. -// -// main runs the checks that need no event, and starts the collection; the verdict comes from the -// census's release, and a deadline fails by name if it never comes. Node exits once nothing is -// pending. - -#include -#include // once per program: the JavaScript exports - -#include -#include -#include -#include - -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -namespace { - -struct state { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - val deadline = val::undefined(); - bool done = false; -}; - -state& the_state() { - static state s; - return s; -} - -val census() { - return val::take_ownership(webcpp_trystero_js_census()); -} - -/** Calls `setTimeout` with a function that runs `f` through the loop, as the page's events do. */ -val after(int milliseconds, trystero::browser::event_loop::callback f) { - auto& loop = the_state().loop; - const int id = loop.add(std::move(f)); - return val::global("setTimeout")(loop.handler(id, 0), val(milliseconds), val::undefined()); -} - -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -/** Once a collection released a connection, the backend makes one again. */ -void on_release(int /*slot*/, const val& held) { - auto& s = the_state(); - if (s.done || held.as() >= trystero::browser::backend::max_peer_connections) { - return; - } - s.done = true; - BOOST_TEST(s.backend.make_peer_connection({}, std::pmr::get_default_resource()) != nullptr); - val::global("clearTimeout")(s.deadline); - set_exit_code(boost::report_errors()); -} - -} // namespace - -int main() { - auto& s = the_state(); - std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); - - // node has no RTCPeerConnection. - BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); - - // One whose constructor throws, as a browser's does at its limit of connections. - EM_ASM({ - globalThis.RTCPeerConnection = class { - constructor() { throw new DOMException('too many connections', 'OperationError'); } - }; - }); - BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); - BOOST_TEST_EQ(census()["held"].as(), 0); - - // One that is made, whose createDataChannel throws, as a closed connection's does. - EM_ASM({ - globalThis.RTCPeerConnection = class { - createDataChannel() { throw new DOMException('closed', 'InvalidStateError'); } - close() {} - }; - }); - { - const auto pc = s.backend.make_peer_connection({}, memory); - if (BOOST_TEST(pc != nullptr)) { - BOOST_TEST(pc->create_data_channel("data") == nullptr); - pc->close(); - } - } - - // The page's budget: the one above still counts, closed and dropped. - constexpr std::size_t budget = trystero::browser::backend::max_peer_connections; - { - std::vector> made; - for (std::size_t i = 0; i < budget; ++i) { - if (auto pc = s.backend.make_peer_connection({}, memory)) { - made.push_back(std::move(pc)); - } - } - BOOST_TEST_EQ(made.size(), budget - 1); - BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); - for (const auto& pc : made) { - pc->close(); - } - } - BOOST_TEST_EQ(census()["held"].as(), static_cast(budget)); - BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); - - // A collection frees them: node's gc, exposed for this test, from an event after this one. - census().set("onrelease", s.loop.handler(s.loop.add(on_release), 0)); - after(0, [](int /*slot*/, const val& /*event*/) { - EM_ASM({ - require('v8').setFlagsFromString('--expose-gc'); - require('vm').runInNewContext('gc')(); - }); - }); - s.deadline = after(10'000, [](int /*slot*/, const val& /*event*/) { - BOOST_ERROR("no collection released a connection"); - set_exit_code(boost::report_errors()); - }); - set_exit_code(1); // until the verdict - return 0; -} diff --git a/test/browser_sealer_test.cpp b/test/browser_sealer_test.cpp deleted file mode 100644 index 73a242e..0000000 --- a/test/browser_sealer_test.cpp +++ /dev/null @@ -1,167 +0,0 @@ -// 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) - -// Tests the browser backend's sealer, under node, whose crypto.subtle is the page's Web Crypto: a -// text it seals opens again, and every completion runs after the call that started it, never -// inside it, as the backend interface says. Before the fix, three completions ran inside the call: -// opening a text that is not a sealed one, and every operation when the key cannot be imported, -// here because there is no crypto.subtle, as on a page that is not a secure context. -// -// main starts the first step and returns with node's exit code at 1; each step starts from the -// completions of the one before, the last sets the exit code to `boost::report_errors()`, and a -// deadline fails by name if the chain stops. Node exits once nothing is pending. - -#include -#include // once per program: the JavaScript exports - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -namespace { - -/** What a completion saw: its error, its text, and whether it ran inside the call. */ -struct outcome { - boost::system::error_code ec; - std::string text; - bool inline_call = false; -}; - -struct state { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - std::shared_ptr sealer; - bool in_call = false; - std::optional sealed; - std::optional opened; - std::optional garbage; - std::optional without_subtle; - std::optional after_failure; - val deadline = val::undefined(); -}; - -state& the_state() { - static state s; - return s; -} - -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -/** A completion that records what it saw into `into`, then runs `next`. */ -trystero::handler record( - std::optional& into, void (*next)()) { - return [&into, next](boost::system::error_code ec, std::string_view text) { - into = outcome{.ec = ec, .text = std::string(text), .inline_call = the_state().in_call}; - next(); - }; -} - -/** Calls `f` with `in_call` raised, so that a completion run inside it says so. */ -template -void call(F f) { - the_state().in_call = true; - f(); - the_state().in_call = false; -} - -std::shared_ptr make_sealer() { - std::array key{}; - key.fill(7); - return the_state().backend.make_sealer(key, std::pmr::get_default_resource()); -} - -/** Checks that a completion came, after its call, with `expected`. */ -void expect(const std::optional& got, boost::system::error_code expected) { - if (BOOST_TEST(got.has_value())) { - BOOST_TEST(got->ec == expected); - BOOST_TEST(!got->inline_call); - } -} - -void verdict() { - const auto& s = the_state(); - expect(s.opened, {}); - if (s.opened) { - BOOST_TEST_EQ(s.opened->text, "hello"); - } - expect(s.garbage, trystero::error::wrong_password); - expect(s.without_subtle, trystero::error::backend_failure); - expect(s.after_failure, trystero::error::backend_failure); - val::global("clearTimeout")(s.deadline); - set_exit_code(boost::report_errors()); -} - -/** Once the key could not be imported: an operation after the failure completes after its call. */ -void open_after_failure() { - call([] { the_state().sealer->open("x$AAAA", record(the_state().after_failure, verdict)); }); -} - -/** - * Without crypto.subtle, as outside a secure context: the key cannot be imported, and the first - * operation completes after its call. - */ -void seal_without_subtle() { - val descriptor = val::object(); - descriptor.set("value", val::object()); - val::global("Object").call("defineProperty", val::global(), val("crypto"), descriptor); - the_state().sealer = make_sealer(); - call([] { - the_state().sealer->seal("hello", record(the_state().without_subtle, open_after_failure)); - }); -} - -/** Once both opens completed, the next step. */ -void opened() { - const auto& s = the_state(); - if (s.opened && s.garbage) { - seal_without_subtle(); - } -} - -/** - * Once the key is imported and the text sealed: the sealed text opens, and a text that is not a - * sealed one is refused after the call. - */ -void open_sealed() { - if (!BOOST_TEST(!the_state().sealed->ec)) { - verdict(); - return; - } - call([] { - auto& s = the_state(); - s.sealer->open(s.sealed->text, record(s.opened, opened)); - s.sealer->open("not a sealed text", record(s.garbage, opened)); - }); -} - -} // namespace - -int main() { - auto& s = the_state(); - s.sealer = make_sealer(); - call([] { the_state().sealer->seal("hello", record(the_state().sealed, open_sealed)); }); - const int id = s.loop.add([](int /*slot*/, const val& /*event*/) { - BOOST_ERROR("the steps stopped before the verdict"); - set_exit_code(boost::report_errors()); - }); - s.deadline = val::global("setTimeout")(s.loop.handler(id, 0), val(10'000), val::undefined()); - set_exit_code(1); // until the verdict - return 0; -} diff --git a/test/browser_websocket_bound_test.cpp b/test/browser_websocket_bound_test.cpp deleted file mode 100644 index e96ca68..0000000 --- a/test/browser_websocket_bound_test.cpp +++ /dev/null @@ -1,133 +0,0 @@ -// 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) - -// Tests the browser backend's bound on what a relay's WebSocket holds unsent, under node, over a -// stand-in for the page's WebSocket: a relay that stops reading, whose bufferedAmount only grows, -// and whose close never completes. The room sends texts of 64 KiB on it, 6.4 MiB in all; past -// protocol::max_queued_relay_bytes the socket is dropped and reports one close, at once, and holds -// no more than the bound. Without the bound, the stand-in held all 6.4 MiB and no close came. -// -// main sets the test up and returns with node's exit code at 1; the verdict comes once the texts -// are sent and the close is reported, or from a deadline that fails by name. - -#include -#include // once per program: the JavaScript exports -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -// The stand-in: it opens on the next turn, adds each text's UTF-8 length to bufferedAmount and -// never drains it, and records close() without ever firing onclose. Its counts are on globalThis. -// clang-format off -// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) -EM_JS(void, install_stalled_websocket, (), { - globalThis.stalledHeld = 0; - globalThis.stalledCloses = 0; - globalThis.WebSocket = class { - constructor(url) { - this.url = url; - this.readyState = 0; - this.bufferedAmount = 0; - setTimeout(() => { - this.readyState = 1; - if (this.onopen) this.onopen({}); - }, 0); - } - send(text) { - this.bufferedAmount += new TextEncoder().encode(text).length; - globalThis.stalledHeld = Math.max(globalThis.stalledHeld, this.bufferedAmount); - } - close() { - this.readyState = 2; - ++globalThis.stalledCloses; - } - }; -}); -// clang-format on - -namespace { - -constexpr int texts = 100; - -struct state { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - std::shared_ptr socket; - int closes = 0; - bool sent = false; - val deadline = val::undefined(); -}; - -state& the_state() { - static state s; - return s; -} - -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -void verdict() { - auto& s = the_state(); - if (!s.sent || s.closes == 0) { - return; - } - BOOST_TEST_EQ(s.closes, 1); - const auto held = static_cast(val::global("stalledHeld").as()); - BOOST_TEST_LE(held, trystero::protocol::max_queued_relay_bytes); - BOOST_TEST_EQ(val::global("stalledCloses").as(), 1); - val::global("clearTimeout")(s.deadline); - s.socket.reset(); - set_exit_code(boost::report_errors()); -} - -} // namespace - -int main() { - install_stalled_websocket(); - auto& s = the_state(); - s.socket = s.backend.connect("wss://relay.test", - { - .open = - [] { - auto& s = the_state(); - const std::string text(std::size_t{64} * 1024, 't'); - for (int i = 0; i < texts; ++i) { - s.socket->send(text); - } - s.sent = true; - verdict(); - }, - .message = {}, - .close = - [] { - ++the_state().closes; - verdict(); - }, - }, - std::pmr::get_default_resource()); - const int id = s.loop.add([](int /*slot*/, const val& /*event*/) { - BOOST_ERROR("the stalled relay was never dropped"); - BOOST_TEST_LE(static_cast(val::global("stalledHeld").as()), - trystero::protocol::max_queued_relay_bytes); - set_exit_code(boost::report_errors()); - }); - s.deadline = val::global("setTimeout")(s.loop.handler(id, 0), val(10'000), val::undefined()); - set_exit_code(1); // until the verdict - return 0; -} diff --git a/test/browser_websocket_late_events_test.cpp b/test/browser_websocket_late_events_test.cpp deleted file mode 100644 index f8218c6..0000000 --- a/test/browser_websocket_late_events_test.cpp +++ /dev/null @@ -1,169 +0,0 @@ -// 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) - -// Tests that a relay's WebSocket the browser backend dropped at protocol::max_queued_relay_bytes -// runs none of its handlers again, under node, over a stand-in for the page's WebSocket that, as a -// browser does, has a message event queued for every text sent (a relay message already in the -// page's event loop) and, after close(), a close event, each dispatched to whatever its handler -// property holds when it runs. Without the detach, the 64 messages queued before the drop reached -// the room after its close was reported. A second socket sends one text larger than the bound -// alone: it is dropped at once, and reports one close. -// -// main sets the test up and returns with node's exit code at 1. The verdict runs on the timer -// queue once both closes are reported, behind every event the stand-in had queued by then, or a -// deadline fails by name. - -#include -#include // once per program: the JavaScript exports -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -// The stand-in: it opens on the next turn, adds each text's UTF-8 length to bufferedAmount and -// never drains it, queues a message event for each text sent and a close event after close(). -// clang-format off -// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) -EM_JS(void, install_late_websocket, (), { - globalThis.lateCloses = 0; - globalThis.WebSocket = class { - constructor(url) { - this.url = url; - this.readyState = 0; - this.bufferedAmount = 0; - setTimeout(() => { - this.readyState = 1; - if (this.onopen) this.onopen({}); - }, 0); - } - send(text) { - this.bufferedAmount += new TextEncoder().encode(text).length; - setTimeout(() => { - if (this.onmessage) this.onmessage({data: "late"}); - }, 0); - } - close() { - this.readyState = 2; - ++globalThis.lateCloses; - setTimeout(() => { - this.readyState = 3; - if (this.onclose) this.onclose({code: 1006}); - }, 0); - } - }; -}); -// clang-format on - -namespace { - -struct state { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - std::shared_ptr stalled; - std::shared_ptr big; - int stalled_closes = 0; - int messages_after_close = 0; - int big_closes = 0; - int verdict = 0; - val deadline = val::undefined(); -}; - -state& the_state() { - static state s; - return s; -} - -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -void judge(int /*slot*/, const val& /*event*/) { - auto& s = the_state(); - BOOST_TEST_EQ(s.stalled_closes, 1); - BOOST_TEST_EQ(s.messages_after_close, 0); - BOOST_TEST_EQ(s.big_closes, 1); - BOOST_TEST_EQ(val::global("lateCloses").as(), 2); - val::global("clearTimeout")(s.deadline); - s.stalled.reset(); - s.big.reset(); - set_exit_code(boost::report_errors()); -} - -/** Once both sockets reported their close, judges behind every event the stand-in queued. */ -void closed() { - const auto& s = the_state(); - if (s.stalled_closes == 0 || s.big_closes == 0) { - return; - } - val::global("setTimeout")(s.loop.handler(s.verdict, 0), val(0), val::undefined()); -} - -} // namespace - -int main() { - install_late_websocket(); - auto& s = the_state(); - s.verdict = s.loop.add(judge); - s.stalled = s.backend.connect("wss://relay.test", - { - .open = - [] { - const auto& s = the_state(); - const std::string text(std::size_t{64} * 1024, 't'); - for (int i = 0; i < 100; ++i) { - s.stalled->send(text); - } - }, - .message = - [](std::string_view /*text*/) { - auto& s = the_state(); - if (s.stalled_closes != 0) { - ++s.messages_after_close; - } - }, - .close = - [] { - ++the_state().stalled_closes; - closed(); - }, - }, - std::pmr::get_default_resource()); - s.big = s.backend.connect( - "wss://relay.test", - { - .open = - [] { - const auto& s = the_state(); - s.big->send(std::string(trystero::protocol::max_queued_relay_bytes + 1, 'b')); - }, - .message = {}, - .close = - [] { - ++the_state().big_closes; - closed(); - }, - }, - std::pmr::get_default_resource()); - const int id = s.loop.add([](int /*slot*/, const val& /*event*/) { - BOOST_ERROR("a dropped socket did not report its close"); - set_exit_code(boost::report_errors()); - }); - s.deadline = val::global("setTimeout")(s.loop.handler(id, 0), val(10'000), val::undefined()); - set_exit_code(1); // until the verdict - return 0; -} diff --git a/test/browser_websocket_test.cpp b/test/browser_websocket_test.cpp deleted file mode 100644 index 43d1033..0000000 --- a/test/browser_websocket_test.cpp +++ /dev/null @@ -1,120 +0,0 @@ -// 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) - -// Tests the browser backend's WebSockets, under node, whose WebSocket refuses URLs as a browser's -// does: what `new WebSocket` makes of each URL is the browser's to decide. A URL it throws for -// makes no socket and reports a close, as the backend interface says of a relay it cannot connect -// to; one it accepts makes a socket, whose failed connection to a port where nothing listens, or -// its close, reports a close too. Each reports exactly one, after the call that made it, never -// inside it, and nothing is thrown. Before the fix, `new WebSocket` threw a SyntaxError through the -// room's constructor. -// -// main sets the test up and returns with node's exit code at 1; the verdict comes when every URL -// has reported its close, or from a deadline that fails by name, and node exits once nothing is -// pending. - -#include -#include // once per program: the JavaScript exports - -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -namespace { - -/** - * URLs node's WebSocket throws for (another scheme, a fragment, no URL, a relative one without a - * page to resolve it against) and ones the WHATWG constructor accepts, mapping http and https to - * ws and wss, to a port where nothing listens. - */ -constexpr std::array urls{ - "ftp://relay.invalid", "wss://relay.invalid/#fragment", "not a url", "/relative", - "http://127.0.0.1:9", "https://127.0.0.1:9", -}; - -struct state { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - std::array, urls.size()> sockets; - std::array closes{}; - std::size_t total = 0; - val deadline = val::undefined(); -}; - -state& the_state() { - static state s; - return s; -} - -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -/** Ends the test once every URL has reported its close. */ -void closed(std::size_t i) { - auto& s = the_state(); - ++s.closes.at(i); - if (++s.total < urls.size()) { - return; - } - for (std::size_t j = 0; j < urls.size(); ++j) { - BOOST_TEST_EQ(s.closes.at(j), 1); - } - val::global("clearTimeout")(s.deadline); - s.sockets = {}; // destroyed after the close: nothing more is reported - set_exit_code(boost::report_errors()); -} - -/** Makes a WebSocket of each URL, then sends on it and closes it, from an event of the page, as a - * room does from its handlers. */ -void connect_all(int /*slot*/, const val& /*event*/) { - auto& s = the_state(); - for (std::size_t i = 0; i < urls.size(); ++i) { - // What node makes of the URL, as the page's own code would see it. - const auto probe = - trystero::browser::detail::js_new(val::global("WebSocket"), s.loop.text(urls.at(i))); - if (probe.ok) { - probe.value.call("close"); - } - std::cout << urls.at(i) << (probe.ok ? ": a socket\n" : ": refused\n"); - - s.sockets.at(i) = s.backend.connect(urls.at(i), - { - .open = [] { BOOST_ERROR("a URL opened"); }, - .message = {}, - .close = [i] { closed(i); }, - }, - std::pmr::get_default_resource()); - s.sockets.at(i)->send("ignored"); - s.sockets.at(i)->close(); - BOOST_TEST_EQ(s.closes.at(i), 0); // not inside the call - } -} - -} // namespace - -int main() { - auto& s = the_state(); - const int start = s.loop.add(connect_all); - val::global("setTimeout")(s.loop.handler(start, 0), val(0), val::undefined()); - const int id = s.loop.add([](int /*slot*/, const val& /*event*/) { - BOOST_ERROR("not every URL reported a close"); - set_exit_code(boost::report_errors()); - }); - s.deadline = val::global("setTimeout")(s.loop.handler(id, 0), val(10'000), val::undefined()); - set_exit_code(1); // until the verdict - return 0; -} diff --git a/test/cases.hpp b/test/cases.hpp new file mode 100644 index 0000000..106d3a7 --- /dev/null +++ b/test/cases.hpp @@ -0,0 +1,35 @@ +// 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) + +// How a test's main runs its cases: each in a frame of its own, which main's frame never holds, +// whatever the link. Under Asyncify each suspension saves every frame from main down to the call +// that suspends, each with the locals its instrumentation keeps. A case that main alone calls is +// inlined into it at -O3, and a program linked without optimization, as b2 linked a release build +// until 2026-11-15 and as -O0 still links one, then keeps the locals of every case in +// main's frame at each suspension of any: the room test's main saved 29,776 bytes so, past the +// 8,192 of webcpp::asio's stack, and stopped at its first suspension. Through run_case its deepest +// suspension writes 3,072 bytes linked so, 564 linked at -O3 and 2,344 in a debug build (measured +// on 2026-11-15 with Emscripten 6.0.11). + +#ifndef WEBCPP_TEST_TRYSTERO_CASES_HPP +#define WEBCPP_TEST_TRYSTERO_CASES_HPP + +#include + +namespace webcpp::test { + +/** A case of a test, which its main calls once. */ +using test_case = void (*)(); + +/** Runs `run` in a frame of its own: never inlined into its caller, it calls the case through a + * pointer, so that no case is inlined into main. */ +BOOST_NOINLINE inline void run_case(test_case run) { + run(); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_TRYSTERO_CASES_HPP diff --git a/test/connection_test.cpp b/test/connection_test.cpp index 1928971..60859b3 100644 --- a/test/connection_test.cpp +++ b/test/connection_test.cpp @@ -13,8 +13,10 @@ #include "support/memory_backend.hpp" -#include +#include + #include +#include #include #include @@ -31,7 +33,7 @@ #include "require.hpp" -namespace asio = boost::asio; +namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; namespace detail = webcpp::trystero::detail; using namespace std::chrono_literals; @@ -272,12 +274,47 @@ void a_withdrawn_token_drops_its_kept_frames() { BOOST_TEST_EQ(p.b.c->take_kept("T3").size(), 1U); } +// A room frame the app keeps advertises its token, as the remote's presence does, and reports no +// presence: only the remote writes to its connection, and its presence for a room comes once per +// connection, which a page can lose (Chrome drops what a page sends on an answering channel as it +// opens). A frame the app does not keep advertises nothing. +void a_kept_frame_advertises_its_token() { + const std::array tokens{"T1"}; + link_pair p(tokens, tokens); + auto* m = std::pmr::get_default_resource(); + const std::array action{2, 0}; + p.a.c->send(trystero::protocol::room_frame("nobody", action, m)); + p.a.c->send(trystero::protocol::room_frame("T2", action, m)); + webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; }))); + BOOST_TEST(p.b.c->advertised("T2")); + BOOST_TEST(!p.b.c->advertised("nobody")); + BOOST_TEST(p.b.presence == (std::vector{"+T1"})); +} + +// A kept frame never advertises a 65th token, nor ends the connection as a 65th presence does: +// it is kept, and its token is not advertised. +void a_kept_frame_never_advertises_a_65th_token() { + const std::array tokens{"T1"}; + link_pair p(tokens, tokens); + auto* m = std::pmr::get_default_resource(); + for (std::size_t i = 0; i < 63; ++i) { + p.a.c->send(trystero::protocol::presence_frame("X" + std::to_string(i), true, m)); + } + const std::array action{2, 0}; + p.a.c->send(trystero::protocol::room_frame("T2", action, m)); + webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; }))); + BOOST_TEST_EQ(p.b.presence.size(), 64U); + BOOST_TEST(!p.b.c->advertised("T2")); + BOOST_TEST(p.b.ended.empty()); + BOOST_TEST(p.b.c->live()); +} + void a_65th_advertised_token_ends_the_connection() { const std::array tokens{"T1"}; link_pair p(tokens, tokens); auto* m = std::pmr::get_default_resource(); // T1 and 63 more: 64 tokens, the most a remote may advertise. - for (int i = 0; i < 63; ++i) { + for (std::size_t i = 0; i < 63; ++i) { p.a.c->send(trystero::protocol::presence_frame("X" + std::to_string(i), true, m)); } webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 64; }))); @@ -308,7 +345,7 @@ void kept_frames_are_bounded_and_dropped_after_10_s() { const std::vector action(trystero::protocol::max_action_frame_bytes, 0); const auto frame = trystero::protocol::room_frame(token, action, m); BOOST_TEST_EQ(frame.size(), 16'515U); - for (int i = 0; i < 65; ++i) { + for (std::size_t i = 0; i < 65; ++i) { p.a.c->send(trystero::protocol::room_frame(token, action, m)); } BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 64; })); @@ -345,7 +382,7 @@ void drain_turns_follow_the_order_of_waiting() { auto* m = std::pmr::get_default_resource(); // Frames the other side drops, past the threshold: 5 x 16,000 bytes. const std::vector payload(16'000, 0); - for (int i = 0; i < 5; ++i) { + for (std::size_t i = 0; i < 5; ++i) { BOOST_TEST(t1->send(trystero::protocol::room_frame("nobody", payload, m))); } webcpp::test::require( @@ -379,7 +416,7 @@ void the_end_fails_every_drain_waiter() { p.net.channel_capacity = 1; auto* m = std::pmr::get_default_resource(); const std::vector payload(16'000, 0); - for (int i = 0; i < 5; ++i) { + for (std::size_t i = 0; i < 5; ++i) { t1->send(trystero::protocol::room_frame("nobody", payload, m)); } std::vector turns; @@ -729,7 +766,7 @@ void taking_every_kept_frame_restarts_the_window() { } // A withdrawal that leaves nothing kept stops the window too, as Trystero's syncDataTimers does -// (C/shared-peer.mjs:417-422, 468-472). +// (dist/shared-peer.mjs:417-422, 468-472). void a_withdrawal_that_empties_the_kept_frames_restarts_the_window() { const std::array tokens{"T1"}; link_pair p(tokens, tokens); @@ -830,6 +867,8 @@ int main() { a_withdrawn_token_is_forgotten(); a_bound_token_reaches_its_binding_and_another_is_kept(); a_withdrawn_token_drops_its_kept_frames(); + a_kept_frame_advertises_its_token(); + a_kept_frame_never_advertises_a_65th_token(); a_65th_advertised_token_ends_the_connection(); a_malformed_frame_ends_the_connection(); kept_frames_are_bounded_and_dropped_after_10_s(); @@ -855,5 +894,6 @@ int main() { kept_may_take_its_frame(); the_end_closes_the_connection_and_frees_the_kept_frames(); a_disconnection_ends_after_5_s_unless_it_reconnects(); - return boost::report_errors(); + // Under Asyncify, a main that suspended loses what it returns: the status goes first. + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/fixtures/cases/protocol.json b/test/fixtures/cases/protocol.json index b1b6421..4c3ccf9 100644 --- a/test/fixtures/cases/protocol.json +++ b/test/fixtures/cases/protocol.json @@ -36,5 +36,108 @@ "chunked": {"type": "file", "length": 40000, "multiplier": 7, "metadata": {"name": "big.bin"}} }, "controls": {"max_receive_bytes": 30000}, - "envelope": {"app_id": "my-app", "room_id": "room-1", "frame": [2, 0, 99, 104, 97, 116], "timeout": 60000} + "envelope": {"app_id": "my-app", "room_id": "room-1", "frame": [2, 0, 99, 104, 97, 116], "timeout": 60000}, + "event_messages": { + "random": {"multiplier": 29, "offset": 11}, + "created_at": 1759700000, + "events": [ + ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"], + ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "quote \" backslash \\ both \\\" solidus / space tilde ~"], + ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "line separator 
 paragraph separator 
 delete \u007f"], + ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "astral 🎉 𝄞, two bytes é \u0080 ߿, three ☕ ࠀ ￿"], + ["topic \u0000 \u001f \" \\ 
 
 \u007f 🎉", "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}"], + ["", ""] + ] + }, + "signal_texts": [ + {"peerId": "\u0000\u0001\u001f", "nonce": "\" \\ 
 
 \u007f 🎉"}, + {"peerId": "\b\f\n\r\t\u000b", "passive": true, "nonce": "n0nce"}, + {"peerId": "p", "offerId": "
\u007f", "offer": "🎉\u0000𝄞 é"}, + {"peerId": "p", "offerId": "o", "candidate": "\u001f \u007f \u0080 \"\\", "passive": true}, + {"peerId": "q\"\\\n", "answer": "
\u0000"}, + {"peerId": "a", "answer": "sealed \u007f", "offerId": "o"}, + {"peerId": "a", "candidate": "\u2028\u2029", "offerId": "o", "passive": true} + ], + "duplicate_keys": { + "signals": [ + "{\"peerId\":\"first\",\"peerId\":\"last\",\"nonce\":\"n\"}", + "{\"peerId\":\"plain\",\"peer\\u0049d\":\"escaped\"}", + "{\"peerId\":\"p\",\"offerId\":\"first\",\"offer\":\"first\",\"offerId\":\"last\",\"offer\":\"last\"}", + "{\"peerId\":\"p\",\"offer\":\"\",\"offer\":\"sealed\"}", + "{\"peerId\":\"p\",\"offer\":\"sealed\",\"offer\":\"\"}", + "{\"peerId\":\"p\",\"candidate\":1,\"candidate\":\"sealed\"}", + "{\"peerId\":\"p\",\"answer\":\"sealed\",\"answer\":null}", + "{\"peerId\":\"p\",\"passive\":true,\"passive\":false}", + "{\"peerId\":\"p\",\"passive\":false,\"passive\":true}", + "{\"peerId\":\"p\",\"peerId\":\"\"}", + "{\"peerId\":\"\",\"answer\":\"sealed\",\"peerId\":\"p\"}", + "{\"peerId\":\"p\",\"peer\":\"x\",\"offer\":\"sealed\"}", + "{\"peerId\":\"p\",\"peer\":null,\"nonce\":\"n\"}" + ], + "events": { + "app_id": "my-app", + "room_id": "room-1", + "texts": [ + [ + ["tags", [["x", "{root}"]]], + ["content", "{\"peerId\":\"content-first\",\"answer\":\"x\"}"], + ["content", "{\"peerId\":\"content-last\",\"answer\":\"x\"}"] + ], + [ + ["tags", [["x", "{root}"]]], + ["content", "{\"peerId\":\"escaped-first\",\"answer\":\"x\"}"], + ["con\\u0074ent", "{\"peerId\":\"escaped-last\",\"answer\":\"x\"}"] + ], + [ + ["tags", [["x", "another-topic"]]], + ["content", "{\"peerId\":\"root-tags-last\",\"answer\":\"x\"}"], + ["tags", [["x", "{root}"]]] + ], + [ + ["tags", [["x", "{root}"]]], + ["content", "{\"peerId\":\"root-tags-first\",\"answer\":\"x\"}"], + ["tags", [["x", "another-topic"]]] + ], + [ + ["tags", [["x", "{root}"]]], + ["content", 7], + ["content", "{\"peerId\":\"text-content-last\",\"answer\":\"x\"}"] + ], + [ + ["tags", [["x", "{root}"]]], + ["content", "{\"peerId\":\"text-content-first\",\"answer\":\"x\"}"], + ["content", 7] + ] + ] + } + }, + "answerer": { + "app_id": "my-app", + "room_id": "room-1", + "password": "secret", + "self_id_random": {"multiplier": 23, "offset": 5}, + "random": {"multiplier": 31, "offset": 7}, + "offer_sdp": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=offer\r\n", + "answer_sdp": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n", + "candidate": { + "candidate": "candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host", + "sdpMid": "0", + "sdpMLineIndex": 0, + "usernameFragment": "uf" + }, + "offers": [ + {"peerId": "zzzzzzzzzzzzzzzzzzz1", "offerId": "o\"\\ 
 é"}, + {"peerId": "zzzzzzzzzzzzzzzzzzz2"} + ] + }, + "payload_texts": [ + "{\"b\":1,\"a\":2,\"10\":3,\"2\":4,\"-1\":5,\"01\":6,\"1.5\":7,\"4294967294\":8,\"4294967295\":9,\"0\":10}", + "{\"z\":{\"y\":[1,{\"3\":true,\"x\":null,\"1\":false}],\"0\":\"\"},\"a\":[]}", + "[0,-0,1,-1,100,1E3,1e+2,12e-1,0.1,1.5,123.45,0.30000000000000004,1e20,1e21,123e19,0.000001,1e-6,1e-7,2.5e-8]", + "[1.5e300,-1.5e-300,5e-324,1.7976931348623157e308,9007199254740991,-9007199254740991,4294967296]", + "[\"\\u2028\\u0000\\u007f é 🎉\\\"\\\\/\",true,false,null,{}]" + ], + "payload_beyond_doubles": [ + "[9007199254740993,-9223372036854775808,0.1000000000000000055511151231257827,1e400]" + ] } diff --git a/test/fixtures/expected/expected.json b/test/fixtures/expected/expected.json index 7de4191..9525ab0 100644 --- a/test/fixtures/expected/expected.json +++ b/test/fixtures/expected/expected.json @@ -372,5 +372,295 @@ "01004032653466303963373734303634316634643332333364646431656530636435346162613165376664633639653862336532646466636465643838626163643364020063686174", "0200004032653466303963373734303634316634643332333364646431656530636435346162613165376664633639653862336532646466636465643838626163643364" ] - } + }, + "event_messages": { + "secret_key": "ea25be8deb88b3e137d8e64800a8f1f323fdf2a5ec32e8d5f28fc5bafad693df", + "aux": "0b2845627f9cb9d6f3102d4a6784a1bedbf815324f6c89a6c3e0fd1a3754718e", + "created_at": 1759700000, + "events": [ + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f", + "id": "1a1d25f95e3d191c5013f25147ae177218b97ace92b83429191abe55eb0c396b", + "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"1a1d25f95e3d191c5013f25147ae177218b97ace92b83429191abe55eb0c396b\",\"sig\":\"f20743fac20bca48ec3d3e5545188fcf392cf719607a52e5ab4a42978d42036c68bafec56f1727484c1c2232c55ec170db5dab795edf776ed56cb2ec1ba09d9e\"}]" + }, + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "quote \" backslash \\ both \\\" solidus / space tilde ~", + "id": "5389620285f316864588a74ab8b06f8d7bf0cf6b3536ad8b0fb5e3bfb8b41bc6", + "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"quote \\\" backslash \\\\ both \\\\\\\" solidus / space tilde ~\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"5389620285f316864588a74ab8b06f8d7bf0cf6b3536ad8b0fb5e3bfb8b41bc6\",\"sig\":\"b57c6506bbc141d819181a6af8c52820cd058ae1c3df78c8772f39d4ec7b56d86fa41521375fe3c8a9ced10dd7996c70a3483a8506a899884d4a8474d7792329\"}]" + }, + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "line separator 
 paragraph separator 
 delete ", + "id": "8cb08d994e6070975ebaa7b1448a76df8f11af1ea39d17ec7e0021fd4936ee17", + "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"line separator 
 paragraph separator 
 delete \",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"8cb08d994e6070975ebaa7b1448a76df8f11af1ea39d17ec7e0021fd4936ee17\",\"sig\":\"76a457faff38f4daaa016a67185d71fa9cac213de3b474c442680d59e9e2b30bfb907cbbf92f7134e435836cd8f94f14b90efa0f1301316e54724b192ec4e9c5\"}]" + }, + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "astral 🎉 𝄞, two bytes é € ߿, three ☕ ࠀ ￿", + "id": "2d68203eac4a759e21079a3f4b4871d31e912ce44f2ad8ba8746d313ea9d7053", + "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"astral 🎉 𝄞, two bytes é € ߿, three ☕ ࠀ ￿\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"2d68203eac4a759e21079a3f4b4871d31e912ce44f2ad8ba8746d313ea9d7053\",\"sig\":\"24ffe69b6129f4e4144f48c441df99fc578a021e73141d7b9452bd98234e0b56a0224399e80e344ab7642cf22c3467c0f1c20463667c7a32e803dc780ae0443c\"}]" + }, + { + "topic": "topic \u0000 \u001f \" \\ 
 
  🎉", + "content": "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}", + "id": "23e556c7184e81b671731fa9f7c7a0d52ffcdf4c7a9c9ebbde4dd6fde2a5d115", + "message": "[\"EVENT\",{\"kind\":20129,\"tags\":[[\"x\",\"topic \\u0000 \\u001f \\\" \\\\ 
 
  🎉\"]],\"created_at\":1759700000,\"content\":\"{\\\"peerId\\\":\\\"abc\\\",\\\"nonce\\\":\\\"12345678\\\"}\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"23e556c7184e81b671731fa9f7c7a0d52ffcdf4c7a9c9ebbde4dd6fde2a5d115\",\"sig\":\"3c9df43a7063d0e2f5cc1d6feec3cd2dad55f1e3c56073cf884ca1aa57c23b312b27d7a970bea57e746d507d3407b381f7c000655c27e8c111803c952030f924\"}]" + }, + { + "topic": "", + "content": "", + "id": "cff4dd0852bd9746a0b233a890ae9e67db1559f3bd0744d74f5fc2ee0ff50e02", + "message": "[\"EVENT\",{\"kind\":20000,\"tags\":[[\"x\",\"\"]],\"created_at\":1759700000,\"content\":\"\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"cff4dd0852bd9746a0b233a890ae9e67db1559f3bd0744d74f5fc2ee0ff50e02\",\"sig\":\"f99498986e5f1779cd7c8762f3719517193528e511f292db4b7a6feefb0ed6601c2f972c262f6f1a58288982688002861828c4e350b693aa4290186fd16daef3\"}]" + } + ] + }, + "signal_texts": [ + { + "signal": { + "peerId": "\u0000\u0001\u001f", + "nonce": "\" \\ 
 
  🎉" + }, + "text": "{\"peerId\":\"\\u0000\\u0001\\u001f\",\"nonce\":\"\\\" \\\\ 
 
  🎉\"}" + }, + { + "signal": { + "peerId": "\b\f\n\r\t\u000b", + "passive": true, + "nonce": "n0nce" + }, + "text": "{\"peerId\":\"\\b\\f\\n\\r\\t\\u000b\",\"passive\":true,\"nonce\":\"n0nce\"}" + }, + { + "signal": { + "peerId": "p", + "offerId": "
", + "offer": "🎉\u0000𝄞 é" + }, + "text": "{\"peerId\":\"p\",\"offerId\":\"
\",\"offer\":\"🎉\\u0000𝄞 é\"}" + }, + { + "signal": { + "peerId": "p", + "offerId": "o", + "candidate": "\u001f  € \"\\", + "passive": true + }, + "text": "{\"peerId\":\"p\",\"offerId\":\"o\",\"candidate\":\"\\u001f  € \\\"\\\\\",\"passive\":true}" + }, + { + "signal": { + "peerId": "q\"\\\n", + "answer": "
\u0000" + }, + "text": "{\"peerId\":\"q\\\"\\\\\\n\",\"answer\":\"
\\u0000\"}" + }, + { + "signal": { + "peerId": "a", + "answer": "sealed ", + "offerId": "o" + }, + "text": "{\"peerId\":\"a\",\"answer\":\"sealed \",\"offerId\":\"o\"}" + }, + { + "signal": { + "peerId": "a", + "candidate": "

", + "offerId": "o", + "passive": true + }, + "text": "{\"peerId\":\"a\",\"candidate\":\"

\",\"offerId\":\"o\",\"passive\":true}" + } + ], + "duplicate_keys": { + "signals": [ + { + "text": "{\"peerId\":\"first\",\"peerId\":\"last\",\"nonce\":\"n\"}", + "read": { + "peer_id": "last", + "passive": false + } + }, + { + "text": "{\"peerId\":\"plain\",\"peer\\u0049d\":\"escaped\"}", + "read": { + "peer_id": "escaped", + "passive": false + } + }, + { + "text": "{\"peerId\":\"p\",\"offerId\":\"first\",\"offer\":\"first\",\"offerId\":\"last\",\"offer\":\"last\"}", + "read": { + "peer_id": "p", + "offer": "last", + "offer_id": "last", + "passive": false + } + }, + { + "text": "{\"peerId\":\"p\",\"offer\":\"\",\"offer\":\"sealed\"}", + "read": { + "peer_id": "p", + "offer": "sealed", + "passive": false + } + }, + { + "text": "{\"peerId\":\"p\",\"offer\":\"sealed\",\"offer\":\"\"}", + "read": null + }, + { + "text": "{\"peerId\":\"p\",\"candidate\":1,\"candidate\":\"sealed\"}", + "read": { + "peer_id": "p", + "candidate": "sealed", + "passive": false + } + }, + { + "text": "{\"peerId\":\"p\",\"answer\":\"sealed\",\"answer\":null}", + "read": null + }, + { + "text": "{\"peerId\":\"p\",\"passive\":true,\"passive\":false}", + "read": { + "peer_id": "p", + "passive": false + } + }, + { + "text": "{\"peerId\":\"p\",\"passive\":false,\"passive\":true}", + "read": { + "peer_id": "p", + "passive": true + } + }, + { + "text": "{\"peerId\":\"p\",\"peerId\":\"\"}", + "read": null + }, + { + "text": "{\"peerId\":\"\",\"answer\":\"sealed\",\"peerId\":\"p\"}", + "read": { + "peer_id": "p", + "answer": "sealed", + "passive": false + } + }, + { + "text": "{\"peerId\":\"p\",\"peer\":\"x\",\"offer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"p\",\"peer\":null,\"nonce\":\"n\"}", + "read": null + } + ], + "root_topic": "731p275e6u4l455l3849481dl46536q3g1r6h5y", + "events": [ + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"content-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"content\":\"{\\\"peerId\\\":\\\"content-last\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "content-last" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"escaped-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"con\\u0074ent\":\"{\\\"peerId\\\":\\\"escaped-last\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "escaped-last" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"another-topic\"]],\"content\":\"{\\\"peerId\\\":\\\"root-tags-last\\\",\\\"answer\\\":\\\"x\\\"}\",\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]]}]", + "acted": "root-tags-last" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"root-tags-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"tags\":[[\"x\",\"another-topic\"]]}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":7,\"content\":\"{\\\"peerId\\\":\\\"text-content-last\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "text-content-last" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"text-content-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"content\":7}]", + "acted": null + } + ] + }, + "answerer": { + "self_id": "5JuBmYeQ3ItAlXdP1Hs8", + "app_id": "my-app", + "room_id": "room-1", + "answer_sdp": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n", + "candidate": "{\"candidate\":\"candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\"}", + "sealed": [ + { + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=offer\r\n", + "text": "7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cYdiY235agss4Yz6zXoOPHcepm9bcphyewQqvfpvvs2gwPQJETj4gYc719bGYIKY=" + }, + { + "plaintext": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n", + "text": "7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cY9ie235agss4Yz6zXoOPHcepm9bcphyezwK6bIyQtMvVseJhAyE4HRH0kfRvD/5a" + }, + { + "plaintext": "{\"candidate\":\"candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\"}", + "text": "7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$UNhTroc6OtcdJJ2IwRV3w+wMPnrjGNGbHMmolZK13E+Rn177Kd/Si/PNl4WOZYZxegGCVXXhJjfEgqGQo8VwP4iA3AS52+5RcDzVW8PyGn+zNeJwpRALn6lQTPLPLn8oYaes+TjSqjTGct1fs70+l7hPk8xZdRG0HBGROwxx2cUwNhUmqm1ywDYfDwM=" + } + ], + "cases": [ + { + "offer": "{\"peerId\":\"zzzzzzzzzzzzzzzzzzz1\",\"offerId\":\"o\\\"\\\\ 
 é\",\"offer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cYdiY235agss4Yz6zXoOPHcepm9bcphyewQqvfpvvs2gwPQJETj4gYc719bGYIKY=\"}", + "published": [ + { + "topic": "u1l2v1r6s2h4j64g721v372v194qs5g3w3b2y", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"answer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cY9ie235agss4Yz6zXoOPHcepm9bcphyezwK6bIyQtMvVseJhAyE4HRH0kfRvD/5a\",\"offerId\":\"o\\\"\\\\ 
 é\"}" + }, + { + "topic": "u1l2v1r6s2h4j64g721v372v194qs5g3w3b2y", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"candidate\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$UNhTroc6OtcdJJ2IwRV3w+wMPnrjGNGbHMmolZK13E+Rn177Kd/Si/PNl4WOZYZxegGCVXXhJjfEgqGQo8VwP4iA3AS52+5RcDzVW8PyGn+zNeJwpRALn6lQTPLPLn8oYaes+TjSqjTGct1fs70+l7hPk8xZdRG0HBGROwxx2cUwNhUmqm1ywDYfDwM=\",\"offerId\":\"o\\\"\\\\ 
 é\"}" + } + ] + }, + { + "offer": "{\"peerId\":\"zzzzzzzzzzzzzzzzzzz2\",\"offer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cYdiY235agss4Yz6zXoOPHcepm9bcphyewQqvfpvvs2gwPQJETj4gYc719bGYIKY=\"}", + "published": [ + { + "topic": "18705o161g2q2q714y46684f4710141d4x2y3n22", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"answer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cY9ie235agss4Yz6zXoOPHcepm9bcphyezwK6bIyQtMvVseJhAyE4HRH0kfRvD/5a\"}" + }, + { + "topic": "18705o161g2q2q714y46684f4710141d4x2y3n22", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"candidate\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$UNhTroc6OtcdJJ2IwRV3w+wMPnrjGNGbHMmolZK13E+Rn177Kd/Si/PNl4WOZYZxegGCVXXhJjfEgqGQo8VwP4iA3AS52+5RcDzVW8PyGn+zNeJwpRALn6lQTPLPLn8oYaes+TjSqjTGct1fs70+l7hPk8xZdRG0HBGROwxx2cUwNhUmqm1ywDYfDwM=\"}" + } + ] + } + ] + }, + "payload_texts": [ + { + "text": "{\"b\":1,\"a\":2,\"10\":3,\"2\":4,\"-1\":5,\"01\":6,\"1.5\":7,\"4294967294\":8,\"4294967295\":9,\"0\":10}", + "written": "{\"0\":10,\"2\":4,\"10\":3,\"4294967294\":8,\"b\":1,\"a\":2,\"-1\":5,\"01\":6,\"1.5\":7,\"4294967295\":9}" + }, + { + "text": "{\"z\":{\"y\":[1,{\"3\":true,\"x\":null,\"1\":false}],\"0\":\"\"},\"a\":[]}", + "written": "{\"z\":{\"0\":\"\",\"y\":[1,{\"1\":false,\"3\":true,\"x\":null}]},\"a\":[]}" + }, + { + "text": "[0,-0,1,-1,100,1E3,1e+2,12e-1,0.1,1.5,123.45,0.30000000000000004,1e20,1e21,123e19,0.000001,1e-6,1e-7,2.5e-8]", + "written": "[0,0,1,-1,100,1000,100,1.2,0.1,1.5,123.45,0.30000000000000004,100000000000000000000,1e+21,1.23e+21,0.000001,0.000001,1e-7,2.5e-8]" + }, + { + "text": "[1.5e300,-1.5e-300,5e-324,1.7976931348623157e308,9007199254740991,-9007199254740991,4294967296]", + "written": "[1.5e+300,-1.5e-300,5e-324,1.7976931348623157e+308,9007199254740991,-9007199254740991,4294967296]" + }, + { + "text": "[\"\\u2028\\u0000\\u007f é 🎉\\\"\\\\/\",true,false,null,{}]", + "written": "[\"
\\u0000 é 🎉\\\"\\\\/\",true,false,null,{}]" + } + ], + "payload_beyond_doubles": [ + { + "text": "[9007199254740993,-9223372036854775808,0.1000000000000000055511151231257827,1e400]", + "written": "[9007199254740992,-9223372036854776000,0.1,null]" + } + ] } diff --git a/test/memory_backend_test.cpp b/test/memory_backend_test.cpp index f76997a..c2ba605 100644 --- a/test/memory_backend_test.cpp +++ b/test/memory_backend_test.cpp @@ -10,11 +10,14 @@ #include "support/memory_backend.hpp" -#include +#include + #include +#include #include #include +#include #include #include #include @@ -24,7 +27,7 @@ #include "require.hpp" -namespace asio = boost::asio; +namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; using trystero::test::memory_network; using namespace std::chrono_literals; @@ -250,7 +253,7 @@ void a_frame_is_delivered_once_its_last_byte_drained() { // Each poll_one runs one drain step, the only handler queued, which posts the next. io.poll_one(); BOOST_TEST_EQ(net.buffered(p.offerer_id), frame.size() - 1024); - for (int step = 1; step < 15; ++step) { + for (std::size_t step = 1; step < 15; ++step) { io.poll_one(); } BOOST_TEST_EQ(net.buffered(p.offerer_id), 1024U); @@ -350,13 +353,13 @@ void a_release_after_the_sender_went_drops_its_frames() { } // The virtual clock: a timer fires only when the test advances the clock to it, in order, and -// now_ms is the clock's. +// steady_now and unix_now are the clock's. void the_virtual_clock_moves_only_when_advanced() { asio::io_context io; memory_network net{io}; net.virtual_clock = true; auto* m = std::pmr::get_default_resource(); - std::vector fired; + std::vector fired; const auto t10 = net.make_timer(m); const auto t5 = net.make_timer(m); const auto cancelled = net.make_timer(m); @@ -366,20 +369,22 @@ void the_virtual_clock_moves_only_when_advanced() { cancelled->cancel(); io.poll(); BOOST_TEST(fired.empty()); - BOOST_TEST_EQ(net.now_ms(), 0.0); + BOOST_TEST(net.steady_now().time_since_epoch() == 0s); + BOOST_TEST(net.unix_now() == std::chrono::sys_seconds(1'759'700'000s)); net.advance(7s); - BOOST_TEST(fired == std::vector{5}); - BOOST_TEST_EQ(net.now_ms(), 7000.0); + BOOST_TEST(fired == std::vector{5}); + BOOST_TEST(net.steady_now().time_since_epoch() == 7s); + BOOST_TEST(net.unix_now() == std::chrono::sys_seconds(1'759'700'007s)); net.advance(3s); - BOOST_TEST((fired == std::vector{5, 10})); - BOOST_TEST_EQ(net.now_ms(), 10000.0); + BOOST_TEST((fired == std::vector{5, 10})); + BOOST_TEST(net.steady_now().time_since_epoch() == 10s); // Two timers due at the same instant both fire, in the order they were started, not made. const auto made_first = net.make_timer(m); const auto made_second = net.make_timer(m); made_second->start(2s, [&fired] { fired.push_back(21); }); made_first->start(2s, [&fired] { fired.push_back(22); }); net.advance(2s); - BOOST_TEST((fired == std::vector{5, 10, 21, 22})); + BOOST_TEST((fired == std::vector{5, 10, 21, 22})); } // The clock moves from the first advance, before any timer is made, and a timer made then starts @@ -389,7 +394,7 @@ void the_virtual_clock_moves_before_any_timer() { memory_network net{io}; net.virtual_clock = true; BOOST_TEST(net.advance(5s)); - BOOST_TEST_EQ(net.now_ms(), 5000.0); + BOOST_TEST(net.steady_now().time_since_epoch() == 5s); const auto t = net.make_timer(std::pmr::get_default_resource()); bool fired = false; t->start(1s, [&fired] { fired = true; }); @@ -397,7 +402,7 @@ void the_virtual_clock_moves_before_any_timer() { BOOST_TEST(!fired); net.advance(1ms); BOOST_TEST(fired); - BOOST_TEST_EQ(net.now_ms(), 6000.0); + BOOST_TEST(net.steady_now().time_since_epoch() == 6s); } /** Counts the bytes it has out, from the default resource. */ @@ -477,7 +482,7 @@ void a_run_of_max_steps_timers_reaches_the_end() { t3->start(3s, [&fired] { ++fired; }); BOOST_TEST(net.advance(5s)); BOOST_TEST_EQ(fired, 3U); - BOOST_TEST_EQ(net.now_ms(), 5000.0); + BOOST_TEST(net.steady_now().time_since_epoch() == 5s); } void a_buffering_channel_drains_and_says_so() { @@ -543,5 +548,6 @@ int main() { a_timer_rearmed_without_delay_stops_the_clock(); a_run_of_max_steps_timers_reaches_the_end(); ready_work_is_bounded(); - return boost::report_errors(); + // Under Asyncify, a main that suspended loses what it returns: the status goes first. + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/native_peer_connection_test.cpp b/test/native_peer_connection_test.cpp deleted file mode 100644 index 7f203bc..0000000 --- a/test/native_peer_connection_test.cpp +++ /dev/null @@ -1,534 +0,0 @@ -// 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) - -// Tests the native peer connection, libdatachannel's, between two connections in one process, -// wired to each other directly: what the signaling would carry over the relays is handed across -// here. Each connection is bound to 127.0.0.1, so that its one host candidate is the loopback's and -// no other interface is needed. The backend makes at most -// `backend_config::max_peer_connections_per_minute` of them in a minute, whatever became of them. - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "require.hpp" - -namespace asio = boost::asio; -namespace trystero = webcpp::trystero; -namespace backend = trystero::backend; -namespace protocol = trystero::protocol; -using namespace std::chrono_literals; - -using webcpp::test::require; - -namespace { - -constexpr const char* loopback = "127.0.0.1"; - -bool run_until(asio::io_context& io, const std::function& done, - std::chrono::milliseconds limit = 10s) { - const auto end = std::chrono::steady_clock::now() + limit; - while (!done() && std::chrono::steady_clock::now() < end) { - io.run_for(10ms); // lint-run: libdatachannel's threads post the connections' events to it - if (io.stopped()) { - io.restart(); - } - } - return done(); -} - -/** Two connected peers: the offerer's channel and the answerer's, with what each received. */ -struct pair { - asio::io_context io; - std::thread::id io_thread = std::this_thread::get_id(); - std::shared_ptr offerer = trystero::native::peer_connection::create( - io.get_executor(), {}, loopback, std::pmr::get_default_resource()); - std::shared_ptr answerer = trystero::native::peer_connection::create( - io.get_executor(), {}, loopback, std::pmr::get_default_resource()); - std::shared_ptr offer_end; - std::shared_ptr answer_end; - std::vector at_offerer, at_answerer; - bool offer_open = false, answer_open = false, off_thread = false; - std::vector answerer_states; - int answer_closes = 0; - - void on_io_thread() { - if (std::this_thread::get_id() != io_thread) { - off_thread = true; - } - } - - void connect(std::pmr::memory_resource* channel_memory = nullptr, - const std::optional& channel_executor = {}) { - offerer->set_handlers({ - .ice_candidate = - [this](std::string_view c) { - on_io_thread(); - answerer->add_ice_candidate(c, [](backend::error_code) {}); - }, - .data_channel = {}, - .state = [this](backend::connection_state) { on_io_thread(); }, - }); - answerer->set_handlers({ - .ice_candidate = - [this](std::string_view c) { - on_io_thread(); - offerer->add_ice_candidate(c, [](backend::error_code) {}); - }, - .data_channel = - [this](std::shared_ptr channel) { - on_io_thread(); - answer_end = std::move(channel); - watch(answer_end, answer_open, at_answerer, &answer_closes); - }, - .state = - [this](backend::connection_state s) { - on_io_thread(); - answerer_states.push_back(s); - }, - }); - 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) { - on_io_thread(); - require(BOOST_TEST(!ec)); - BOOST_TEST_EQ(type, "offer"); - answerer->set_remote_description(type, sdp, [this](backend::error_code ec) { - require(BOOST_TEST(!ec)); - BOOST_TEST(answerer->has_remote_description()); - answerer->set_local_description( - [this](backend::error_code ec, std::string_view type, std::string_view sdp) { - require(BOOST_TEST(!ec)); - BOOST_TEST_EQ(type, "answer"); - offerer->set_remote_description( - type, sdp, [](backend::error_code ec) { BOOST_TEST(!ec); }); - }); - }); - }); - } - - void watch(const std::shared_ptr& channel, bool& open, - std::vector& received, int* closes) { - channel->set_handlers({ - .open = - [this, &open] { - on_io_thread(); - open = true; - }, - .message = - [this, &received](backend::bytes b) { - on_io_thread(); - received.push_back(std::move(b)); - }, - .close = - [this, closes] { - on_io_thread(); - if (closes != nullptr) { - ++*closes; - } - }, - .buffered_amount_low = {}, - }); - } -}; - -// 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(); - if (!BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))) { - return; - } - BOOST_TEST(p.offer_end->is_open()); - BOOST_TEST(p.answer_end->is_open()); - const backend::bytes hello{1, 2, 3, 250}; - p.offer_end->send(hello); - // One byte more than any room frame is dropped before it is read; the largest one arrives. - p.answer_end->send(backend::bytes(protocol::max_room_frame_bytes + 1, 6)); - p.answer_end->send(backend::bytes(protocol::max_room_frame_bytes, 7)); - if (!BOOST_TEST(run_until( - p.io, [&] { return p.at_answerer.size() == 1 && p.at_offerer.size() == 1; }))) { - return; - } - BOOST_TEST_ALL_EQ(p.at_answerer.front().begin(), p.at_answerer.front().end(), hello.begin(), - hello.end()); - BOOST_TEST_EQ(p.at_offerer.size(), 1U); - BOOST_TEST_EQ(p.at_offerer.front().size(), protocol::max_room_frame_bytes); - BOOST_TEST_LE(p.offer_end->buffered_amount(), backend::data_channel::low_threshold); - // Every handler ran on the executor, never on libdatachannel's threads. - BOOST_TEST(!p.off_thread); -} - -void closing_one_end_is_seen_by_the_other() { - pair p; - p.connect(); - if (!BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))) { - return; - } - p.offerer->close(); - BOOST_TEST(run_until(p.io, [&] { return p.answer_closes == 1; })); - 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, - std::pmr::get_default_resource()); - std::optional result; - pc->add_ice_candidate("not json", [&](backend::error_code ec) { result = ec; }); - if (!BOOST_TEST(run_until(io, [&] { return result.has_value(); }))) { - return; - } - BOOST_TEST(*result == trystero::error::backend_failure); -} - -void the_backend_makes_at_most_its_budget_in_a_minute() { - asio::io_context io; - trystero::native::backend factory( - io.get_executor(), - {.bind_address = std::pmr::string(loopback), .max_peer_connections_per_minute = 3}); - std::vector> made; - for (int i = 0; i < 3; ++i) { - made.push_back(factory.make_peer_connection({}, std::pmr::get_default_resource())); - BOOST_TEST(made.back() != nullptr); - } - BOOST_TEST(factory.make_peer_connection({}, std::pmr::get_default_resource()) == nullptr); - // Closed and dropped, they still count: the budget counts what was made. - for (const auto& pc : made) { - pc->close(); - } - made.clear(); - BOOST_TEST(factory.make_peer_connection({}, std::pmr::get_default_resource()) == nullptr); -} - -} // namespace - -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/native_sealer_test.cpp b/test/native_sealer_test.cpp deleted file mode 100644 index 0334070..0000000 --- a/test/native_sealer_test.cpp +++ /dev/null @@ -1,117 +0,0 @@ -// 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) - -// Tests the native sealer, OpenSSL's AES-GCM, against text Trystero JS sealed with WebCrypto, -// which the original's oracle wrote into fixtures/expected/expected.json. The fixture's path is the -// test's one argument. - -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "require.hpp" - -namespace json = boost::json; -namespace tp = webcpp::trystero::protocol; -namespace trystero = webcpp::trystero; - -using webcpp::test::require; - -namespace { - -json::value load(const char* path) { - const std::ifstream file(path); - std::stringstream text; - text << file.rdbuf(); - return json::parse(text.str()); -} - -struct outcome { - boost::system::error_code ec; - std::string text; -}; - -/** Runs one sealer operation to its completion, which the sealer posts to the executor. */ -template -outcome run(boost::asio::io_context& io, Operation operation) { - std::optional result; - operation([&](boost::system::error_code ec, std::string_view text) { - result = outcome{.ec = ec, .text = std::string(text)}; - }); - io.restart(); - io.poll(); // the sealer works synchronously: its completion is already posted - require(BOOST_TEST(result.has_value())); - return *result; -} - -void opens_what_trystero_js_sealed(const json::object& sealed) { - boost::asio::io_context io; - trystero::native::sealer sealer(io.get_executor(), tp::seal_key("secret", "my-app", "room-1"), - std::pmr::get_default_resource()); - const auto opened = - run(io, [&](auto done) { sealer.open(sealed.at("text").as_string(), done); }); - BOOST_TEST(!opened.ec); - BOOST_TEST_EQ(opened.text, std::string_view(sealed.at("plaintext").as_string())); -} - -void seals_in_trystero_form_and_opens_it_back() { - boost::asio::io_context io; - trystero::native::sealer sealer(io.get_executor(), tp::seal_key("", "app", "room"), - std::pmr::get_default_resource()); - const std::string plaintext = - R"({"candidate":"candidate:1 1 udp 2122260223 192.0.2.1 54321 typ host"})"; - const auto sealed = run(io, [&](auto done) { sealer.seal(plaintext, done); }); - BOOST_TEST(!sealed.ec); - const auto parts = tp::parse_sealed(sealed.text); - if (!BOOST_TEST(parts.has_value())) { - return; - } - BOOST_TEST_EQ(parts->iv.size(), tp::seal_iv_size); - // The GCM tag follows, as WebCrypto writes it. - BOOST_TEST_EQ(parts->ciphertext.size(), plaintext.size() + 16); - const auto opened = run(io, [&](auto done) { sealer.open(sealed.text, done); }); - BOOST_TEST(!opened.ec); - BOOST_TEST_EQ(opened.text, plaintext); -} - -void another_key_is_a_wrong_password(const json::object& sealed) { - boost::asio::io_context io; - trystero::native::sealer sealer(io.get_executor(), tp::seal_key("secret", "my-app", "room-1"), - std::pmr::get_default_resource()); - trystero::native::sealer intruder(io.get_executor(), tp::seal_key("guess", "my-app", "room-1"), - std::pmr::get_default_resource()); - const auto opened = - run(io, [&](auto done) { intruder.open(sealed.at("text").as_string(), done); }); - BOOST_TEST(opened.ec == trystero::error::wrong_password); - const auto garbage = run(io, [&](auto done) { sealer.open("not sealed text", done); }); - BOOST_TEST(garbage.ec == trystero::error::wrong_password); -} - -} // namespace - -int main(int argc, char* argv[]) { - if (!BOOST_TEST_EQ(argc, 2)) { - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << "usage: native_sealer_test \n"; - return boost::report_errors(); - } - const auto loaded = load(argv[1]); - const auto& sealed = loaded.at("sealed").as_object(); - opens_what_trystero_js_sealed(sealed); - seals_in_trystero_form_and_opens_it_back(); - another_key_is_a_wrong_password(sealed); - return boost::report_errors(); -} diff --git a/test/native_timer_test.cpp b/test/native_timer_test.cpp deleted file mode 100644 index 1980e26..0000000 --- a/test/native_timer_test.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// 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) - -// Tests the native timer, Asio's steady_timer: a wait that is cancelled, restarted or destroyed -// never calls its handler, even when its expiry was already queued, which Asio cannot take back. - -#include - -#include -#include - -#include -#include -#include - -namespace asio = boost::asio; -namespace trystero = webcpp::trystero; -using namespace std::chrono_literals; - -namespace { - -std::shared_ptr make_timer(asio::io_context& io) { - return std::allocate_shared( - std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), io.get_executor(), - std::pmr::get_default_resource()); -} - -/** - * Starts `first`, then `second`, both at 0 ms, so that both have expired when the io_context first - * looks: Asio then queues both completions as successes in one pass, `first`'s ahead, and what - * `first` does to `second` comes after `second`'s expiry was queued. - */ -template -void both_expired(asio::io_context& io, trystero::native::timer& first, - trystero::native::timer& second, int& second_fired, Then then) { - first.start(0ms, then); - second.start(0ms, [&second_fired] { ++second_fired; }); - io.run_for(100ms); // lint-run: the timers' expiries are the events under test - io.restart(); -} - -void a_cancelled_wait_never_fires() { - asio::io_context io; - const auto first = make_timer(io); - const auto second = make_timer(io); - int fired = 0; - both_expired(io, *first, *second, fired, [&] { second->cancel(); }); - BOOST_TEST_EQ(fired, 0); -} - -void a_destroyed_timer_never_fires() { - asio::io_context io; - const auto first = make_timer(io); - auto second = make_timer(io); - int fired = 0; - both_expired(io, *first, *second, fired, [&] { second.reset(); }); - BOOST_TEST_EQ(fired, 0); -} - -void a_restarted_timer_fires_only_its_new_wait() { - asio::io_context io; - const auto first = make_timer(io); - const auto second = make_timer(io); - int fired = 0; - int restarted = 0; - both_expired(io, *first, *second, fired, [&] { second->start(10ms, [&] { ++restarted; }); }); - io.run_for(100ms); // lint-run: the restarted wait expires - BOOST_TEST_EQ(fired, 0); - BOOST_TEST_EQ(restarted, 1); -} - -void an_uncancelled_wait_fires_once() { - asio::io_context io; - const auto timer = make_timer(io); - int fired = 0; - timer->start(1ms, [&] { ++fired; }); - io.run_for(100ms); // lint-run: the wait expires - BOOST_TEST_EQ(fired, 1); -} - -} // namespace - -int main() { - an_uncancelled_wait_fires_once(); - a_cancelled_wait_never_fires(); - a_destroyed_timer_never_fires(); - a_restarted_timer_fires_only_its_new_wait(); - return boost::report_errors(); -} diff --git a/test/native_websocket_test.cpp b/test/native_websocket_test.cpp deleted file mode 100644 index d8cc7b4..0000000 --- a/test/native_websocket_test.cpp +++ /dev/null @@ -1,496 +0,0 @@ -// 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) - -// Tests the native WebSocket client, Boost.Beast's, against an echo server in the same process, -// on 127.0.0.1. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace asio = boost::asio; -namespace beast = boost::beast; -namespace trystero = webcpp::trystero; -using asio::ip::tcp; -using namespace std::chrono_literals; - -namespace { - -/** - * Accepts WebSocket connections and sends every text message back. - * - * Tip: each coroutine ends on its first error, read from a tuple, so the server needs no - * exceptions, as the client it tests does not. - */ -struct echo_server { - explicit echo_server(asio::io_context& io) - : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}) { - asio::co_spawn(io, accept(), asio::detached); - } - - [[nodiscard]] std::string url() const { - return "ws://127.0.0.1:" + std::to_string(acceptor.local_endpoint().port()) + "/relay"; - } - - asio::awaitable accept() { - for (;;) { - auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); - if (ec) { - co_return; - } - asio::co_spawn(acceptor.get_executor(), echo(std::move(socket)), asio::detached); - } - } - - static asio::awaitable echo(tcp::socket socket) { - beast::websocket::stream ws(std::move(socket)); - auto [accepted] = co_await ws.async_accept(asio::as_tuple(asio::use_awaitable)); - if (accepted) { - co_return; - } - beast::flat_buffer buffer; - for (;;) { - auto [read, read_size] = - co_await ws.async_read(buffer, asio::as_tuple(asio::use_awaitable)); - if (read) { - co_return; - } - ws.text(true); - auto [written, written_size] = - co_await ws.async_write(buffer.data(), asio::as_tuple(asio::use_awaitable)); - if (written) { - co_return; - } - buffer.consume(buffer.size()); - } - } - - tcp::acceptor acceptor; -}; - -/** What a hostile relay does once it reads a client's first message. */ -enum class misbehaviour { - /** Sends a text one byte longer than a room reads, then goes on reading. */ - too_long_text, - /** Drops the TCP connection with a reset. */ - reset, -}; - -/** - * Accepts WebSocket connections, reads every message, and misbehaves at the first: what any relay - * of a room's list can do, and what a network drop does by chance. - */ -struct hostile_server { - hostile_server(asio::io_context& io, misbehaviour m) - : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}), what(m) { - asio::co_spawn(io, accept(), asio::detached); - } - - [[nodiscard]] std::string url() const { - return "ws://127.0.0.1:" + std::to_string(acceptor.local_endpoint().port()) + "/relay"; - } - - asio::awaitable accept() { - for (;;) { - auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); - if (ec) { - co_return; - } - asio::co_spawn(acceptor.get_executor(), serve(std::move(socket), what), asio::detached); - } - } - - static asio::awaitable serve(tcp::socket socket, misbehaviour what) { - const auto ws = std::make_shared>(std::move(socket)); - auto [accepted] = co_await ws->async_accept(asio::as_tuple(asio::use_awaitable)); - if (accepted) { - co_return; - } - beast::flat_buffer buffer; - for (bool first = true;; first = false) { - auto [read, read_size] = - co_await ws->async_read(buffer, asio::as_tuple(asio::use_awaitable)); - if (read) { - co_return; - } - buffer.consume(buffer.size()); - if (!first) { - continue; - } - if (what == misbehaviour::reset) { - // A linger of 0 makes the close a reset. - boost::system::error_code ec; - const bool reset = - !ws->next_layer().set_option(asio::socket_base::linger(true, 0), ec) && - !ws->next_layer().close(ec); - BOOST_TEST(reset); - co_return; - } - // Written beside the reads, so that the client's writes keep draining meanwhile. - asio::co_spawn( - ws->get_executor(), - [ws]() -> asio::awaitable { - const std::string text(trystero::protocol::max_relay_message_bytes + 1, 'x'); - ws->text(true); - co_await ws->async_write(asio::buffer(text), - asio::as_tuple(asio::use_awaitable)); - }, - asio::detached); - } - } - - tcp::acceptor acceptor; - misbehaviour what; -}; - -/** - * Accepts WebSocket connections, answers the handshake, and never reads again, keeping each - * connection open: a relay that stalls, or a path that died without a reset. - */ -struct stalled_server { - explicit stalled_server(asio::io_context& io) - : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}) { - asio::co_spawn(io, accept(), asio::detached); - } - - [[nodiscard]] std::string url() const { - return "ws://127.0.0.1:" + std::to_string(acceptor.local_endpoint().port()) + "/relay"; - } - - asio::awaitable accept() { - for (;;) { - auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); - if (ec) { - co_return; - } - auto ws = std::make_shared>(std::move(socket)); - auto [accepted] = co_await ws->async_accept(asio::as_tuple(asio::use_awaitable)); - if (!accepted) { - held.push_back(std::move(ws)); - } - } - } - - tcp::acceptor acceptor; - std::vector>> held; -}; - -bool run_until(asio::io_context& io, const std::function& done, - std::chrono::milliseconds limit = 5s) { - const auto end = std::chrono::steady_clock::now() + limit; - while (!done() && std::chrono::steady_clock::now() < end) { - io.run_for(10ms); // lint-run: the client and the echo server do loopback network I/O - if (io.stopped()) { - io.restart(); - } - } - return done(); -} - -void urls_name_a_scheme_host_port_and_path() { - const auto secure = trystero::native::detail::parse_url("wss://relay.example.org"); - if (!BOOST_TEST(secure.has_value())) { - return; - } - BOOST_TEST(secure->secure); - BOOST_TEST_EQ(secure->host, "relay.example.org"); - BOOST_TEST_EQ(secure->port, "443"); - BOOST_TEST_EQ(secure->target, "/"); - const auto plain = trystero::native::detail::parse_url("ws://127.0.0.1:7447/nostr?x=1"); - if (!BOOST_TEST(plain.has_value())) { - return; - } - BOOST_TEST(!plain->secure); - BOOST_TEST_EQ(plain->host, "127.0.0.1"); - BOOST_TEST_EQ(plain->port, "7447"); - BOOST_TEST_EQ(plain->target, "/nostr?x=1"); - BOOST_TEST(!trystero::native::detail::parse_url("https://example.org").has_value()); - BOOST_TEST(!trystero::native::detail::parse_url("wss://").has_value()); -} - -void opens_sends_in_order_receives_and_closes_once() { - asio::io_context io; - const echo_server server(io); - asio::ssl::context tls(asio::ssl::context::tls_client); - bool opened = false; - int closes = 0; - std::vector received; - const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), - { - .open = [&] { opened = true; }, - .message = [&](std::string_view text) { received.emplace_back(text); }, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource()); - if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { - return; - } - for (const char* text : {"one", "two", R"(["EVENT",{"content":"three"}])"}) { - socket->send(text); - } - if (!BOOST_TEST(run_until(io, [&] { return received.size() == 3; }))) { - return; - } - const std::vector sent{"one", "two", R"(["EVENT",{"content":"three"}])"}; - BOOST_TEST_ALL_EQ(received.begin(), received.end(), sent.begin(), sent.end()); - socket->close(); - BOOST_TEST(run_until(io, [&] { return closes == 1; })); - socket->close(); - run_until(io, [] { return false; }, 100ms); - BOOST_TEST_EQ(closes, 1); -} - -// A message longer than any relay's (protocol::max_relay_message_bytes) is never handed over: the -// socket closes, as the browser's does, and the room's strategy reconnects. -void a_message_longer_than_a_relay_sends_closes_the_socket() { - asio::io_context io; - const echo_server server(io); - asio::ssl::context tls(asio::ssl::context::tls_client); - bool opened = false; - int closes = 0; - std::vector received; - const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), - { - .open = [&] { opened = true; }, - .message = [&](std::string_view text) { received.push_back(text.size()); }, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource()); - if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { - return; - } - socket->send(std::string(trystero::protocol::max_relay_message_bytes, 'x')); - if (!BOOST_TEST(run_until(io, [&] { return received.size() == 1; }))) { - return; - } - socket->send(std::string(trystero::protocol::max_relay_message_bytes + 1, 'x')); - BOOST_TEST(run_until(io, [&] { return closes == 1; })); - BOOST_TEST_EQ(received.size(), 1U); - BOOST_TEST_EQ(received.at(0), trystero::protocol::max_relay_message_bytes); -} - -void an_unreachable_relay_closes_without_opening() { - asio::io_context io; - tcp::acceptor taken(io, {asio::ip::make_address("127.0.0.1"), 0}); - const auto port = taken.local_endpoint().port(); - taken.close(); // nothing listens there now - asio::ssl::context tls(asio::ssl::context::tls_client); - bool opened = false; - int closes = 0; - const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, "ws://127.0.0.1:" + std::to_string(port), - { - .open = [&] { opened = true; }, - .message = {}, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource()); - BOOST_TEST(run_until(io, [&] { return closes == 1; })); - BOOST_TEST(!opened); -} - -void a_dropped_socket_reports_nothing() { - asio::io_context io; - const echo_server server(io); - asio::ssl::context tls(asio::ssl::context::tls_client); - int events = 0; - { - const auto socket = - trystero::native::connect_websocket(io.get_executor(), tls, server.url(), - { - .open = [&] { ++events; }, - .message = [&](std::string_view) { ++events; }, - .close = [&] { ++events; }, - }, - std::pmr::get_default_resource()); - } - run_until(io, [] { return false; }, 200ms); - BOOST_TEST_EQ(events, 0); -} - -void closing_right_after_a_send_lets_the_write_finish_first() { - asio::io_context io; - const echo_server server(io); - asio::ssl::context tls(asio::ssl::context::tls_client); - bool opened = false; - int closes = 0; - const auto socket = trystero::native::connect_websocket(io.get_executor(), tls, server.url(), - { - .open = [&] { opened = true; }, - .message = {}, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource()); - if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { - return; - } - // What the Nostr strategy sends before it closes a relay. - socket->send(R"(["CLOSE","subscription"])"); - socket->close(); - BOOST_TEST(run_until(io, [&] { return closes == 1; })); -} - -// A connection that ends while a write is in flight: the relay sends a text too long to read, or -// resets the connection, while the client has many texts queued. The socket reports one close, and -// the write that was in flight finishes after it on a text it still owns. Each misbehaviour is met -// several times, since which of the read and the write completes first is the network's choice. -// The test is built with the standard library's own checks (test/Jamfile), so that a write -// completion that touches a cleared queue fails at once. -void a_connection_that_ends_during_a_write_closes_once(misbehaviour what) { - constexpr int connections = 10; - constexpr int texts = 200; - asio::io_context io; - const hostile_server server(io, what); - asio::ssl::context tls(asio::ssl::context::tls_client); - const std::string text(std::size_t{64} * 1024, 't'); - for (int i = 0; i < connections; ++i) { - bool opened = false; - int closes = 0; - std::shared_ptr socket; - socket = trystero::native::connect_websocket(io.get_executor(), tls, server.url(), - { - .open = - [&] { - opened = true; - for (int t = 0; t < texts; ++t) { - socket->send(text); - } - }, - .message = {}, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource()); - if (!BOOST_TEST(run_until(io, [&] { return closes == 1; }))) { - return; - } - BOOST_TEST(opened); - socket.reset(); // as the room's strategy replaces a relay's socket when it reconnects - run_until(io, [] { return false; }, 50ms); - BOOST_TEST_EQ(closes, 1); - } -} - -// A relay that stops reading: the texts a room sends it pile up in the socket's queue. At -// websocket_limits::max_queued_bytes the socket drops the connection, reports one close, and holds -// no more, so that the room reconnects with its backoff. -void a_relay_that_stops_reading_is_dropped_at_the_queue_bound() { - asio::io_context io; - const stalled_server server(io); - asio::ssl::context tls(asio::ssl::context::tls_client); - bool opened = false; - int closes = 0; - const auto socket = trystero::native::connect_websocket(io.get_executor(), tls, server.url(), - { - .open = [&] { opened = true; }, - .message = {}, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource()); - if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { - return; - } - const std::string text(std::size_t{64} * 1024, 't'); - for (int i = 0; i < 2000 && closes == 0; ++i) { - socket->send(text); - io.poll(); - } - BOOST_TEST(run_until(io, [&] { return closes == 1; })); - run_until(io, [] { return false; }, 100ms); - BOOST_TEST_EQ(closes, 1); -} - -// A relay that stops answering while the room has nothing to send: a keep-alive ping goes -// unanswered, and the socket closes after websocket_limits::idle_timeout, here 1 s. -void a_relay_that_stops_answering_times_out() { - asio::io_context io; - const stalled_server server(io); - asio::ssl::context tls(asio::ssl::context::tls_client); - bool opened = false; - int closes = 0; - const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), - { - .open = [&] { opened = true; }, - .message = {}, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource(), - { - .max_queued_bytes = trystero::native::websocket_limits{}.max_queued_bytes, - .idle_timeout = 1s, - }); - if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { - return; - } - BOOST_TEST(run_until(io, [&] { return closes == 1; }, 10s)); -} - -// A relay that is quiet but healthy: it sends nothing, but reads, so it answers each keep-alive -// ping. With a 1 s idle timeout, the socket stays open well past it, and then still echoes. -void a_quiet_relay_that_answers_pings_stays_connected() { - asio::io_context io; - const echo_server server(io); - asio::ssl::context tls(asio::ssl::context::tls_client); - bool opened = false; - int closes = 0; - std::vector received; - const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), - { - .open = [&] { opened = true; }, - .message = [&](std::string_view text) { received.emplace_back(text); }, - .close = [&] { ++closes; }, - }, - std::pmr::get_default_resource(), - { - .max_queued_bytes = trystero::native::websocket_limits{}.max_queued_bytes, - .idle_timeout = 1s, - }); - if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { - return; - } - run_until(io, [&] { return closes != 0; }, 3s); // three idle timeouts - BOOST_TEST_EQ(closes, 0); - socket->send("still there"); - BOOST_TEST(run_until(io, [&] { return received.size() == 1; })); -} - -} // namespace - -int main() { - urls_name_a_scheme_host_port_and_path(); - opens_sends_in_order_receives_and_closes_once(); - a_message_longer_than_a_relay_sends_closes_the_socket(); - an_unreachable_relay_closes_without_opening(); - a_dropped_socket_reports_nothing(); - closing_right_after_a_send_lets_the_write_finish_first(); - a_connection_that_ends_during_a_write_closes_once(misbehaviour::too_long_text); - a_connection_that_ends_during_a_write_closes_once(misbehaviour::reset); - a_relay_that_stops_reading_is_dropped_at_the_queue_bound(); - a_relay_that_stops_answering_times_out(); - a_quiet_relay_that_answers_pings_stays_connected(); - return boost::report_errors(); -} diff --git a/test/oracle/Jamfile b/test/oracle/Jamfile index f081437..b15dad4 100644 --- a/test/oracle/Jamfile +++ b/test/oracle/Jamfile @@ -6,33 +6,41 @@ # The oracle of trystero: Trystero 0.26.0 itself, pinned by package.json and # package-lock.json, run by Node. It computes the protocol's values that the -# protocol test must reproduce, and meets the C++ peers in the interop tests. +# protocol test must reproduce, runs the twins of the examples, and meets the +# C++ peers in the interop tests. werift, pinned beside it, is the WebRTC the +# twins give Trystero JS in Node, as its README says to. import webcpp ; webcpp.targets native emscripten ; +# The twins of the examples run under run_twin.mjs, which gives each a relay of +# its own on 127.0.0.1 (twins/without-twin.txt names the programs that have +# none, with the reason). +path-constant ORACLE : . ; + # tag::oracle[] -webcpp.original node ; +webcpp.original node --conditions=development ; +webcpp.twins ../../example : twins : .mjs : $(ORACLE)/run_twin.mjs ; webcpp.cases protocol : oracle.mjs : ../fixtures/cases : ../fixtures/expected ; -webcpp.lane oracle : cases-protocol ; +webcpp.lane oracle : twins cases-protocol ; # end::oracle[] # Trystero JS meets each C++ peer over a relay of its own on 127.0.0.1: the -# browser's peer in headless Chrome, and the native peer as a process. The -# native peer needs exceptions whatever the build asks: native::backend -# exists only with them, since libdatachannel reports errors by throwing. It -# is built with the standard libraries' own checks, so that a completion -# that touches a container its socket cleared fails at once. Each driver has +# browser's peer in headless Chrome, and the native peer as a process, both +# over the platform backend. The native peer is built with the standard +# libraries' own checks, so that a completion that touches a container its +# socket cleared fails at once. Each driver has # 2400 s for its bounded scenarios and Chrome's start, including the # wrong-password observation windows and transient-handshake recovery. The # scenarios report their peer events on failure before this outer bound. # tag::interop[] webcpp.drive interop_browser : interop/peer.cpp - : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH 2400 + : /webcpp/trystero//platform -sENVIRONMENT=web + -sALLOW_MEMORY_GROWTH 2400 : interop/run.mjs : --browser : emscripten ; webcpp.drive interop_native : interop/native_peer.cpp - : /webcpp/trystero//native multi on 2400 + : /webcpp/trystero//platform multi 2400 _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS : interop/run.mjs : --native : native ; diff --git a/test/oracle/interop/cpp.html b/test/oracle/interop/cpp.html index 64b1cdc..c594cac 100644 --- a/test/oracle/interop/cpp.html +++ b/test/oracle/interop/cpp.html @@ -43,8 +43,8 @@ return super.close() } } -var Module = {onRuntimeInitialized: () => Module.start()} -window.leave = () => Module.leave() +// The program's main starts the peer, runs it for the page's life, and defines window.leave, which +// posts the leave to it. // The program run.mjs serves under /build/, as b2 linked it: interop_browser.js, beside its wasm. const program = document.createElement('script') program.src = '/build/' + new URLSearchParams(location.search).get('program') diff --git a/test/oracle/interop/native_peer.cpp b/test/oracle/interop/native_peer.cpp index 0225ec6..2e1dd52 100644 --- a/test/oracle/interop/native_peer.cpp +++ b/test/oracle/interop/native_peer.cpp @@ -27,28 +27,36 @@ // | --delayOpen | defer native open delivery while transport messages arrive, optional | // | --ping2 | any value: ping each peer of room2 every second, optional | #include -#include +#include #include +#include +#include +#include +#include + #include #include #include #include #include -#include #include +#include #include #include +#include #include #include #include +#include #include #include #include #include #include #include +#include #include #include @@ -56,11 +64,65 @@ namespace trystero = webcpp::trystero; namespace { -/** An event for the driver: a kind and fields, one JSON object per line. */ -void record(std::string_view kind, boost::json::object fields = {}) { - fields["kind"] = kind; +/** Appends `text` as `JSON.stringify` writes a string; a text that is not UTF-8, which no + * JavaScript string is, as `null`. */ +void append_string(std::string& out, std::string_view text) { + if (!webcpp::document::quote(text, out).has_value()) { + out += "null"; + } +} + +/** A field of an event for the driver: its key, and its value as JSON text. */ +struct field { + /** A string. */ + field(std::string_view name, std::string_view text) : key(name) { append_string(json, text); } + + /** An integer, in decimal. */ + template + requires(!std::same_as) + field(std::string_view name, I number) : key(name) { + std::array digits{}; + const auto written = std::to_chars(digits.data(), digits.data() + digits.size(), number); + json.assign(digits.data(), written.ptr); + } + + /** Strings, as an array of them. */ + field(std::string_view name, std::span texts) : key(name) { + json += '['; + for (const auto& text : texts) { + if (json.size() > 1) { + json += ','; + } + append_string(json, text); + } + json += ']'; + } + + /** A JSON value, as `JSON.stringify` writes it. */ + field(std::string_view name, const webcpp::document::document& value) + : key(name), json(value.stringify()) {} + + /** The key. */ + std::string_view key; + /** The value, as JSON text. */ + std::string json; +}; + +/** An event for the driver: a kind and fields, one JSON object per line, the kind last. */ +void record(std::string_view kind, std::initializer_list fields = {}) { + std::string line = "{"; + for (const field& f : fields) { + append_string(line, f.key); + line += ':'; + line += f.json; + line += ','; + } + append_string(line, "kind"); + line += ':'; + append_string(line, kind); + line += '}'; // flushed: the driver reads each event from a pipe as it comes - std::cout << boost::json::serialize(fields) << '\n' << std::flush; + std::cout << line << '\n' << std::flush; } /** Milliseconds from a parameter's digits, or `fallback` when it has none. */ @@ -152,7 +214,7 @@ trystero::room join(trystero::app& app, const std::string& room_id, } // 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. +// 100 ms later. Real messages still use the backend's WebRTC, including its pre-handoff queue. class delayed_channel : public trystero::backend::data_channel, public std::enable_shared_from_this { public: @@ -250,18 +312,18 @@ class observed_connection : public trystero::backend::peer_connection { 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 { +/** The platform backend, which records each peer connection it makes, for the scenarios that + * count them. */ +class counting_backend : public trystero::platform::backend { public: 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)) {} + const trystero::platform::backend_config& config) + : trystero::platform::backend(ex, config), ex_(std::move(ex)) {} std::shared_ptr make_peer_connection( std::span servers, std::pmr::memory_resource* memory) override { - auto pc = trystero::native::backend::make_peer_connection(servers, memory); + auto pc = trystero::platform::backend::make_peer_connection(servers, memory); if (pc) { record("made-connection"); if (delay_open) { @@ -461,14 +523,10 @@ int main(int argc, char* argv[]) { record("error", {{"peer", peer}, {"error", ec.message()}, {"what", what}}); }); trystero::room room = join(app, args["room"], options_of(args)); - boost::json::array relays; - for (const auto& url : room.relay_urls()) { - relays.emplace_back(url); - } - record("joined", {{"self", room.self_id()}, {"relays", relays}}); + record("joined", {{"self", room.self_id()}, {"relays", room.relay_urls()}}); auto chat = room.make_action("chat"); - auto drink = room.make_action("drink"); + auto drink = room.make_action("drink"); auto file = room.make_action("file"); room.on_peer_join([&](std::string_view peer_view) { @@ -482,9 +540,15 @@ int main(int argc, char* argv[]) { }; chat.async_send("hello from C++", trystero::send_options{.targets = {peer}, .metadata = {}}, done("chat")); - drink.async_send( - boost::json::object{{"drink", "cafezinho"}, {"withIce", false}, {"from", "c++"}}, - trystero::send_options{.targets = {peer}, .metadata = {}}, done("drink")); + auto cafezinho = + webcpp::document::parse(R"({"drink":"cafezinho","withIce":false,"from":"c++"})"); + if (cafezinho.has_value()) { + drink.async_send(std::move(*cafezinho), + trystero::send_options{.targets = {peer}, .metadata = {}}, + done("drink")); + } else { + done("drink")(cafezinho.error()); + } trystero::bytes big(100'000); for (std::size_t i = 0; i < big.size(); ++i) { big[i] = static_cast((i * 13) % 256); @@ -514,7 +578,7 @@ int main(int argc, char* argv[]) { [](boost::system::error_code) {}); } }); - drink.on_message([](boost::json::value v, const trystero::message_info& info) { + drink.on_message([](const webcpp::document::document& v, const trystero::message_info& info) { record("drink", {{"from", info.from}, {"value", v}}); }); file.on_message([](const trystero::bytes& data, const trystero::message_info& info) { diff --git a/test/oracle/interop/peer.cpp b/test/oracle/interop/peer.cpp index fc90aeb..d75b16a 100644 --- a/test/oracle/interop/peer.cpp +++ b/test/oracle/interop/peer.cpp @@ -6,7 +6,8 @@ // // The C++ side of the interop test: a page that joins a room with the library, built for the // browser. The driver (run.mjs) configures it through the URL and reads what happened from -// `window.events`. +// `window.events`. Its main starts the peer and runs the io_context for the page's life, under a +// work guard; the driver's one call, `window.leave`, a `platform::page_call`, only posts to it. // // | Query parameter | Meaning | // | app, room | the app id and room id | @@ -23,21 +24,30 @@ // | ping2 | any value: ping each peer of room2 every second, optional | // | program | the program's JavaScript, which cpp.html loads; not read here | #include -#include -#include // once per program: the JavaScript export +#include +#include + +#include +#include + +#include +#include +#include +#include -#include #include -#include -#include -#include +#include #include #include +#include #include +#include #include #include +#include #include +#include #include using emscripten::val; @@ -53,16 +63,15 @@ struct extra_room { std::unique_ptr> file; }; -/** Everything the page keeps alive: the io_context, the event loop, the backend, the app, the room - * and its actions. */ +/** Everything the page keeps alive: the io_context, the backend, the app, the room and its + * actions. */ struct page { - boost::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + webcpp::asio::io_context io; + trystero::platform::backend backend{io.get_executor()}; std::unique_ptr app; std::unique_ptr room; std::unique_ptr> chat; - std::unique_ptr> drink; + std::unique_ptr> drink; std::unique_ptr> file; extra_room second{.which = "second", .room = {}, .chat = {}, .file = {}}; extra_room third{.which = "third", .room = {}, .chat = {}, .file = {}}; @@ -72,7 +81,8 @@ struct page { std::uint64_t next_ping = 0; }; -/** The page's one state, made when the driver starts the peer, kept as long as the tab. */ +/** The page's one state, which main runs and the driver's calls post to, kept as long as the tab. + */ page& the_page() { static page state; return state; @@ -85,11 +95,65 @@ std::string param(std::string_view name) { return value.isNull() ? std::string() : value.as(); } -/** An event for the driver: a kind and fields, pushed to `window.events`. */ -void record(std::string_view kind, boost::json::object fields = {}) { - fields["kind"] = kind; - val::global("window")["events"].call( - "push", val::global("JSON").call("parse", val(boost::json::serialize(fields)))); +/** Appends `text` as `JSON.stringify` writes a string; a text that is not UTF-8, which no + * JavaScript string is, as `null`. */ +void append_string(std::string& out, std::string_view text) { + if (!webcpp::document::quote(text, out).has_value()) { + out += "null"; + } +} + +/** A field of an event for the driver: its key, and its value as JSON text. */ +struct field { + /** A string. */ + field(std::string_view name, std::string_view text) : key(name) { append_string(json, text); } + + /** An integer, in decimal. */ + template + requires(!std::same_as) + field(std::string_view name, I number) : key(name) { + std::array digits{}; + const auto written = std::to_chars(digits.data(), digits.data() + digits.size(), number); + json.assign(digits.data(), written.ptr); + } + + /** Strings, as an array of them. */ + field(std::string_view name, std::span texts) : key(name) { + json += '['; + for (const auto& text : texts) { + if (json.size() > 1) { + json += ','; + } + append_string(json, text); + } + json += ']'; + } + + /** A JSON value, as `JSON.stringify` writes it. */ + field(std::string_view name, const webcpp::document::document& value) + : key(name), json(value.stringify()) {} + + /** The key. */ + std::string_view key; + /** The value, as JSON text. */ + std::string json; +}; + +/** An event for the driver: a kind and fields, pushed to `window.events`, the kind last. */ +void record(std::string_view kind, std::initializer_list fields = {}) { + std::string text = "{"; + for (const field& f : fields) { + append_string(text, f.key); + text += ':'; + text += f.json; + text += ','; + } + append_string(text, "kind"); + text += ':'; + append_string(text, kind); + text += '}'; + val::global("window")["events"].call("push", + val::global("JSON").call("parse", val(text))); } /** Milliseconds from a parameter's digits, or `fallback` when it has none. */ @@ -122,8 +186,8 @@ void record_connection(std::string_view category, std::string_view text) { void log(std::string_view category, std::string_view text) { record_connection(category, text); - val::global("window").call("trysteroLog", the_page().loop.text(category), - the_page().loop.text(text)); + val::global("window").call("trysteroLog", trystero::platform::js_string(category), + trystero::platform::js_string(text)); } /** A checksum the driver can compare without moving the payload: sum of bytes times their position, @@ -263,8 +327,7 @@ void ping_second() { void start() { page& app = the_page(); - app.app = - std::make_unique(app.loop.get_executor(), app.backend, config_of_page()); + app.app = std::make_unique(app.io.get_executor(), app.backend, config_of_page()); app.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}}); @@ -274,16 +337,12 @@ void start() { return; } auto& room = *app.room; - boost::json::array relays; - for (const auto& url : room.relay_urls()) { - relays.emplace_back(url); - } - record("joined", {{"self", room.self_id()}, {"relays", relays}}); + record("joined", {{"self", room.self_id()}, {"relays", room.relay_urls()}}); app.chat = std::make_unique>(room.make_action("chat")); - app.drink = std::make_unique>( - room.make_action("drink")); + app.drink = std::make_unique>( + room.make_action("drink")); app.file = std::make_unique>( room.make_action("file")); @@ -298,9 +357,13 @@ void start() { }; const trystero::send_options to_peer{.targets = {peer}, .metadata = {}}; the_page().chat->async_send("hello from C++", to_peer, done("chat")); - the_page().drink->async_send( - boost::json::object{{"drink", "cafezinho"}, {"withIce", false}, {"from", "c++"}}, - to_peer, done("drink")); + auto cafezinho = + webcpp::document::parse(R"({"drink":"cafezinho","withIce":false,"from":"c++"})"); + if (cafezinho.has_value()) { + the_page().drink->async_send(std::move(*cafezinho), to_peer, done("drink")); + } else { + done("drink")(cafezinho.error()); + } trystero::bytes big(100'000); for (std::size_t i = 0; i < big.size(); ++i) { big[i] = static_cast((i * 13) % 256); @@ -331,9 +394,10 @@ void start() { [](boost::system::error_code) {}); } }); - app.drink->on_message([](boost::json::value v, const trystero::message_info& info) { - record("drink", {{"from", info.from}, {"value", v}}); - }); + app.drink->on_message( + [](const webcpp::document::document& v, const trystero::message_info& info) { + record("drink", {{"from", info.from}, {"value", v}}); + }); app.file->on_message([](const trystero::bytes& data, const trystero::message_info& info) { record("file", { {"from", info.from}, @@ -358,15 +422,25 @@ void start() { } } -/** Called by the driver: leave the room with Trystero's farewell. */ +/** The driver's call, `window.leave`: leaves the room with Trystero's farewell. */ void leave() { + if (!the_page().room) { + return; + } the_page().room->async_leave( [](boost::system::error_code ec) { record("left", {{"error", ec ? ec.message() : ""}}); }); } } // namespace -EMSCRIPTEN_BINDINGS(interop_peer) { - emscripten::function("start", &start); - emscripten::function("leave", &leave); +int main() { + page& app = the_page(); + // Between the driver's calls the page may have no work: the guard keeps the run going. + const auto guard = webcpp::asio::make_work_guard(app.io); + // The driver's one call, a function of webcpp::asio's bridge that posts the leave. + const trystero::platform::page_call leave_call(app.io.get_executor(), + [](const val& /*argument*/) { leave(); }); + val::global("window").set("leave", leave_call.function()); + start(); + app.io.run(); // lint-run: the page's program, suspended into the browser's event loop } diff --git a/test/oracle/interop/relay.mjs b/test/oracle/interop/relay.mjs index 3a1a36c..8767032 100644 --- a/test/oracle/interop/relay.mjs +++ b/test/oracle/interop/relay.mjs @@ -4,10 +4,10 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A Nostr relay for the interop test, NIP-01 only and in memory: REQ with kinds, since and #x filters, CLOSE, and -// EVENT, which it verifies like a public relay (the id is the SHA-256 of the canonical serialization, the signature a -// valid BIP-340 one) before forwarding it to the subscriptions open at that moment. Nothing is stored: Trystero's -// kinds are ephemeral. +// A Nostr relay for the interop test, the examples that run over a relay and their twins, NIP-01 only and in memory: +// REQ with kinds, since and #x filters, CLOSE, and EVENT, which it verifies like a public relay (the id is the SHA-256 +// of the canonical serialization, the signature a valid BIP-340 one) before forwarding it to the subscriptions open +// at that moment. Nothing is stored: Trystero's kinds are ephemeral. import {createHash} from 'node:crypto' import {schnorr} from '@noble/secp256k1' import {WebSocketServer} from 'ws' diff --git a/test/oracle/interop/run.mjs b/test/oracle/interop/run.mjs index 25fa9ec..9864bdf 100644 --- a/test/oracle/interop/run.mjs +++ b/test/oracle/interop/run.mjs @@ -810,30 +810,56 @@ const leavingEveryRoomScenario = (name, cppKind) => return seconds >= 1.5 ? null : `the connection closed ${seconds} s after the leaves, before the idle time of 2 s` }) +// The negotiations a C++ peer opened with `peer`, by its log: the offers it sent that peer, each once however often it +// resent it, and the offers of that peer it answered. Each made a connection for that peer, where the counts of +// connections made (cpp.html's madePeerConnections, the native peer's made-connection events) count every peer's. +const negotiationsWith = async (cpp, peer) => { + const log = await cpp.log() + const offers = new Set([...log.matchAll(new RegExp(`sending offer (\\w+) to ${peer}\\b`, 'g'))].map(m => m[1])) + return offers.size + [...log.matchAll(new RegExp(`signal: offer \\w+ from ${peer}\\b`, 'g'))].length +} + // 4. A public app exposes its other rooms to a peer on its connection. A separate password-protected app has // another peer id, so public-channel presence and readiness injections cannot reach its rooms or broadcasts. +// The protected app joins the public app's first room once the public connection is up, so that the two apps meet +// within the window observed: whatever the passwords, the lower id offers to a higher one it sees announced, as +// Trystero does, and the other cannot open the offer. The public app, when it has the lower id, so makes a connection +// for the protected app when they meet, and another each time its unanswered offer expires (57 s): its connection with +// the page is judged by the negotiations it opened with the page, not by every connection it made. const openToOtherRoomsScenario = (name, cppKind) => scenario(name, async open => { for (const protectedSelf of ['00000000000000000000', 'zzzzzzzzzzzzzzzzzzzz']) { const publicSelf = protectedSelf.startsWith('0') ? 'zzzzzzzzzzzzzzzzzzzz' : '00000000000000000000' const rooms = {room: room(), room2: room(), secret: room()} const cpp = await open(cppKind, {room: rooms.room, room2: rooms.room2, self: publicSelf, ...relayParams}) - const protectedCpp = await open(cppKind, { - room: rooms.room, room2: rooms.secret, self: protectedSelf, password: 'vault', ...relayParams, - }) // The page knows the protected room id but has no password. It also injects that token over its public // connection, alongside the public app's actual advertisements. const js = await open('js', {room: rooms.room, room3: rooms.secret, ...relayParams}) const ok = await until(async () => exchangeComplete(inRoom(await cpp.events(), 'first'), false) && exchangeComplete(inRoom(await js.events(), 'first'), true), 30_000) if (!ok) return `${protectedSelf}: the public room did not complete in 30 s` + if (!(await until(async () => (await js.value('window.advertisedCount()')) >= 2, 10_000))) { + return `${protectedSelf}: the public app did not advertise both rooms` + } + const pageSelf = (await js.events()).find(e => e.kind === 'joined')?.self + const publicConnection = async () => + ({withPage: await negotiationsWith(cpp, pageSelf), ...await connectionCounts(cpp, cppKind, js)}) + const before = await publicConnection() + if (before.withPage < 1) return `${protectedSelf}: the public app's log names no negotiation with the page` + const protectedCpp = await open(cppKind, { + room: rooms.room, room2: rooms.secret, self: protectedSelf, password: 'vault', ...relayParams, + }) const refused = async () => inRoom(await protectedCpp.events(), 'second').some(e => e.kind === 'error') || inRoom(await js.events(), 'third').some(e => e.kind === 'error' && e.peer === protectedSelf) if (!(await until(refused, 15_000))) return `${protectedSelf}: the protected room saw no attempted negotiation` - if (!(await until(async () => (await js.value('window.advertisedCount()')) >= 2, 10_000))) { - return `${protectedSelf}: the public app did not advertise both rooms` + // The two apps met: the higher id could not open the lower id's offer, or a candidate of it, whichever came + // first (it says so once per negotiation). + const higher = protectedSelf > publicSelf ? protectedCpp : cpp + const lowerSelf = protectedSelf > publicSelf ? publicSelf : protectedSelf + const met = async () => new RegExp(`could not open the \\w+ from ${lowerSelf}`).test(await higher.log()) + if (!(await until(met, 15_000))) { + return `${protectedSelf}: the public and the protected apps did not meet in 15 s` } - const before = await connectionCounts(cpp, cppKind, js) const echoed = await js.value(`window.echoPresence([${JSON.stringify(rooms.secret)}])`) if (echoed < 3) return `${protectedSelf}: the injection omitted a public or protected token` const joined2 = async () => inRoom(await cpp.events(), 'second').some(e => e.kind === 'peer-join') @@ -853,8 +879,8 @@ const openToOtherRoomsScenario = (name, cppKind) => (await js.value(`window.roomFrames(${JSON.stringify(rooms.secret)}, 'file')`)) !== 0) { return `${protectedSelf}: protected broadcasts reached the public page` } - const after = await connectionCounts(cpp, cppKind, js) - if (after.cppMade !== before.cppMade || after.jsConnected !== 1) { + const after = await publicConnection() + if (after.withPage !== before.withPage || after.jsConnected !== 1) { return `${protectedSelf}: the public connection changed: before ${JSON.stringify(before)}, after ${JSON.stringify(after)}` } } diff --git a/test/oracle/oracle.mjs b/test/oracle/oracle.mjs index 751d1e4..44f3d53 100644 --- a/test/oracle/oracle.mjs +++ b/test/oracle/oracle.mjs @@ -13,7 +13,7 @@ import {mkdirSync, readFileSync, writeFileSync} from 'node:fs' import {dirname, join} from 'node:path' import {fileURLToPath} from 'node:url' -import {defaultRelayUrls} from '@trystero-p2p/nostr' +import {schnorr} from '@noble/secp256k1' if (process.argv.length !== 4) { console.error('usage: node oracle.mjs ') @@ -22,11 +22,35 @@ if (process.argv.length !== 4) { const [casesDirectory, outputDirectory] = process.argv.slice(2) const cases = JSON.parse(readFileSync(join(casesDirectory, 'protocol.json'), 'utf8')) +// Trystero draws its peer id, selfId, from Math.random once, when utils.mjs is loaded: from the +// answerer fixture's draws while the modules load, so that the signals carrying it are the same +// every run. Draw i is ((i * multiplier + offset) % 62 + 0.5) / 62, which picks character +// (i * multiplier + offset) % 62 of Trystero's alphabet. +const random = Math.random +{ + const {multiplier, offset} = cases.answerer.self_id_random + let draw = 0 + Math.random = () => ((((draw++ * multiplier) + offset) % 62) + 0.5) / 62 +} const core = join(dirname(fileURLToPath(import.meta.url)), 'node_modules/@trystero-p2p/core/dist') -const {sha1, hashWith, deriveRoomNamespace, encrypt, genKey} = await import(join(core, 'crypto.mjs')) -const {strToNum, getRelays, toHex, toJson, topicPath, shuffle} = await import(join(core, 'utils.mjs')) +const {sha1, hashWith, deriveRoomNamespace, encrypt, decrypt, genKey} = await import(join(core, 'crypto.mjs')) +const {strToNum, getRelays, toHex, toJson, topicPath, shuffle, selfId} = await import(join(core, 'utils.mjs')) const {createActionWireManager} = await import(join(core, 'action-wire.mjs')) const {SharedPeerManager} = await import(join(core, 'shared-peer.mjs')) +const {createSignalHandler} = await import(join(core, 'signal-handler.mjs')) +Math.random = random + +// The bytes getRandomValues gives while a fixture draws them, the same every run: byte i of a draw +// is (i * multiplier + offset) % 256. Trystero draws an IV with it when it seals, and noble's +// secp256k1 a key and a signature's auxiliary bytes. +const patterned = ({multiplier, offset}) => array => array.map((_, i) => (i * multiplier + offset) % 256) +const getRandomValues = crypto.getRandomValues.bind(crypto) + +// Trystero's Nostr strategy draws its key once, when it is loaded: from the bytes of the event +// messages' fixture, so that its events are the same every run and the C++ signer can sign them. +crypto.getRandomValues = patterned(cases.event_messages.random) +const {defaultRelayUrls, createEvent, joinRoom} = await import('@trystero-p2p/nostr') +crypto.getRandomValues = getRandomValues const hex = bytes => Buffer.from(bytes).toString('hex') const out = {} @@ -71,8 +95,7 @@ const sealed = cases.sealed const key = genKey(sealed.password, sealed.app_id, sealed.room_id) const plaintext = sealed.plaintext // A fixed IV keeps the fixture deterministic; Trystero draws it from getRandomValues. -const getRandomValues = crypto.getRandomValues.bind(crypto) -crypto.getRandomValues = array => array.map((_, i) => (i * sealed.random.multiplier + sealed.random.offset) % 256) +crypto.getRandomValues = patterned(sealed.random) const sealedText = await encrypt(key, plaintext) crypto.getRandomValues = getRandomValues out.sealed = { @@ -175,6 +198,256 @@ out.actions = await captureActions() out.envelope = {room_token: token, frames: [...frames]} } +// Event messages, written by Trystero's own createEvent, `["EVENT",{kind,tags,created_at,content, +// pubkey,id,sig}]`, whose topics and contents hold the characters JSON.stringify escapes and those +// it writes as they are: the controls U+0000 to U+001F, `"`, `\`, U+2028, U+2029, DEL and astral +// ones. The key is the one the strategy drew when it was loaded, and the clock and the signature's +// auxiliary bytes are the fixture's; noble's keygen makes the key again from the same 48 bytes, so +// that the C++ signer signs with it. +{ + const messages = cases.event_messages + const draw = patterned(messages.random) + const {secretKey} = schnorr.keygen(draw(new Uint8Array(48))) + const now = Date.now + Date.now = () => messages.created_at * 1000 + crypto.getRandomValues = draw + out.event_messages = { + secret_key: hex(secretKey), + aux: hex(draw(new Uint8Array(32))), + created_at: messages.created_at, + events: [], + } + for (const [topic, content] of messages.events) { + const message = await createEvent(topic, content) + out.event_messages.events.push({topic, content, id: JSON.parse(message)[1].id, message}) + } + crypto.getRandomValues = getRandomValues + Date.now = now +} + +// Signals' texts, written as Trystero writes each, with toJson (JSON.stringify), their members in +// the order Trystero gives them: an announcement {peerId, passive, nonce} (the topic strategy's +// announce, then the Nostr strategy's nonce), an offer {peerId, offerId, offer} and the offerer's +// candidate {peerId, offerId, candidate, passive} (handleAnnouncement), an answer to an offer +// without an id {peerId, answer}, and the answerer's answer and candidate, whose offerId follows +// them {peerId, answer, offerId} and {peerId, candidate, offerId, passive} (handleOffer's +// publishAnswerSignal); their strings hold the event messages' characters. +out.signal_texts = cases.signal_texts.map(signal => ({signal, text: toJson(signal)})) + +// Signals whose objects hold a key twice, as Trystero's own signal handler reads them: it runs in a +// room of the oracle's, which records the peer id it looks up (reusePeer), the sealed text it opens +// (toPlain), by kind, and an offer's id, and opens nothing, so that the handler stops there. A +// passive room ignores a passive sender before it looks the peer up, which a second run, in such a +// room, shows. `read` is null when Trystero ignores the signal. +const readSignal = async text => { + const run = async passive => { + const read = {} + const ctx = { + appId: 'app', + roomId: 'room', + config: {}, + peerStates: {}, + rootTopicPlaintext: topicPath('Trystero', 'app', 'room'), + rootTopicP: Promise.resolve('root'), + selfTopicP: Promise.resolve('self'), + isPassive: passive, + isActive: true, + // The room leaves once it looked the peer up, so that an announcement makes no offer. + isLeaving: () => read.peer_id !== undefined, + reusePeer: peerId => { + read.peer_id = peerId + return false + }, + toPlain: async ({type, sdp}) => { + read[type] = sdp + if (type === 'offer') read.offer_id = ctx.peerStates[read.peer_id].answerReplay.offerId + throw new Error('the oracle opens nothing') + }, + initPeer: () => ({ + isDead: false, + setHandlers: () => {}, + signal: async () => {}, + destroy: () => {}, + }), + offerManager: {checkout: async () => Promise.reject(new Error('the oracle makes no offer'))}, + connectPeer: () => {}, + disconnectPeer: () => {}, + checkDeactivate: () => {}, + announceIntervals: [], + announceIntervalMs: 5333, + } + await createSignalHandler(ctx)(0)('root', text, () => {}) + return read + } + const read = await run(false) + if (read.peer_id === undefined) return null + read.passive = (await run(true)).peer_id === undefined + return read +} +out.duplicate_keys = {signals: []} +for (const text of cases.duplicate_keys.signals) { + out.duplicate_keys.signals.push({text, read: await readSignal(text)}) +} + +// Relay events whose objects hold a key twice, as Trystero's own Nostr strategy reads them. A room +// of the cases' app joins through a WebSocket of the oracle's, which hands it each case's members +// as an event of the room's subscription, keys as they are written and values as toJson writes +// them, `{root}` being the room's root topic. Every content is an answer that does not open, so +// that the room reports its sender (onJoinError) exactly when it acted on the event: when it read +// the event's topic as the room's root topic and its content as the signal. After each case comes +// an event of the oracle's own, whose report closes the case's. `acted` is the sender the room +// reported, or null; in what is written the subscription's id, which Trystero draws, is `sub`. +class OracleSocket { + static opened = [] + + constructor(url) { + this.url = url + this.readyState = 0 + this.sent = [] + OracleSocket.opened.push(this) + setTimeout(() => { + this.readyState = 1 + this.onopen?.() + }, 0) + } + + send(text) { + this.sent.push(text) + } + + close() { + this.readyState = 3 + } +} +const until = async (done, what) => { + for (let waited = 0; !done(); waited += 10) { + if (waited >= 10_000) throw new Error(`the oracle waited 10 s for ${what}`) + await new Promise(resolve => setTimeout(resolve, 10)) + } +} +{ + const events = cases.duplicate_keys.events + const rootTopic = await sha1(topicPath('Trystero', events.app_id, events.room_id)) + const eventText = (subscription, members) => { + const fields = members.map(([key, value]) => `"${key}":${toJson(value)}`).join(',') + return `["EVENT",${toJson(subscription)},{${fields}}]`.replaceAll('{root}', rootTopic) + } + const acted = [] + const WebSocket = globalThis.WebSocket + globalThis.WebSocket = OracleSocket + const room = joinRoom({appId: events.app_id, relayConfig: {urls: ['wss://relay.oracle.invalid']}}, + events.room_id, {onJoinError: ({peerId}) => acted.push(peerId)}) + const [socket] = OracleSocket.opened + const subscribed = () => socket.sent.map(text => JSON.parse(text)) + .find(([type, , filter]) => type === 'REQ' && filter['#x'].includes(rootTopic)) + await until(subscribed, 'the subscription to the root topic') + const subscription = subscribed()[1] + out.duplicate_keys.root_topic = rootTopic + out.duplicate_keys.events = [] + for (const [i, members] of events.texts.entries()) { + acted.length = 0 + socket.onmessage({data: eventText(subscription, members)}) + const closing = `oracle-${i}` + socket.onmessage({data: eventText(subscription, [ + ['tags', [['x', '{root}']]], + ['content', toJson({peerId: closing, answer: 'x'})], + ])}) + await until(() => acted.includes(closing), `the report of ${closing}`) + const senders = acted.filter(peerId => peerId !== closing) + if (senders.length > 1) throw new Error(`one event reported ${senders.length} senders`) + out.duplicate_keys.events.push({text: eventText('sub', members), acted: senders[0] ?? null}) + } + await room.leave() + globalThis.WebSocket = WebSocket +} + +// The answerer's signals, as Trystero's own signal handler publishes them (handleOffer): for each +// case, a room of the oracle's, as readSignal's, gets an offer on its self topic, sealed under the +// room's key, opens it, and hands it to its answering peer, a stand-in that gives an answer and +// then a candidate, as an RTCIceCandidate's toJSON in JSON.stringify's text (peer.mjs); the room +// seals each with Trystero's encrypt, the fixture's IV drawn every time, and publishes the answer, +// then the candidate it held. `sealed` holds every text sealed, the offers' and the room's, with +// its plaintext; `published`, the topic and the text of each signal the room sent, in order. +{ + const answerer = cases.answerer + const key = genKey(answerer.password, answerer.app_id, answerer.room_id) + const root = topicPath('Trystero', answerer.app_id, answerer.room_id) + const candidate = JSON.stringify(answerer.candidate) + const sealed = [] + const seal = async plaintext => { + const text = await encrypt(key, plaintext) + if (!sealed.some(entry => entry.plaintext === plaintext)) sealed.push({plaintext, text}) + return text + } + crypto.getRandomValues = patterned(answerer.random) + const offer = await seal(answerer.offer_sdp) + out.answerer = { + self_id: selfId, + app_id: answerer.app_id, + room_id: answerer.room_id, + answer_sdp: answerer.answer_sdp, + candidate, + sealed, + cases: [], + } + for (const {peerId, offerId} of answerer.offers) { + const handlers = {} + const errors = [] + const published = [] + const ctx = { + appId: answerer.app_id, + roomId: answerer.room_id, + config: {}, + peerStates: {}, + rootTopicPlaintext: root, + rootTopicP: sha1(root), + selfTopicP: sha1(topicPath(root, selfId)), + isPassive: false, + isActive: true, + isLeaving: () => false, + reusePeer: () => false, + toPlain: async ({type, sdp}) => ({type, sdp: await decrypt(key, sdp)}), + toCipher: async ({type, sdp}) => ({type, sdp: await seal(sdp)}), + initPeer: () => ({ + isDead: false, + setHandlers: given => Object.assign(handlers, given), + signal: async description => { + if (description.type !== 'offer' || description.sdp !== answerer.offer_sdp) { + throw new Error('the oracle answers its own offer alone') + } + handlers.signal({type: 'answer', sdp: answerer.answer_sdp}) + handlers.signal({type: 'candidate', sdp: candidate}) + }, + destroy: () => {}, + }), + offerManager: {checkout: async () => Promise.reject(new Error('the oracle makes no offer'))}, + connectPeer: () => {}, + disconnectPeer: () => {}, + checkDeactivate: () => {}, + onJoinError: ({error}) => errors.push(error), + announceIntervals: [], + announceIntervalMs: 5333, + } + const text = toJson({peerId, ...(offerId === undefined ? {} : {offerId}), offer}) + await createSignalHandler(ctx)(0)(await ctx.selfTopicP, text, + (topic, message) => published.push({topic, text: message})) + await until(() => published.length === 2 || errors.length > 0, `the answer to ${peerId}`) + if (errors.length > 0) throw new Error(`the room reported ${errors[0]}`) + out.answerer.cases.push({offer: text, published}) + } + crypto.getRandomValues = getRandomValues +} + +// JSON payloads, as Trystero sends one: the value an action is given, written by toJson +// (JSON.stringify), here each case's text as JSON.parse reads it. Their numbers are those a double +// holds, written as JavaScript writes them, and their keys in JavaScript's order: array indices +// first, in increasing order, then the other keys in the order they were written. +out.payload_texts = cases.payload_texts.map(text => ({text, written: toJson(JSON.parse(text))})) +// And numbers a double cannot hold, which JSON.parse rounds to the nearest double, or to Infinity, +// which JSON.stringify writes null. +out.payload_beyond_doubles = + cases.payload_beyond_doubles.map(text => ({text, written: toJson(JSON.parse(text))})) + mkdirSync(outputDirectory, {recursive: true}) const target = join(outputDirectory, 'expected.json') writeFileSync(target, JSON.stringify(out, null, 4) + '\n') diff --git a/test/oracle/package-lock.json b/test/oracle/package-lock.json index 5570078..6f47d97 100644 --- a/test/oracle/package-lock.json +++ b/test/oracle/package-lock.json @@ -10,9 +10,70 @@ "@trystero-p2p/core": "0.26.0", "@trystero-p2p/nostr": "0.26.0", "trystero": "0.26.0", + "werift": "0.24.4", "ws": "8.22.0" } }, + "node_modules/@fidm/asn1": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz", + "integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@fidm/x509": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz", + "integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@fidm/asn1": "^1.0.4", + "tweetnacl": "^1.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@leichtgewicht/ip-codec": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz", + "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@noble/secp256k1": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/@noble/secp256k1/-/secp256k1-3.2.0.tgz", @@ -23,6 +84,219 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@peculiar/asn1-cms": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.11.1.tgz", + "integrity": "sha512-Bk+oatE62dW0Tzzpfk6vdQxfGGEfvuGdWgmijnKjcv7HqZCJISs85z4zw2uDArrk+R1Oel1wts/BBl7HHrtAcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "@peculiar/asn1-x509-attr": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-csr": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.11.1.tgz", + "integrity": "sha512-KVfbXaKng8886/tOPG55t5K1XkTkGbR4amjIJzytXWobFU5nZgw/sKnSpa1hxP17nUSsrOF/7Mt9WUYeyLsi6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-ecc": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.11.1.tgz", + "integrity": "sha512-7MSNji77fQa/oN3WAfwagMy8EoJFg50sW4hZ1dtr0zU1BSugit0I2DGpIdPhvkNplopQhz5bogxpn1077eaamA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pfx": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.11.1.tgz", + "integrity": "sha512-2SN2z8qkc2hk/GgTYA8RN54wtsCDZShg9gI2Mq1vLhdj1adcv5fhTbiEmExZUaAMqlizxiEpULQDfHM5iYtn1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.11.1", + "@peculiar/asn1-pkcs8": "^2.11.1", + "@peculiar/asn1-rsa": "^2.11.1", + "@peculiar/asn1-schema": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs8": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.11.1.tgz", + "integrity": "sha512-HqsSrnpQghRp9SM9QSmR6fa4z/BNktnKq7928+oq4qF0VAnuHZ4cyePKvcxh9fP4taBCP/WHNItlVNsYaQm2qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs9": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.11.1.tgz", + "integrity": "sha512-OHFkTg8D2zYafILqFE4KPbqX8srpvd3diGDc2h2cduumawc765mOHGcuFMGvLWlL2bbCMWMmMSCtlXptsOuiPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.11.1", + "@peculiar/asn1-pfx": "^2.11.1", + "@peculiar/asn1-pkcs8": "^2.11.1", + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "@peculiar/asn1-x509-attr": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-rsa": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.11.1.tgz", + "integrity": "sha512-6KwKGjulF489CpidZqkogNgLj6oGzgC4BL2FClM8PuJQ4t5NqT4q4a6A4vrSxBIBhMnL8hGYkLOpbVw0Vq38Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-schema": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.11.1.tgz", + "integrity": "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.11.1.tgz", + "integrity": "sha512-SXU4/X6B3FquqQAN6ARI0bFDUV7+L1WlvPEPMKzEMkstd2D7UyM0r93fv241+OjdhqAKYGx5MvV3gzZMAp0APA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509-attr": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.11.1.tgz", + "integrity": "sha512-n7RKFrbTzt8pGBlZ90kmKEn1qsLTTyw7lrvHMK0xsA42kQugPk/GXYpNbEcl7DkkdVsU/one5UX7KQPfxLj8vQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.11.1", + "@peculiar/asn1-x509": "^2.11.1", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz", + "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/@peculiar/x509": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz", + "integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.6.0", + "@peculiar/asn1-csr": "^2.6.0", + "@peculiar/asn1-ecc": "^2.6.0", + "@peculiar/asn1-pkcs9": "^2.6.0", + "@peculiar/asn1-rsa": "^2.6.0", + "@peculiar/asn1-schema": "^2.6.0", + "@peculiar/asn1-x509": "^2.6.0", + "pvtsutils": "^1.3.6", + "reflect-metadata": "^0.2.2", + "tslib": "^2.8.1", + "tsyringe": "^4.10.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@shinyoshiaki/binary-data": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@shinyoshiaki/binary-data/-/binary-data-0.6.1.tgz", + "integrity": "sha512-7HDb/fQAop2bCmvDIzU5+69i+UJaFgIVp99h1VzK1mpg1JwSODOkjbqD7ilTYnqlnadF8C4XjpwpepxDsGY6+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "generate-function": "^2.3.1", + "is-plain-object": "^2.0.3" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/@trystero-p2p/core": { "version": "0.26.0", "resolved": "https://registry.npmjs.org/@trystero-p2p/core/-/core-0.26.0.tgz", @@ -41,6 +315,250 @@ "@trystero-p2p/core": "0.26.0" } }, + "node_modules/@types/dom-mediacapture-transform": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz", + "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/dom-webcodecs": "*" + } + }, + "node_modules/@types/dom-webcodecs": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz", + "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/asn1js": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz", + "integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.2.0", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dns-packet": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz", + "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@leichtgewicht/ip-codec": "^2.0.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "license": "MIT", + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "dev": true, + "license": "MIT" + }, + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mediabunny": { + "version": "1.66.0", + "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.66.0.tgz", + "integrity": "sha512-0Zff/qLkY1ZRyjBEt2vQjLeMigmU/dFKwJLpiPyCiskIel2f2R2kqMxaLYbeHN+rmyz4PVwwLSnU9anjUHHeJQ==", + "dev": true, + "license": "MPL-2.0", + "workspaces": [ + ".", + "packages/*" + ], + "dependencies": { + "@types/dom-mediacapture-transform": "^0.1.11", + "@types/dom-webcodecs": "0.1.13" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/Vanilagy" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/multicast-dns": { + "version": "7.2.5", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz", + "integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==", + "dev": true, + "license": "MIT", + "dependencies": { + "dns-packet": "^5.2.2", + "thunky": "^1.0.2" + }, + "bin": { + "multicast-dns": "cli.js" + } + }, + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/thunky": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", + "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==", + "dev": true, + "license": "MIT" + }, "node_modules/trystero": { "version": "0.26.0", "resolved": "https://registry.npmjs.org/trystero/-/trystero-0.26.0.tgz", @@ -51,6 +569,61 @@ "@trystero-p2p/nostr": "0.26.0" } }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD" + }, + "node_modules/tsyringe": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz", + "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^1.9.3" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/tsyringe/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true, + "license": "0BSD" + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "dev": true, + "license": "Unlicense" + }, + "node_modules/werift": { + "version": "0.24.4", + "resolved": "https://registry.npmjs.org/werift/-/werift-0.24.4.tgz", + "integrity": "sha512-NoROZ11L/ZqAB5ombCB4VBuVNdIZfwI493zlxlIX7BlwfWRy55eDJdtWMC2VX35yBXFaWwA8NtYbmJ8qWtVk9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@fidm/x509": "^1.2.1", + "@noble/curves": "^1.8.1", + "@peculiar/x509": "^1.12.3", + "@shinyoshiaki/binary-data": "^0.6.1", + "buffer": "^6.0.3", + "debug": "4.4.0", + "mediabunny": "^1.45.2", + "multicast-dns": "^7.2.5", + "tweetnacl": "^1.0.3" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/ws": { "version": "8.22.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", diff --git a/test/oracle/package.json b/test/oracle/package.json index f9f0771..f50e3a7 100644 --- a/test/oracle/package.json +++ b/test/oracle/package.json @@ -2,12 +2,13 @@ "name": "webcpp-trystero-tests", "private": true, "type": "module", - "description": "The JavaScript side of the tests: Trystero JS 0.26 as the oracle and as the interop peer, and a local Nostr relay.", + "description": "The JavaScript side of the tests: Trystero JS 0.26 as the oracle, as the twins of the examples and as the interop peer, werift as its WebRTC in Node, and a local Nostr relay.", "devDependencies": { "@noble/secp256k1": "3.2.0", "@trystero-p2p/core": "0.26.0", "@trystero-p2p/nostr": "0.26.0", "trystero": "0.26.0", + "werift": "0.24.4", "ws": "8.22.0" } } diff --git a/test/oracle/page.mjs b/test/oracle/page.mjs new file mode 100644 index 0000000..5a24796 --- /dev/null +++ b/test/oracle/page.mjs @@ -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) + +// Another page for a twin whose room must meet a peer. Trystero JS has one self id per page, its +// module's selfId, so two rooms of one twin's module would be the same peer; a C++ program makes +// a second app instead. The other peer runs in a worker thread, with module instances of its own, +// as a second page would: +// +// import {openPage} from '../page.mjs' +// const other = openPage(async ({joinRoom, RTCPeerConnection, data, post, next}) => { ... }, data) +// +// The function is the page's program, written in the twin and run in the worker from its source, +// so it reaches nothing of the twin's but what it is given: Trystero's joinRoom and selfId, +// werift's RTCPeerConnection (the WebRTC Trystero's README names for Node, as rtcPolyfill), the +// data given to openPage, which must be cloneable, post(message), which sends the twin a message, +// and next(), which resolves to the next message the twin sends it. The twin's side holds +// next() and post(message) the other way round, `done`, which settles when the page's function +// does, and close(), which ends the worker. What a page prints goes to the twin's standard output +// out of order with the twin's own lines: a page posts what the twin is to print. +import {isMainThread, parentPort, Worker, workerData} from 'node:worker_threads' + +/** A queue of the messages one side receives, read by next(). */ +const inbox = port => { + const waiting = [] + const ready = [] + port.on('message', message => (waiting.length ? waiting.shift()(message) : ready.push(message))) + return () => (ready.length ? Promise.resolve(ready.shift()) : new Promise(take => waiting.push(take))) +} + +export const openPage = (program, data) => { + const worker = new Worker(new URL(import.meta.url), {workerData: {source: program.toString(), data}}) + const next = inbox(worker) + const done = new Promise((resolve, reject) => { + worker.on('error', reject) + worker.on('exit', resolve) + }) + return {next, post: message => worker.postMessage(message), done, close: () => worker.terminate()} +} + +if (!isMainThread) { + const {joinRoom, selfId} = await import('trystero') + const {RTCPeerConnection} = await import('werift') + const program = (0, eval)(`(${workerData.source})`) + await program({ + joinRoom, + selfId, + RTCPeerConnection, + data: workerData.data, + post: message => parentPort.postMessage(message), + next: inbox(parentPort), + }) + process.exit(0) +} diff --git a/test/oracle/run_twin.mjs b/test/oracle/run_twin.mjs new file mode 100644 index 0000000..79002e2 --- /dev/null +++ b/test/oracle/run_twin.mjs @@ -0,0 +1,35 @@ +// 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) + +// Runs one twin over a Nostr relay of its own on 127.0.0.1, interop/relay.mjs, as webcpp.twins +// runs every twin of trystero's examples (Jamfile), the twin's path last: +// +// node --conditions=development test/oracle/run_twin.mjs test/oracle/twins/.mjs +// +// The relay's URL is in the environment, TRYSTERO_RELAY_URL, which the twin reads as its C++ +// program reads it (example/run_over_relay.mjs starts the program's relay). The run ends once the +// twin's module has evaluated, its top-level awaits included, and what it printed has been +// written: Trystero JS keeps its relay sockets open after its rooms have left, as a page does, +// so the process would not end by itself. A twin that throws, or whose module fails to load, +// ends the run with status 1. +import {resolve} from 'node:path' +import {pathToFileURL} from 'node:url' +import {startRelay} from './interop/relay.mjs' + +const twin = process.argv.at(-1) +const relay = await startRelay() +process.env.TRYSTERO_RELAY_URL = relay.url +let status = 0 +try { + await import(pathToFileURL(resolve(twin)).href) +} catch (error) { + console.error(error) + status = 1 +} +// Every line the twin printed is written before the process ends: a pipe's writes are +// asynchronous on macOS, and a write's callback runs once those before it are done. +await new Promise(done => process.stdout.write('', done)) +process.exit(status) diff --git a/test/oracle/twins/diff_already_joined.expected b/test/oracle/twins/diff_already_joined.expected new file mode 100644 index 0000000..50acfd3 --- /dev/null +++ b/test/oracle/twins/diff_already_joined.expected @@ -0,0 +1,2 @@ +the first join: a room +the second join: the room of the first join diff --git a/test/oracle/twins/diff_already_joined.mjs b/test/oracle/twins/diff_already_joined.mjs new file mode 100644 index 0000000..fb4115c --- /dev/null +++ b/test/oracle/twins/diff_already_joined.mjs @@ -0,0 +1,14 @@ +// 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 {joinRoom} from 'trystero' + +const config = {appId: 'webcpp-trystero-differences', relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}} +const first = joinRoom(config, 'lobby') +const second = joinRoom(config, 'lobby') +console.log('the first join: a room') +console.log(`the second join: ${second === first ? 'the room of the first join' : 'another room'}`) +await first.leave() diff --git a/test/oracle/twins/diff_json_numbers.expected b/test/oracle/twins/diff_json_numbers.expected new file mode 100644 index 0000000..b615a84 --- /dev/null +++ b/test/oracle/twins/diff_json_numbers.expected @@ -0,0 +1,3 @@ +9007199254740993 arrives as 9007199254740992 +0.1000000000000000000000000000000001 arrives as 0.1 +1e999 arrives as null diff --git a/test/oracle/twins/diff_json_numbers.mjs b/test/oracle/twins/diff_json_numbers.mjs new file mode 100644 index 0000000..45c1405 --- /dev/null +++ b/test/oracle/twins/diff_json_numbers.mjs @@ -0,0 +1,40 @@ +// 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 {joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node. +const config = { + appId: 'webcpp-trystero-differences', + relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}, + rtcConfig: {iceServers: []}, +} +// The other peer, another page, which posts what it receives for this page to print. +const other = openPage(async ({joinRoom, RTCPeerConnection, data, post, next}) => { + const room = joinRoom({...data, rtcPolyfill: RTCPeerConnection}, 'lobby') + room.makeAction('payload').onMessage = received => post(received) + await next() + await room.leave() +}, config) +const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby') + +// tag::example[] +// The numbers of the payload's JSON text, none of which a double holds: an integer past 2^53, a +// decimal of 34 digits, and a number past a double's range. +const numbers = ['9007199254740993', '0.1000000000000000000000000000000001', '1e999'] +const text = `[${numbers.join(',')}]` +// This page sends the payload its JSON text makes, once it meets the other peer. +const payload = room.makeAction('payload') +await new Promise(joined => (room.onPeerJoin = joined)) +await payload.send(JSON.parse(text)) +// What the other peer receives, number by number. +const received = await other.next() +numbers.forEach((number, i) => console.log(`${number} arrives as ${JSON.stringify(received[i])}`)) +// end::example[] +other.post('leave') +await Promise.all([room.leave(), other.done]) diff --git a/test/oracle/twins/diff_json_refused.expected b/test/oracle/twins/diff_json_refused.expected new file mode 100644 index 0000000..069074d --- /dev/null +++ b/test/oracle/twins/diff_json_refused.expected @@ -0,0 +1,4 @@ +the payload nested 257 deep: delivered +the payload holding a lone surrogate: delivered +the payload of 1,000 zeros: delivered +the payload sent after them: delivered diff --git a/test/oracle/twins/diff_json_refused.mjs b/test/oracle/twins/diff_json_refused.mjs new file mode 100644 index 0000000..e207ef4 --- /dev/null +++ b/test/oracle/twins/diff_json_refused.mjs @@ -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) + +import {joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node. +const config = { + appId: 'webcpp-trystero-differences', + relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}, + rtcConfig: {iceServers: []}, +} +// The payloads the other peer sends, as JSON text, each an array of its label and a value: one +// nested 257 deep, one holding a lone surrogate, an array of 1,000 zeros, and a last one sent +// after them. +const payloads = [ + ['nested 257 deep', '['.repeat(256) + ']'.repeat(256)], + ['holding a lone surrogate', '"\\ud800"'], + ['of 1,000 zeros', JSON.stringify(new Array(1000).fill(0))], + ['sent after them', '"plain"'], +] +// The other peer, another page, which sends each payload JSON.parse makes of its text once it +// meets this page, each once the one before is sent. +const other = openPage(async ({joinRoom, RTCPeerConnection, data: {config, texts}, next}) => { + const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby') + const payload = room.makeAction('payload') + await new Promise(joined => (room.onPeerJoin = joined)) + for (const text of texts) await payload.send(JSON.parse(text)) + await next() + await room.leave() +}, {config, texts: payloads.map(([label, value]) => `["${label}",${value}]`)}) +const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby') + +// tag::example[] +// What this page delivers of them, by label, once the last has come. +const payload = room.makeAction('payload') +const delivered = [] +await new Promise(last => { + payload.onMessage = ([label]) => { + delivered.push(label) + if (label === payloads.at(-1)[0]) last() + } +}) +for (const [label] of payloads) { + console.log(`the payload ${label}: ${delivered.includes(label) ? 'delivered' : 'not delivered'}`) +} +// end::example[] +other.post('leave') +await Promise.all([room.leave(), other.done]) diff --git a/test/oracle/twins/diff_passwords.expected b/test/oracle/twins/diff_passwords.expected new file mode 100644 index 0000000..84226ed --- /dev/null +++ b/test/oracle/twins/diff_passwords.expected @@ -0,0 +1,3 @@ +the lobby, with the password "one": joined +the kitchen, with the password "two": joined +the peer in both rooms: one peer diff --git a/test/oracle/twins/diff_passwords.mjs b/test/oracle/twins/diff_passwords.mjs new file mode 100644 index 0000000..26ebc3d --- /dev/null +++ b/test/oracle/twins/diff_passwords.mjs @@ -0,0 +1,37 @@ +// 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 {joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node. +const config = { + appId: 'webcpp-trystero-differences', + relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}, + rtcConfig: {iceServers: []}, +} +// The other peer, another page, with the same passwords for the same rooms. +const other = openPage(async ({joinRoom, RTCPeerConnection, data, next}) => { + const lobby = joinRoom({...data, password: 'one', rtcPolyfill: RTCPeerConnection}, 'lobby') + const kitchen = joinRoom({...data, password: 'two', rtcPolyfill: RTCPeerConnection}, 'kitchen') + await next() + await Promise.all([lobby.leave(), kitchen.leave()]) +}, config) + +// tag::example[] +// A password is a room's: one page joins rooms of different passwords. +const lobby = joinRoom({...config, password: 'one', rtcPolyfill: RTCPeerConnection}, 'lobby') +const kitchen = joinRoom({...config, password: 'two', rtcPolyfill: RTCPeerConnection}, 'kitchen') +// What the two rooms meet. +const met = room => new Promise(joined => (room.onPeerJoin = joined)) +const [inLobby, inKitchen] = await Promise.all([met(lobby), met(kitchen)]) +console.log('the lobby, with the password "one": joined') +console.log('the kitchen, with the password "two": joined') +console.log(`the peer in both rooms: ${inLobby === inKitchen ? 'one peer' : 'two peers'}`) +// end::example[] +other.post('leave') +await Promise.all([lobby.leave(), kitchen.leave(), other.done]) diff --git a/test/oracle/twins/diff_peer_join.expected b/test/oracle/twins/diff_peer_join.expected new file mode 100644 index 0000000..a3a2255 --- /dev/null +++ b/test/oracle/twins/diff_peer_join.expected @@ -0,0 +1,3 @@ +the handler set before the join: called +the handler set after the join: called +peers: 1 diff --git a/test/oracle/twins/diff_peer_join.mjs b/test/oracle/twins/diff_peer_join.mjs new file mode 100644 index 0000000..a7d6e42 --- /dev/null +++ b/test/oracle/twins/diff_peer_join.mjs @@ -0,0 +1,37 @@ +// 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 {joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node. +const config = { + appId: 'webcpp-trystero-differences', + relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}, + rtcConfig: {iceServers: []}, +} +const other = openPage(async ({joinRoom, RTCPeerConnection, data, next}) => { + const room = joinRoom({...data, rtcPolyfill: RTCPeerConnection}, 'lobby') + await next() + await room.leave() +}, config) +const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby') + +// tag::example[] +await new Promise(joined => { + room.onPeerJoin = () => { + console.log('the handler set before the join: called') + joined() + } +}) +let lateCalls = 0 +room.onPeerJoin = () => ++lateCalls +console.log(`the handler set after the join: ${lateCalls === 0 ? 'not called' : 'called'}`) +console.log(`peers: ${Object.keys(room.getPeers()).length}`) +// end::example[] +other.post('leave') +await Promise.all([room.leave(), other.done]) diff --git a/test/oracle/twins/diff_peers.expected b/test/oracle/twins/diff_peers.expected new file mode 100644 index 0000000..cb96a48 --- /dev/null +++ b/test/oracle/twins/diff_peers.expected @@ -0,0 +1,2 @@ +peers: 1 +the joined peer's entry: its RTCPeerConnection diff --git a/test/oracle/twins/diff_peers.mjs b/test/oracle/twins/diff_peers.mjs new file mode 100644 index 0000000..0927f6c --- /dev/null +++ b/test/oracle/twins/diff_peers.mjs @@ -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) + +import {joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node. +const config = { + appId: 'webcpp-trystero-differences', + relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}, + rtcConfig: {iceServers: []}, +} +const other = openPage(async ({joinRoom, RTCPeerConnection, data, next}) => { + const room = joinRoom({...data, rtcPolyfill: RTCPeerConnection}, 'lobby') + await next() + await room.leave() +}, config) +const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby') + +// tag::example[] +const peerId = await new Promise(joined => { + room.onPeerJoin = joined +}) +const peers = room.getPeers() +console.log(`peers: ${Object.keys(peers).length}`) +console.log(`the joined peer's entry: its ${peers[peerId].constructor.name}`) +// end::example[] +other.post('leave') +await Promise.all([room.leave(), other.done]) diff --git a/test/oracle/twins/diff_relay_config.expected b/test/oracle/twins/diff_relay_config.expected new file mode 100644 index 0000000..0e8fada --- /dev/null +++ b/test/oracle/twins/diff_relay_config.expected @@ -0,0 +1,4 @@ +the lobby's relays: the first configuration's +the kitchen's relays: the first configuration's +the lobby's connection: the first configuration's ICE servers +the kitchen's connection: the first configuration's ICE servers diff --git a/test/oracle/twins/diff_relay_config.mjs b/test/oracle/twins/diff_relay_config.mjs new file mode 100644 index 0000000..2559ffd --- /dev/null +++ b/test/oracle/twins/diff_relay_config.mjs @@ -0,0 +1,58 @@ +// 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 {getRelaySockets, joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +const relay = process.env.TRYSTERO_RELAY_URL +const config = {appId: 'webcpp-trystero-differences', rtcPolyfill: RTCPeerConnection} +// Two configurations. The second relay is the same local relay under a path, which it accepts as +// it accepts any, and its STUN server one where nothing answers; the first has no ICE server, so +// that the peers meet on this machine alone. +const first = {relayConfig: {urls: [relay]}, rtcConfig: {iceServers: []}} +const second = { + relayConfig: {urls: [`${relay}/second`]}, + rtcConfig: {iceServers: [{urls: 'stun:127.0.0.1:19'}]}, +} +// The other peer, another page: the lobby with the first configuration, then, once this page asks, +// the kitchen with the second. +const other = openPage(async ({joinRoom, RTCPeerConnection, data: {first, second}, next}) => { + const config = {appId: 'webcpp-trystero-differences', rtcPolyfill: RTCPeerConnection} + const lobby = joinRoom({...config, ...first}, 'lobby') + await next() + const kitchen = joinRoom({...config, ...second}, 'kitchen') + await next() + await Promise.all([lobby.leave(), kitchen.leave()]) +}, {first, second}) +// The configuration whose URLs, and only they, are `urls`, each configuration's read by `urlsOf`. +const which = (urls, urlsOf) => { + const same = c => JSON.stringify([...urls].sort()) === JSON.stringify([...urlsOf(c)].sort()) + return same(first) ? "the first configuration's" : same(second) ? "the second configuration's" : 'another' +} +// The relays the rooms use: the page's relay sockets, which every room of the page shares. +const relaysOf = () => which(Object.keys(getRelaySockets()), c => c.relayConfig.urls) +// The ICE servers of the connection a room meets a peer on. +const iceUrls = rtcConfig => rtcConfig.iceServers.flatMap(server => [server.urls].flat()) +const iceServersOf = (room, peer) => + which(iceUrls(room.getPeers()[peer].getConfiguration()), c => iceUrls(c.rtcConfig)) +const met = room => new Promise(joined => (room.onPeerJoin = joined)) + +// tag::example[] +// A configuration is a room's: each room is joined with its own. +const lobby = joinRoom({...config, ...first}, 'lobby') +const lobbyPeer = await met(lobby) +// The kitchen, joined with the second configuration once the lobby has met the other peer. +other.post('kitchen') +const kitchen = joinRoom({...config, ...second}, 'kitchen') +const kitchenPeer = await met(kitchen) +console.log(`the lobby's relays: ${relaysOf()}`) +console.log(`the kitchen's relays: ${relaysOf()}`) +console.log(`the lobby's connection: ${iceServersOf(lobby, lobbyPeer)} ICE servers`) +console.log(`the kitchen's connection: ${iceServersOf(kitchen, kitchenPeer)} ICE servers`) +// end::example[] +other.post('leave') +await Promise.all([lobby.leave(), kitchen.leave(), other.done]) diff --git a/test/oracle/twins/diff_relay_sockets.expected b/test/oracle/twins/diff_relay_sockets.expected new file mode 100644 index 0000000..1769009 --- /dev/null +++ b/test/oracle/twins/diff_relay_sockets.expected @@ -0,0 +1 @@ +the WebSockets the two rooms opened to their one relay: 1 diff --git a/test/oracle/twins/diff_relay_sockets.mjs b/test/oracle/twins/diff_relay_sockets.mjs new file mode 100644 index 0000000..781962a --- /dev/null +++ b/test/oracle/twins/diff_relay_sockets.mjs @@ -0,0 +1,16 @@ +// 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 {getRelaySockets, joinRoom} from 'trystero' + +const config = {appId: 'webcpp-trystero-differences', relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}} +// tag::example[] +const lobby = joinRoom(config, 'lobby') +const kitchen = joinRoom(config, 'kitchen') +const sockets = Object.values(getRelaySockets()) +console.log(`the WebSockets the two rooms opened to their one relay: ${sockets.length}`) +// end::example[] +await Promise.all([lobby.leave(), kitchen.leave()]) diff --git a/test/oracle/twins/diff_rooms_per_app.expected b/test/oracle/twins/diff_rooms_per_app.expected new file mode 100644 index 0000000..ba57790 --- /dev/null +++ b/test/oracle/twins/diff_rooms_per_app.expected @@ -0,0 +1,4 @@ +joins 1 to 64: 64 rooms +join 65: a room +join 66, while room 1 is leaving: a room +join 67, once room 1 has left: a room diff --git a/test/oracle/twins/diff_rooms_per_app.mjs b/test/oracle/twins/diff_rooms_per_app.mjs new file mode 100644 index 0000000..e54c353 --- /dev/null +++ b/test/oracle/twins/diff_rooms_per_app.mjs @@ -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) + +import {joinRoom} from 'trystero' + +const config = {appId: 'webcpp-trystero-differences', relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}} +const rooms = [] +// What a join gives, a room kept until the end or the error that refused it. +const join = roomId => { + try { + rooms.push(joinRoom(config, roomId)) + return 'a room' + } catch (error) { + return error.message + } +} +// tag::example[] +for (let n = 1; n <= 64; ++n) join(`room-${n}`) +console.log(`joins 1 to 64: ${rooms.length} rooms`) +console.log(`join 65: ${join('room-65')}`) +const leaving = rooms[0].leave() +console.log(`join 66, while room 1 is leaving: ${join('room-66')}`) +await leaving +console.log(`join 67, once room 1 has left: ${join('room-67')}`) +// end::example[] +await Promise.all(rooms.slice(1).map(room => room.leave())) diff --git a/test/oracle/twins/diff_self_id.expected b/test/oracle/twins/diff_self_id.expected new file mode 100644 index 0000000..c36229e --- /dev/null +++ b/test/oracle/twins/diff_self_id.expected @@ -0,0 +1,2 @@ +two rooms of one app: one id +rooms of two apps: one id diff --git a/test/oracle/twins/diff_self_id.mjs b/test/oracle/twins/diff_self_id.mjs new file mode 100644 index 0000000..56259df --- /dev/null +++ b/test/oracle/twins/diff_self_id.mjs @@ -0,0 +1,39 @@ +// 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 {joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node. +const config = { + relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}, + rtcConfig: {iceServers: []}, +} +const firstApp = 'webcpp-trystero-differences' +const secondApp = 'webcpp-trystero-differences-second' +// The other peer, another page, in the rooms this page joins: it posts the id it meets first in +// each. +const other = openPage(async ({joinRoom, RTCPeerConnection, data, post, next}) => { + const {config, firstApp, secondApp} = data + const join = (appId, roomId) => joinRoom({...config, appId, rtcPolyfill: RTCPeerConnection}, roomId) + const rooms = [join(firstApp, 'lobby'), join(firstApp, 'kitchen'), join(secondApp, 'lobby')] + post(await Promise.all(rooms.map(room => new Promise(met => (room.onPeerJoin = met))))) + await next() + await Promise.all(rooms.map(room => room.leave())) +}, {config, firstApp, secondApp}) + +// tag::example[] +// Every room of the page announces the page's selfId, which Trystero draws once, as it loads. +const join = (appId, roomId) => joinRoom({...config, appId, rtcPolyfill: RTCPeerConnection}, roomId) +const rooms = [join(firstApp, 'lobby'), join(firstApp, 'kitchen'), join(secondApp, 'lobby')] +// What the other peer meets in those three rooms. +const [inLobby, inKitchen, inSecondLobby] = await other.next() +console.log(`two rooms of one app: ${inLobby === inKitchen ? 'one id' : 'two ids'}`) +console.log(`rooms of two apps: ${inLobby === inSecondLobby ? 'one id' : 'two ids'}`) +// end::example[] +other.post('leave') +await Promise.all([...rooms.map(room => room.leave()), other.done]) diff --git a/test/oracle/twins/diff_send_to_absent_peer.expected b/test/oracle/twins/diff_send_to_absent_peer.expected new file mode 100644 index 0000000..a4169e1 --- /dev/null +++ b/test/oracle/twins/diff_send_to_absent_peer.expected @@ -0,0 +1 @@ +the send to a peer that has not joined: succeeded diff --git a/test/oracle/twins/diff_send_to_absent_peer.mjs b/test/oracle/twins/diff_send_to_absent_peer.mjs new file mode 100644 index 0000000..e79a732 --- /dev/null +++ b/test/oracle/twins/diff_send_to_absent_peer.mjs @@ -0,0 +1,19 @@ +// 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 {joinRoom} from 'trystero' + +const config = {appId: 'webcpp-trystero-differences', relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}} +const room = joinRoom(config, 'lobby') +// tag::example[] +const greeting = room.makeAction('greeting') +const outcome = await greeting.send('hello', {target: 'a-peer-that-has-not-joined'}).then( + () => 'succeeded', + error => `failed: ${error.message}`, +) +console.log(`the send to a peer that has not joined: ${outcome}`) +// end::example[] +await room.leave() diff --git a/test/oracle/twins/quick_start.mjs b/test/oracle/twins/quick_start.mjs new file mode 100644 index 0000000..3d2a7ec --- /dev/null +++ b/test/oracle/twins/quick_start.mjs @@ -0,0 +1,42 @@ +// 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 {joinRoom} from 'trystero' +import {RTCPeerConnection} from 'werift' +import {openPage} from '../page.mjs' + +// Trystero draws one selfId per page, so bob is another page, and each peer prints the other's +// name where the C++ program prints the ids it gave its apps. The peers meet on this machine +// alone: no ICE server, werift's WebRTC for Node. +const config = { + appId: 'webcpp-trystero-quick-start', + relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}, + rtcConfig: {iceServers: []}, +} + +// bob's part: waits for a message, posts the line the twin prints for it, answers its sender, and +// leaves the room. +const bob = openPage(async ({joinRoom, RTCPeerConnection, data, post}) => { + const room = joinRoom({...data, rtcPolyfill: RTCPeerConnection}, 'lobby') + const chat = room.makeAction('chat') + const [text, {peerId}] = await new Promise(received => { + chat.onMessage = (...message) => received(message) + }) + post(`alice: ${text}`) + await chat.send('hello back', {target: peerId}) + await room.leave() +}, config) + +// alice greets each peer that joins, prints the answer, and leaves. +const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby') +const chat = room.makeAction('chat') +room.onPeerJoin = peerId => chat.send('hello', {target: peerId}) +const answer = new Promise(received => { + chat.onMessage = text => received(text) +}) +console.log(await bob.next()) +console.log(`bob: ${await answer}`) +await Promise.all([room.leave(), bob.done]) diff --git a/test/oracle/twins/without-twin.txt b/test/oracle/twins/without-twin.txt new file mode 100644 index 0000000..b34e059 --- /dev/null +++ b/test/oracle/twins/without-twin.txt @@ -0,0 +1,12 @@ +# 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 examples that have no twin, each with the reason. Every other program +# of example/ has its twin beside this file (tools/oracle/twins.py), which +# runs over a relay of its own on 127.0.0.1 (../run_twin.mjs): a relay is not +# what keeps those below from one. +chat/chat: a page: its program draws what happens in the room into the page, prints nothing, and runs as long as the tab; a twin would be a page too, with nothing printed to compare +diff_self_id_not_utf8: Trystero JS draws its selfId when its module loads and takes none from a program, so no program of Trystero's can give it an id, nor one that is not UTF-8 diff --git a/test/platform_backend_test.cpp b/test/platform_backend_test.cpp new file mode 100644 index 0000000..dc43d1a --- /dev/null +++ b/test/platform_backend_test.cpp @@ -0,0 +1,182 @@ +// 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) + +// Tests the platform backend itself, on both targets, natively and in a page under node: +// +// - Its own state, its copy of the bind address, its window of constructions and its own +// webcpp::webrtc runtime, is in `backend_config::memory`, and the default resource sees none of +// it; all of it is given back when the backend is destroyed. Before, the backend made its window +// and its runtime in the default resource. +// - Its clocks are the standard library's: the wall clock's whole seconds, as the test reads them, +// and the steady clock, which a 20 ms wait moves forward. +// - Its randomness fills what it is given, differently each time, also beyond a piece of the +// platform's source (65536 bytes in a page). +// - Its executor is the one it was given, and its relays' TLS context was made. +// +// main runs the io_context for the wait; a wait that does not come within 10 s fails by name. + +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bookkeeping.hpp" +#include "cases.hpp" + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +namespace { + +/** A resource that counts what it gives, and what is still out. */ +class counting_resource final : public std::pmr::memory_resource { +public: + /** How many allocations it made, a standard container's own (bookkeeping.hpp) left out: a + * moved string's proxy, on MSVC's debug STL, is no state of the backend's. */ + std::size_t allocations = 0; + /** How many of them are not yet returned, every one counted. */ + std::size_t outstanding = 0; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + if (!webcpp::test::is_bookkeeping(bytes, alignment)) { + ++allocations; + } + ++outstanding; + return std::pmr::new_delete_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + --outstanding; + 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; + } +}; + +/** The default resource, replaced by `with` for the life of the object. */ +class default_resource { +public: + explicit default_resource(std::pmr::memory_resource* with) + : previous_(std::pmr::set_default_resource(with)) {} + + default_resource(const default_resource&) = delete; + default_resource& operator=(const default_resource&) = delete; + + ~default_resource() { std::pmr::set_default_resource(previous_); } + +private: + std::pmr::memory_resource* previous_; +}; + +void its_own_state_is_in_its_memory() { + asio::io_context io; + counting_resource memory; + counting_resource elsewhere; + { + // An address longer than a string holds in place, which the backend copies. + std::pmr::string address("0000:0000:0000:0000:0000:0000:0000:0001", &elsewhere); + const default_resource guard(&elsewhere); + const std::size_t before = elsewhere.allocations; + const trystero::platform::backend backend( + io.get_executor(), {.bind_address = std::move(address), .memory = &memory}); + BOOST_TEST_EQ(elsewhere.allocations, before); + // The address, the window and the runtime. + BOOST_TEST_GE(memory.allocations, 3U); + } + BOOST_TEST_EQ(memory.outstanding, 0U); +} + +void its_clocks_are_the_standard_librarys() { + asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + const auto before = std::chrono::floor(std::chrono::system_clock::now()); + const std::chrono::sys_seconds read = backend.unix_now(); + BOOST_TEST(before <= read); + BOOST_TEST(read <= before + 1s); + + const auto start = backend.steady_now(); + asio::steady_timer wait(io, 20ms); + std::optional waited; + wait.async_wait([&](boost::system::error_code) { waited = backend.steady_now() - start; }); + io.run_for(10s); // lint-run: the test's 20 ms wait + if (BOOST_TEST(waited.has_value())) { + BOOST_TEST(*waited >= 19ms); // a whole millisecond of the steady clock's rounding + } +} + +void its_randomness_fills_and_differs() { + asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + std::array first{}; + std::array second{}; + backend.random(first); + backend.random(second); + BOOST_TEST(first != second); + BOOST_TEST(std::ranges::any_of(first, [](std::uint8_t b) { return b != 0; })); +} + +// More than one piece of the platform's source, which a page fills at most 65536 bytes a call (and +// the C library's entropy call 256): every 256 bytes, the last few included, are filled, and +// differently each time. On the heap, beyond a page's stack. +void its_randomness_fills_more_than_a_piece() { + asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + constexpr std::size_t size = (2 * 65536) + 300; + constexpr std::size_t stride = 256; + std::vector first(size); + std::vector second(size); + backend.random(first); + backend.random(second); + std::size_t unfilled = 0; + std::size_t repeated = 0; + for (std::size_t at = 0; at < size; at += stride) { + const auto end = std::min(size, at + stride); + const auto a = std::span(first).subspan(at, end - at); + const auto b = std::span(second).subspan(at, end - at); + unfilled += std::ranges::all_of(a, [](std::uint8_t byte) { return byte == 0; }) ? 1 : 0; + repeated += std::ranges::equal(a, b) ? 1 : 0; + } + BOOST_TEST_EQ(unfilled, 0U); + BOOST_TEST_EQ(repeated, 0U); +} + +void its_executor_and_tls_context_are_there() { + asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + BOOST_TEST(backend.get_executor() == asio::any_io_executor(io.get_executor())); + BOOST_TEST(backend.tls_context().has_value()); +} + +} // namespace + +int main() { + // Each case in a frame of its own, which main's never holds (cases.hpp). + using webcpp::test::run_case; + run_case(its_own_state_is_in_its_memory); + run_case(its_clocks_are_the_standard_librarys); + run_case(its_randomness_fills_and_differs); + run_case(its_randomness_fills_more_than_a_piece); + run_case(its_executor_and_tls_context_are_there); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_call_test.cpp b/test/platform_page_call_test.cpp new file mode 100644 index 0000000..7e8434b --- /dev/null +++ b/test/platform_page_call_test.cpp @@ -0,0 +1,213 @@ +// 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) + +// Tests the lifetimes of a page's calls into C++, `platform::page_call`, under node, in a program +// whose main runs its io_context under a work guard, as a page's does: +// +// - A call's handler is given the page's value as it is when the handler runs: the page passes an +// object and changes it before the run resumes, and the handler sees it changed. +// - A handler reads a number as a double and checks its range before it makes it an integer, as +// page.hpp says: 1e10, -1e10, 2.5, NaN, a string and undefined are no 32-bit integer, and none +// throws. Before the fix the test read `isNumber() ? as()`, which for 1e10 throws a +// TypeError in a build with assertions. +// - A JavaScript function the page kept after its page_call was destroyed reaches nothing and +// breaks nothing: the page calls it from a timer, while the run is suspended, and the call +// returns undefined and runs nothing, and the page's next call, of another page_call, reaches +// C++. +// - A page_call that outlives its io_context is harmless: a call the page made before the +// io_context was destroyed is destroyed with it, unrun, and gives its memory back to the +// page_call's resource; then `function()` returns undefined, the function the page kept reaches +// nothing, and the page_call is destroyed after the io_context. +// +// main ends with the errors counted once the run returns; a step that does not come within 10 s +// fails by name. + +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using emscripten::val; +using namespace std::chrono_literals; + +namespace { + +/** A resource over the default one that counts the bytes it gave and has not taken back. */ +class counting_resource final : public std::pmr::memory_resource { +public: + std::size_t outstanding = 0; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + outstanding += bytes; + return std::pmr::get_default_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* pointer, std::size_t bytes, std::size_t alignment) override { + outstanding -= bytes; + std::pmr::get_default_resource()->deallocate(pointer, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } +}; + +struct program; + +/** What a page_call of the test runs: a step of the program, given the page's value. */ +struct step { + program* p; + void (*run)(program&, const val&); + + void operator()(const val& argument) const { run(*p, argument); } +}; + +using call = trystero::platform::page_call; + +/** What the page keeps alive: the io_context, its guard, and its calls. */ +struct program { + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + std::optional doomed; + std::optional next; + std::size_t stage = 0; + std::int32_t seen_n = 0; + std::size_t doomed_calls = 0; + std::size_t orphan_calls = 0; + bool judged = false; +}; + +/** + * A page_call on an io_context destroyed before it: the call the page made meanwhile is destroyed + * unrun, with its memory given back, and nothing reaches C++ from then on. + */ +void outlive_the_io_context(program& p) { + // Declared first, so that it outlives both the io_context and the page_call. + counting_resource memory; + std::optional orphan; + std::optional other(std::in_place); + orphan.emplace( + other->get_executor(), + step{.p = &p, .run = [](program& q, const val& /*argument*/) { ++q.orphan_calls; }}, + &memory); + const std::size_t made = memory.outstanding; + const val kept = orphan->function(); + // Posted to the other io_context, which never runs. + BOOST_TEST(kept(1).isUndefined()); + BOOST_TEST_GT(memory.outstanding, made); + other.reset(); + BOOST_TEST_EQ(memory.outstanding, made); + BOOST_TEST(orphan->function().isUndefined()); + BOOST_TEST(kept(2).isUndefined()); + orphan.reset(); + BOOST_TEST_EQ(memory.outstanding, 0U); + BOOST_TEST_EQ(p.orphan_calls, 0U); +} + +/** + * The page's value as a 32-bit integer, or nothing when it is no number in that range: its type is + * checked first, and its range as a double, since embind's `as()` of a number beyond + * the range, as 1e10, throws a TypeError in a build with assertions. + */ +std::optional read_int32(const val& value) { + if (!value.isNumber()) { + return std::nullopt; + } + const auto number = value.as(); + // NaN fails every comparison, and so the first. + if (!(number >= std::numeric_limits::min()) || + number > std::numeric_limits::max() || number != std::trunc(number)) { + return std::nullopt; + } + return static_cast(number); +} + +/** What a page_call's handler reads of a number, whatever the page passed. */ +void numbers_are_read_within_their_range() { + BOOST_TEST(read_int32(val(2)) == std::optional(2)); + BOOST_TEST(read_int32(val(-2147483648.0)) == + std::optional(std::numeric_limits::min())); + BOOST_TEST(!read_int32(val(1e10)).has_value()); + BOOST_TEST(!read_int32(val(-1e10)).has_value()); + BOOST_TEST(!read_int32(val(2.5)).has_value()); + BOOST_TEST(!read_int32(val::global("NaN")).has_value()); + BOOST_TEST(!read_int32(val("2")).has_value()); + BOOST_TEST(!read_int32(val::undefined()).has_value()); +} + +/** + * Each call of the page's `next`: reads the page's object and destroys the doomed page_call, then + * judges what followed. + */ +void advance(program& p, const val& argument) { + if (p.stage++ == 0) { + // The page's value is checked before it is read, as a page_call's handler does. + if (!argument.isNull() && !argument.isUndefined()) { + p.seen_n = read_int32(argument["n"]).value_or(-1); + } + p.doomed.reset(); + // The page calls the function it kept, then the next. + EM_ASM({ + setTimeout( + function() { + globalThis.keptReturned = globalThis.kept("late"); + globalThis.next(null); + }, + 0); + }); + return; + } + BOOST_TEST_EQ(p.seen_n, 2); + BOOST_TEST(val::global("keptReturned").isUndefined()); + BOOST_TEST_EQ(p.doomed_calls, 0U); + outlive_the_io_context(p); + p.judged = true; + p.guard.reset(); +} + +} // namespace + +int main() { + numbers_are_read_within_their_range(); + program p; + p.doomed.emplace( + p.io.get_executor(), + step{.p = &p, .run = [](program& q, const val& /*argument*/) { ++q.doomed_calls; }}); + p.next.emplace(p.io.get_executor(), step{.p = &p, .run = advance}); + // clang-format off + EM_ASM(({ + globalThis.kept = Emval.toValue($0); + globalThis.next = Emval.toValue($1); + globalThis.keptReturned = "not called"; + setTimeout(() => { + const value = {n: 1}; + globalThis.next(value); + value.n = 2; + }, 0); + }), p.doomed->function().as_handle(), p.next->function().as_handle()); + // clang-format on + p.io.run_for(10s); // lint-run: the page's program, held by its work guard until the verdict + if (!p.judged) { + BOOST_ERROR("the page's calls stopped before the verdict"); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_data_channel_test.cpp b/test/platform_page_data_channel_test.cpp new file mode 100644 index 0000000..b413cce --- /dev/null +++ b/test/platform_page_data_channel_test.cpp @@ -0,0 +1,139 @@ +// 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) + +// Tests the platform backend's data channels in a page, webcpp::webrtc's, under node, over plain +// objects in +// place of the page's RTCPeerConnection and RTCDataChannel: what a peer can send that is no frame +// is dropped. A text message "1e300" once threw a RangeError out of `new Uint8Array`, and +// "300000000" made a 300 MB frame: webcpp::webrtc delivers a text as the few bytes it holds, which +// the channel drops; a binary message larger than any room frame is dropped too. Only the frame +// sent last reaches the handler, and nothing larger than the largest message sent is allocated. +// +// main runs the io_context under a work guard, which the verdict releases when the last frame +// arrives; a frame that does not come within 10 s fails by name. + +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "require.hpp" + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using emscripten::val; +using namespace std::chrono_literals; + +namespace { + +/** A resource that remembers the largest allocation it made. */ +class watching_resource final : public std::pmr::memory_resource { +public: + std::size_t largest = 0; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + largest = std::max(largest, bytes); + 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; + } +}; + +struct state { + watching_resource memory; + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; + std::shared_ptr connection; + std::shared_ptr wrapper; + std::size_t messages = 0; + std::size_t last_size = 0; +}; + +/** Delivers `data` to the channel's `onmessage` from a timer, as the page delivers a message. */ +void deliver(const val& data) { + val event = val::object(); + event.set("data", data); + val::global("setTimeout")(val::global("lastChannel")["onmessage"], val(0), event); +} + +} // namespace + +int main() { + state s; + // A connection whose channel is open from the start, and which the test reaches as + // lastChannel. + EM_ASM({ + globalThis.RTCPeerConnection = class { + constructor() { + this.connectionState = 'new'; + this.iceConnectionState = 'new'; + this.localDescription = null; + this.remoteDescription = null; + } + createDataChannel(label) { + const channel = {}; + channel.label = label; + channel.readyState = 'open'; + channel.bufferedAmount = 0; + channel.send = function(){}; + channel.close = function(){}; + globalThis.lastChannel = channel; + return channel; + } + close() {} + }; + }); + s.connection = s.backend.make_peer_connection({}, &s.memory); + webcpp::test::require(BOOST_TEST(s.connection != nullptr)); + s.wrapper = s.connection->create_data_channel("data"); + webcpp::test::require(BOOST_TEST(s.wrapper != nullptr)); + s.wrapper->set_handlers({ + .open = {}, + .message = + [&s](const trystero::backend::bytes& frame) { + ++s.messages; + s.last_size = frame.size(); + s.guard.reset(); + s.io.stop(); + }, + .close = {}, + .buffered_amount_low = {}, + }); + + deliver(val("1e300")); + deliver(val("300000000")); + deliver(val::global("ArrayBuffer").new_(val(20'000))); + deliver(val::global("ArrayBuffer").new_(val(3))); + + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the verdict + if (s.messages == 0) { + BOOST_ERROR("the frame sent last never arrived"); + } + // The first frame to arrive is the last one sent: the run stopped there. + BOOST_TEST_EQ(s.messages, 1U); + BOOST_TEST_EQ(s.last_size, 3U); + BOOST_TEST_LE(s.memory.largest, std::size_t{20'000}); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_handlers_test.cpp b/test/platform_page_handlers_test.cpp new file mode 100644 index 0000000..6cf91e9 --- /dev/null +++ b/test/platform_page_handlers_test.cpp @@ -0,0 +1,209 @@ +// 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) + +// Tests that the platform backend's handlers in a page run outside the page's events, under node: +// a relay socket's open, message and close handlers, over a stand-in for the page's WebSocket, and +// a sealer's completions of a seal and an open, through the page's Web Crypto, each find +// webcpp::asio's bridge delivering nothing (`bridge::delivering()` false): the page's event, or the +// settlement of a promise, only posts to the io_context, and the run family runs the handler after +// it. A probe proves that the check sees a delivery: inside a call of a bridge's function, which a +// page's event is, `delivering()` is true. +// +// main runs the io_context under a work guard, as a page's program does; once the socket reported +// its close and the sealer opened what it sealed, the verdict releases the guard. A step that does +// not come within 10 s fails by name. + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using emscripten::val; +using namespace std::chrono_literals; + +// The stand-in relay: it opens on the next turn, answers the first text sent with a message event +// that carries it, and on the turn after, closes. Its events are a page's: each names its type, and +// a close its code and reason. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, install_echo_websocket, (), { + globalThis.WebSocket = class { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + constructor(url) { + this.url = url; + this.readyState = 0; + this.bufferedAmount = 0; + setTimeout(() => { + this.readyState = 1; + if (this.onopen) this.onopen({type: "open"}); + }, 0); + } + send(text) { + setTimeout(() => { + if (this.onmessage) this.onmessage({type: "message", data: text}); + setTimeout(() => { + this.readyState = 3; + if (this.onclose) this.onclose({type: "close", code: 1000, reason: "done"}); + }, 0); + }, 0); + } + close() { + this.readyState = 3; + } + }; +}); +// clang-format on + +namespace { + +/** A registration of the bridge's that records whether the bridge delivers while it is called. */ +class probe final : public asio::browser::registration { +public: + explicit probe(asio::browser::bridge& bridge) : bridge_(bridge) {} + + bool deliver(const val& /*event*/) override { + saw_delivering = bridge_.delivering(); + return false; + } + + void shutdown() noexcept override {} + + bool saw_delivering = false; + +private: + asio::browser::bridge& bridge_; +}; + +/** Where a handler ran: whether it ran at all, and whether inside a delivery of the bridge's. */ +struct seen { + bool ran = false; + bool inside_an_event = false; +}; + +struct state { + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; + std::shared_ptr socket; + std::shared_ptr sealer = + backend.make_sealer(trystero::protocol::seal_key("secret", "my-app", "room-1"), + std::pmr::get_default_resource()); + std::string echoed; + std::string opened; + seen open; + seen message; + seen close; + seen sealed; + seen opened_text; + bool judged = false; +}; + +/** Records that a handler ran, and whether the bridge was delivering an event while it did. */ +void record(state& s, seen& into) { + into.ran = true; + into.inside_an_event = asio::use_service(s.io).delivering(); +} + +/** Once the socket closed and the sealer opened what it sealed: the verdict. */ +void judge(state& s) { + if (!s.close.ran || !s.opened_text.ran) { + return; + } + s.socket.reset(); + s.judged = true; + s.guard.reset(); +} + +/** Seals a text, and opens what was sealed, recording where each completion ran. */ +void seal_and_open(state& s) { + s.sealer->seal("a candidate", [&s](boost::system::error_code ec, std::string_view text) { + record(s, s.sealed); + BOOST_TEST(!ec); + s.sealer->open(text, [&s](boost::system::error_code ec, std::string_view plain) { + record(s, s.opened_text); + BOOST_TEST(!ec); + s.opened = plain; + judge(s); + }); + }); +} + +/** Checks that a handler ran outside every event of the page's. */ +void expect_outside(const seen& got, const char* name) { + if (!got.ran) { + BOOST_ERROR(name); + return; + } + BOOST_TEST(!got.inside_an_event); +} + +} // namespace + +int main() { + install_echo_websocket(); + state s; + { + auto& bridge = asio::use_service(s.io); + probe p(bridge); + const std::uint64_t key = bridge.add(p); + bridge.function(key)(0); + bridge.remove(key); + BOOST_TEST(p.saw_delivering); + BOOST_TEST(!bridge.delivering()); + } + s.socket = s.backend.connect("wss://relay.test", + { + .open = + [&s] { + record(s, s.open); + s.socket->send("hello"); + }, + .message = + [&s](std::string_view text) { + record(s, s.message); + s.echoed = text; + }, + .close = + [&s] { + record(s, s.close); + judge(s); + }, + }, + std::pmr::get_default_resource()); + seal_and_open(s); + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the verdict + if (!s.judged) { + BOOST_ERROR("the socket's close or the sealer's open never came"); + } + expect_outside(s.open, "the socket's open handler never ran"); + expect_outside(s.message, "the socket's message handler never ran"); + expect_outside(s.close, "the socket's close handler never ran"); + expect_outside(s.sealed, "the seal never completed"); + expect_outside(s.opened_text, "the open never completed"); + BOOST_TEST_EQ(s.echoed, "hello"); + BOOST_TEST_EQ(s.opened, "a candidate"); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_peer_connection_test.cpp b/test/platform_page_peer_connection_test.cpp new file mode 100644 index 0000000..488c22d --- /dev/null +++ b/test/platform_page_peer_connection_test.cpp @@ -0,0 +1,180 @@ +// 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) + +// Tests the platform backend's peer connections in a page, webcpp::webrtc's, under node, which has +// no WebRTC of its own: when the page makes no `RTCPeerConnection` (none exists, or its constructor +// throws, as for a server it cannot use or with as many connections as the browser allows), the +// backend makes none and says so with a null connection, which the room reports, rather than +// letting the exception through; a connection whose `createDataChannel` throws, as a closed one's +// does, opens no channel. +// +// The page holds at most `runtime_options::max_peer_connections` of them, 256 by default, the cap +// of the backend's webcpp::webrtc runtime, counted by webcpp::webrtc's census of the page from +// their construction until the garbage collector frees them, as Chromium counts them: beyond, the +// backend makes none, closed or dropped connections still count, and once a collection frees them +// it makes one again. The backend's window, `backend_config::max_peer_connections_per_minute`, +// holds in a page as natively: a backend whose window is two makes no third connection within the +// minute, however many the census allows. The census's backend gets a window wider than all it +// makes here. +// +// main runs the checks that need no event, and runs the io_context, where a timer collects and +// looks every 10 ms for the census to count a connection less, the verdict; a verdict that does +// not come within 10 s fails by name. + +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using emscripten::val; +using namespace std::chrono_literals; + +namespace { + +/** The page's cap on its connections alive at once: the default of the backend's runtime. */ +constexpr std::size_t budget = webcpp::webrtc::runtime_options{}.max_peer_connections; + +struct state { + asio::io_context io; + trystero::platform::backend backend{io.get_executor(), + {.max_peer_connections_per_minute = 4 * budget}}; + asio::steady_timer look{io}; + bool done = false; +}; + +/** The connections webcpp::webrtc's census of the page counts. */ +std::size_t held() { + const val census = val::global( + "globalThis")[val::global("Symbol").call("for", val("webcpp.webrtc.census"))]; + return census.isUndefined() ? 0 : static_cast(census["held"].as()); +} + +/** Runs node's garbage collector, exposed for this test. */ +void collect() { + EM_ASM({ + require('v8').setFlagsFromString('--expose-gc'); + require('vm').runInNewContext('gc')(); + }); +} + +/** Once a collection released a connection, the backend makes one again; until then, it collects + * and looks again 10 ms later, while node runs the collection's finalizers. */ +void look_for_release(state& s) { + if (held() >= budget) { + collect(); + s.look.expires_after(10ms); + s.look.async_wait([&s](boost::system::error_code ec) { + if (!ec) { + look_for_release(s); + } + }); + return; + } + s.done = true; + BOOST_TEST(s.backend.make_peer_connection({}, std::pmr::get_default_resource()) != nullptr); + s.io.stop(); +} + +} // namespace + +int main() { + state s; + std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); + + // node has no RTCPeerConnection. + BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); + + // One whose constructor throws, as a browser's does at its limit of connections. + EM_ASM({ + globalThis.RTCPeerConnection = class { + constructor() { throw new DOMException('too many connections', 'OperationError'); } + }; + }); + BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); + BOOST_TEST_EQ(held(), 0); + + // One that is made, whose createDataChannel throws, as a closed connection's does. + EM_ASM({ + globalThis.RTCPeerConnection = class { + constructor() { + this.connectionState = 'new'; + this.iceConnectionState = 'new'; + this.localDescription = null; + this.remoteDescription = null; + } + createDataChannel() { throw new DOMException('closed', 'InvalidStateError'); } + close() {} + }; + }); + { + const auto pc = s.backend.make_peer_connection({}, memory); + if (BOOST_TEST(pc != nullptr)) { + BOOST_TEST(pc->create_data_channel("data") == nullptr); + pc->close(); + } + } + + // The backend's window: two in a minute, while the census has room for more. + { + trystero::platform::backend windowed(s.io.get_executor(), + {.max_peer_connections_per_minute = 2}); + const auto first = windowed.make_peer_connection({}, memory); + const auto second = windowed.make_peer_connection({}, memory); + BOOST_TEST(first != nullptr); + BOOST_TEST(second != nullptr); + BOOST_TEST(windowed.make_peer_connection({}, memory) == nullptr); + BOOST_TEST_EQ(held(), 3); + for (const auto& pc : {first, second}) { + if (pc) { + pc->close(); + } + } + } + + // The page's budget: the three above still count, closed and dropped. + { + std::vector> made; + for (std::size_t i = 0; i < budget; ++i) { + if (auto pc = s.backend.make_peer_connection({}, memory)) { + made.push_back(std::move(pc)); + } + } + BOOST_TEST_EQ(made.size(), budget - 3); + BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); + for (const auto& pc : made) { + pc->close(); + } + } + BOOST_TEST_EQ(held(), budget); + BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); + + // A collection frees them: node's gc, from a handler of the io_context, after the + // connections' own posted work; the census counts the release once the FinalizationRegistry + // has seen it, from node's event loop, while the run waits. + asio::post(s.io, [&s] { look_for_release(s); }); + s.io.run_for(10s); // lint-run: the test's event loop, held by its timer until the verdict + if (!s.done) { + BOOST_ERROR("no collection released a connection"); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_relay_allocation_test.cpp b/test/platform_page_relay_allocation_test.cpp new file mode 100644 index 0000000..c12af89 --- /dev/null +++ b/test/platform_page_relay_allocation_test.cpp @@ -0,0 +1,498 @@ +// 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) + +// Tests what a relay's WebSocket allocates outside the room's resource in a page, under node, over +// a stand-in for the page's WebSocket: the global operator new, replaced here, and the C library's +// allocation functions, which Emscripten's dlmalloc defines weak and the test replaces, count +// exactly what the guide's "What stays outside the resource" lists, no more and no fewer, so that a +// change either way is seen: +// +// - a connection, from the call that makes it to its open: three `operator new` of the page's +// resolver for its results (Asio's list of one entry, its shared count and the entry's storage), +// two more for the host's two copies when it is longer than a short string holds (10 bytes in a +// page), and one C library allocation, embind's for the type of the open event, which +// webcpp::beast's page stream reads as a `std::string`; +// - each message the relay sends, to its arrival in the room: two C library allocations, embind's +// for the event's type and for the type of its data, which the stream reads as `std::string`s; +// - the close, from the call to the page's close event, delivered after the room was told: one C +// library allocation, embind's for the event's type. +// +// The room's resource sees the session's own allocations in each. A first round, uncounted, makes +// the io_context's once-per-context allocations (the bridge, its map, the scheduler's first +// operation, the timer queue). Each embind allocation is freed before the call that made it +// returns. Two allocations of the platform's are kept out of the count, as allocation_test does: +// the test replaces select(), which Asio's reactor calls on every wait of the io_context and which +// Emscripten implements with an array it callocs on every call; and under Asyncify, where the run +// suspends while it waits for the page, Asyncify allocates the unwind data of the suspension with +// the C library's malloc, which the test marks and counts apart. +// +// main runs the io_context under a work guard, which the last round releases; each step starts from +// the one before. A step that does not come within 10 s fails by name. + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +// The stand-in: it opens on the next turn; relayEmit(n) has the socket of the last construction +// send n texts, each in a turn of its own; close() closes it on the next turn, once. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, install_relay, (), { + globalThis.WebSocket = class { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + constructor(url) { + globalThis.relaySocket = this; + this.url = url; + this.readyState = 0; + this.bufferedAmount = 0; + setTimeout(() => { + this.readyState = 1; + if (this.onopen) this.onopen({type: "open"}); + }, 0); + } + send(text) {} + close() { + if (this.readyState >= 2) return; + this.readyState = 2; + setTimeout(() => { + this.readyState = 3; + if (this.onclose) this.onclose({type: "close", code: 1000, reason: ""}); + }, 0); + } + }; +}); + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, relay_emit, (int count), { + const socket = globalThis.relaySocket; + for (let i = 0; i < count; ++i) { + setTimeout(() => { + if (socket.onmessage) socket.onmessage({type: "message", data: '["EOSE","sub"]'}); + }, 0); + } +}); +// clang-format on + +namespace { + +// What the replaced operator new and the C library's allocation functions count while counting is +// set: global and mutable, since an operator new can reach nothing else. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t global_allocations = 0; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t c_allocations = 0; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +bool counting = false; +// Set, from JavaScript, while Asyncify allocates the unwind data of a call that suspends: that +// allocation is the platform's (webcpp::asio's page "Allocation"), counted apart. A char, which +// JavaScript writes through HEAPU8. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::uint8_t inside_runtime = 0; +// The C library's allocations made while inside_runtime is set. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t runtime_allocations = 0; + +void* counted(void* pointer) { + if (counting) { + ++(inside_runtime != 0 ? runtime_allocations : c_allocations); + } + return pointer; +} + +} // namespace + +// The C library's allocation functions, replaced for this program alone, forwarding to +// Emscripten's own: the C library declares them with parameter names of its own, and cert-dcl58-cpp +// takes a replacement of what declares for a change to namespace std. +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) +extern "C" { +void* malloc(std::size_t size) { + return counted(emscripten_builtin_malloc(size)); +} + +void* calloc(std::size_t count, std::size_t size) { + return counted(emscripten_builtin_calloc(count, size)); +} + +void* realloc(void* pointer, std::size_t size) { + return counted(emscripten_builtin_realloc(pointer, size)); +} + +void free(void* pointer) { + emscripten_builtin_free(pointer); +} + +void* memalign(std::size_t alignment, std::size_t size) { + return counted(emscripten_builtin_memalign(alignment, size)); +} + +void* aligned_alloc(std::size_t alignment, std::size_t size) { + return counted(emscripten_builtin_memalign(alignment, size)); +} + +int posix_memalign(void** out, std::size_t alignment, std::size_t size) { + *out = counted(emscripten_builtin_memalign(alignment, size)); + return *out == nullptr ? ENOMEM : 0; +} +} +// NOLINTEND(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) + +// Emscripten's select() is a poll() over an array of pollfd it callocs on every call +// (system/lib/libc/musl/src/select/select.c), and Asio's reactor calls it on every wait of the +// io_context, once in each seal and each open (measured): the C library's wait, not the sealer's. +// This one keeps the array on the stack, as webcpp::asio's allocation test does, so that the count +// sees the sealer's allocations. +namespace { + +/** The poll() event `event` when `set` holds `fd`, else none. */ +std::uint32_t requested_event(int fd, const fd_set* set, std::uint32_t event) { + return set != nullptr && FD_ISSET(fd, set) ? event : 0U; +} + +void clear_set(fd_set* set) { + if (set != nullptr) { + FD_ZERO(set); + } +} + +/** Adds the descriptor to `set` when poll() reported one of `events` on it; 1 when it did. */ +int ready_event(const pollfd& descriptor, fd_set* set, std::uint32_t events) { + if (set != nullptr && (static_cast(descriptor.revents) & events) != 0) { + FD_SET(descriptor.fd, set); + return 1; + } + return 0; +} + +} // namespace + +// select's C declaration requires a mutable timeval pointer, although this implementation +// does not change it. +extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, + timeval* timeout) { // NOLINT(misc-const-correctness) + if (nfds < 0 || nfds > FD_SETSIZE) { + errno = EINVAL; + return -1; + } + std::array fds{}; + std::size_t n = 0; + for (int fd = 0; fd < nfds; ++fd) { + const std::uint32_t events = requested_event(fd, readfds, POLLIN) | + requested_event(fd, writefds, POLLOUT) | + requested_event(fd, exceptfds, POLLPRI); + if (events != 0) { + fds[n++] = pollfd{.fd = fd, .events = static_cast(events), .revents = 0}; + } + } + const int milliseconds = + timeout == nullptr ? -1 + : static_cast((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000)); + const int ready = poll(fds.data(), static_cast(n), milliseconds); + if (ready < 0) { + return ready; + } + clear_set(readfds); + clear_set(writefds); + clear_set(exceptfds); + int count = 0; + for (std::size_t i = 0; i < n && ready > 0; ++i) { + count += ready_event(fds[i], readfds, POLLIN | POLLHUP | POLLERR); + count += ready_event(fds[i], writefds, POLLOUT | POLLERR); + count += ready_event(fds[i], exceptfds, POLLPRI); + } + return count; +} + +namespace { + +/** What the replaced operator new does: counts, then takes the memory from the C library, uncounted + * there. */ +void* allocate(std::size_t size, std::size_t alignment) { + if (counting) { + ++global_allocations; + } + alignment = alignment < sizeof(void*) ? sizeof(void*) : alignment; + void* pointer = emscripten_builtin_memalign(alignment, size == 0 ? alignment : size); + if (pointer == nullptr) { + boost::throw_exception(std::bad_alloc()); + } + return pointer; +} + +} // namespace + +// The standard library declares the replaceable allocation functions with parameter names reserved +// to the implementation, which a program may not use, hence the exemption on each. + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void* operator new(std::size_t size) { + return allocate(size, alignof(std::max_align_t)); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void* operator new(std::size_t size, std::align_val_t alignment) { + return allocate(size, static_cast(alignment)); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer) noexcept { + emscripten_builtin_free(pointer); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, std::size_t /*size*/) noexcept { + emscripten_builtin_free(pointer); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, std::align_val_t /*alignment*/) noexcept { + emscripten_builtin_free(pointer); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, std::size_t /*size*/, std::align_val_t /*alignment*/) noexcept { + emscripten_builtin_free(pointer); +} + +namespace { + +/** + * The room's resource: a buffer made before anything is counted, which counts what it gives. + */ +class counting_resource final : public std::pmr::memory_resource { +public: + std::size_t allocations = 0; + +private: + std::vector storage_ = std::vector(std::size_t{1} << 20U); + std::pmr::monotonic_buffer_resource buffer_{storage_.data(), storage_.size(), + std::pmr::null_memory_resource()}; + + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations; + return buffer_.allocate(bytes, alignment); + } + + void do_deallocate(void* /*pointer*/, std::size_t /*bytes*/, + std::size_t /*alignment*/) override {} + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } +}; + +/** What one counted phase saw, from its start to its end. */ +struct counts { + bool completed = false; + std::size_t global = 0; + std::size_t c_library = 0; + std::size_t room = 0; +}; + +/** What one connection's phases saw. */ +struct connection_counts { + counts open; + counts one_message; + counts ten_messages; + counts close; +}; + +/** The relays of the rounds: the first warms up, uncounted; the third's host is a long string. */ +constexpr std::array relays{ + "wss://relay.test", + "wss://relay.test", + "wss://relay.example.org", +}; + +enum class phase : std::uint8_t { open, one_message, ten_messages, close }; + +struct state { + counting_resource room; + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; + asio::steady_timer settle{io}; + std::shared_ptr socket; + std::size_t round = 0; + phase at = phase::open; + std::size_t messages = 0; + std::size_t expected = 0; + std::array rounds; + bool done = false; +}; + +void start_counting(const state& s, counts& into) { + global_allocations = 0; + c_allocations = 0; + into.room = s.room.allocations; + counting = true; +} + +void stop_counting(const state& s, counts& into) { + counting = false; + into.completed = true; + into.global = global_allocations; + into.c_library = c_allocations; + into.room = s.room.allocations - into.room; +} + +/** Has the relay send `count` texts, counting into `into` until the last reaches the room. */ +void emit(state& s, std::size_t count, counts& into) { + s.messages = 0; + s.expected = count; + start_counting(s, into); + relay_emit(static_cast(count)); +} + +void on_open(state& s) { + auto& counted = s.rounds.at(s.round); + stop_counting(s, counted.open); + s.at = phase::one_message; + emit(s, 1, counted.one_message); +} + +void on_message(state& s) { + if (++s.messages != s.expected) { + return; + } + auto& counted = s.rounds.at(s.round); + if (s.at == phase::one_message) { + stop_counting(s, counted.one_message); + s.at = phase::ten_messages; + emit(s, 10, counted.ten_messages); + return; + } + stop_counting(s, counted.ten_messages); + s.at = phase::close; + start_counting(s, counted.close); + s.socket->close(); +} + +void connect(state& s); + +/** + * The close is reported: the count goes on until the page's close event, which comes after it, has + * been delivered, behind a wait of the room's. + */ +void on_close(state& s) { + s.settle.expires_after(20ms); + s.settle.async_wait(asio::bind_allocator(std::pmr::polymorphic_allocator<>(&s.room), + [&s](boost::system::error_code /*ec*/) { + stop_counting(s, s.rounds.at(s.round).close); + s.socket.reset(); + if (++s.round == relays.size()) { + s.done = true; + s.guard.reset(); + return; + } + connect(s); + })); +} + +/** Connects to the round's relay, counting from the call to the open. */ +void connect(state& s) { + s.at = phase::open; + start_counting(s, s.rounds.at(s.round).open); + s.socket = s.backend.connect(relays.at(s.round), + { + .open = [&s] { on_open(s); }, + .message = [&s](std::string_view /*text*/) { on_message(s); }, + .close = [&s] { on_close(s); }, + }, + &s.room); +} + +/** + * Marks Asyncify's allocation of a suspension's unwind data, on emscripten under Asyncify, as + * allocation_test does: the C library's allocations made during it are counted apart. + */ +void mark_the_runtime_allocations() { + // clang-format off + EM_ASM({ + if (typeof Asyncify !== "object" || typeof Asyncify.allocateData !== "function") { + return; + } + const flag = $0; + const allocate = Asyncify.allocateData; + Asyncify.allocateData = function(...values) { + const previous = HEAPU8[flag]; + HEAPU8[flag] = 1; + try { + return allocate.apply(this, values); + } finally { + HEAPU8[flag] = previous; + } + }; + }, &inside_runtime); + // clang-format on +} + +/** Checks what one phase allocated outside the room's resource, and that the room saw some. */ +void expect(const counts& got, std::size_t global, std::size_t c_library, const char* name) { + if (!got.completed) { + BOOST_ERROR(name); + return; + } + BOOST_TEST_EQ(got.global, global); + BOOST_TEST_EQ(got.c_library, c_library); + BOOST_TEST_GT(got.room, 0U); +} + +/** Checks a counted round, whose host's two copies take `host_copies` more `operator new`. */ +void expect_round(const connection_counts& got, std::size_t host_copies) { + expect(got.open, 3 + host_copies, 1, "a connection did not open"); + expect(got.one_message, 0, 2, "a message did not reach the room"); + expect(got.ten_messages, 0, 20, "ten messages did not reach the room"); + expect(got.close, 0, 1, "a connection did not close"); +} + +} // namespace + +int main() { + mark_the_runtime_allocations(); + install_relay(); + state s; + connect(s); + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the close + counting = false; + if (!s.done) { + BOOST_ERROR("the rounds stopped before the last"); + } + expect_round(s.rounds.at(1), 0); // relay.test, a short string + expect_round(s.rounds.at(2), 2); // relay.example.org, longer + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_sealer_allocation_test.cpp b/test/platform_page_sealer_allocation_test.cpp new file mode 100644 index 0000000..a71f75f --- /dev/null +++ b/test/platform_page_sealer_allocation_test.cpp @@ -0,0 +1,409 @@ +// 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) + +// Tests that a page's sealer allocates nothing outside the room's resource while it seals and +// opens, under node: from the start of a seal to its completion, and from the start of an open to +// its, the global operator new, replaced here, and the C library's allocation functions, which +// Emscripten's dlmalloc defines weak and the test replaces, count none, while the room's resource +// sees each Web Crypto wait and its completion. A first seal and open come before, uncounted: they +// import the key and make the io_context's once-per-context allocations (the bridge, its map, the +// scheduler's first operation). Before the fix the sealer awaited each Web Crypto promise through +// its type-erased executor, `webcpp::asio::any_io_executor`, through which Asio posts the +// settlement in a function object and an operation of `std::allocator`, which Asio takes from the +// C library when its per-run cache has none (measured: two for a seal, two for an open). +// +// Two allocations of the platform's are kept out of the count, as allocation_test does: the test +// replaces select(), which Asio's reactor calls on every wait of the io_context and which +// Emscripten implements with an array it callocs on every call; and under Asyncify, where the run +// suspends while a promise is pending and Asyncify allocates the unwind data of the suspension with +// the C library's malloc, the test marks that allocation and counts it apart. +// +// main runs the io_context; each step starts from the completion of the one before, and the run +// ends when the last completes. A step that does not come within 10 s fails by name. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +namespace { + +// What the replaced operator new and the C library's allocation functions count while counting is +// set: global and mutable, since an operator new can reach nothing else. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t global_allocations = 0; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t c_allocations = 0; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +bool counting = false; +// Set, from JavaScript, while Asyncify allocates the unwind data of a call that suspends: that +// allocation is the platform's (webcpp::asio's page "Allocation"), counted apart. A char, which +// JavaScript writes through HEAPU8. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::uint8_t inside_runtime = 0; +// The C library's allocations made while inside_runtime is set. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t runtime_allocations = 0; + +void* counted(void* pointer) { + if (counting) { + ++(inside_runtime != 0 ? runtime_allocations : c_allocations); + } + return pointer; +} + +} // namespace + +// The C library's allocation functions, replaced for this program alone, forwarding to +// Emscripten's own: the C library declares them with parameter names of its own, and cert-dcl58-cpp +// takes a replacement of what declares for a change to namespace std. +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) +extern "C" { +void* malloc(std::size_t size) { + return counted(emscripten_builtin_malloc(size)); +} + +void* calloc(std::size_t count, std::size_t size) { + return counted(emscripten_builtin_calloc(count, size)); +} + +void* realloc(void* pointer, std::size_t size) { + return counted(emscripten_builtin_realloc(pointer, size)); +} + +void free(void* pointer) { + emscripten_builtin_free(pointer); +} + +void* memalign(std::size_t alignment, std::size_t size) { + return counted(emscripten_builtin_memalign(alignment, size)); +} + +void* aligned_alloc(std::size_t alignment, std::size_t size) { + return counted(emscripten_builtin_memalign(alignment, size)); +} + +int posix_memalign(void** out, std::size_t alignment, std::size_t size) { + *out = counted(emscripten_builtin_memalign(alignment, size)); + return *out == nullptr ? ENOMEM : 0; +} +} +// NOLINTEND(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) + +// Emscripten's select() is a poll() over an array of pollfd it callocs on every call +// (system/lib/libc/musl/src/select/select.c), and Asio's reactor calls it on every wait of the +// io_context, once in each seal and each open (measured): the C library's wait, not the sealer's. +// This one keeps the array on the stack, as webcpp::asio's allocation test does, so that the count +// sees the sealer's allocations. +namespace { + +/** The poll() event `event` when `set` holds `fd`, else none. */ +std::uint32_t requested_event(int fd, const fd_set* set, std::uint32_t event) { + return set != nullptr && FD_ISSET(fd, set) ? event : 0U; +} + +void clear_set(fd_set* set) { + if (set != nullptr) { + FD_ZERO(set); + } +} + +/** Adds the descriptor to `set` when poll() reported one of `events` on it; 1 when it did. */ +int ready_event(const pollfd& descriptor, fd_set* set, std::uint32_t events) { + if (set != nullptr && (static_cast(descriptor.revents) & events) != 0) { + FD_SET(descriptor.fd, set); + return 1; + } + return 0; +} + +} // namespace + +// select's C declaration requires a mutable timeval pointer, although this implementation +// does not change it. +extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, + timeval* timeout) { // NOLINT(misc-const-correctness) + if (nfds < 0 || nfds > FD_SETSIZE) { + errno = EINVAL; + return -1; + } + std::array fds{}; + std::size_t n = 0; + for (int fd = 0; fd < nfds; ++fd) { + const std::uint32_t events = requested_event(fd, readfds, POLLIN) | + requested_event(fd, writefds, POLLOUT) | + requested_event(fd, exceptfds, POLLPRI); + if (events != 0) { + fds[n++] = pollfd{.fd = fd, .events = static_cast(events), .revents = 0}; + } + } + const int milliseconds = + timeout == nullptr ? -1 + : static_cast((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000)); + const int ready = poll(fds.data(), static_cast(n), milliseconds); + if (ready < 0) { + return ready; + } + clear_set(readfds); + clear_set(writefds); + clear_set(exceptfds); + int count = 0; + for (std::size_t i = 0; i < n && ready > 0; ++i) { + count += ready_event(fds[i], readfds, POLLIN | POLLHUP | POLLERR); + count += ready_event(fds[i], writefds, POLLOUT | POLLERR); + count += ready_event(fds[i], exceptfds, POLLPRI); + } + return count; +} + +namespace { + +/** What the replaced operator new does: counts, then takes the memory from the C library, uncounted + * there. */ +void* allocate(std::size_t size, std::size_t alignment) { + if (counting) { + ++global_allocations; + } + alignment = alignment < sizeof(void*) ? sizeof(void*) : alignment; + void* pointer = emscripten_builtin_memalign(alignment, size == 0 ? alignment : size); + if (pointer == nullptr) { + boost::throw_exception(std::bad_alloc()); + } + return pointer; +} + +} // namespace + +// The standard library declares the replaceable allocation functions with parameter names reserved +// to the implementation, which a program may not use, hence the exemption on each. + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void* operator new(std::size_t size) { + return allocate(size, alignof(std::max_align_t)); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void* operator new(std::size_t size, std::align_val_t alignment) { + return allocate(size, static_cast(alignment)); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer) noexcept { + emscripten_builtin_free(pointer); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, std::size_t /*size*/) noexcept { + emscripten_builtin_free(pointer); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, std::align_val_t /*alignment*/) noexcept { + emscripten_builtin_free(pointer); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, std::size_t /*size*/, std::align_val_t /*alignment*/) noexcept { + emscripten_builtin_free(pointer); +} + +namespace { + +/** + * The room's resource: a buffer made before anything is counted, which counts what it gives. + */ +class counting_resource final : public std::pmr::memory_resource { +public: + std::size_t allocations = 0; + +private: + std::vector storage_ = std::vector(std::size_t{1} << 20U); + std::pmr::monotonic_buffer_resource buffer_{storage_.data(), storage_.size(), + std::pmr::null_memory_resource()}; + + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations; + return buffer_.allocate(bytes, alignment); + } + + void do_deallocate(void* /*pointer*/, std::size_t /*bytes*/, + std::size_t /*alignment*/) override {} + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } +}; + +/** What one counted operation saw, from its start to its completion. */ +struct counts { + bool completed = false; + boost::system::error_code ec; + std::size_t global = 0; + std::size_t c_library = 0; + std::size_t room = 0; +}; + +/** The plaintext sealed and opened: a candidate's JSON, as a room seals it. */ +constexpr std::string_view plaintext = + R"({"candidate":"candidate:1 1 udp 2122260223 192.0.2.1 54321 typ host"})"; + +struct state { + counting_resource room; + asio::io_context io; + std::shared_ptr sealer = + std::allocate_shared( + std::pmr::polymorphic_allocator<>(&room), io.get_executor(), + trystero::protocol::seal_key("secret", "my-app", "room-1"), &room); + std::pmr::string sealed{&room}; + std::pmr::string opened{&room}; + bool warmed_up = false; + counts seal; + counts open; +}; + +using done_handler = trystero::platform::sealer::done_handler; + +/** A completion of the sealer's, allocated in the room's resource. */ +template +done_handler completion(state& s, F f) { + return {std::allocator_arg, std::pmr::polymorphic_allocator<>(&s.room), f}; +} + +/** Starts counting what `into` will report, from zero. */ +void start_counting(const state& s, counts& into) { + global_allocations = 0; + c_allocations = 0; + into.room = s.room.allocations; + counting = true; +} + +/** Stops counting, and records what was counted since start_counting into `into`. */ +void stop_counting(const state& s, counts& into, boost::system::error_code ec) { + counting = false; + into.completed = true; + into.ec = ec; + into.global = global_allocations; + into.c_library = c_allocations; + into.room = s.room.allocations - into.room; +} + +/** Opens the counted seal's text, counting from the start of the open to its completion. */ +void counted_open(state& s) { + start_counting(s, s.open); + s.sealer->open(s.sealed, + completion(s, [&s](boost::system::error_code ec, std::string_view text) { + stop_counting(s, s.open, ec); + s.opened.assign(text); + })); +} + +/** Seals, counting from the start of the seal to its completion. */ +void counted_seal(state& s) { + start_counting(s, s.seal); + s.sealer->seal(plaintext, + completion(s, [&s](boost::system::error_code ec, std::string_view text) { + stop_counting(s, s.seal, ec); + s.sealed.assign(text); + counted_open(s); + })); +} + +/** A first seal and open, uncounted, which import the key and make what an io_context makes once. + */ +void warm_up(state& s) { + s.sealer->seal( + plaintext, completion(s, [&s](boost::system::error_code ec, std::string_view text) { + BOOST_TEST(!ec); + s.sealed.assign(text); + s.sealer->open(s.sealed, + completion(s, [&s](boost::system::error_code ec, std::string_view text) { + BOOST_TEST(!ec); + BOOST_TEST_EQ(text, plaintext); + s.warmed_up = true; + counted_seal(s); + })); + })); +} + +/** + * Marks Asyncify's allocation of a suspension's unwind data, on emscripten under Asyncify, as + * allocation_test does: the C library's allocations made during it are counted apart. + */ +void mark_the_runtime_allocations() { + // clang-format off + EM_ASM({ + if (typeof Asyncify !== "object" || typeof Asyncify.allocateData !== "function") { + return; + } + const flag = $0; + const allocate = Asyncify.allocateData; + Asyncify.allocateData = function(...values) { + const previous = HEAPU8[flag]; + HEAPU8[flag] = 1; + try { + return allocate.apply(this, values); + } finally { + HEAPU8[flag] = previous; + } + }; + }, &inside_runtime); + // clang-format on +} + +/** Checks that one counted operation completed with no allocation outside the room's resource. */ +void expect_none_outside(const counts& got, const char* name) { + if (!got.completed) { + BOOST_ERROR(name); + return; + } + BOOST_TEST(!got.ec); + BOOST_TEST_EQ(got.global, 0U); + BOOST_TEST_EQ(got.c_library, 0U); + // The Web Crypto wait, at least, is the room's. + BOOST_TEST_GT(got.room, 0U); +} + +} // namespace + +int main() { + mark_the_runtime_allocations(); + state s; + warm_up(s); + s.io.run_for(10s); // lint-run: the test's event loop, held by the sealer's Web Crypto waits + counting = false; + if (!s.warmed_up) { + BOOST_ERROR("the first seal and open did not complete"); + } + expect_none_outside(s.seal, "the counted seal did not complete"); + expect_none_outside(s.open, "the counted open did not complete"); + BOOST_TEST_EQ(s.opened, plaintext); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_sealer_test.cpp b/test/platform_page_sealer_test.cpp new file mode 100644 index 0000000..1cfc695 --- /dev/null +++ b/test/platform_page_sealer_test.cpp @@ -0,0 +1,231 @@ +// 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) + +// Tests a page's randomness and sealer against a page whose crypto misbehaves, under node: no +// JavaScript exception enters WebAssembly, and each failure is the error the backend interface +// has. +// +// - When the page's `crypto.getRandomValues` throws, or is missing, the platform's source of +// randomness reports that it filled nothing, and a seal completes with `error::backend_failure`, +// after its call; once the function is back, both work again. Before the fix the C library's +// entropy call, Emscripten's, let the function's exception through into WebAssembly, and the +// program ended with it. +// - When `crypto.subtle.encrypt` or `decrypt` settles with something other than an ArrayBuffer, the +// seal or the open completes with `error::backend_failure`. Before the fix the sealer read the +// settlement as an ArrayBuffer whatever it was: a seal's -1 threw a RangeError into WebAssembly, +// and an open's undefined opened as an empty text. +// +// main runs the io_context; each step starts from the completion of the one before, and the last +// stops the run. A step that does not come within 10 s fails by name. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +// What the page's crypto does: 0, as the page has it; 1, getRandomValues throws; 2, it is missing; +// 3, subtle.encrypt settles with -1; 4, subtle.decrypt settles with undefined. node's own crypto +// object will not take another getRandomValues, so the page's is replaced by one that calls node's, +// but for what it changes, and put back for 0. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, misbehave, (int what), { + if (!globalThis.pageCrypto) globalThis.pageCrypto = globalThis.crypto; + const page = globalThis.pageCrypto; + let crypto = page; + if (what !== 0) { + crypto = { + getRandomValues: view => page.getRandomValues(view), + subtle: { + importKey: (...values) => page.subtle.importKey(...values), + encrypt: (...values) => page.subtle.encrypt(...values), + decrypt: (...values) => page.subtle.decrypt(...values), + }, + }; + } + if (what === 1) { + crypto.getRandomValues = () => { throw new Error("no entropy"); }; + } else if (what === 2) { + crypto.getRandomValues = undefined; + } else if (what === 3) { + crypto.subtle.encrypt = async () => -1; + } else if (what === 4) { + crypto.subtle.decrypt = async () => undefined; + } + Object.defineProperty(globalThis, "crypto", {value: crypto, configurable: true, writable: true}); +}); +// clang-format on + +namespace { + +/** What the page's crypto does, as misbehave() takes it. */ +enum class page_crypto : std::uint8_t { + working = 0, + throwing_random = 1, + missing_random = 2, + encrypt_not_a_buffer = 3, + decrypt_not_a_buffer = 4, +}; + +void set(page_crypto what) { + misbehave(static_cast(what)); +} + +/** What a completion saw: its error, its text, and whether it ran inside the call. */ +struct outcome { + boost::system::error_code ec; + std::string text; + bool inline_call = false; +}; + +struct state { + asio::io_context io; + std::shared_ptr sealer = + std::make_shared( + io.get_executor(), trystero::protocol::seal_key("secret", "my-app", "room-1"), + std::pmr::get_default_resource()); + bool in_call = false; + bool judged = false; + std::optional imported; + std::optional filled_while_throwing; + std::optional sealed_while_throwing; + std::optional filled_while_missing; + std::optional sealed_while_missing; + std::optional filled_once_back; + std::optional sealed_once_back; + std::optional sealed_not_a_buffer; + std::optional opened_not_a_buffer; +}; + +/** The plaintext sealed: a candidate's JSON, as a room seals it. */ +constexpr std::string_view plaintext = + R"({"candidate":"candidate:1 1 udp 2122260223 192.0.2.1 54321 typ host"})"; + +/** Fills a buffer from the platform's source of randomness, as the backend's `random()` does. */ +bool fill() { + std::array bytes{}; + return trystero::platform::detail::fill_random(bytes); +} + +/** A completion that records what it saw into `into`, then runs `next`. */ +trystero::platform::sealer::done_handler record(state& s, std::optional& into, + void (*next)(state&)) { + return [&s, &into, next](boost::system::error_code ec, std::string_view text) { + into = outcome{.ec = ec, .text = std::string(text), .inline_call = s.in_call}; + next(s); + }; +} + +/** Seals with `in_call` raised, so that a completion run inside the call says so. */ +void seal(state& s, std::optional& into, void (*next)(state&)) { + s.in_call = true; + s.sealer->seal(plaintext, record(s, into, next)); + s.in_call = false; +} + +/** Checks that a completion came, after its call, with `expected`. */ +void expect(const std::optional& got, boost::system::error_code expected, + const char* name) { + if (!got) { + BOOST_ERROR(name); + return; + } + BOOST_TEST(got->ec == expected); + BOOST_TEST(!got->inline_call); +} + +void verdict(state& s) { + set(page_crypto::working); + expect(s.imported, {}, "the first seal did not complete"); + BOOST_TEST(s.filled_while_throwing == std::optional(false)); + expect(s.sealed_while_throwing, trystero::error::backend_failure, + "the seal without randomness, getRandomValues throwing, did not complete"); + BOOST_TEST(s.filled_while_missing == std::optional(false)); + expect(s.sealed_while_missing, trystero::error::backend_failure, + "the seal without randomness, getRandomValues missing, did not complete"); + BOOST_TEST(s.filled_once_back == std::optional(true)); + expect(s.sealed_once_back, {}, "the seal with randomness back did not complete"); + expect(s.sealed_not_a_buffer, trystero::error::backend_failure, + "the seal whose encrypt settled with no ArrayBuffer did not complete"); + expect(s.opened_not_a_buffer, trystero::error::backend_failure, + "the open whose decrypt settled with no ArrayBuffer did not complete"); + s.judged = true; + s.io.stop(); +} + +/** decrypt settles with undefined: the text sealed once randomness was back does not open. */ +void open_not_a_buffer(state& s) { + set(page_crypto::decrypt_not_a_buffer); + if (!s.sealed_once_back || s.sealed_once_back->ec) { + verdict(s); + return; + } + s.in_call = true; + s.sealer->open(s.sealed_once_back->text, record(s, s.opened_not_a_buffer, verdict)); + s.in_call = false; +} + +/** encrypt settles with -1: the seal fails. */ +void seal_not_a_buffer(state& s) { + set(page_crypto::encrypt_not_a_buffer); + seal(s, s.sealed_not_a_buffer, open_not_a_buffer); +} + +/** getRandomValues is back: the source fills again, and a seal works. */ +void seal_once_back(state& s) { + set(page_crypto::working); + s.filled_once_back = fill(); + seal(s, s.sealed_once_back, seal_not_a_buffer); +} + +/** getRandomValues is missing: the source fills nothing, and the seal fails. */ +void seal_while_missing(state& s) { + set(page_crypto::missing_random); + s.filled_while_missing = fill(); + seal(s, s.sealed_while_missing, seal_once_back); +} + +/** getRandomValues throws: the source fills nothing, and the seal fails. */ +void seal_while_throwing(state& s) { + set(page_crypto::throwing_random); + s.filled_while_throwing = fill(); + seal(s, s.sealed_while_throwing, seal_while_missing); +} + +} // namespace + +int main() { + state s; + // The first seal imports the key, with the page's crypto working. + seal(s, s.imported, seal_while_throwing); + s.io.run_for(10s); // lint-run: the test's event loop, held by the sealer's Web Crypto waits + if (!s.judged) { + set(page_crypto::working); + BOOST_ERROR("the steps stopped before the verdict"); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_test.cpp b/test/platform_page_test.cpp new file mode 100644 index 0000000..c68710c --- /dev/null +++ b/test/platform_page_test.cpp @@ -0,0 +1,179 @@ +// 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) + +// Tests the shape of a page's program, under node: main runs the io_context from the start, under +// a work guard, and the page calls into C++ through `platform::page_call`, functions of +// webcpp::asio's bridge that only post to it (nothing runs the io_context from a JavaScript event). +// +// - A page with no room yet keeps running: nothing but the work guard holds the io_context until +// the page's first call, 50 ms after main started it, whose posted work joins a room of each of +// two apps over the memory relays. Without the guard, the run returns at once, having run +// nothing, and no room is ever joined. +// - A page's call made while the run is suspended reaches the room: once the two rooms meet, the +// page calls the second function with two texts from a JavaScript timer, and its posted work +// sends each text on the first room's action, which the second room receives. A call returns +// undefined at once, and its work runs from the run, never inside the call. Under Asyncify an +// embind function called while main is suspended returns a promise that never settles, and its +// second call aborts a debug build (measured with Emscripten 6.0.11): page_call is no embind +// function. +// - A page's call with a value its handler does not expect breaks nothing: before its texts, the +// page calls the second function with a number and with undefined, which the handler checks +// for a string and ignores, and the texts that follow still reach the other room. Before the +// handler checked, `as()` threw embind's BindingError out of the run, which ended +// the program. +// - A call of a page_call destroyed meanwhile reaches nothing. +// +// main ends with the errors counted once the run returns; a step that does not come within 10 s +// fails by name. + +#include "support/rooms.hpp" + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +namespace test = webcpp::trystero::test; +using emscripten::val; +using namespace std::chrono_literals; + +namespace { + +/** What the page keeps alive: the io_context and its guard, the memory relays, two apps, a room of + * each, and their actions. */ +struct page { + test::fixture f; + asio::executor_work_guard guard{f.io.get_executor()}; + std::optional a_app; + std::optional z_app; + std::optional a; + std::optional z; + std::optional> chat_a; + std::optional> chat_z; + bool ran_inside_a_call = false; + bool joined = false; + std::size_t met = 0; + std::vector received; + std::size_t ignored = 0; + std::size_t late = 0; +}; + +/** Records whether posted work runs inside a call of the page's, which it never should. */ +void handling(page& p) { + if (asio::use_service(p.f.io).delivering()) { + p.ran_inside_a_call = true; + } +} + +/** + * Calls the page's second function from a JavaScript timer, once both rooms met: with a number and + * with undefined, then twice with a text. + */ +void met(page& p) { + if (++p.met != 2) { + return; + } + // A function expression: clang-format splits an arrow function's => into = >. + EM_ASM({ + setTimeout( + function() { + globalThis.pageSend(42); + globalThis.pageSend(undefined); + globalThis.pageReturned = globalThis.pageSend("from the page"); + globalThis.pageSend("again"); + }, + 0); + }); +} + +/** Joins a room of each app, and sets their handlers. */ +void join(page& p) { + handling(p); + p.joined = true; + p.a_app.emplace(p.f.io.get_executor(), p.f.net, test::app_config("AAAAAAAAAAAAAAAAAAAA")); + p.z_app.emplace(p.f.io.get_executor(), p.f.net, test::app_config("zzzzzzzzzzzzzzzzzzzz")); + p.a.emplace(test::join(*p.a_app, "lobby")); + p.z.emplace(test::join(*p.z_app, "lobby")); + p.chat_a.emplace(p.a->make_action("chat")); + p.chat_z.emplace(p.z->make_action("chat")); + p.a->on_peer_join([&p](std::string_view /*peer*/) { met(p); }); + p.z->on_peer_join([&p](std::string_view /*peer*/) { met(p); }); + p.chat_z->on_message([&p](std::string text, const trystero::message_info& /*info*/) { + p.received.push_back(std::move(text)); + if (p.received.size() == 2) { + p.f.io.stop(); + } + }); +} + +/** + * Sends the page's text on the first room's action, and ignores a value that is not a string: + * converting it would throw embind's BindingError out of the run. + */ +void send(page& p, const val& text) { + handling(p); + if (!text.isString()) { + ++p.ignored; + return; + } + p.chat_a->async_send(text.as(), + [](boost::system::error_code ec) { BOOST_TEST(!ec); }); +} + +} // namespace + +int main() { + page p; + const trystero::platform::page_call join_call(p.f.io.get_executor(), + [&p](const val& /*argument*/) { join(p); }); + const trystero::platform::page_call send_call(p.f.io.get_executor(), + [&p](const val& text) { send(p, text); }); + { + // A call of a page_call destroyed before its work runs reaches nothing. + const trystero::platform::page_call gone(p.f.io.get_executor(), + [&p](const val& /*argument*/) { ++p.late; }); + gone.function()(val(1)); + } + // clang-format off + EM_ASM(({ + const join = Emval.toValue($0); + globalThis.pageSend = Emval.toValue($1); + globalThis.pageReturned = "not called"; + setTimeout(() => join(null), 50); + }), join_call.function().as_handle(), send_call.function().as_handle()); + // clang-format on + p.f.io.run_for(10s); // lint-run: the page's program, held by its work guard + if (!p.joined) { + BOOST_ERROR("the run ended before the page's first call"); + } else if (p.received.size() != 2) { + BOOST_ERROR("the page's sends never reached the other room"); + } + const std::vector expected{"from the page", "again"}; + BOOST_TEST_ALL_EQ(p.received.begin(), p.received.end(), expected.begin(), expected.end()); + BOOST_TEST(val::global("pageReturned").isUndefined()); + BOOST_TEST_EQ(p.ignored, 2U); + BOOST_TEST(!p.ran_inside_a_call); + BOOST_TEST_EQ(p.late, 0U); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_websocket_bound_test.cpp b/test/platform_page_websocket_bound_test.cpp new file mode 100644 index 0000000..17370a3 --- /dev/null +++ b/test/platform_page_websocket_bound_test.cpp @@ -0,0 +1,153 @@ +// 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) + +// Tests the platform backend's bound on what a relay's WebSocket holds unsent in a page, under +// node, over a stand-in for the page's WebSocket: a relay that stops reading, whose bufferedAmount +// only grows, and whose close never completes. The room sends texts of 64 KiB on it, one a turn of +// the io_context, so that each write reaches the page before the next and the session's own queue +// stays empty, 6.4 MiB in all: past protocol::max_queued_relay_bytes of bufferedAmount, +// webcpp::beast's send limit fails the write, and the socket is dropped and reports one close, +// never inside a send, holding no more than the bound. Without a bound, the page's own backend +// that this replaced held all 6.4 MiB and no close came. +// +// main runs the io_context under a work guard, which the verdict releases once the texts are sent +// and the close is reported; a step that does not come within 10 s fails by name. + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using emscripten::val; +using namespace std::chrono_literals; + +// The stand-in: it opens on the next turn, adds each text's UTF-8 length to bufferedAmount and +// never drains it, and records close() without ever firing onclose. Its counts are on globalThis. +// Its events are a page's: each names its type. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, install_stalled_websocket, (), { + globalThis.stalledHeld = 0; + globalThis.stalledCloses = 0; + globalThis.WebSocket = class { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + constructor(url) { + this.url = url; + this.readyState = 0; + this.bufferedAmount = 0; + setTimeout(() => { + this.readyState = 1; + if (this.onopen) this.onopen({type: "open"}); + }, 0); + } + send(text) { + this.bufferedAmount += new TextEncoder().encode(text).length; + globalThis.stalledHeld = Math.max(globalThis.stalledHeld, this.bufferedAmount); + } + close() { + this.readyState = 2; + ++globalThis.stalledCloses; + } + }; +}); +// clang-format on + +namespace { + +constexpr std::size_t texts = 100; + +struct state { + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; + std::shared_ptr socket; + const std::string text = std::string(std::size_t{64} * 1024, 't'); + std::size_t sending = 0; + std::size_t closes = 0; + bool in_send = false; + bool sent = false; + bool judged = false; +}; + +std::size_t held() { + return static_cast(val::global("stalledHeld").as()); +} + +void verdict(state& s) { + if (!s.sent || s.closes == 0) { + return; + } + BOOST_TEST_EQ(s.closes, 1U); + BOOST_TEST_LE(held(), trystero::protocol::max_queued_relay_bytes); + BOOST_TEST_GE(val::global("stalledCloses").as(), 1U); + s.socket.reset(); + s.judged = true; + s.guard.reset(); +} + +/** + * Sends the next text, and posts the one after it, so that one text is sent a turn. + * + * A loop of posted calls, not a recursion: each runs from the io_context once the one that posted + * it has returned, so the stack never grows; hence its exemption, and its lambda's, from + * misc-no-recursion, which sees the cycle through Asio's post. + */ +void send_next(state& s) { // NOLINT(misc-no-recursion) + if (s.sending == texts) { + s.sent = true; + verdict(s); + return; + } + ++s.sending; + s.in_send = true; + s.socket->send(s.text); + s.in_send = false; + asio::post(s.io, [&s] { send_next(s); }); // NOLINT(misc-no-recursion) +} + +} // namespace + +int main() { + install_stalled_websocket(); + state s; + s.socket = s.backend.connect("wss://relay.test", + { + .open = [&s] { send_next(s); }, + .message = {}, + .close = + [&s] { + BOOST_TEST(!s.in_send); // not inside a send + ++s.closes; + verdict(s); + }, + }, + std::pmr::get_default_resource()); + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the verdict + if (!s.judged) { + BOOST_ERROR("the stalled relay was never dropped"); + BOOST_TEST_LE(held(), trystero::protocol::max_queued_relay_bytes); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_websocket_ingress_test.cpp b/test/platform_page_websocket_ingress_test.cpp new file mode 100644 index 0000000..aecdcc9 --- /dev/null +++ b/test/platform_page_websocket_ingress_test.cpp @@ -0,0 +1,180 @@ +// 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) + +// Tests what the platform backend's relay WebSocket takes of what a relay sends in a page, under +// node, over a stand-in for the page's WebSocket whose events are a page's: +// +// - A text longer than protocol::max_relay_message_bytes that the relay sends in the same task of +// the page as its open, as a relay that answers the handshake and writes at once can have the +// page deliver them, closes the connection, and the room never sees it: the stand-in fires its +// open and then a text of 1 MiB and one byte from one callback. Before the fix the session set +// its bound only once the handshake had completed on the executor, after both events had entered +// webcpp::beast's page stream, so the text was checked against beast's default of 16 MiB, copied +// into WebAssembly and handed to the room whole. +// - A binary message is dropped, as the page's own backend that this replaced dropped what was not +// a string, and the text after it reaches the room: the stand-in sends an ArrayBuffer, then a +// text. Before the fix the room was handed the binary message's bytes as a text. +// +// Each socket reports one open and one close. main runs the io_context under a work guard, which +// the verdict releases once both closes are reported; a step that does not come within 10 s fails +// by name. + +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using emscripten::val; +using namespace std::chrono_literals; + +// The stand-in: on the next turn it opens and, from the same callback, sends what its URL's path +// names: /oversized, a text of $0 bytes; /binary, an ArrayBuffer of six bytes and then a text. A +// close() closes it on the next turn, once. Its constructions are counted on globalThis. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, install_sending_websocket, (double oversized), { + globalThis.sendingSockets = 0; + globalThis.WebSocket = class { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + constructor(url) { + ++globalThis.sendingSockets; + this.url = url; + this.readyState = 0; + this.bufferedAmount = 0; + setTimeout(() => { + this.readyState = 1; + if (this.onopen) this.onopen({type: "open"}); + if (url.endsWith("/oversized")) { + if (this.onmessage) this.onmessage({type: "message", data: "o".repeat(oversized)}); + } else if (url.endsWith("/binary")) { + const bytes = new TextEncoder().encode("binary"); + if (this.onmessage) this.onmessage({type: "message", data: bytes.buffer}); + if (this.onmessage) this.onmessage({type: "message", data: "after"}); + } + }, 0); + } + send(text) {} + close() { + if (this.readyState >= 2) return; + this.readyState = 2; + setTimeout(() => { + this.readyState = 3; + if (this.onclose) this.onclose({type: "close", code: 1006, reason: ""}); + }, 0); + } + }; +}); +// clang-format on + +namespace { + +/** What one socket reported. */ +struct reports { + std::size_t opens = 0; + std::size_t closes = 0; + std::vector messages; +}; + +struct state { + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; + std::shared_ptr oversized; + std::shared_ptr binary; + reports oversized_reports; + reports binary_reports; + bool judged = false; +}; + +void verdict(state& s) { + if (s.oversized_reports.closes == 0 || s.binary_reports.closes == 0) { + return; + } + BOOST_TEST_EQ(s.oversized_reports.opens, 1U); + BOOST_TEST_EQ(s.oversized_reports.closes, 1U); + BOOST_TEST_EQ(s.oversized_reports.messages.size(), 0U); + for (const auto& text : s.oversized_reports.messages) { + BOOST_ERROR("the oversized text reached the room"); + BOOST_TEST_EQ(text.size(), trystero::protocol::max_relay_message_bytes + 1); + } + BOOST_TEST_EQ(s.binary_reports.opens, 1U); + BOOST_TEST_EQ(s.binary_reports.closes, 1U); + if (BOOST_TEST_EQ(s.binary_reports.messages.size(), 1U)) { + BOOST_TEST_EQ(s.binary_reports.messages.front(), "after"); + } + BOOST_TEST_EQ(val::global("sendingSockets").as(), 2U); + s.oversized.reset(); + s.binary.reset(); + s.judged = true; + s.guard.reset(); +} + +/** The handlers of a socket that records into `into`, and runs `on_message` after each message. */ +trystero::backend::websocket::handlers recording(state& s, reports& into, + void (*on_message)(const state&)) { + return { + .open = [&into] { ++into.opens; }, + .message = + [&s, &into, on_message](std::string_view text) { + into.messages.emplace_back(text); + on_message(s); + }, + .close = + [&s, &into] { + ++into.closes; + verdict(s); + }, + }; +} + +/** A text reached the binary socket, the one after its binary message: it is closed. */ +void close_binary(const state& s) { + s.binary->close(); +} + +/** A text reached the oversized socket, which none should: it is closed, so that the verdict runs. + */ +void close_oversized(const state& s) { + s.oversized->close(); +} + +} // namespace + +int main() { + install_sending_websocket(static_cast(trystero::protocol::max_relay_message_bytes + 1)); + state s; + s.oversized = s.backend.connect("wss://relay.test/oversized", + recording(s, s.oversized_reports, close_oversized), + std::pmr::get_default_resource()); + s.binary = + s.backend.connect("wss://relay.test/binary", recording(s, s.binary_reports, close_binary), + std::pmr::get_default_resource()); + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the verdict + if (!s.judged) { + BOOST_ERROR("a socket did not report its close"); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_websocket_late_events_test.cpp b/test/platform_page_websocket_late_events_test.cpp new file mode 100644 index 0000000..e2ae36d --- /dev/null +++ b/test/platform_page_websocket_late_events_test.cpp @@ -0,0 +1,173 @@ +// 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) + +// Tests that a relay's WebSocket the platform backend dropped at protocol::max_queued_relay_bytes +// in a page runs none of its handlers again, under node, over a stand-in for the page's WebSocket +// that, as a browser does, has a message event queued for every text sent (a relay message already +// in the page's event loop) and, after close(), a close event, each dispatched to whatever its +// handler property holds when it runs. The room sends 100 texts of 64 KiB in one call: the first +// reaches the page and the rest wait in the session's queue, which drops the socket past the bound; +// the message the page queued for the first finds no handler. In the page's own backend that this +// replaced, before its socket was detached, the 64 messages queued before the drop reached the room +// after its close was reported. A second socket sends one text larger than the bound alone: it is +// dropped at once, and reports one close. +// +// main runs the io_context under a work guard. Once both closes are reported, the verdict waits +// for a promise that a JavaScript timer settles, behind every event the stand-in had queued by +// then, and releases the guard; a step that does not come within 10 s fails by name. + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include // once per program: its EM_JS +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using emscripten::val; +using namespace std::chrono_literals; + +// The stand-in: it opens on the next turn, adds each text's UTF-8 length to bufferedAmount and +// never drains it, queues a message event for each text sent and a close event after close(). Its +// events are a page's: each names its type, and a close its code and reason. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, install_late_websocket, (), { + globalThis.lateCloses = 0; + globalThis.WebSocket = class { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + constructor(url) { + this.url = url; + this.readyState = 0; + this.bufferedAmount = 0; + setTimeout(() => { + this.readyState = 1; + if (this.onopen) this.onopen({type: "open"}); + }, 0); + } + send(text) { + this.bufferedAmount += new TextEncoder().encode(text).length; + setTimeout(() => { + if (this.onmessage) this.onmessage({type: "message", data: "late"}); + }, 0); + } + close() { + this.readyState = 2; + ++globalThis.lateCloses; + setTimeout(() => { + this.readyState = 3; + if (this.onclose) this.onclose({type: "close", code: 1006, reason: ""}); + }, 0); + } + }; +}); +// clang-format on + +namespace { + +struct state { + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; + std::shared_ptr stalled; + std::shared_ptr big; + std::size_t stalled_closes = 0; + std::size_t messages_after_close = 0; + std::size_t big_closes = 0; + bool judged = false; +}; + +void judge(state& s) { + BOOST_TEST_EQ(s.stalled_closes, 1U); + BOOST_TEST_EQ(s.messages_after_close, 0U); + BOOST_TEST_EQ(s.big_closes, 1U); + BOOST_TEST_EQ(val::global("lateCloses").as(), 2U); + s.stalled.reset(); + s.big.reset(); + s.judged = true; + s.guard.reset(); +} + +/** Once both sockets reported their close, judges behind every event the stand-in queued. */ +void closed(state& s) { + if (s.stalled_closes == 0 || s.big_closes == 0) { + return; + } + asio::browser::async_await(s.io.get_executor(), + val::take_ownership(test_promise_after(0, 0, false)), + [&s](boost::system::error_code ec, const val& /*value*/) { + BOOST_TEST(!ec); + judge(s); + }); +} + +} // namespace + +int main() { + install_late_websocket(); + state s; + s.stalled = s.backend.connect("wss://relay.test", + { + .open = + [&s] { + const std::string text(std::size_t{64} * 1024, 't'); + for (std::size_t i = 0; i < 100; ++i) { + s.stalled->send(text); + } + }, + .message = + [&s](std::string_view /*text*/) { + if (s.stalled_closes != 0) { + ++s.messages_after_close; + } + }, + .close = + [&s] { + ++s.stalled_closes; + closed(s); + }, + }, + std::pmr::get_default_resource()); + s.big = s.backend.connect( + "wss://relay.test", + { + .open = + [&s] { + s.big->send(std::string(trystero::protocol::max_queued_relay_bytes + 1, 'b')); + }, + .message = {}, + .close = + [&s] { + ++s.big_closes; + closed(s); + }, + }, + std::pmr::get_default_resource()); + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the verdict + if (!s.judged) { + BOOST_ERROR("a dropped socket did not report its close"); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_page_websocket_tls_test.cpp b/test/platform_page_websocket_tls_test.cpp new file mode 100644 index 0000000..51df7cf --- /dev/null +++ b/test/platform_page_websocket_tls_test.cpp @@ -0,0 +1,234 @@ +// 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) + +// Tests the TLS contexts with which the platform backend reaches a `wss://` relay in a page, under +// node, over a stand-in for the page's WebSocket, which the browser verifies against its own +// authorities: +// +// - A program's context made as Asio makes a client's, `ssl::context(ssl::context::tls_client)`, +// whose verify mode is verify_none, reaches the relay, as the backend's own context does, and as +// it does natively, where the relay is verified whatever the context's mode. Before the fix the +// session set verify_peer on its stream natively only, and webcpp::beast's page stream, which +// refuses a mode other than verify_peer, refused the program's context: every `wss://` relay +// reported a close. +// - A context the page cannot honour reports a close without making a WebSocket, rather than reach +// the relay with less than it asks: one with an authority added, with a client certificate, with +// an option, of a method that is not a client's of every version, or with a verify callback of +// its own. +// +// main runs the io_context under a work guard, which the verdict releases once every socket has +// reported its close; a step that does not come within 10 s fails by name. + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +namespace ssl = webcpp::asio::ssl; +using emscripten::val; +using namespace std::chrono_literals; + +// The stand-in: it records the URL of each construction on globalThis, opens on the next turn, +// and closes on the next turn after close(), once. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, install_recording_websocket, (), { + globalThis.recordedUrls = []; + globalThis.WebSocket = class { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + constructor(url) { + globalThis.recordedUrls.push(url); + this.url = url; + this.readyState = 0; + this.bufferedAmount = 0; + setTimeout(() => { + this.readyState = 1; + if (this.onopen) this.onopen({type: "open"}); + }, 0); + } + send(text) {} + close() { + if (this.readyState >= 2) return; + this.readyState = 2; + setTimeout(() => { + this.readyState = 3; + if (this.onclose) this.onclose({type: "close", code: 1000, reason: ""}); + }, 0); + } + }; +}); +// clang-format on + +namespace { + +/** One backend with a context of its own, its socket to the relay, and what the socket reported. */ +struct relay { + relay(asio::io_context& io, ssl::context context) + : backend(io.get_executor(), std::move(context)) {} + + trystero::platform::backend backend; + std::shared_ptr socket; + std::size_t opens = 0; + std::size_t closes = 0; +}; + +/** The contexts the page cannot honour, by what each asks. */ +enum class refused : std::uint8_t { + authority, + certificate, + option, + method, + callback, +}; + +constexpr std::array refusals{ + refused::authority, // add_certificate_authority + refused::certificate, // use_certificate_chain + refused::option, // set_options(no_compression) + refused::method, // tlsv12_client + refused::callback, // a verify callback of its own +}; + +/** A context of `tls_client` that asks for `what`, which a page's stream refuses. */ +ssl::context refused_context(refused what) { + ssl::context context(what == refused::method ? ssl::context::tlsv12_client + : ssl::context::tls_client); + boost::system::error_code ec; + constexpr std::string_view pem = "-----BEGIN CERTIFICATE-----"; + switch (what) { + case refused::authority: context.add_certificate_authority(asio::buffer(pem), ec); break; + case refused::certificate: context.use_certificate_chain(asio::buffer(pem), ec); break; + case refused::option: context.set_options(ssl::context::no_compression, ec); break; + case refused::method: break; + case refused::callback: + context.set_verify_callback( + [](bool preverified, auto& /*context*/) { return preverified; }, ec); + break; + } + BOOST_TEST(!ec); + return context; +} + +struct state { + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + // A program's context as Asio makes a client's, and the backend's own. + relay asio_client{io, ssl::context(ssl::context::tls_client)}; + std::optional own{std::in_place, io.get_executor()}; + std::shared_ptr own_socket; + std::size_t own_opens = 0; + std::size_t own_closes = 0; + std::array, refusals.size()> refusing; + bool judged = false; +}; + +void verdict(state& s) { + if (s.asio_client.closes == 0 || s.own_closes == 0) { + return; + } + for (const auto& r : s.refusing) { + if (r->closes == 0) { + return; + } + } + BOOST_TEST_EQ(s.asio_client.opens, 1U); + BOOST_TEST_EQ(s.asio_client.closes, 1U); + BOOST_TEST_EQ(s.own_opens, 1U); + BOOST_TEST_EQ(s.own_closes, 1U); + for (std::size_t i = 0; i < refusals.size(); ++i) { + BOOST_TEST_EQ(s.refusing.at(i)->opens, 0U); + BOOST_TEST_EQ(s.refusing.at(i)->closes, 1U); + } + // The two that opened, over TLS, and no other: a refused context makes no WebSocket. + // webcpp::beast writes the port into the URL it gives the page. + const val urls = val::global("recordedUrls"); + if (BOOST_TEST_EQ(urls["length"].as(), 2U)) { + BOOST_TEST(urls[0].strictlyEquals(val("wss://relay.test:443/"))); + BOOST_TEST(urls[1].strictlyEquals(val("wss://relay.test:443/"))); + } + s.asio_client.socket.reset(); + s.own_socket.reset(); + for (auto& r : s.refusing) { + r->socket.reset(); + } + s.judged = true; + s.guard.reset(); +} + +/** Handlers that count into `r`, and close the socket once it opens. */ +trystero::backend::websocket::handlers counting(state& s, relay& r) { + return { + .open = + [&r] { + ++r.opens; + r.socket->close(); + }, + .message = {}, + .close = + [&s, &r] { + ++r.closes; + verdict(s); + }, + }; +} + +} // namespace + +int main() { + install_recording_websocket(); + state s; + s.asio_client.socket = s.asio_client.backend.connect( + "wss://relay.test", counting(s, s.asio_client), std::pmr::get_default_resource()); + s.own_socket = s.own->connect("wss://relay.test", + { + .open = + [&s] { + ++s.own_opens; + s.own_socket->close(); + }, + .message = {}, + .close = + [&s] { + ++s.own_closes; + verdict(s); + }, + }, + std::pmr::get_default_resource()); + for (std::size_t i = 0; i < refusals.size(); ++i) { + auto& r = s.refusing.at(i).emplace(s.io, refused_context(refusals.at(i))); + r.socket = + r.backend.connect("wss://relay.test", counting(s, r), std::pmr::get_default_resource()); + } + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the verdict + if (!s.judged) { + BOOST_ERROR("a socket did not report its close"); + BOOST_TEST_EQ(s.asio_client.opens, 1U); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_peer_connection_test.cpp b/test/platform_peer_connection_test.cpp new file mode 100644 index 0000000..2a3f6ff --- /dev/null +++ b/test/platform_peer_connection_test.cpp @@ -0,0 +1,925 @@ +// 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) + +// Tests the platform backend's peer connection natively, webcpp::webrtc's over libdatachannel, +// between two connections in one process, wired to each other directly: what the signaling would +// carry over the relays is handed across here. Each connection is bound to 127.0.0.1, so that its +// one host candidate is the loopback's and no other interface is needed. The backend makes at most +// `backend_config::max_peer_connections_per_minute` of them in a minute, whatever became of them, +// and holds at most its runtime's `max_peer_connections` at once. + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "require.hpp" + +namespace asio = boost::asio; +namespace trystero = webcpp::trystero; +namespace backend = trystero::backend; +namespace protocol = trystero::protocol; +using namespace std::chrono_literals; + +using webcpp::test::require; + +namespace { + +constexpr const char* loopback = "127.0.0.1"; + +bool run_until(asio::io_context& io, const std::function& done, + std::chrono::milliseconds limit = 10s) { + const auto end = std::chrono::steady_clock::now() + limit; + while (!done() && std::chrono::steady_clock::now() < end) { + io.run_for(10ms); // lint-run: libdatachannel's threads post the connections' events to it + if (io.stopped()) { + io.restart(); + } + } + return done(); +} + +/** The program's runtime, which outlives its io_context and every connection. */ +std::shared_ptr program_runtime(webcpp::webrtc::runtime& runtime) { + return {std::shared_ptr(), &runtime}; +} + +/** Two connected peers: the offerer's channel and the answerer's, with what each received. */ +struct pair { + webcpp::webrtc::runtime runtime; + asio::io_context io; + trystero::platform::backend factory{io.get_executor(), runtime, {.bind_address = loopback}}; + std::thread::id io_thread = std::this_thread::get_id(); + std::shared_ptr offerer; + std::shared_ptr answerer; + std::shared_ptr offer_end; + std::shared_ptr answer_end; + std::vector at_offerer, at_answerer; + bool offer_open = false, answer_open = false, off_thread = false; + std::vector answerer_states; + std::size_t answer_closes = 0; + + /** What makes the offerer's executor of the io_context's. */ + using executor_wrapper = std::function; + + /** The offerer is made in `offer_memory`, on the executor `wrap` makes of the io_context's; + * the answerer as an app's. */ + explicit pair(std::pmr::memory_resource* offer_memory = std::pmr::get_default_resource(), + const executor_wrapper& wrap = {}) + : offerer(made(trystero::webrtc::peer_connection::make( + program_runtime(runtime), wrap ? wrap(io.get_executor()) : io.get_executor(), {}, + loopback, factory, offer_memory))), + answerer(made(trystero::webrtc::peer_connection::make( + program_runtime(runtime), io.get_executor(), {}, loopback, factory, + std::pmr::get_default_resource()))) {} + + pair(const pair&) = delete; + pair& operator=(const pair&) = delete; + + /** Lets go of both connections and channels, which aborts what they wait for. */ + void reset() { + offer_end.reset(); + answer_end.reset(); + offerer.reset(); + answerer.reset(); + } + + static std::shared_ptr made( + boost::system::result> r) { + require(BOOST_TEST(r.has_value())); + return std::move(*r); + } + + void on_io_thread() { + if (std::this_thread::get_id() != io_thread) { + off_thread = true; + } + } + + void connect() { + offerer->set_handlers({ + .ice_candidate = + [this](std::string_view c) { + on_io_thread(); + answerer->add_ice_candidate(c, [](backend::error_code) {}); + }, + .data_channel = {}, + .state = [this](backend::connection_state) { on_io_thread(); }, + }); + answerer->set_handlers({ + .ice_candidate = + [this](std::string_view c) { + on_io_thread(); + offerer->add_ice_candidate(c, [](backend::error_code) {}); + }, + .data_channel = + [this](std::shared_ptr channel) { + on_io_thread(); + answer_end = std::move(channel); + watch(answer_end, answer_open, at_answerer, &answer_closes); + }, + .state = + [this](backend::connection_state s) { + on_io_thread(); + answerer_states.push_back(s); + }, + }); + offer_end = offerer->create_data_channel("data"); + require(BOOST_TEST(offer_end != nullptr)); + 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) { + on_io_thread(); + require(BOOST_TEST(!ec)); + BOOST_TEST_EQ(type, "offer"); + answerer->set_remote_description(type, sdp, [this](backend::error_code ec) { + require(BOOST_TEST(!ec)); + BOOST_TEST(answerer->has_remote_description()); + answerer->set_local_description( + [this](backend::error_code ec, std::string_view type, std::string_view sdp) { + require(BOOST_TEST(!ec)); + BOOST_TEST_EQ(type, "answer"); + offerer->set_remote_description( + type, sdp, [](backend::error_code ec) { BOOST_TEST(!ec); }); + }); + }); + }); + } + + void watch(const std::shared_ptr& channel, bool& open, + std::vector& received, std::size_t* closes) { + channel->set_handlers({ + .open = + [this, &open] { + on_io_thread(); + open = true; + }, + .message = + [this, &received](backend::bytes b) { + on_io_thread(); + received.push_back(std::move(b)); + }, + .close = + [this, closes] { + on_io_thread(); + if (closes != nullptr) { + ++*closes; + } + }, + .buffered_amount_low = {}, + }); + } +}; + +// Observes the offerer's posted callbacks, webcpp::webrtc's and the channel's, without running +// them. This lets a test install a receiver after a real message is read and before its delivery +// is dispatched. +struct queued_tasks { + std::mutex mutex; + std::deque> ready; + + std::size_t size() { + const std::scoped_lock lock(mutex); + return ready.size(); + } + + /** Runs the one task queued first, if any. */ + void run_one() { + std::function f; + { + const std::scoped_lock lock(mutex); + if (ready.empty()) { + return; + } + f = std::move(ready.front()); + ready.pop_front(); + } + f(); + } + + 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_; + } +}; + +/** A pair whose offerer posts to a queue the test runs, in `memory`. */ +struct queued_pair : pair { + std::shared_ptr tasks; + + explicit queued_pair( + std::pmr::memory_resource* memory = std::pmr::get_default_resource(), + const std::shared_ptr& queue = std::make_shared()) + : pair(memory, + [queue](asio::any_io_executor inner) { + return asio::any_io_executor(queued_executor(std::move(inner), queue)); + }), + tasks(queue) {} + + queued_pair(const queued_pair&) = delete; + queued_pair& operator=(const queued_pair&) = delete; + + /** Lets go of the connections, then of what their ends posted: a queued task holds the + * queue's executor, which holds the queue. */ + // The queued tasks are the connections' handlers, which raise nothing; a failure to allocate + // while they run ends the test, as in any destructor. + // NOLINTNEXTLINE(bugprone-exception-escape) + ~queued_pair() { + reset(); + tasks->run(); + const std::scoped_lock lock(tasks->mutex); + tasks->ready.clear(); + } + + /** Connects the pair, and runs the offerer's events until both channels are open. */ + void open() { + connect(); + 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); + } + + /** Runs the offerer's events until its channel keeps `count` frames for a receiver. */ + void receive(std::size_t count) { + require(BOOST_TEST(until([&] { return kept() >= count; }))); + } + + /** The frames the offerer's channel keeps for a receiver. */ + [[nodiscard]] std::size_t kept() const { + return std::static_pointer_cast(offer_end) + ->pending_frames(); + } +}; + +void two_connections_open_a_data_channel_and_exchange_bytes() { + pair p; + p.connect(); + if (!BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))) { + return; + } + BOOST_TEST(p.offer_end->is_open()); + BOOST_TEST(p.answer_end->is_open()); + const backend::bytes hello{1, 2, 3, 250}; + p.offer_end->send(hello); + // One byte more than any room frame is dropped before it is read; the largest one arrives. + p.answer_end->send(backend::bytes(protocol::max_room_frame_bytes + 1, 6)); + p.answer_end->send(backend::bytes(protocol::max_room_frame_bytes, 7)); + if (!BOOST_TEST(run_until( + p.io, [&] { return p.at_answerer.size() == 1 && p.at_offerer.size() == 1; }))) { + return; + } + BOOST_TEST_ALL_EQ(p.at_answerer.front().begin(), p.at_answerer.front().end(), hello.begin(), + hello.end()); + BOOST_TEST_EQ(p.at_offerer.size(), 1U); + BOOST_TEST_EQ(p.at_offerer.front().size(), protocol::max_room_frame_bytes); + BOOST_TEST_LE(p.offer_end->buffered_amount(), backend::data_channel::low_threshold); + // Every handler ran on the executor, never on libdatachannel's threads. + BOOST_TEST(!p.off_thread); +} + +void closing_one_end_is_seen_by_the_other() { + pair p; + p.connect(); + if (!BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))) { + return; + } + p.offerer->close(); + BOOST_TEST(run_until(p.io, [&] { return p.answer_closes == 1; })); + 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.open(); + 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.open(); + 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 frame's delivery is already queued before set_handlers posts its flush: the + // channel's read, then its completion. + p.answer_end->send(backend::bytes{64}); + require(BOOST_TEST(run_until(p.io, [&] { return p.tasks->size() >= 1; }))); + p.tasks->run_one(); + 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(), 65U); +} + +void a_pending_queue_overflow_closes_the_channel() { + queued_pair p; + p.open(); + 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.open(); + 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.open(); + 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); + std::size_t 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, 1U); +} + +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(&memory); + p.open(); + require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); + p.offer_end->set_handlers({}); + for (std::size_t 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; + trystero::platform::backend factory(io.get_executor(), {.bind_address = loopback}); + const auto pc = factory.make_peer_connection({}, std::pmr::get_default_resource()); + require(BOOST_TEST(pc != nullptr)); + std::vector results; + pc->add_ice_candidate("not json", [&](backend::error_code ec) { results.push_back(ec); }); + pc->add_ice_candidate(R"({"sdpMid":"0"})", + [&](backend::error_code ec) { results.push_back(ec); }); + // A candidate before a remote description, which the signaling never adds. + pc->add_ice_candidate( + R"({"candidate":"candidate:1 1 UDP 1 127.0.0.1 9 typ host","sdpMid":"0"})", + [&](backend::error_code ec) { results.push_back(ec); }); + pc->set_remote_description("neither", "v=0", + [&](backend::error_code ec) { results.push_back(ec); }); + if (!BOOST_TEST(run_until(io, [&] { return results.size() == 4; }))) { + return; + } + for (const auto& ec : results) { + BOOST_TEST(ec == trystero::error::backend_failure); + } +} + +/** `json`, an object's text, with spaces before its closing brace, to `size` bytes. */ +std::string padded(std::string_view json, std::size_t size) { + require(BOOST_TEST(json.ends_with('}') && json.size() <= size)); + std::string out(json.substr(0, json.size() - 1)); + out.append(size - json.size(), ' '); + out += '}'; + return out; +} + +// A remote candidate of protocol::max_sealed_candidate_bytes, a host candidate's JSON with spaces +// before its closing brace, is added once an offer is the connection's remote description; one +// byte longer fails with error::backend_failure before it is read. +void a_candidate_past_its_bound_fails() { + asio::io_context io; + trystero::platform::backend factory(io.get_executor(), {.bind_address = loopback}); + const auto offerer = factory.make_peer_connection({}, std::pmr::get_default_resource()); + const auto answerer = factory.make_peer_connection({}, std::pmr::get_default_resource()); + require(BOOST_TEST(offerer != nullptr && answerer != nullptr)); + const auto channel = offerer->create_data_channel("data"); + require(BOOST_TEST(channel != nullptr)); + std::string mid; + bool applied = false; + offerer->set_local_description( + [&](backend::error_code ec, std::string_view type, std::string_view sdp) { + require(BOOST_TEST(!ec)); + // The data channel's media section, "a=mid:", which a candidate names. + const auto at = sdp.find("a=mid:"); + require(BOOST_TEST(at != std::string_view::npos)); + const auto rest = sdp.substr(at + 6); + mid = rest.substr(0, rest.find_first_of("\r\n")); + answerer->set_remote_description(type, sdp, [&](backend::error_code ec) { + require(BOOST_TEST(!ec)); + applied = true; + }); + }); + require(BOOST_TEST(run_until(io, [&] { return applied; }))); + const std::string candidate = + R"({"candidate":"candidate:1 1 UDP 2122317823 127.0.0.1 9 typ host","sdpMid":")" + mid + + R"("})"; + constexpr std::size_t bound = protocol::max_sealed_candidate_bytes; + std::vector results; + answerer->add_ice_candidate(padded(candidate, bound), + [&](backend::error_code ec) { results.push_back(ec); }); + answerer->add_ice_candidate(padded(candidate, bound + 1), + [&](backend::error_code ec) { results.push_back(ec); }); + if (!BOOST_TEST(run_until(io, [&] { return results.size() == 2; }))) { + return; + } + BOOST_TEST(!results[0]); + BOOST_TEST(results[1] == trystero::error::backend_failure); +} + +// A local candidate is reported as the JSON of an RTCIceCandidateInit, as JSON.stringify writes a +// browser's: its mid and index null when unknown, its user name fragment only when it has one. One +// whose candidate, mid or user name fragment is not UTF-8, which JSON cannot carry, is refused, so +// the connection reports none. +void a_candidate_that_is_not_utf8_is_not_written() { + const auto json = [](std::string_view candidate, std::string_view mid, + std::optional index, std::string_view fragment) { + return trystero::webrtc::detail::candidate_json(candidate, mid, index, fragment, + std::pmr::get_default_resource()); + }; + const auto full = json("candidate:1 1 UDP 1 127.0.0.1 9 typ host", "0", 0, "uf\xc3\xa9"); + if (BOOST_TEST(full.has_value())) { + BOOST_TEST_EQ(*full, + "{\"candidate\":\"candidate:1 1 UDP 1 127.0.0.1 9 typ host\"," + "\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\xc3\xa9\"}"); + } + const auto bare = json("candidate:\"", {}, std::nullopt, {}); + if (BOOST_TEST(bare.has_value())) { + BOOST_TEST_EQ(*bare, + "{\"candidate\":\"candidate:\\\"\",\"sdpMid\":null,\"sdpMLineIndex\":null}"); + } + for (const auto& refused : { + json("candidate:\xff", "0", 0, {}), + json("candidate:1", "\xc0\xaf", 0, {}), + json("candidate:1", "0", 0, "\xed\xa0\x80"), + }) { + BOOST_TEST(refused.has_error() && refused.error() == webcpp::document::errc::type); + } +} + +void the_backend_makes_at_most_its_budget_in_a_minute() { + asio::io_context io; + trystero::platform::backend factory( + io.get_executor(), + {.bind_address = std::pmr::string(loopback), .max_peer_connections_per_minute = 3}); + std::vector> made; + for (std::size_t i = 0; i < 3; ++i) { + made.push_back(factory.make_peer_connection({}, std::pmr::get_default_resource())); + BOOST_TEST(made.back() != nullptr); + } + BOOST_TEST(factory.make_peer_connection({}, std::pmr::get_default_resource()) == nullptr); + // Closed and dropped, they still count: the budget counts what was made. + for (const auto& pc : made) { + pc->close(); + } + made.clear(); + BOOST_TEST(factory.make_peer_connection({}, std::pmr::get_default_resource()) == nullptr); +} + +void the_runtime_holds_at_most_its_cap_at_once() { + asio::io_context io; + trystero::platform::backend factory( + io.get_executor(), + {.bind_address = std::pmr::string(loopback), .runtime = {.max_peer_connections = 2}}); + auto first = factory.make_peer_connection({}, std::pmr::get_default_resource()); + const auto second = factory.make_peer_connection({}, std::pmr::get_default_resource()); + BOOST_TEST(first != nullptr); + BOOST_TEST(second != nullptr); + BOOST_TEST_EQ(factory.runtime().peer_connections(), 2U); + BOOST_TEST(factory.make_peer_connection({}, std::pmr::get_default_resource()) == nullptr); + // Unlike the minute's budget, a connection gives its place back once it is gone. + first.reset(); + BOOST_TEST_EQ(factory.runtime().peer_connections(), 1U); + BOOST_TEST(factory.make_peer_connection({}, std::pmr::get_default_resource()) != nullptr); +} + +void a_url_libdatachannel_cannot_parse_is_left_out() { + asio::io_context io; + trystero::platform::backend factory(io.get_executor(), {.bind_address = loopback}); + // stuns:, which WebRTC admits and libdatachannel does not know, beside a server it parses. + std::vector servers; + servers.push_back({ + .urls = {"stuns:127.0.0.1:9", "stun:127.0.0.1:9"}, + .username = {}, + .credential = {}, + }); + servers.push_back({.urls = {"stuns:127.0.0.1:10"}, .username = {}, .credential = {}}); + const auto pc = factory.make_peer_connection(servers, std::pmr::get_default_resource()); + BOOST_TEST(pc != nullptr); + // The probes are given up: only the connection made counts. + BOOST_TEST_EQ(factory.runtime().peer_connections(), 1U); +} + +/** The JSON of a candidate of webcpp::webrtc, as a peer sends it. */ +std::string json_of(const webcpp::webrtc::ice_candidate& c) { + auto made = webcpp::document::document::create(); + require(BOOST_TEST(made.has_value())); + const auto set = made->root().set(webcpp::document::object{ + {"candidate", std::string_view(c.candidate)}, + {"sdpMid", std::string_view(c.sdp_mid)}, + {"sdpMLineIndex", c.sdp_m_line_index.value_or(0)}, + }); + require(BOOST_TEST(set.has_value())); + return made->stringify(); +} + +/** + * The platform backend's connection, offering, and a peer connection of webcpp::webrtc's own, + * answering, in one process: what the signaling would carry is handed across, each candidate held + * until the side it goes to has both descriptions. + */ +struct mixed_pair { + webcpp::webrtc::runtime runtime; + asio::io_context io; + trystero::platform::backend factory{io.get_executor(), runtime, {.bind_address = loopback}}; + std::shared_ptr local = + factory.make_peer_connection({}, std::pmr::get_default_resource()); + std::optional remote; + std::optional sender; + std::shared_ptr channel; + std::vector received; + bool negotiated = false; + std::vector to_remote; + std::vector to_local; + + mixed_pair() { + require(BOOST_TEST(local != nullptr)); + webcpp::webrtc::configuration config; + config.bind_address = loopback; + auto made = webcpp::webrtc::peer_connection::make(runtime, io.get_executor(), config); + require(BOOST_TEST(made.has_value())); + remote.emplace(std::move(*made)); + } + + mixed_pair(const mixed_pair&) = delete; + mixed_pair& operator=(const mixed_pair&) = delete; + + /** Lets go of the remote peer first, then of the backend's connection. */ + ~mixed_pair() { + sender.reset(); + remote.reset(); + channel.reset(); + local.reset(); + } + + void add_to_remote(std::string_view json) { + const auto parsed = webcpp::document::parse(json); + require(BOOST_TEST(parsed.has_value())); + const auto text = parsed->root()["candidate"].get(); + const auto mid = parsed->root()["sdpMid"].get(); + require(BOOST_TEST(text.has_value() && mid.has_value())); + remote->async_add_ice_candidate({.candidate = *text, .sdp_mid = *mid}, + [](webcpp::webrtc::detail::error_code) {}); + } + + void add_to_local(const webcpp::webrtc::ice_candidate& c) { + if (negotiated) { + local->add_ice_candidate(json_of(c), [](backend::error_code) {}); + } else { + to_local.push_back(json_of(c)); + } + } + + void trickle_remote() { + remote->async_wait_ice_candidate( + [this](webcpp::webrtc::detail::error_code ec, const webcpp::webrtc::ice_candidate& c) { + if (!ec && !c.candidate.empty()) { + add_to_local(c); + trickle_remote(); + } + }); + } + + /** Both descriptions are set: the candidates held go now. */ + void on_negotiated() { + negotiated = true; + for (const auto& c : std::exchange(to_remote, {})) { + add_to_remote(c); + } + for (const auto& c : std::exchange(to_local, {})) { + local->add_ice_candidate(c, [](backend::error_code) {}); + } + } + + void answer(std::string_view offer) { + remote->async_set_remote_description( + {.type = webcpp::webrtc::sdp_type::offer, .sdp = offer}, + [this](webcpp::webrtc::detail::error_code ec) { + require(BOOST_TEST(!ec)); + remote->async_set_local_description( + [this](webcpp::webrtc::detail::error_code ec, + const webcpp::webrtc::session_description& d) { + require(BOOST_TEST(!ec)); + local->set_remote_description("answer", d.sdp, + [this](backend::error_code ec) { + require(BOOST_TEST(!ec)); + on_negotiated(); + }); + }); + }); + } + + /** Opens the backend's channel to the remote peer, which accepts it as `sender`. */ + void connect() { + local->set_handlers({ + .ice_candidate = + [this](std::string_view json) { + if (negotiated) { + add_to_remote(json); + } else { + to_remote.emplace_back(json); + } + }, + .data_channel = {}, + .state = {}, + }); + trickle_remote(); + remote->async_accept_data_channel( + [this](webcpp::webrtc::detail::error_code ec, webcpp::webrtc::data_channel c) { + if (!ec) { + sender.emplace(std::move(c)); + } + }); + channel = local->create_data_channel("data"); + require(BOOST_TEST(channel != nullptr)); + channel->set_handlers({ + .open = {}, + .message = [this](backend::bytes frame) { received.push_back(std::move(frame)); }, + .close = {}, + .buffered_amount_low = {}, + }); + local->set_local_description( + [this](backend::error_code ec, std::string_view, std::string_view offer) { + require(BOOST_TEST(!ec)); + answer(offer); + }); + require(BOOST_TEST(run_until(io, [this] { + return channel->is_open() && sender && + sender->ready_state() == webcpp::webrtc::data_channel_state::open; + }))); + } +}; + +// A peer may send what is no frame: a text message, which a data channel of webcpp::webrtc +// delivers as text, is dropped, and the frames around it arrive. The remote peer is +// webcpp::webrtc's own, which sends text. +void a_text_message_is_dropped_and_the_frames_around_it_arrive() { + mixed_pair p; + p.connect(); + const std::vector before{1, 2, 3}; + const std::vector after{4, 5}; + BOOST_TEST(!p.sender->send(asio::buffer(before))); + BOOST_TEST(!p.sender->send_text("1e300")); + BOOST_TEST(!p.sender->send(asio::buffer(after))); + require(BOOST_TEST(run_until(p.io, [&] { return p.received.size() == 2; }))); + BOOST_TEST_ALL_EQ(p.received[0].begin(), p.received[0].end(), before.begin(), before.end()); + BOOST_TEST_ALL_EQ(p.received[1].begin(), p.received[1].end(), after.begin(), after.end()); + // Nothing more arrives: the text was dropped, not delivered late. + run_until(p.io, [] { return false; }, 200ms); + BOOST_TEST_EQ(p.received.size(), 2U); +} + +} // namespace + +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(); + a_candidate_past_its_bound_fails(); + a_candidate_that_is_not_utf8_is_not_written(); + the_backend_makes_at_most_its_budget_in_a_minute(); + the_runtime_holds_at_most_its_cap_at_once(); + a_url_libdatachannel_cannot_parse_is_left_out(); + a_text_message_is_dropped_and_the_frames_around_it_arrive(); + pending_frames_and_delivery_use_the_channels_resource(); + return boost::report_errors(); +} diff --git a/test/native_room_test.cpp b/test/platform_room_test.cpp similarity index 82% rename from test/native_room_test.cpp rename to test/platform_room_test.cpp index c767afe..81f0b8a 100644 --- a/test/native_room_test.cpp +++ b/test/platform_room_test.cpp @@ -4,14 +4,18 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Tests whole rooms over the native backend: real WebRTC through libdatachannel, AES-GCM through -// OpenSSL, Asio's timers. Only the relays are the memory ones of support/memory_backend.hpp, and -// the backend binds every connection to 127.0.0.1, so the loopback is the only network needed. +// Tests whole rooms over the platform backend natively: real WebRTC through libdatachannel, AES-GCM +// through OpenSSL, webcpp::asio's timers. Only the relays are the memory ones of +// support/memory_backend.hpp, and the backend binds every connection to 127.0.0.1, so the loopback +// is the only network needed. #include -#include +#include #include +#include +#include + #include #include @@ -38,11 +42,11 @@ namespace { constexpr const char* relay_url = "wss://relay.test"; -/** The native backend bound to the loopback, with the memory relays instead of the network's. */ -class native_over_memory_relays : public trystero::native::backend { +/** The platform backend bound to the loopback, with the memory relays instead of the network's. */ +class native_over_memory_relays : public trystero::platform::backend { public: native_over_memory_relays(asio::io_context& io, trystero::test::memory_network& relays) - : trystero::native::backend(io.get_executor(), {.bind_address = "127.0.0.1"}), + : trystero::platform::backend(io.get_executor(), {.bind_address = "127.0.0.1"}), relays_(relays) {} std::shared_ptr connect( @@ -104,13 +108,13 @@ void native_rooms_join_and_exchange_every_format() { app_config("zzzzzzzzzzzzzzzzzzzz", "s3cret")); auto z = join(z_app, "lobby"); std::string text; - boost::json::value json; + std::optional json; trystero::bytes file; std::string metadata; z.make_action("chat").on_message( [&](std::string v, const trystero::message_info&) { text = std::move(v); }); - z.make_action("drink").on_message( - [&](boost::json::value v, const trystero::message_info&) { json = std::move(v); }); + z.make_action("drink").on_message( + [&](webcpp::document::document v, const trystero::message_info&) { json = std::move(v); }); z.make_action("file").on_message( [&](trystero::bytes v, const trystero::message_info& info) { file = std::move(v); @@ -127,18 +131,21 @@ void native_rooms_join_and_exchange_every_format() { } a.make_action("chat").async_send( "hello over libdatachannel", [](boost::system::error_code ec) { BOOST_TEST(!ec); }); - a.make_action("drink").async_send( - boost::json::object{{"drink", "negroni"}}, - [](boost::system::error_code ec) { BOOST_TEST(!ec); }); + auto negroni = webcpp::document::parse(R"({"drink":"negroni"})"); + if (!BOOST_TEST(negroni.has_value())) { + return; + } + a.make_action("drink").async_send( + std::move(*negroni), [](boost::system::error_code ec) { BOOST_TEST(!ec); }); a.make_action("file").async_send( big, trystero::send_options{.targets = {}, .metadata = R"({"name":"big.bin"})"}, [](boost::system::error_code ec) { BOOST_TEST(!ec); }); if (!BOOST_TEST( - run_until(f.io, [&] { return !text.empty() && !json.is_null() && !file.empty(); }))) { + run_until(f.io, [&] { return !text.empty() && json.has_value() && !file.empty(); }))) { return; } BOOST_TEST_EQ(text, "hello over libdatachannel"); - BOOST_TEST_EQ(json.at("drink").as_string(), "negroni"); + BOOST_TEST_EQ((*json)["drink"].value_or(std::string_view()), "negroni"); BOOST_TEST_ALL_EQ(file.begin(), file.end(), big.begin(), big.end()); BOOST_TEST_EQ(metadata, R"({"name":"big.bin"})"); diff --git a/test/platform_sealer_test.cpp b/test/platform_sealer_test.cpp new file mode 100644 index 0000000..ec54a27 --- /dev/null +++ b/test/platform_sealer_test.cpp @@ -0,0 +1,289 @@ +// 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) + +// Tests the platform backend's sealer on both targets, natively OpenSSL's AES-GCM and on +// emscripten the page's Web Crypto under node, against text Trystero JS sealed with WebCrypto, +// which the original's oracle wrote into fixtures/expected/expected.json, the test's one argument: +// it opens what Trystero JS sealed, a text it seals opens again in Trystero's form, a text sealed +// under another key or that is no sealed text is a wrong password, and every completion runs after +// the call that started it, never inside it, as the backend interface says; a fresh sealer given +// two seals and two opens in one call, which in a page wait while it imports its key, completes +// each with its own result. On emscripten, without crypto.subtle, as on a page that is not a secure +// context, the key cannot be imported: the first operation and one after the failure complete +// after their calls with a backend failure. Before the fix, three of the page's completions ran +// inside the call. +// +// main starts the first step and runs the io_context, which each completion the sealer posts, or +// each Web Crypto promise it awaits, holds; each step starts from the completion of the one before, +// and the last ends the run. A step that does not come within 10 s fails by name. + +#include +#include + +#include + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#include +#endif +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace tp = webcpp::trystero::protocol; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +namespace { + +/** The fixture at `path`, read with webcpp::document; nothing when it does not parse. */ +std::optional load(const char* path) { + const std::ifstream file(path); + std::stringstream text; + text << file.rdbuf(); + auto parsed = webcpp::document::parse(text.str()); + if (!parsed.has_value()) { + return std::nullopt; + } + return std::move(parsed).unsafe_value(); +} + +/** The resource of every sealer and text of the test. */ +std::pmr::memory_resource* memory() { + return std::pmr::get_default_resource(); +} + +/** What a completion saw: its error, its text, and whether it ran inside the call. */ +struct outcome { + boost::system::error_code ec; + std::string text; + bool inline_call = false; +}; + +struct state { + explicit state(webcpp::document::document fixture) : fixture(std::move(fixture)) {} + + /** The fixture's string `key` of what Trystero JS sealed; empty when it holds none. */ + [[nodiscard]] std::string_view sealed_by_js(std::string_view key) const { + return fixture["sealed"][key].value_or(std::string_view()); + } + + webcpp::document::document fixture; + asio::io_context io; + trystero::platform::backend backend{io.get_executor()}; + std::shared_ptr sealer = + backend.make_sealer(tp::seal_key("secret", "my-app", "room-1"), memory()); + std::shared_ptr intruder = + backend.make_sealer(tp::seal_key("guess", "my-app", "room-1"), memory()); + std::shared_ptr fresh = + backend.make_sealer(tp::seal_key("", "app", "room"), memory()); + bool in_call = false; + bool judged = false; + std::optional opened_js; + std::optional sealed; + std::optional opened; + std::optional wrong_key; + std::optional garbage; + std::optional without_subtle; + std::optional after_failure; + // A sealer given four operations in one call, while it imports its key in a page. + std::shared_ptr queued; + std::array, 4> queued_outcomes; +}; + +/** The plaintext sealed and opened again: a candidate's JSON, as a room seals it. */ +constexpr std::string_view plaintext = + R"({"candidate":"candidate:1 1 udp 2122260223 192.0.2.1 54321 typ host"})"; + +/** A completion that records what it saw into `into`, then runs `next`. */ +trystero::handler record( + state& s, std::optional& into, void (*next)(state&)) { + return [&s, &into, next](boost::system::error_code ec, std::string_view text) { + into = outcome{.ec = ec, .text = std::string(text), .inline_call = s.in_call}; + next(s); + }; +} + +/** Calls `f` with `in_call` raised, so that a completion run inside it says so. */ +template +void call(state& s, F f) { + s.in_call = true; + f(); + s.in_call = false; +} + +/** Checks that a completion came, after its call, with `expected`. */ +void expect(const std::optional& got, boost::system::error_code expected) { + if (BOOST_TEST(got.has_value())) { + BOOST_TEST(got->ec == expected); + BOOST_TEST(!got->inline_call); + } +} + +void verdict(state& s) { + expect(s.opened_js, {}); + if (s.opened_js) { + BOOST_TEST_EQ(s.opened_js->text, s.sealed_by_js("plaintext")); + } + expect(s.sealed, {}); + if (s.sealed) { + const auto parts = tp::parse_sealed(s.sealed->text); + if (BOOST_TEST(parts.has_value())) { + BOOST_TEST_EQ(parts->iv.size(), tp::seal_iv_size); + // The GCM tag follows, as WebCrypto writes it. + BOOST_TEST_EQ(parts->ciphertext.size(), plaintext.size() + 16); + } + } + expect(s.opened, {}); + if (s.opened) { + BOOST_TEST_EQ(s.opened->text, plaintext); + } + expect(s.wrong_key, trystero::error::wrong_password); + expect(s.garbage, trystero::error::wrong_password); + const auto& queued = s.queued_outcomes; + expect(queued[0], {}); + expect(queued[1], {}); + if (queued[0] && queued[1]) { + const auto first = tp::parse_sealed(queued[0]->text); + const auto second = tp::parse_sealed(queued[1]->text); + if (BOOST_TEST(first.has_value() && second.has_value())) { + BOOST_TEST(first->iv != second->iv); // a fresh IV each + } + } + expect(queued[2], {}); + if (queued[2]) { + BOOST_TEST_EQ(queued[2]->text, s.sealed_by_js("plaintext")); + } + expect(queued[3], trystero::error::wrong_password); +#ifdef WEBCPP_TARGET_EMSCRIPTEN + expect(s.without_subtle, trystero::error::backend_failure); + expect(s.after_failure, trystero::error::backend_failure); +#endif + s.judged = true; + s.io.stop(); +} + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +/** Once the key could not be imported: an operation after the failure completes after its call. */ +void open_after_failure(state& s) { + call(s, [&s] { s.fresh->open("x$AAAA", record(s, s.after_failure, verdict)); }); +} + +/** + * Without crypto.subtle, as outside a secure context: the key cannot be imported, and the first + * operation completes after its call. + */ +void seal_without_subtle(state& s) { + emscripten::val descriptor = emscripten::val::object(); + descriptor.set("value", emscripten::val::object()); + emscripten::val::global("Object").call("defineProperty", emscripten::val::global(), + emscripten::val("crypto"), descriptor); + s.fresh = s.backend.make_sealer(tp::seal_key("", "app", "room"), memory()); + call(s, [&s] { s.fresh->seal("hello", record(s, s.without_subtle, open_after_failure)); }); +} +#endif + +/** Once every queued operation completed: on emscripten, a page without crypto.subtle. */ +void queued_completed(state& s) { + for (const auto& got : s.queued_outcomes) { + if (!got) { + return; + } + } +#ifdef WEBCPP_TARGET_EMSCRIPTEN + seal_without_subtle(s); +#else + verdict(s); +#endif +} + +/** + * A fresh sealer given two seals and two opens in one call, which in a page wait while it imports + * its key, started by the first: each completes, after the call, with its own result. + */ +void queue_during_import(state& s) { + s.queued = s.backend.make_sealer(tp::seal_key("secret", "my-app", "room-1"), memory()); + call(s, [&s] { + s.queued->seal(plaintext, record(s, s.queued_outcomes[0], queued_completed)); + s.queued->seal(plaintext, record(s, s.queued_outcomes[1], queued_completed)); + s.queued->open(s.sealed_by_js("text"), record(s, s.queued_outcomes[2], queued_completed)); + s.queued->open("not a sealed text", record(s, s.queued_outcomes[3], queued_completed)); + }); +} + +/** Once the wrong key and the garbage are refused. */ +void refused(state& s) { + if (!s.wrong_key || !s.garbage) { + return; + } + queue_during_import(s); +} + +/** + * Another key's sealer opens what Trystero JS sealed as a wrong password, and the room's opens a + * text that is no sealed one so too. + */ +void refuse(state& s) { + call(s, [&s] { + s.intruder->open(s.sealed_by_js("text"), record(s, s.wrong_key, refused)); + s.sealer->open("not a sealed text", record(s, s.garbage, refused)); + }); +} + +/** Once its text is sealed, the sealer opens it again. */ +void open_sealed(state& s) { + if (!s.sealed || s.sealed->ec) { + verdict(s); + return; + } + call(s, [&s] { s.fresh->open(s.sealed->text, record(s, s.opened, refuse)); }); +} + +/** Once Trystero JS's text is opened, a sealer under another key seals one of its own. */ +void seal(state& s) { + call(s, [&s] { s.fresh->seal(plaintext, record(s, s.sealed, open_sealed)); }); +} + +/** Opens what Trystero JS sealed under the room's key. */ +void open_what_js_sealed(state& s) { + call(s, [&s] { s.sealer->open(s.sealed_by_js("text"), record(s, s.opened_js, seal)); }); +} + +} // namespace + +int main(int argc, char* argv[]) { + if (!BOOST_TEST_EQ(argc, 2)) { + BOOST_LIGHTWEIGHT_TEST_OSTREAM + << "usage: platform_sealer_test \n"; + return webcpp::test::exit_status(boost::report_errors()); + } + auto fixture = load(argv[1]); + if (!BOOST_TEST(fixture.has_value() && (*fixture)["sealed"].is_object())) { + return webcpp::test::exit_status(boost::report_errors()); + } + state s(std::move(*fixture)); + open_what_js_sealed(s); + s.io.run_for(10s); // lint-run: the test's event loop, held by the sealers' completions + if (!s.judged) { + BOOST_ERROR("the steps stopped before the verdict"); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_websocket_allocation_test.cpp b/test/platform_websocket_allocation_test.cpp new file mode 100644 index 0000000..62bbba8 --- /dev/null +++ b/test/platform_websocket_allocation_test.cpp @@ -0,0 +1,337 @@ +// 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) + +// Tests that natively a relay's message allocates nothing outside the room's resource: from the +// send of a text to the receipt of its echo, ten times over, the global operator new, replaced +// here, counts none on the room's thread, while the room's resource sees the session's texts and +// operations. The relay is an echo server of Boost.Beast's own, on a thread of its own, which the +// count leaves out; the first three echoes, uncounted, make what a connection makes once (the +// WebSocket's write buffer, Asio's per-thread cache of the operations it recycles). +// +// Before the fix the session's reads and writes completed into Asio's type-erased handler, +// `any_completion_handler`, whose executor is of another type than the stream's: for each +// operation Asio made an `any_completion_executor` around the stream's executor, with `new`, and +// dispatched each completion through it in a function object of its own. Measured: six +// `operator new` for a text sent and its echo received, and four of Asio's recycled blocks. +// +// A relay that refuses the upgrade with a body of 4 MiB has the handshake read its header alone: +// from the call that makes the socket to its close, reported without an open, operator new gives +// the room's thread less than 64 KiB (measured: 5,144 bytes, the connection's own state among +// them). Before the session's next layer was webcpp::beast's bounded handshake layer, Beast's own +// parser read the body whole, up to its default limit for a response, 8 MiB, outside the room's +// resource (measured: 4,199,353 bytes). +// +// main runs an io_context for each case: in the first each echo sends the next text, and the last +// closes the socket; in the second the refusal ends the connection. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace asio = boost::asio; +namespace beast = boost::beast; +namespace trystero = webcpp::trystero; +using asio::ip::tcp; + +namespace { + +// What the replaced operator new counts while counting is set, on the thread that set it: global +// and mutable, since an operator new can reach nothing else. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +thread_local bool counting = false; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +thread_local std::size_t global_allocations = 0; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +thread_local std::size_t global_bytes = 0; + +/** What the replaced operator new does: counts, then takes the memory from the C library. */ +void* allocate(std::size_t size) { + if (counting) { + ++global_allocations; + global_bytes += size; + } + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc): the global operator new's own storage + void* pointer = std::malloc(size == 0 ? 1 : size); + if (pointer == nullptr) { + boost::throw_exception(std::bad_alloc()); + } + return pointer; +} + +} // namespace + +// The standard library declares the replaceable allocation functions with parameter names reserved +// to the implementation, which a program may not use, hence the exemption on each. Asio's +// type-erased executors take their storage with the nothrow form. + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void* operator new(std::size_t size) { + return allocate(size); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void* operator new(std::size_t size, const std::nothrow_t& /*tag*/) noexcept { + if (counting) { + ++global_allocations; + global_bytes += size; + } + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc): the global operator new's own storage + return std::malloc(size == 0 ? 1 : size); +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer) noexcept { + std::free(pointer); // NOLINT(cppcoreguidelines-no-malloc): what operator new took +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, std::size_t /*size*/) noexcept { + std::free(pointer); // NOLINT(cppcoreguidelines-no-malloc): what operator new took +} + +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void operator delete(void* pointer, const std::nothrow_t& /*tag*/) noexcept { + std::free(pointer); // NOLINT(cppcoreguidelines-no-malloc): what operator new took +} + +namespace { + +/** The room's resource: a buffer made before anything is counted, which counts what it gives. */ +class counting_resource final : public std::pmr::memory_resource { +public: + std::size_t allocations = 0; + +private: + std::vector storage_ = std::vector(std::size_t{4} << 20U); + std::pmr::monotonic_buffer_resource buffer_{storage_.data(), storage_.size(), + std::pmr::null_memory_resource()}; + + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations; + return buffer_.allocate(bytes, alignment); + } + + void do_deallocate(void* /*pointer*/, std::size_t /*bytes*/, + std::size_t /*alignment*/) override {} + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } +}; + +/** + * A relay that sends every text back, on a thread of its own, with Boost.Beast's synchronous + * stream: one connection, until it closes. + */ +class echo_relay { +public: + echo_relay() : acceptor_(io_, {asio::ip::make_address("127.0.0.1"), 0}) { + thread_ = std::thread([this] { serve(); }); + } + + echo_relay(const echo_relay&) = delete; + echo_relay& operator=(const echo_relay&) = delete; + echo_relay(echo_relay&&) = delete; + echo_relay& operator=(echo_relay&&) = delete; + + ~echo_relay() { thread_.join(); } + + [[nodiscard]] std::string url() const { + return "ws://127.0.0.1:" + std::to_string(acceptor_.local_endpoint().port()) + "/"; + } + +private: + void serve() { + boost::system::error_code ec; + tcp::socket socket(io_); + if (acceptor_.accept(socket, ec)) { + return; + } + beast::websocket::stream ws(std::move(socket)); + ws.accept(ec); + beast::flat_buffer buffer; + while (!ec) { + ws.read(buffer, ec); + if (ec) { + return; + } + ws.text(true); + ws.write(buffer.data(), ec); + buffer.consume(buffer.size()); + } + } + + asio::io_context io_; + tcp::acceptor acceptor_; + std::thread thread_; +}; + +/** + * A relay that refuses the upgrade, on a thread of its own: it reads the request's header and + * answers 403 with a body of `body` bytes, then closes. + */ +class refusing_relay { +public: + explicit refusing_relay(std::size_t body) + : acceptor_(io_, {asio::ip::make_address("127.0.0.1"), 0}), body_(body) { + thread_ = std::thread([this] { serve(); }); + } + + refusing_relay(const refusing_relay&) = delete; + refusing_relay& operator=(const refusing_relay&) = delete; + refusing_relay(refusing_relay&&) = delete; + refusing_relay& operator=(refusing_relay&&) = delete; + + ~refusing_relay() { thread_.join(); } + + [[nodiscard]] std::string url() const { + return "ws://127.0.0.1:" + std::to_string(acceptor_.local_endpoint().port()) + "/"; + } + +private: + void serve() { + boost::system::error_code ec; + tcp::socket socket(io_); + if (acceptor_.accept(socket, ec)) { + return; + } + std::string request; + asio::read_until(socket, asio::dynamic_buffer(request), "\r\n\r\n", ec); + if (ec) { + return; + } + const std::string response = + "HTTP/1.1 403 Forbidden\r\nContent-Length: " + std::to_string(body_) + "\r\n\r\n" + + std::string(body_, 'r'); + // The client may close once it has read what it reads: the write then fails, as it may, + // and the socket is closed all the same. + asio::write(socket, asio::buffer(response), ec); + if (socket.close(ec)) { + return; + } + } + + asio::io_context io_; + tcp::acceptor acceptor_; + std::size_t body_; + std::thread thread_; +}; + +constexpr std::size_t warm_up = 3; +constexpr std::size_t counted = 10; + +struct state { + asio::io_context io; + counting_resource room; + asio::ssl::context tls{asio::ssl::context::tls_client}; + std::shared_ptr socket; + const std::string text = std::string(200, 't'); + std::size_t echoes = 0; + std::size_t room_before = 0; + std::size_t room_counted = 0; + std::size_t global_counted = 0; + bool done = false; +}; + +/** Sends the next text, counting from the first counted one; the last echo closes the socket. */ +void on_echo(state& s) { + ++s.echoes; + if (s.echoes == warm_up) { + global_allocations = 0; + s.room_before = s.room.allocations; + counting = true; + } + if (s.echoes == warm_up + counted) { + counting = false; + s.global_counted = global_allocations; + s.room_counted = s.room.allocations - s.room_before; + s.done = true; + s.socket->close(); + return; + } + s.socket->send(s.text); +} + +/** A text sent and its echo received, ten times, allocate nothing outside the room's resource. */ +void messages_allocate_nothing_outside_the_room() { + const echo_relay relay; + state s; + s.socket = trystero::platform::connect_websocket( + s.io.get_executor(), &s.tls, relay.url(), + { + .open = [&s] { s.socket->send(s.text); }, + .message = [&s](std::string_view /*text*/) { on_echo(s); }, + .close = {}, + }, + &s.room); + s.io.run(); // lint-run: the session and its relay do loopback network I/O, until the close + counting = false; + if (!BOOST_TEST(s.done)) { + return; + } + BOOST_TEST_EQ(s.global_counted, 0U); + // The session's texts and operations, at least one of each a message. + BOOST_TEST_GE(s.room_counted, counted); + s.socket.reset(); +} + +/** + * A relay that refuses the upgrade with a body of 4 MiB: the connection reports its close without + * opening, and the room's thread allocated less than 64 KiB with operator new meanwhile, its + * resolver's results and its streams' state among them, the refusal's body none of it. + */ +void a_refusals_body_is_not_read() { + constexpr std::size_t body = std::size_t{4} << 20U; + const refusing_relay relay(body); + asio::io_context io; + counting_resource room; + asio::ssl::context tls{asio::ssl::context::tls_client}; + std::size_t opens = 0; + std::size_t closes = 0; + global_bytes = 0; + counting = true; + auto socket = trystero::platform::connect_websocket(io.get_executor(), &tls, relay.url(), + { + .open = [&opens] { ++opens; }, + .message = {}, + .close = [&closes] { ++closes; }, + }, + &room); + io.run(); // lint-run: the session and its relay do loopback network I/O, until the refusal + counting = false; + BOOST_TEST_EQ(opens, 0U); + BOOST_TEST_EQ(closes, 1U); + BOOST_TEST_LT(global_bytes, std::size_t{64} << 10U); + socket.reset(); +} + +} // namespace + +int main() { + messages_allocate_nothing_outside_the_room(); + a_refusals_body_is_not_read(); + return boost::report_errors(); +} diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp new file mode 100644 index 0000000..8fb964a --- /dev/null +++ b/test/platform_websocket_test.cpp @@ -0,0 +1,929 @@ +// 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) + +// Tests the platform backend's relay WebSocket natively, webcpp::beast's, there Boost.Beast's, +// against servers in the same process, on 127.0.0.1: an echo server in the clear and one over TLS, +// with a test authority of its own, and relays that misbehave. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "require.hpp" + +namespace asio = boost::asio; +namespace beast = boost::beast; +namespace trystero = webcpp::trystero; +using asio::ip::tcp; +using namespace std::chrono_literals; + +namespace { + +// The test's own authority and a relay's certificate it signed, for the name localhost alone +// (no address), with the relay's key: EC P-256, valid from 2026 to 2126. Made with OpenSSL's +// command line once; nothing else trusts the authority. +constexpr std::string_view test_authority = R"(-----BEGIN CERTIFICATE----- +MIIBqjCCAVGgAwIBAgIUIlj5fjUA1vNsiodeLDxZZrfAED0wCgYIKoZIzj0EAwIw +IjEgMB4GA1UEAwwXd2ViY3BwIHRyeXN0ZXJvIHRlc3QgQ0EwIBcNMjYwMTAxMDAw +MDAwWhgPMjEyNjAxMDEwMDAwMDBaMCIxIDAeBgNVBAMMF3dlYmNwcCB0cnlzdGVy +byB0ZXN0IENBMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzvwWZu/uKAs+QRvH +XRwLYFz8blZJ+lF0HLMZDQ9hUmiv8EDAcba20o5LMjN0P5nOdJo/036+KXrm9DXw +KbPvQaNjMGEwHQYDVR0OBBYEFBOTazg3MnmU2S1gvIPSiWLRGCyoMB8GA1UdIwQY +MBaAFBOTazg3MnmU2S1gvIPSiWLRGCyoMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0P +AQH/BAQDAgEGMAoGCCqGSM49BAMCA0cAMEQCIE98bCTUol8DDmoGh81Lh5NirVxq +aMYwfaQM+b4lxJqzAiAsWzw2WW3UbPWI2arYUKE6IMfU+n0pDQd7wfsoDHsqaA== +-----END CERTIFICATE----- +)"; + +constexpr std::string_view relay_certificate = R"(-----BEGIN CERTIFICATE----- +MIIBxzCCAW2gAwIBAgIUQCMGnMaDIkHCtKl7oV2FPaItruYwCgYIKoZIzj0EAwIw +IjEgMB4GA1UEAwwXd2ViY3BwIHRyeXN0ZXJvIHRlc3QgQ0EwIBcNMjYwMTAxMDAw +MDAwWhgPMjEyNjAxMDEwMDAwMDBaMBQxEjAQBgNVBAMMCWxvY2FsaG9zdDBZMBMG +ByqGSM49AgEGCCqGSM49AwEHA0IABNxV13TdSt0NISLCl7RN2hmPTZVHQbL3ScpF +Upnb9xFsg7XND5KgmoxaqqcNYvre7LvYikPFCMGe9Sxm9RVU9m+jgYwwgYkwDAYD +VR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwEw +FAYDVR0RBA0wC4IJbG9jYWxob3N0MB0GA1UdDgQWBBTWHv+8dJ288V0jMxEgRATx +q0m9qzAfBgNVHSMEGDAWgBQTk2s4NzJ5lNktYLyD0oli0RgsqDAKBggqhkjOPQQD +AgNIADBFAiBueKyDNiLgTph5gxvoeIG4sywlcZ7JzxWPjgvy6mM6xwIhAP5tU9pZ +uTxXlM1V/h/SZPPaX5Y+Nmyqe+mVyQOrjnRh +-----END CERTIFICATE----- +)"; + +constexpr std::string_view relay_key = R"(-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcDsozgW+FL+py13F +ilAkInuO5noQH76ZndqbFsKzwXahRANCAATcVdd03UrdDSEiwpe0TdoZj02VR0Gy +90nKRVKZ2/cRbIO1zQ+SoJqMWqqnDWL63uy72IpDxQjBnvUsZvUVVPZv +-----END PRIVATE KEY----- +)"; + +/** Sends every text message of `ws` back, until its first error. */ +template +asio::awaitable echo_messages(beast::websocket::stream& ws) { + beast::flat_buffer buffer; + for (;;) { + auto [read, read_size] = + co_await ws.async_read(buffer, asio::as_tuple(asio::use_awaitable)); + if (read) { + co_return; + } + ws.text(true); + auto [written, written_size] = + co_await ws.async_write(buffer.data(), asio::as_tuple(asio::use_awaitable)); + if (written) { + co_return; + } + buffer.consume(buffer.size()); + } +} + +/** + * Accepts WebSocket connections and sends every text message back. + * + * Tip: each coroutine ends on its first error, read from a tuple, so the server needs no + * exceptions, as the client it tests does not. + */ +struct echo_server { + explicit echo_server(asio::io_context& io) + : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}) { + asio::co_spawn(io, accept(), asio::detached); + } + + [[nodiscard]] std::string url() const { + return "ws://127.0.0.1:" + std::to_string(acceptor.local_endpoint().port()) + "/relay"; + } + + asio::awaitable accept() { + for (;;) { + auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); + if (ec) { + co_return; + } + asio::co_spawn(acceptor.get_executor(), echo(std::move(socket)), asio::detached); + } + } + + static asio::awaitable echo(tcp::socket socket) { + beast::websocket::stream ws(std::move(socket)); + auto [accepted] = co_await ws.async_accept(asio::as_tuple(asio::use_awaitable)); + if (accepted) { + co_return; + } + co_await echo_messages(ws); + } + + tcp::acceptor acceptor; +}; + +/** + * Accepts WebSocket connections over TLS with the relay's certificate, records the name each + * client sent (SNI) and each handshake that failed, and sends every text message back. + */ +struct tls_echo_server { + explicit tls_echo_server(asio::io_context& io) + : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}), + context(asio::ssl::context::tls_server) { + boost::system::error_code ec; + webcpp::test::require( + BOOST_TEST(!context.use_certificate_chain(asio::buffer(relay_certificate), ec))); + webcpp::test::require(BOOST_TEST( + !context.use_private_key(asio::buffer(relay_key), asio::ssl::context::pem, ec))); + // Called for every client hello, with the name the client sent or none. + SSL_CTX_set_tlsext_servername_callback(context.native_handle(), &record_server_name); + SSL_CTX_set_tlsext_servername_arg(context.native_handle(), this); + asio::co_spawn(io, accept(), asio::detached); + } + + tls_echo_server(const tls_echo_server&) = delete; + tls_echo_server& operator=(const tls_echo_server&) = delete; + tls_echo_server(tls_echo_server&&) = delete; + tls_echo_server& operator=(tls_echo_server&&) = delete; + ~tls_echo_server() = default; + + /** The URL of the relay under `host`, a name or an address of the loopback. */ + [[nodiscard]] std::string url(std::string_view host) const { + return "wss://" + std::string(host) + ":" + + std::to_string(acceptor.local_endpoint().port()) + "/relay"; + } + + static int record_server_name(SSL* ssl, int* /*alert*/, void* server) { + const char* const name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); + static_cast(server)->server_names.emplace_back(name != nullptr ? name + : ""); + return SSL_TLSEXT_ERR_OK; + } + + asio::awaitable accept() { + for (;;) { + auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); + if (ec) { + co_return; + } + asio::co_spawn(acceptor.get_executor(), echo(std::move(socket)), asio::detached); + } + } + + asio::awaitable echo(tcp::socket socket) { + beast::websocket::stream> ws(std::move(socket), context); + auto [shaken] = co_await ws.next_layer().async_handshake( + asio::ssl::stream_base::server, asio::as_tuple(asio::use_awaitable)); + if (shaken) { + ++failed_handshakes; + co_return; + } + auto [accepted] = co_await ws.async_accept(asio::as_tuple(asio::use_awaitable)); + if (accepted) { + co_return; + } + co_await echo_messages(ws); + } + + tcp::acceptor acceptor; + asio::ssl::context context; + // Written by the server's own callbacks, also while a test holds the server const. + mutable std::vector server_names; + mutable std::size_t failed_handshakes = 0; +}; + +/** What a hostile relay does once it reads a client's first message. */ +enum class misbehaviour { + /** Sends a text one byte longer than a room reads, then goes on reading. */ + too_long_text, + /** Drops the TCP connection with a reset. */ + reset, + /** Sends a binary message, which no Nostr relay sends, then a text, and goes on reading. */ + binary_then_text, +}; + +/** + * Accepts WebSocket connections, reads every message, and misbehaves at the first: what any relay + * of a room's list can do, and what a network drop does by chance. + */ +struct hostile_server { + hostile_server(asio::io_context& io, misbehaviour m) + : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}), what(m) { + asio::co_spawn(io, accept(), asio::detached); + } + + [[nodiscard]] std::string url() const { + return "ws://127.0.0.1:" + std::to_string(acceptor.local_endpoint().port()) + "/relay"; + } + + asio::awaitable accept() { + for (;;) { + auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); + if (ec) { + co_return; + } + asio::co_spawn(acceptor.get_executor(), serve(std::move(socket), what), asio::detached); + } + } + + static asio::awaitable serve(tcp::socket socket, misbehaviour what) { + const auto ws = std::make_shared>(std::move(socket)); + auto [accepted] = co_await ws->async_accept(asio::as_tuple(asio::use_awaitable)); + if (accepted) { + co_return; + } + beast::flat_buffer buffer; + for (bool first = true;; first = false) { + auto [read, read_size] = + co_await ws->async_read(buffer, asio::as_tuple(asio::use_awaitable)); + if (read) { + co_return; + } + buffer.consume(buffer.size()); + if (!first) { + continue; + } + if (what == misbehaviour::reset) { + // A linger of 0 makes the close a reset. + boost::system::error_code ec; + const bool reset = + !ws->next_layer().set_option(asio::socket_base::linger(true, 0), ec) && + !ws->next_layer().close(ec); + BOOST_TEST(reset); + co_return; + } + // Written beside the reads, so that the client's writes keep draining meanwhile. + if (what == misbehaviour::binary_then_text) { + asio::co_spawn( + ws->get_executor(), + [ws]() -> asio::awaitable { + ws->binary(true); + auto [binary, binary_size] = + co_await ws->async_write(asio::buffer(std::string_view("binary")), + asio::as_tuple(asio::use_awaitable)); + if (binary) { + co_return; + } + ws->text(true); + co_await ws->async_write(asio::buffer(std::string_view("after")), + asio::as_tuple(asio::use_awaitable)); + }, + asio::detached); + continue; + } + asio::co_spawn( + ws->get_executor(), + [ws]() -> asio::awaitable { + const std::string text(trystero::protocol::max_relay_message_bytes + 1, 'x'); + ws->text(true); + co_await ws->async_write(asio::buffer(text), + asio::as_tuple(asio::use_awaitable)); + }, + asio::detached); + } + } + + tcp::acceptor acceptor; + misbehaviour what; +}; + +/** + * Accepts WebSocket connections, answers the handshake, and never reads again, keeping each + * connection open: a relay that stalls, or a path that died without a reset. + */ +struct stalled_server { + explicit stalled_server(asio::io_context& io) + : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}) { + asio::co_spawn(io, accept(), asio::detached); + } + + [[nodiscard]] std::string url() const { + return "ws://127.0.0.1:" + std::to_string(acceptor.local_endpoint().port()) + "/relay"; + } + + asio::awaitable accept() { + for (;;) { + auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); + if (ec) { + co_return; + } + auto ws = std::make_shared>(std::move(socket)); + auto [accepted] = co_await ws->async_accept(asio::as_tuple(asio::use_awaitable)); + if (!accepted) { + held.push_back(std::move(ws)); + } + } + } + + tcp::acceptor acceptor; + std::vector>> held; +}; + +bool run_until(asio::io_context& io, const std::function& done, + std::chrono::milliseconds limit = 5s) { + const auto end = std::chrono::steady_clock::now() + limit; + while (!done() && std::chrono::steady_clock::now() < end) { + io.run_for(10ms); // lint-run: the client and the echo server do loopback network I/O + if (io.stopped()) { + io.restart(); + } + } + return done(); +} + +// A relay at an IPv6 literal, here 127.0.0.1 written as an IPv4-mapped IPv6 address so that the +// test stays on the loopback where IPv6 has no address: its brackets must not reach the resolver. +// The connection is a socket of IPv6's family, which a kernel without IPv6 cannot open (one with +// IPv6 disabled by sysctl opens it, and reaches the mapped address): there the case does not apply. +void a_relay_at_an_ipv6_address_opens() { + asio::io_context io; + tcp::socket probe(io); + if (boost::system::error_code ec; probe.open(tcp::v6(), ec)) { + std::cout + << "a_relay_at_an_ipv6_address_opens: not applicable, no socket of IPv6's family (" + << ec.message() << ")\n"; + return; + } + const echo_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + std::vector received; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, + "ws://[::ffff:127.0.0.1]:" + std::to_string(server.acceptor.local_endpoint().port()) + + "/relay", + { + .open = [&] { opened = true; }, + .message = [&](std::string_view text) { received.emplace_back(text); }, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return opened || closes != 0; }))) { + return; + } + if (!BOOST_TEST(opened)) { + return; + } + socket->send("over IPv6"); + BOOST_TEST(run_until(io, [&] { return received.size() == 1; })); + BOOST_TEST_EQ(closes, 0U); +} + +// What a socket reported, recorded by the handlers record() makes. +struct reports { + bool opened = false; + std::size_t closes = 0; + std::vector received; + + trystero::backend::websocket::handlers record() { + return { + .open = [this] { opened = true; }, + .message = [this](std::string_view text) { received.emplace_back(text); }, + .close = [this] { ++closes; }, + }; + } +}; + +// The context of make_tls_context, the backend's own: a client of TLS 1.2 or newer that verifies +// its peer. +void the_tls_context_verifies_peers_from_tls_1_2() { + auto tls = trystero::platform::make_tls_context(); + if (!BOOST_TEST(tls.has_value())) { + return; + } + BOOST_TEST_EQ(SSL_CTX_get_verify_mode(tls->native_handle()), SSL_VERIFY_PEER); + BOOST_TEST_EQ(SSL_CTX_get_min_proto_version(tls->native_handle()), TLS1_2_VERSION); +} + +// OpenSSL's queue holds what earlier calls left in it: the error reported is the one queued last, +// the failure's own, and the queue is emptied, so that a later failure is not reported with it. +void the_openssl_error_reported_is_the_one_queued_last() { + ERR_clear_error(); + ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH); // what an earlier call left behind + ERR_raise(ERR_LIB_SSL, SSL_R_NO_CIPHERS_AVAILABLE); // the failure's own + const auto last = ERR_peek_last_error(); + const auto error = trystero::platform::detail::openssl_error(); + BOOST_TEST_EQ(error.value(), static_cast(last)); + BOOST_TEST(error.category() == asio::error::get_ssl_category()); + BOOST_TEST_EQ(ERR_peek_error(), 0U); +} + +// A relay over TLS whose certificate an authority the context trusts signed for the URL's name: +// the socket names the host to the server (SNI), opens, and exchanges texts. +void a_relay_over_tls_opens_and_is_sent_its_name() { + asio::io_context io; + tls_echo_server server(io); + auto tls = webcpp::asio::make_tls_client_context(test_authority); + if (!BOOST_TEST(tls.has_value())) { + return; + } + reports seen; + const auto socket = + trystero::platform::connect_websocket(io.get_executor(), &*tls, server.url("localhost"), + seen.record(), std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return seen.opened || seen.closes != 0; })) || + !BOOST_TEST(seen.opened)) { + return; + } + socket->send("over TLS"); + BOOST_TEST(run_until(io, [&] { return seen.received.size() == 1; })); + BOOST_TEST_EQ(seen.closes, 0U); + BOOST_TEST_EQ(server.failed_handshakes, 0U); + const std::vector names{"localhost"}; + BOOST_TEST_ALL_EQ(server.server_names.begin(), server.server_names.end(), names.begin(), + names.end()); +} + +// The same relay reached at its address, which its certificate does not name: the socket sends +// no name (SNI names no address), refuses the certificate, and closes without opening. +void a_relay_whose_certificate_names_another_host_closes_without_opening() { + asio::io_context io; + tls_echo_server server(io); + auto tls = webcpp::asio::make_tls_client_context(test_authority); + if (!BOOST_TEST(tls.has_value())) { + return; + } + reports seen; + const auto socket = + trystero::platform::connect_websocket(io.get_executor(), &*tls, server.url("127.0.0.1"), + seen.record(), std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return seen.closes == 1 && server.failed_handshakes == 1; })); + BOOST_TEST(!seen.opened); + const std::vector names{""}; + BOOST_TEST_ALL_EQ(server.server_names.begin(), server.server_names.end(), names.begin(), + names.end()); +} + +// The same relay at its address written with escaped digits, which a page reads as the address: +// the socket sends no name either, and refuses the certificate, which names localhost alone. +void a_relay_at_an_escaped_address_is_sent_no_name() { + asio::io_context io; + tls_echo_server server(io); + auto tls = webcpp::asio::make_tls_client_context(test_authority); + if (!BOOST_TEST(tls.has_value())) { + return; + } + reports seen; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &*tls, server.url("%31%32%37.0.0.1"), seen.record(), + std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return seen.closes == 1 && server.failed_handshakes == 1; })); + BOOST_TEST(!seen.opened); + const std::vector names{""}; + BOOST_TEST_ALL_EQ(server.server_names.begin(), server.server_names.end(), names.begin(), + names.end()); +} + +// The same relay under its name, through the backend's own context, which trusts the system's +// authorities and not the test's: the socket refuses the certificate and closes without opening. +void a_relay_of_an_authority_not_trusted_closes_without_opening() { + asio::io_context io; + tls_echo_server server(io); + auto tls = trystero::platform::make_tls_context(); + if (!BOOST_TEST(tls.has_value())) { + return; + } + reports seen; + const auto socket = + trystero::platform::connect_websocket(io.get_executor(), &*tls, server.url("localhost"), + seen.record(), std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return seen.closes == 1 && server.failed_handshakes == 1; })); + BOOST_TEST(!seen.opened); +} + +// A program's context made as Asio makes a client's, whose verify mode is verify_none, whether it +// trusts the test's authority or nothing: the socket still verifies the relay, as a page's +// WebSocket always does, so it refuses the relay's certificate at the address the certificate does +// not name, and under its name when the context trusts nothing; the context itself is unchanged. +void a_programs_context_that_verifies_nothing_still_refuses_a_relay() { + asio::io_context io; + tls_echo_server server(io); + asio::ssl::context trusting(asio::ssl::context::tls_client); + boost::system::error_code ec; + if (!BOOST_TEST(!trusting.add_certificate_authority(asio::buffer(test_authority), ec))) { + return; + } + asio::ssl::context trusting_nothing(asio::ssl::context::tls_client); + reports other_name; + const auto at_address = trystero::platform::connect_websocket( + io.get_executor(), &trusting, server.url("127.0.0.1"), other_name.record(), + std::pmr::get_default_resource()); + reports untrusted; + const auto under_name = trystero::platform::connect_websocket( + io.get_executor(), &trusting_nothing, server.url("localhost"), untrusted.record(), + std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { + return other_name.closes == 1 && untrusted.closes == 1 && server.failed_handshakes == 2; + })); + BOOST_TEST(!other_name.opened); + BOOST_TEST(!untrusted.opened); + // The relay under its name, which the trusted authority signed, is still reached. + reports named; + const auto reached = + trystero::platform::connect_websocket(io.get_executor(), &trusting, server.url("localhost"), + named.record(), std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return named.opened || named.closes != 0; })); + BOOST_TEST(named.opened); + BOOST_TEST_EQ(SSL_CTX_get_verify_mode(trusting.native_handle()), SSL_VERIFY_NONE); + BOOST_TEST_EQ(SSL_CTX_get_verify_mode(trusting_nothing.native_handle()), SSL_VERIFY_NONE); +} + +// A backend given the authorities a program trusts reaches a relay they sign; one whose context +// could not be made holds the error, reaches no wss:// relay, and still reaches a ws:// one. +void a_backend_reaches_relays_with_the_tls_context_it_is_given() { + asio::io_context io; + const echo_server plain(io); + const tls_echo_server secure(io); + { + trystero::platform::backend backend(io.get_executor(), + webcpp::asio::make_tls_client_context(test_authority)); + BOOST_TEST(backend.tls_context().has_value()); + reports seen; + const auto socket = backend.connect(secure.url("localhost"), seen.record(), + std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return seen.opened || seen.closes != 0; })); + BOOST_TEST(seen.opened); + } + trystero::platform::backend backend(io.get_executor(), + webcpp::asio::make_tls_client_context("")); + const auto held = backend.tls_context(); + if (!BOOST_TEST(!held.has_value())) { + return; + } + BOOST_TEST(held.error() == + webcpp::asio::make_error_code(webcpp::asio::tls_context_error::invalid_ca_bundle)); + const auto handshakes = secure.server_names.size(); + reports refused; + const auto socket = backend.connect(secure.url("localhost"), refused.record(), + std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return refused.closes == 1; })); + BOOST_TEST(!refused.opened); + BOOST_TEST_EQ(secure.server_names.size(), handshakes); // never reached + reports reached; + const auto clear = + backend.connect(plain.url(), reached.record(), std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return reached.opened; })); +} + +// The backend made without a context of the program's makes its own, the system's authorities'. +void a_backend_makes_its_own_tls_context() { + asio::io_context io; + trystero::platform::backend backend(io.get_executor()); + BOOST_TEST(backend.tls_context().has_value()); +} + +// A backend that trusts webcpp's embedded Mozilla roots in place of the system's, as the guide +// shows it made (doc: #trystero-platform-relays): the test's authority is not among them, so its +// relay is unreachable. +void a_backend_may_trust_webcpps_embedded_roots() { + asio::io_context io; + const tls_echo_server server(io); + // tag::embedded-roots[] + trystero::platform::backend backend(io.get_executor(), webcpp::asio::make_tls_client_context()); + // end::embedded-roots[] + BOOST_TEST(backend.tls_context().has_value()); + reports seen; + const auto socket = + backend.connect(server.url("localhost"), seen.record(), std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return seen.closes == 1 && server.failed_handshakes == 1; })); + BOOST_TEST(!seen.opened); +} + +void opens_sends_in_order_receives_and_closes_once() { + asio::io_context io; + const echo_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + std::vector received; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, server.url(), + { + .open = [&] { opened = true; }, + .message = [&](std::string_view text) { received.emplace_back(text); }, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { + return; + } + for (const char* text : {"one", "two", R"(["EVENT",{"content":"three"}])"}) { + socket->send(text); + } + if (!BOOST_TEST(run_until(io, [&] { return received.size() == 3; }))) { + return; + } + const std::vector sent{"one", "two", R"(["EVENT",{"content":"three"}])"}; + BOOST_TEST_ALL_EQ(received.begin(), received.end(), sent.begin(), sent.end()); + socket->close(); + BOOST_TEST(run_until(io, [&] { return closes == 1; })); + socket->close(); + run_until(io, [] { return false; }, 100ms); + BOOST_TEST_EQ(closes, 1U); +} + +// A message longer than any relay's (protocol::max_relay_message_bytes) is never handed over: the +// socket closes, as the browser's does, and the room's strategy reconnects. +void a_message_longer_than_a_relay_sends_closes_the_socket() { + asio::io_context io; + const echo_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + std::vector received; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, server.url(), + { + .open = [&] { opened = true; }, + .message = [&](std::string_view text) { received.push_back(text.size()); }, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { + return; + } + socket->send(std::string(trystero::protocol::max_relay_message_bytes, 'x')); + if (!BOOST_TEST(run_until(io, [&] { return received.size() == 1; }))) { + return; + } + socket->send(std::string(trystero::protocol::max_relay_message_bytes + 1, 'x')); + BOOST_TEST(run_until(io, [&] { return closes == 1; })); + BOOST_TEST_EQ(received.size(), 1U); + BOOST_TEST_EQ(received.at(0), trystero::protocol::max_relay_message_bytes); +} + +// A binary message, which no Nostr relay sends, is dropped, as a page drops it, and the text after +// it reaches the room: the connection stays open. +void a_binary_message_from_a_relay_is_dropped() { + asio::io_context io; + const hostile_server server(io, misbehaviour::binary_then_text); + asio::ssl::context tls(asio::ssl::context::tls_client); + reports seen; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, server.url(), seen.record(), std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return seen.opened; }))) { + return; + } + socket->send("hello"); + BOOST_TEST(run_until(io, [&] { return !seen.received.empty(); })); + if (BOOST_TEST_EQ(seen.received.size(), 1U)) { + BOOST_TEST_EQ(seen.received.front(), "after"); + } + BOOST_TEST_EQ(seen.closes, 0U); +} + +void an_unreachable_relay_closes_without_opening() { + asio::io_context io; + tcp::acceptor taken(io, {asio::ip::make_address("127.0.0.1"), 0}); + const auto port = taken.local_endpoint().port(); + taken.close(); // nothing listens there now + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, "ws://127.0.0.1:" + std::to_string(port), + { + .open = [&] { opened = true; }, + .message = {}, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return closes == 1; })); + BOOST_TEST(!opened); +} + +// A relay at 127.1, which a page reads as 127.0.0.1 and the system's resolver may too: the socket +// refuses the URL and closes without opening, rather than reach the address under another name. +void a_relay_at_an_ipv4_shorthand_closes_without_opening() { + asio::io_context io; + const echo_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + reports seen; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, + "ws://127.1:" + std::to_string(server.acceptor.local_endpoint().port()) + "/relay", + seen.record(), std::pmr::get_default_resource()); + BOOST_TEST(run_until(io, [&] { return seen.opened || seen.closes != 0; })); + BOOST_TEST(!seen.opened); + BOOST_TEST_EQ(seen.closes, 1U); +} + +void a_dropped_socket_reports_nothing() { + asio::io_context io; + const echo_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + std::size_t events = 0; + { + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, server.url(), + { + .open = [&] { ++events; }, + .message = [&](std::string_view) { ++events; }, + .close = [&] { ++events; }, + }, + std::pmr::get_default_resource()); + } + run_until(io, [] { return false; }, 200ms); + BOOST_TEST_EQ(events, 0U); +} + +void closing_right_after_a_send_lets_the_write_finish_first() { + asio::io_context io; + const echo_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + const auto socket = trystero::platform::connect_websocket(io.get_executor(), &tls, server.url(), + { + .open = [&] { opened = true; }, + .message = {}, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { + return; + } + // What the Nostr strategy sends before it closes a relay. + socket->send(R"(["CLOSE","subscription"])"); + socket->close(); + BOOST_TEST(run_until(io, [&] { return closes == 1; })); +} + +// A connection that ends while a write is in flight: the relay sends a text too long to read, or +// resets the connection, while the client has many texts queued. The socket reports one close, and +// the write that was in flight finishes after it on a text it still owns. Each misbehaviour is met +// several times, since which of the read and the write completes first is the network's choice. +// The test is built with the standard library's own checks (test/Jamfile), so that a write +// completion that touches a cleared queue fails at once. +void a_connection_that_ends_during_a_write_closes_once(misbehaviour what) { + constexpr std::size_t connections = 10; + constexpr std::size_t texts = 200; + asio::io_context io; + const hostile_server server(io, what); + asio::ssl::context tls(asio::ssl::context::tls_client); + const std::string text(std::size_t{64} * 1024, 't'); + for (std::size_t i = 0; i < connections; ++i) { + bool opened = false; + std::size_t closes = 0; + std::shared_ptr socket; + socket = trystero::platform::connect_websocket(io.get_executor(), &tls, server.url(), + { + .open = + [&] { + opened = true; + for (std::size_t t = 0; + t < texts; ++t) { + socket->send(text); + } + }, + .message = {}, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return closes == 1; }))) { + return; + } + BOOST_TEST(opened); + socket.reset(); // as the room's strategy replaces a relay's socket when it reconnects + run_until(io, [] { return false; }, 50ms); + BOOST_TEST_EQ(closes, 1U); + } +} + +// A relay that stops reading: the texts a room sends it pile up in the socket's queue. At +// websocket_limits::max_queued_bytes the socket drops the connection, reports one close, and holds +// no more, so that the room reconnects with its backoff. +void a_relay_that_stops_reading_is_dropped_at_the_queue_bound() { + asio::io_context io; + const stalled_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + const auto socket = trystero::platform::connect_websocket(io.get_executor(), &tls, server.url(), + { + .open = [&] { opened = true; }, + .message = {}, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource()); + if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { + return; + } + const std::string text(std::size_t{64} * 1024, 't'); + for (std::size_t i = 0; i < 2000 && closes == 0; ++i) { + socket->send(text); + io.poll(); + } + BOOST_TEST(run_until(io, [&] { return closes == 1; })); + run_until(io, [] { return false; }, 100ms); + BOOST_TEST_EQ(closes, 1U); +} + +// A relay that stops answering while the room has nothing to send: a keep-alive ping goes +// unanswered, and the socket closes after websocket_limits::idle_timeout, here 1 s. +void a_relay_that_stops_answering_times_out() { + asio::io_context io; + const stalled_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, server.url(), + { + .open = [&] { opened = true; }, + .message = {}, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource(), + { + .max_queued_bytes = trystero::platform::websocket_limits{}.max_queued_bytes, + .idle_timeout = 1s, + }); + if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { + return; + } + BOOST_TEST(run_until(io, [&] { return closes == 1; }, 10s)); +} + +// A relay that is quiet but healthy: it sends nothing, but reads, so it answers each keep-alive +// ping. With a 1 s idle timeout, the socket stays open well past it, and then still echoes. +void a_quiet_relay_that_answers_pings_stays_connected() { + asio::io_context io; + const echo_server server(io); + asio::ssl::context tls(asio::ssl::context::tls_client); + bool opened = false; + std::size_t closes = 0; + std::vector received; + const auto socket = trystero::platform::connect_websocket( + io.get_executor(), &tls, server.url(), + { + .open = [&] { opened = true; }, + .message = [&](std::string_view text) { received.emplace_back(text); }, + .close = [&] { ++closes; }, + }, + std::pmr::get_default_resource(), + { + .max_queued_bytes = trystero::platform::websocket_limits{}.max_queued_bytes, + .idle_timeout = 1s, + }); + if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { + return; + } + run_until(io, [&] { return closes != 0; }, 3s); // three idle timeouts + BOOST_TEST_EQ(closes, 0U); + socket->send("still there"); + BOOST_TEST(run_until(io, [&] { return received.size() == 1; })); +} + +} // namespace + +int main() { + a_relay_at_an_ipv6_address_opens(); + the_tls_context_verifies_peers_from_tls_1_2(); + the_openssl_error_reported_is_the_one_queued_last(); + a_relay_over_tls_opens_and_is_sent_its_name(); + a_relay_whose_certificate_names_another_host_closes_without_opening(); + a_relay_at_an_escaped_address_is_sent_no_name(); + a_relay_of_an_authority_not_trusted_closes_without_opening(); + a_programs_context_that_verifies_nothing_still_refuses_a_relay(); + a_backend_reaches_relays_with_the_tls_context_it_is_given(); + a_backend_makes_its_own_tls_context(); + a_backend_may_trust_webcpps_embedded_roots(); + opens_sends_in_order_receives_and_closes_once(); + a_message_longer_than_a_relay_sends_closes_the_socket(); + a_binary_message_from_a_relay_is_dropped(); + an_unreachable_relay_closes_without_opening(); + a_relay_at_an_ipv4_shorthand_closes_without_opening(); + a_dropped_socket_reports_nothing(); + closing_right_after_a_send_lets_the_write_finish_first(); + a_connection_that_ends_during_a_write_closes_once(misbehaviour::too_long_text); + a_connection_that_ends_during_a_write_closes_once(misbehaviour::reset); + a_relay_that_stops_reading_is_dropped_at_the_queue_bound(); + a_relay_that_stops_answering_times_out(); + a_quiet_relay_that_answers_pings_stays_connected(); + return boost::report_errors(); +} diff --git a/test/platform_websocket_unreachable_test.cpp b/test/platform_websocket_unreachable_test.cpp new file mode 100644 index 0000000..dd43f54 --- /dev/null +++ b/test/platform_websocket_unreachable_test.cpp @@ -0,0 +1,158 @@ +// 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) + +// Tests the platform backend's relay WebSockets to relays it cannot reach, on both targets: a URL +// the session does not take (another scheme, http and https among them, a fragment, no URL, a +// relative one) makes no connection and reports a close, as the backend interface says of a relay +// it cannot connect to; one it takes, of a port on 127.0.0.1 or ::1 where nothing listens, is +// attempted and fails to connect, natively with Boost.Beast's TCP connect and on emscripten with +// node's WebSocket, whose close comes before any open, and reports a close too. Each reports +// exactly one, after the call that made it, never inside it, and nothing is thrown; a send before +// the connection opened changes nothing, and so does a close of a refused one. On emscripten the +// test counts the WebSockets made: one for each URL taken, none for a refused one. Before the fix, +// a page's `new WebSocket` threw a SyntaxError through the room's constructor; and the test closed +// every socket in the call that made it, so that no URL was attempted, no WebSocket made in a page +// and no connection natively. +// +// main makes the sockets from a handler of the io_context, as a room does, and runs the io_context +// under a work guard, which the verdict releases once every URL has reported its close and a +// little more time has shown no second one; a step that does not come within 10 s fails by name. + +#include + +#include +#include +#include +#include + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#include +#include +#endif +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +#ifdef WEBCPP_TARGET_EMSCRIPTEN +// Counts the WebSockets the page makes, on globalThis, each still node's own. +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type) +EM_JS(void, count_websockets, (), { + globalThis.madeWebSockets = 0; + const Page = globalThis.WebSocket; + globalThis.WebSocket = class extends Page { + constructor(...values) { + ++globalThis.madeWebSockets; + super(...values); + } + }; +}); +// clang-format on +#endif + +namespace { + +/** A relay's URL, and whether the session takes it and attempts a connection. */ +struct relay_url { + std::string_view url; + bool attempted; +}; + +/** + * URLs the session refuses (another scheme, a fragment, no URL, a relative one, and http and https, + * which a page's WebSocket would take as ws and wss), and ones it takes, to a port where nothing + * listens. + */ +constexpr std::array urls{ + relay_url{.url = "ftp://relay.invalid", .attempted = false}, + relay_url{.url = "wss://relay.invalid/#fragment", .attempted = false}, + relay_url{.url = "not a url", .attempted = false}, + relay_url{.url = "/relative", .attempted = false}, + relay_url{.url = "http://127.0.0.1:9", .attempted = false}, + relay_url{.url = "https://127.0.0.1:9", .attempted = false}, + relay_url{.url = "ws://127.0.0.1:9", .attempted = true}, + relay_url{.url = "ws://[::1]:9", .attempted = true}, +}; + +struct state { + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; + asio::steady_timer settle{io}; + std::array, urls.size()> sockets; + std::array closes{}; + std::size_t total = 0; + bool judged = false; +}; + +/** Judges once every URL has reported its close, after 100 ms more, in which a second one of any + * would come. */ +void closed(state& s, std::size_t i) { + ++s.closes.at(i); + if (++s.total != urls.size()) { + return; + } + s.settle.expires_after(100ms); + s.settle.async_wait([&s](boost::system::error_code) { + for (std::size_t j = 0; j < urls.size(); ++j) { + BOOST_TEST_EQ(s.closes.at(j), 1U); + } +#ifdef WEBCPP_TARGET_EMSCRIPTEN + BOOST_TEST_EQ(emscripten::val::global("madeWebSockets").as(), 2U); +#endif + s.sockets = {}; // destroyed after the close: nothing more is reported + s.judged = true; + s.guard.reset(); + }); +} + +/** + * Makes a WebSocket of each URL and sends on it; closes one the session refuses, and leaves one it + * attempts to fail on its own. + */ +void connect_all(state& s) { + for (std::size_t i = 0; i < urls.size(); ++i) { + s.sockets.at(i) = s.backend.connect(urls.at(i).url, + { + .open = [] { BOOST_ERROR("a URL opened"); }, + .message = {}, + .close = [&s, i] { closed(s, i); }, + }, + std::pmr::get_default_resource()); + s.sockets.at(i)->send("ignored"); + if (!urls.at(i).attempted) { + s.sockets.at(i)->close(); + } + BOOST_TEST_EQ(s.closes.at(i), 0U); // not inside the call + } +} + +} // namespace + +int main() { +#ifdef WEBCPP_TARGET_EMSCRIPTEN + count_websockets(); +#endif + state s; + asio::post(s.io, [&s] { connect_all(s); }); + s.io.run_for(10s); // lint-run: the test's event loop, held by its work guard until the verdict + if (!s.judged) { + BOOST_ERROR("not every URL reported a close"); + } + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/platform_websocket_url_test.cpp b/test/platform_websocket_url_test.cpp new file mode 100644 index 0000000..fe478a6 --- /dev/null +++ b/test/platform_websocket_url_test.cpp @@ -0,0 +1,183 @@ +// 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) + +// Tests how the platform backend's relay WebSocket reads a relay's URL, with Boost.URL, by the same +// rules on both targets, natively and in a page under node: a scheme, a host, a port and a path; +// an escaped address read as an address; an IPv6 address without its brackets for the resolver; +// what a page's WebSocket refuses (another scheme, userinfo, a fragment, a port beyond 65535, an +// IPvFuture host), and what a page's URL parser reads otherwise than this one (an IPv4 address in +// another form than a dotted quad, a last label that is a number, an international name, a tab, a +// newline, a backslash, a path character outside RFC 3986), each refused. Its cases ran natively +// only, in platform_websocket, before. + +#include + +#include + +#include +#include + +namespace trystero = webcpp::trystero; + +namespace { + +void urls_name_a_scheme_host_port_and_path() { + const auto secure = trystero::platform::detail::parse_url("wss://relay.example.org"); + if (!BOOST_TEST(secure.has_value())) { + return; + } + BOOST_TEST(secure->secure); + BOOST_TEST(secure->named); + BOOST_TEST_EQ(secure->host, "relay.example.org"); + BOOST_TEST_EQ(secure->port, "443"); + BOOST_TEST_EQ(secure->handshake_host, "relay.example.org"); + BOOST_TEST_EQ(secure->target, "/"); + const auto plain = trystero::platform::detail::parse_url("ws://127.0.0.1:7447/nostr?x=1"); + if (!BOOST_TEST(plain.has_value())) { + return; + } + BOOST_TEST(!plain->secure); + BOOST_TEST(!plain->named); + BOOST_TEST_EQ(plain->host, "127.0.0.1"); + BOOST_TEST_EQ(plain->port, "7447"); + BOOST_TEST_EQ(plain->handshake_host, "127.0.0.1:7447"); + BOOST_TEST_EQ(plain->target, "/nostr?x=1"); + BOOST_TEST(!trystero::platform::detail::parse_url("https://example.org").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("wss://").has_value()); +} + +// A host is a name or an address once its escapes are decoded, as a page reads it: 127.0.0.1 with +// escaped digits, a name to Boost.URL, is an address, which TLS never names to the server (SNI). +void urls_read_an_escaped_address_as_an_address() { + const auto escaped = trystero::platform::detail::parse_url("wss://%31%32%37.0.0.1:7447/"); + if (!BOOST_TEST(escaped.has_value())) { + return; + } + BOOST_TEST(!escaped->named); + BOOST_TEST_EQ(escaped->host, "127.0.0.1"); + BOOST_TEST_EQ(escaped->handshake_host, "127.0.0.1:7447"); + const auto name = trystero::platform::detail::parse_url("wss://%72elay.example.org/"); + if (!BOOST_TEST(name.has_value())) { + return; + } + BOOST_TEST(name->named); + BOOST_TEST_EQ(name->host, "relay.example.org"); +} + +// An IPv6 address reaches the resolver without its brackets; a scheme in capitals is still a +// WebSocket's; userinfo and a fragment, which a page's WebSocket refuses, are refused. +void urls_name_ipv6_hosts_and_refuse_what_a_page_refuses() { + const auto ipv6 = trystero::platform::detail::parse_url("ws://[::1]:7447/nostr"); + if (!BOOST_TEST(ipv6.has_value())) { + return; + } + BOOST_TEST(!ipv6->named); + BOOST_TEST_EQ(ipv6->host, "::1"); + BOOST_TEST_EQ(ipv6->port, "7447"); + BOOST_TEST_EQ(ipv6->handshake_host, "[::1]:7447"); + BOOST_TEST_EQ(ipv6->target, "/nostr"); + const auto default_port = trystero::platform::detail::parse_url("wss://[2001:db8::1]"); + if (!BOOST_TEST(default_port.has_value())) { + return; + } + BOOST_TEST_EQ(default_port->host, "2001:db8::1"); + BOOST_TEST_EQ(default_port->port, "443"); + BOOST_TEST_EQ(default_port->handshake_host, "[2001:db8::1]"); + const auto capitals = trystero::platform::detail::parse_url("WSS://Relay.Example.ORG/Path"); + if (!BOOST_TEST(capitals.has_value())) { + return; + } + BOOST_TEST(capitals->secure); + BOOST_TEST_EQ(capitals->host, "relay.example.org"); + BOOST_TEST_EQ(capitals->port, "443"); + BOOST_TEST_EQ(capitals->target, "/Path"); + // The scheme's own port, written out, is still the default one; an empty port is too. + const auto written_default = + trystero::platform::detail::parse_url("ws://relay.example.org:080"); + if (!BOOST_TEST(written_default.has_value())) { + return; + } + BOOST_TEST_EQ(written_default->port, "80"); + BOOST_TEST_EQ(written_default->handshake_host, "relay.example.org"); + const auto empty_port = trystero::platform::detail::parse_url("wss://relay.example.org:/"); + if (!BOOST_TEST(empty_port.has_value())) { + return; + } + BOOST_TEST_EQ(empty_port->port, "443"); + const auto query = trystero::platform::detail::parse_url("ws://relay.example.org?x=1"); + if (!BOOST_TEST(query.has_value())) { + return; + } + BOOST_TEST_EQ(query->target, "/?x=1"); + const auto escaped = trystero::platform::detail::parse_url("ws://rel%61y.example.org/"); + if (!BOOST_TEST(escaped.has_value())) { + return; + } + BOOST_TEST_EQ(escaped->host, "relay.example.org"); + BOOST_TEST( + !trystero::platform::detail::parse_url("wss://user:pw@relay.example.org").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("wss://relay.example.org/#top").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("wss://relay.example.org:99999").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("ws:relay.example.org").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("ws://[v1.x]/").has_value()); + // A name the resolver would read up to its first NUL. + BOOST_TEST(!trystero::platform::detail::parse_url("ws://relay%00.example.org/").has_value()); +} + +// The URL, or "refused" when parse_url refuses it, so that a failed check names the URL. +std::string read_or_refused(std::string_view url) { + return trystero::platform::detail::parse_url(url).has_value() ? std::string(url) : "refused"; +} + +// What a page's URL parser reads otherwise than this one is refused, never read another way: a +// host a page reads as an IPv4 address in another form than a dotted quad (a shorthand, octal or +// hexadecimal parts, a final dot, a single number), or refuses (a last label of digits); a byte +// beyond ASCII, escaped or not, of an international name, which a page turns into its A-label; a +// tab, a newline or a backslash, which a page drops or reads as a slash; and a path character +// outside RFC 3986, which a page escapes. +void urls_refuse_what_a_page_reads_otherwise() { + for (const std::string_view url : { + "ws://127.1/", + "ws://0x7f.0.0.1/", + "ws://127.000.0.1/", + "ws://0177.0.0.1/", + "ws://127.0.0.1./", + "ws://2130706433/", + "ws://relay.123/", + "ws://relay.0x/", + "ws://relay.0x1f./", + "wss://b%C3%BCcher.example/", + "wss://b\303\274cher.example/", // a u with diaeresis, its UTF-8 bytes not escaped + "ws://rel\tay.example.org/", + "ws://relay.example.org\n/", + R"(ws:\\relay.example.org\)", + R"(ws://relay.example.org\nostr)", + "ws://relay.example.org/a b", + "ws://relay.example.org/{x}", + "ws://relay.example.org/b\303\274cher", + }) { + BOOST_TEST_EQ(read_or_refused(url), "refused"); + } + // A last label that is not a number is a name's, a final dot included. + for (const std::string_view url : { + "ws://relay.example.org./", + "ws://relay.example.1a/", + "ws://relay.0xg/", + "ws://1.2.3.example/", + }) { + BOOST_TEST_EQ(read_or_refused(url), url); + } +} + +} // namespace + +int main() { + urls_name_a_scheme_host_port_and_path(); + urls_read_an_escaped_address_as_an_address(); + urls_name_ipv6_hosts_and_refuse_what_a_page_refuses(); + urls_refuse_what_a_page_reads_otherwise(); + return boost::report_errors(); +} diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index e16f221..6b77dc2 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -6,123 +6,208 @@ // Tests the protocol layer against values Trystero JS 0.26 computed itself, which the original's // oracle wrote into fixtures/expected/expected.json. The fixture's path is the test's one argument, -// as webcpp.run passes its input file. +// as webcpp.run passes its input file. The fixture is read with webcpp::document, and every text +// the protocol writes is read back as a room reads it, with webcpp::document::parse into a +// pmr::document, within protocol::json::protocol_limits of its bound. #include #include +#include #include #include #include #include +#include +#include +#include +#include +#include + #include -#include #include #include +#include #include #include #include -#include +#include +#include +#include +#include #include #include #include #include +#include #include #include -namespace json = boost::json; +#include "bookkeeping.hpp" + +namespace wd = webcpp::document; namespace tp = webcpp::trystero::protocol; namespace { -json::value load(const char* path) { +/** A value of the fixture: a read-only handle of an owned document. */ +using fixture_value = wd::basic_const_value<>; + +/** The fixture, read as JSON.parse reads it. */ +wd::result load(const char* path) { const std::ifstream file(path); std::stringstream text; text << file.rdbuf(); - return json::parse(text.str()); + return wd::parse(text.str()); } -std::string_view str(const json::value& v) { - return v.as_string(); +std::string_view str(const fixture_value& v) { + return v.value_or(std::string_view()); } -tp::bytes hex(const json::value& v) { - return *tp::from_hex(v.as_string()); +// Every number of the fixture is an integer; -1 marks one that is not, or a missing one. +std::int64_t integer(const fixture_value& v) { + return v.value_or(std::int64_t{-1}); } -void topics(const json::object& fixture) { - for (const auto& entry : fixture.at("topics").as_array()) { - const auto& t = entry.as_object(); - const auto app = str(t.at("app_id")); - const auto room = str(t.at("room_id")); - BOOST_TEST_EQ(tp::root_topic(app, room), str(t.at("root_topic"))); - BOOST_TEST_EQ(tp::peer_topic(app, room, str(t.at("peer_id"))), str(t.at("self_topic"))); - BOOST_TEST_EQ(tp::room_token(app, room), str(t.at("room_token"))); +tp::bytes hex(const fixture_value& v) { + return tp::from_hex(str(v)).value(); +} + +/** A protocol text read as a room reads it: at most `max_bytes`, into a document of `memory`. */ +wd::result parse_text( + std::string_view text, std::size_t max_bytes, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + return wd::parse(text, tp::json::protocol_limits(max_bytes), + std::pmr::polymorphic_allocator(memory)); +} + +/** + * A resource that counts what it gives: its allocations, their bytes, the most bytes out at once, + * and what is still out, by address. + */ +class counting_resource final : public std::pmr::memory_resource { +public: + /** How many allocations it made, a standard container's own (bookkeeping.hpp) left out. */ + std::size_t allocations = 0; + /** The bytes of its largest allocation. */ + std::size_t largest = 0; + /** The bytes out now. */ + std::size_t bytes_out = 0; + /** The most bytes that were out at once. */ + std::size_t peak = 0; + /** The allocations not yet returned, with their bytes. */ + std::map live; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + if (!webcpp::test::is_bookkeeping(bytes, alignment)) { + ++allocations; + } + largest = std::max(largest, bytes); + bytes_out += bytes; + peak = std::max(peak, bytes_out); + void* const p = std::pmr::new_delete_resource()->allocate(bytes, alignment); + live.emplace(p, bytes); + return p; } - for (const auto& entry : fixture.at("str_to_num").as_array()) { - const auto& t = entry.as_object(); - BOOST_TEST_EQ(tp::str_to_num(str(t.at("text"))), t.at("unbounded").to_number()); - BOOST_TEST_EQ(tp::str_to_num(str(t.at("text")), 10000), - t.at("mod_10000").to_number()); + + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + bytes_out -= bytes; + live.erase(p); + 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; + } +}; + +void topics(const fixture_value& fixture) { + for (const auto t : fixture["topics"]) { + const auto app = str(t["app_id"]); + const auto room = str(t["room_id"]); + BOOST_TEST_EQ(tp::root_topic(app, room), str(t["root_topic"])); + BOOST_TEST_EQ(tp::peer_topic(app, room, str(t["peer_id"])), str(t["self_topic"])); + BOOST_TEST_EQ(tp::room_token(app, room), str(t["room_token"])); + } + for (const auto t : fixture["str_to_num"]) { + BOOST_TEST_EQ(tp::str_to_num(str(t["text"])), static_cast(integer(t["unbounded"]))); + BOOST_TEST_EQ(tp::str_to_num(str(t["text"]), 10000), + static_cast(integer(t["mod_10000"]))); } } -void relays(const json::object& fixture) { +void relays(const fixture_value& fixture) { std::vector defaults; - for (const auto& url : fixture.at("default_relays").as_array()) { - defaults.push_back(url.as_string()); + for (const auto url : fixture["default_relays"]) { + defaults.push_back(str(url)); } BOOST_TEST(std::ranges::equal(defaults, tp::default_nostr_relays)); - for (const auto& entry : fixture.at("relays").as_array()) { + for (const auto entry : fixture["relays"]) { std::vector expected; - for (const auto& url : entry.at("relays").as_array()) { - expected.push_back(url.as_string()); + for (const auto url : entry["relays"]) { + expected.push_back(str(url)); } - const auto derived = - tp::derive_relays(str(entry.at("app_id")), tp::default_nostr_relays, 5); + const auto derived = tp::derive_relays(str(entry["app_id"]), tp::default_nostr_relays, 5); BOOST_TEST_ALL_EQ(derived.begin(), derived.end(), expected.begin(), expected.end()); } - for (const auto& entry : fixture.at("shuffle").as_array()) { + for (const auto entry : fixture["shuffle"]) { std::vector order(29); for (int i = 0; i < 29; ++i) { order[i] = i; } std::vector expected; - for (const auto& i : entry.at("order").as_array()) { - expected.push_back(static_cast(i.as_int64())); + for (const auto i : entry["order"]) { + expected.push_back(static_cast(integer(i))); } - const auto shuffled = tp::shuffle(order, entry.at("seed").to_number()); + const auto shuffled = tp::shuffle(order, static_cast(integer(entry["seed"]))); BOOST_TEST_ALL_EQ(shuffled.begin(), shuffled.end(), expected.begin(), expected.end()); } } -void handshake_and_sealing(const json::object& fixture) { - for (const auto& entry : fixture.at("handshake").as_array()) { - BOOST_TEST_EQ(tp::handshake_proof(str(entry.at("challenge")), str(entry.at("password")), - str(entry.at("app_id")), str(entry.at("room_id"))), - str(entry.at("hash"))); +void handshake_and_sealing(const fixture_value& fixture) { + for (const auto entry : fixture["handshake"]) { + BOOST_TEST_EQ(tp::handshake_proof(str(entry["challenge"]), str(entry["password"]), + str(entry["app_id"]), str(entry["room_id"])), + str(entry["hash"])); } - const auto& sealed = fixture.at("sealed").as_object(); + const auto sealed = fixture["sealed"]; BOOST_TEST_EQ(tp::to_hex(tp::seal_key("secret", "my-app", "room-1")), - str(sealed.at("key_material"))); - const auto parts = tp::parse_sealed(str(sealed.at("text"))); + str(sealed["key_material"])); + const auto parts = tp::parse_sealed(str(sealed["text"])); BOOST_TEST(parts.has_value()); BOOST_TEST_EQ(parts->iv.size(), tp::seal_iv_size); - BOOST_TEST_EQ(parts->ciphertext.size(), str(sealed.at("plaintext")).size() + 16); - BOOST_TEST_EQ(tp::format_sealed(parts->iv, parts->ciphertext), str(sealed.at("text"))); + BOOST_TEST_EQ(parts->ciphertext.size(), str(sealed["plaintext"]).size() + 16); + BOOST_TEST_EQ(tp::format_sealed(parts->iv, parts->ciphertext), str(sealed["text"])); BOOST_TEST(!tp::parse_sealed("1,2,300$AAAA").has_value()); BOOST_TEST(!tp::parse_sealed("no dollar").has_value()); } -void nostr_events(const json::object& fixture) { - for (const auto& entry : fixture.at("nostr_events").as_array()) { - const auto& e = entry.as_object(); - BOOST_TEST_EQ(tp::nostr::topic_kind(str(e.at("topic"))), e.at("kind").as_int64()); - const auto id = tp::nostr::event_id(str(e.at("pubkey")), e.at("created_at").as_int64(), - static_cast(e.at("kind").as_int64()), - str(e.at("topic")), str(e.at("content"))); - BOOST_TEST_EQ(tp::to_hex(id), str(e.at("id"))); +/** A relay's echo of a client's `["EVENT",]`: the event's text whole, less the client's + * first 9 bytes and its last, in `["EVENT","sub",]`. */ +std::string echo_of(std::string_view message) { + std::string echo = R"(["EVENT","sub",)"; + echo += message.substr(9, message.size() - 10); + echo += ']'; + return echo; +} + +/** The integer a protocol text holds, -1 for any other value. */ +std::int64_t integer_of(const tp::json::const_value& v) { + return v.value_or(std::int64_t{-1}); +} + +void nostr_events(const fixture_value& fixture) { + for (const auto e : fixture["nostr_events"]) { + BOOST_TEST_EQ(tp::nostr::topic_kind(str(e["topic"])), integer(e["kind"])); + const auto created_at = + std::chrono::sys_seconds(std::chrono::seconds(integer(e["created_at"]))); + const auto id = tp::nostr::event_id(str(e["pubkey"]), created_at, + static_cast(integer(e["kind"])), + str(e["topic"]), str(e["content"])); + BOOST_TEST_EQ(tp::to_hex(id), str(e["id"])); } // A signed event verifies, and a relay's echo of it parses back to its topic and content. std::array secret{}; @@ -131,30 +216,203 @@ void nostr_events(const json::object& fixture) { BOOST_TEST(key.has_value()); std::array aux{}; const auto message = - tp::nostr::event_message(*key, 1759700000, "topic-a", R"({"peerId":"p"})", aux); - const auto parsed = json::parse(message).as_array(); - auto event = parsed.at(1).as_object(); - const auto id = *tp::from_hex(event.at("id").as_string()); - const auto sig = *tp::from_hex(event.at("sig").as_string()); - const auto pub = *tp::from_hex(event.at("pubkey").as_string()); + tp::nostr::event_message(*key, std::chrono::sys_seconds(std::chrono::seconds(1759700000)), + "topic-a", R"({"peerId":"p"})", aux); + const auto parsed = parse_text(message, tp::nostr::max_parsed_relay_text_bytes).value(); + const auto event = parsed.root()[1]; + const auto id = tp::from_hex(tp::json::text_of(event["id"])).value(); + const auto sig = tp::from_hex(tp::json::text_of(event["sig"])).value(); + const auto pub = tp::from_hex(tp::json::text_of(event["pubkey"])).value(); BOOST_TEST(tp::nostr::verify(std::span(sig.data(), 64), std::span(id.data(), 32), std::span(pub.data(), 32))); - const auto echoed_document = json::value(json::array{"EVENT", "sub", event}); - const auto echoed = tp::nostr::read_relay_message(echoed_document); + const std::string_view written = message; + BOOST_TEST(written.starts_with(R"(["EVENT",{)") && written.ends_with("}]")); + const auto echoed_document = + parse_text(echo_of(message), tp::nostr::max_parsed_relay_text_bytes).value(); + const auto echoed = tp::nostr::read_relay_message(echoed_document.root()); BOOST_TEST(echoed.has_value()); const auto& e = std::get(*echoed); BOOST_TEST_EQ(e.subscription, "sub"); BOOST_TEST_EQ(e.topic, "topic-a"); BOOST_TEST_EQ(e.content, R"({"peerId":"p"})"); - const auto rejected_document = json::parse(R"(["OK","abc",false,"rate-limited: slow down"])"); - const auto rejected = tp::nostr::read_relay_message(rejected_document); + constexpr std::string_view rate_limited = R"(["OK","abc",false,"rate-limited: slow down"])"; + const auto rejected_document = + parse_text(rate_limited, tp::nostr::max_parsed_relay_text_bytes).value(); + const auto rejected = tp::nostr::read_relay_message(rejected_document.root()); BOOST_TEST_EQ(std::get(*rejected).reason, "rate-limited: slow down"); BOOST_TEST(!std::get(*rejected).accepted); } -void inline_frames(const json::object& fixture) { - const auto& actions = fixture.at("actions").as_object(); +// An event message and a subscription write the values they are given, read back as a relay reads +// them: the kind Trystero gives the topic, `created_at` and `since` the time, the fixture's and one +// past 2^32 seconds, which 32 bits would not hold, and an id computed again from the message's own +// fields. A subscription lists each kind once, in increasing order, and the topics as given. +void nostr_message_fields(const fixture_value& fixture) { + const auto first = fixture["nostr_events"][0]; + const auto topic = str(first["topic"]); + const auto kind = integer(first["kind"]); + // A topic of another kind, which Trystero's own event message for it holds. + const auto other = fixture["event_messages"]["events"][0]; + const auto other_topic = str(other["topic"]); + const auto other_message = + parse_text(str(other["message"]), tp::nostr::max_parsed_relay_text_bytes); + if (!BOOST_TEST(other_message.has_value())) { + return; + } + const auto other_kind = integer_of(other_message->root()[1]["kind"]); + BOOST_TEST_NE(kind, other_kind); + std::array secret{}; + secret.fill(7); + const auto key = tp::nostr::signer::from_secret(secret); + if (!BOOST_TEST(key.has_value())) { + return; + } + const std::array aux{}; + for (const std::int64_t seconds : {integer(first["created_at"]), std::int64_t{4'354'000'000}}) { + const auto at = std::chrono::sys_seconds(std::chrono::seconds(seconds)); + const auto message = tp::nostr::event_message(*key, at, topic, R"({"peerId":"p"})", aux); + const auto document = parse_text(message, tp::nostr::max_parsed_relay_text_bytes); + if (!BOOST_TEST(document.has_value())) { + continue; + } + const auto event = document->root()[1]; + BOOST_TEST_EQ(integer_of(event["created_at"]), seconds); + BOOST_TEST_EQ(integer_of(event["kind"]), kind); + const auto tags = event["tags"]; + BOOST_TEST_EQ(tags.size(), 1U); + BOOST_TEST_EQ(tags[0].size(), 2U); + BOOST_TEST_EQ(tp::json::text_of(tags[0][0]), "x"); + BOOST_TEST_EQ(tp::json::text_of(tags[0][1]), topic); + BOOST_TEST_EQ(tp::json::text_of(event["content"]), R"({"peerId":"p"})"); + BOOST_TEST_EQ(tp::json::text_of(event["pubkey"]), key->pubkey()); + const auto id = tp::nostr::event_id( + tp::json::text_of(event["pubkey"]), + std::chrono::sys_seconds(std::chrono::seconds(integer_of(event["created_at"]))), + static_cast(integer_of(event["kind"])), tp::json::text_of(tags[0][1]), + tp::json::text_of(event["content"])); + BOOST_TEST_EQ(tp::to_hex(id), tp::json::text_of(event["id"])); + + const std::array topics{ + std::pmr::string(topic), + std::pmr::string(other_topic), + std::pmr::string(topic), + }; + const auto request = parse_text(tp::nostr::subscribe_message("sub-1", topics, at), + tp::nostr::max_parsed_relay_text_bytes); + if (!BOOST_TEST(request.has_value())) { + continue; + } + const auto req = request->root(); + BOOST_TEST_EQ(req.size(), 3U); + BOOST_TEST_EQ(tp::json::text_of(req[0]), "REQ"); + BOOST_TEST_EQ(tp::json::text_of(req[1]), "sub-1"); + const auto filter = req[2]; + BOOST_TEST_EQ(integer_of(filter["since"]), seconds); + std::vector kinds; + for (const auto k : filter["kinds"]) { + kinds.push_back(integer_of(k)); + } + const std::array increasing{ + std::min(kind, other_kind), + std::max(kind, other_kind), + }; + BOOST_TEST_ALL_EQ(kinds.begin(), kinds.end(), increasing.begin(), increasing.end()); + std::vector named; + for (const auto t : filter["#x"]) { + named.push_back(tp::json::text_of(t)); + } + BOOST_TEST_ALL_EQ(named.begin(), named.end(), topics.begin(), topics.end()); + } +} + +/** `text` with the first `from` in it replaced by `to`; a `from` it does not hold fails the test. + */ +std::string replaced(std::string_view text, std::string_view from, std::string_view to) { + std::string out(text); + const auto at = out.find(from); + if (BOOST_TEST(at != std::string::npos)) { + out.replace(at, from.size(), to); + } + return out; +} + +/** The id a client's `["EVENT",]` holds, as event_message writes it. */ +std::string_view id_in(std::string_view message) { + constexpr std::string_view key = R"("id":")"; + return message.substr(message.find(key) + key.size(), 64); +} + +/** `hex` with its letters in uppercase. */ +std::string uppercase(std::string_view hex) { + std::string out(hex); + for (char& c : out) { + if (c >= 'a' && c <= 'f') { + c = static_cast(c - 'a' + 'A'); + } + } + return out; +} + +/** Whether the event of a client's `["EVENT",]`, read from a relay's echo of it, has its + * own id; false when it is no event. */ +bool own_id(std::string_view message) { + const auto document = parse_text(echo_of(message), tp::nostr::max_parsed_relay_text_bytes); + if (!document.has_value()) { + return false; + } + const auto read = tp::nostr::read_relay_message(document->root()); + const auto* e = read.has_value() ? std::get_if(&*read) : nullptr; + return e != nullptr && tp::nostr::has_own_id(*e); +} + +// An event's id is its own when it is the SHA-256 of NIP-01's serialization of the event: that of +// each event Trystero's createEvent made, whose contents hold every character JSON escapes, and of +// one whose time is written as another JSON text of the same number. An event changed in any field +// the id hashes, or under another event's id, does not have its own id; neither has one whose tags +// are more than its topic's, which NIP-01 hashes too, nor one whose time or kind is not an integer, +// nor one whose public key or id is not in lowercase, whatever its id. +void event_ids_are_their_own(const fixture_value& fixture) { + for (const auto e : fixture["event_messages"]["events"]) { + BOOST_TEST(own_id(str(e["message"]))); + } + std::array secret{}; + secret.fill(7); + const auto key = tp::nostr::signer::from_secret(secret); + if (!BOOST_TEST(key.has_value())) { + return; + } + const std::array aux{}; + const auto at = std::chrono::sys_seconds(std::chrono::seconds(1759700000)); + const std::string message( + tp::nostr::event_message(*key, at, "topic-a", R"({"peerId":"p"})", aux)); + const std::string kind = R"("kind":)" + std::to_string(tp::nostr::topic_kind("topic-a")); + const std::string other_kind = + R"("kind":)" + std::to_string(tp::nostr::topic_kind("topic-a") + 1); + const std::string created_at = R"("created_at":1759700000)"; + const std::string forged_from( + tp::nostr::event_message(*key, at, "topic-a", R"({"peerId":"forged"})", aux)); + const std::string forged = replaced(forged_from, id_in(forged_from), id_in(message)); + + BOOST_TEST(own_id(message)); + BOOST_TEST(own_id(replaced(message, created_at, R"("created_at":1.7597e9)"))); + BOOST_TEST(!own_id(replaced(message, R"({\"peerId\")", R"({\"peerID\")"))); + BOOST_TEST(!own_id(replaced(message, R"("topic-a")", R"("topic-b")"))); + BOOST_TEST(!own_id(replaced(message, kind, other_kind))); + BOOST_TEST(!own_id(replaced(message, created_at, R"("created_at":1759700001)"))); + BOOST_TEST(!own_id(forged)); + BOOST_TEST(!own_id(replaced(message, R"("topic-a"]])", R"("topic-a"],["e","f"]])"))); + BOOST_TEST(!own_id(replaced(message, R"("topic-a"]])", R"("topic-a","r"]])"))); + BOOST_TEST(!own_id(replaced(message, created_at, R"("created_at":"1759700000")"))); + BOOST_TEST(!own_id(replaced(message, created_at, R"("created_at":1759700000.5)"))); + BOOST_TEST(!own_id(replaced(message, created_at, R"("created_at":1e30)"))); + BOOST_TEST(!own_id(replaced(message, kind, R"("kind":4294967296)"))); + BOOST_TEST(!own_id(replaced(message, key->pubkey(), uppercase(key->pubkey())))); + BOOST_TEST(!own_id(replaced(message, id_in(message), uppercase(id_in(message))))); +} + +void inline_frames(const fixture_value& fixture) { + const auto actions = fixture["actions"]; const auto encode = [](std::string_view name, tp::payload_format format, std::string_view metadata, std::string_view payload) { return tp::encode_inline( @@ -162,33 +420,33 @@ void inline_frames(const json::object& fixture) { std::span(reinterpret_cast(payload.data()), payload.size())); }; const auto text = encode("chat", tp::payload_format::text, "", "hello from Trystero JS"); - const auto expected_text = hex(actions.at("text").at(0)); + const auto expected_text = hex(actions["text"][0]); BOOST_TEST_ALL_EQ(text.begin(), text.end(), expected_text.begin(), expected_text.end()); const auto json_frame = encode("drink", tp::payload_format::json, "", R"({"drink":"negroni","withIce":true,"n":[1,2.5,null]})"); - const auto expected_json = hex(actions.at("json").at(0)); + const auto expected_json = hex(actions["json"][0]); BOOST_TEST_ALL_EQ(json_frame.begin(), json_frame.end(), expected_json.begin(), expected_json.end()); const tp::bytes binary{0, 1, 2, 253, 254, 255}; const auto binary_frame = tp::encode_inline("pic", tp::payload_format::binary, "", binary); - const auto expected_binary = hex(actions.at("binary").at(0)); + const auto expected_binary = hex(actions["binary"][0]); BOOST_TEST_ALL_EQ(binary_frame.begin(), binary_frame.end(), expected_binary.begin(), expected_binary.end()); const auto with_metadata = encode("chat", tp::payload_format::text, R"({"from":"js","n":7})", "hi"); - const auto expected_with_metadata = hex(actions.at("text_with_metadata").at(0)); + const auto expected_with_metadata = hex(actions["text_with_metadata"][0]); BOOST_TEST_ALL_EQ(with_metadata.begin(), with_metadata.end(), expected_with_metadata.begin(), expected_with_metadata.end()); const auto empty = encode("@_hsready", tp::payload_format::text, "", ""); - const auto expected_empty = hex(actions.at("empty_text").at(0)); + const auto expected_empty = hex(actions["empty_text"][0]); BOOST_TEST_ALL_EQ(empty.begin(), empty.end(), expected_empty.begin(), expected_empty.end()); const auto long_name = encode("abcdefghijklmnopqrstuvwxyz012345", tp::payload_format::text, "", "x"); - const auto expected_long_name = hex(actions.at("thirty_two_byte_name").at(0)); + const auto expected_long_name = hex(actions["thirty_two_byte_name"][0]); BOOST_TEST_ALL_EQ(long_name.begin(), long_name.end(), expected_long_name.begin(), expected_long_name.end()); - const auto frame = hex(actions.at("text_with_metadata").at(0)); + const auto frame = hex(actions["text_with_metadata"][0]); const auto decoded = tp::decode_action(frame); const auto& p = std::get(*decoded.frame); BOOST_TEST_EQ(p.name, "chat"); @@ -201,12 +459,11 @@ void inline_frames(const json::object& fixture) { BOOST_TEST(!tp::valid_action_name("")); } -void chunked_frames(const json::object& fixture) { - const auto& actions = fixture.at("actions"); - const auto& chunked = actions.at("chunked").as_object(); - const auto payload = hex(chunked.at("payload")); - const auto& frames = chunked.at("frames").as_array(); - const auto offer = hex(frames.at(0)); +void chunked_frames(const fixture_value& fixture) { + const auto chunked = fixture["actions"]["chunked"]; + const auto payload = hex(chunked["payload"]); + const auto frames = chunked["frames"]; + const auto offer = hex(frames[0]); const auto decoded = tp::decode_action(offer); const auto& p = std::get(*decoded.frame); BOOST_TEST(p.kind == tp::frame_kind::offer); @@ -218,7 +475,7 @@ void chunked_frames(const json::object& fixture) { std::size_t offset = 0; for (std::size_t i = 1; i < frames.size(); ++i) { const auto length = std::min(tp::chunk_size, payload.size() - offset); - const auto expected = hex(frames.at(i)); + const auto expected = hex(frames[i]); const auto encoded = tp::encode_chunk(p.id, offset, std::span(payload).subspan(offset, length)); BOOST_TEST_ALL_EQ(encoded.begin(), encoded.end(), expected.begin(), expected.end()); @@ -228,7 +485,7 @@ void chunked_frames(const json::object& fixture) { offset += length; } BOOST_TEST_EQ(offset, payload.size()); - const auto rejected = hex(fixture.at("controls").at("rejected_too_large")); + const auto rejected = hex(fixture["controls"]["rejected_too_large"]); const auto encoded_rejected = tp::encode_rejected(p.id, "payload exceeds receiver size limit"); BOOST_TEST_ALL_EQ(encoded_rejected.begin(), encoded_rejected.end(), rejected.begin(), rejected.end()); @@ -238,30 +495,30 @@ void chunked_frames(const json::object& fixture) { BOOST_TEST_EQ(tp::encode_accepted(p.id).size(), tp::control_header_size); } -void envelopes(const json::object& fixture) { - const auto& env = fixture.at("envelope").as_object(); - const auto token = str(env.at("room_token")); +void envelopes(const fixture_value& fixture) { + const auto env = fixture["envelope"]; + const auto token = str(env["room_token"]); BOOST_TEST_EQ(token, tp::room_token("my-app", "room-1")); - const auto& frames = env.at("frames").as_array(); + const auto frames = env["frames"]; const auto present = tp::presence_frame(token, true); - const auto expected_present = hex(frames.at(0)); + const auto expected_present = hex(frames[0]); BOOST_TEST_ALL_EQ(present.begin(), present.end(), expected_present.begin(), expected_present.end()); const tp::bytes action{2, 0, 99, 104, 97, 116}; const auto room_frame = tp::room_frame(token, action); - const auto expected_room = hex(frames.at(1)); + const auto expected_room = hex(frames[1]); BOOST_TEST_ALL_EQ(room_frame.begin(), room_frame.end(), expected_room.begin(), expected_room.end()); const auto absent = tp::presence_frame(token, false); - const auto expected_absent = hex(frames.at(2)); + const auto expected_absent = hex(frames[2]); BOOST_TEST_ALL_EQ(absent.begin(), absent.end(), expected_absent.begin(), expected_absent.end()); - const auto room = hex(frames.at(1)); + const auto room = hex(frames[1]); const auto decoded = tp::decode_envelope(room); BOOST_TEST(decoded->type == tp::envelope::kind::room); BOOST_TEST_EQ(decoded->token, token); BOOST_TEST_ALL_EQ(decoded->payload.begin(), decoded->payload.end(), action.begin(), action.end()); - const auto presence = tp::decode_envelope(hex(frames.at(2))); + const auto presence = tp::decode_envelope(hex(frames[2])); BOOST_TEST(presence->type == tp::envelope::kind::presence); BOOST_TEST(!presence->present); BOOST_TEST(!tp::decode_envelope(tp::bytes{1, 0, 0}).has_value()); @@ -269,10 +526,13 @@ void envelopes(const json::object& fixture) { } void signals() { - json::value document; // the views read_signal returns point into it - const auto read = [&document](std::string_view text) { - document = json::parse(text); - return tp::read_signal(document); + std::optional document; // the views read_signal returns point into it + const auto read = [&document](std::string_view text) -> std::optional { + auto parsed = parse_text(text, tp::max_parsed_signal_bytes); + if (!parsed.has_value()) { + return std::nullopt; + } + return tp::read_signal(std::as_const(document.emplace(std::move(parsed).value())).root()); }; const auto announce = read(R"({"peerId":"abc","nonce":"x1"})"); if (!BOOST_TEST(announce.has_value())) { @@ -296,21 +556,120 @@ void signals() { // stringizes the macro's arguments, reads a raw string's \" as an escape and stops (C2017). constexpr std::string_view escaped = R"({"peerId":"q\"\\\n"})"; BOOST_TEST_EQ(tp::write_signal({.peer_id = "q\"\\\n"}), escaped); - // A fixed seed: the test checks the form of an id, the same on every run. - // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) - std::mt19937 generator(42); - const auto id = tp::make_id(tp::peer_id_size, generator); +} + +// An id has one character of Trystero's 62 for each random byte, the byte's remainder in 62: the +// first and the last character, and the remainders 0 and 61 of larger bytes. +void random_ids() { + const std::array random{0, 61, 62, 123, 124, 255}; + BOOST_TEST_EQ(tp::random_id(random), "0z0z07"); + BOOST_TEST_EQ(tp::random_id(std::span{}), ""); + std::array all{}; + for (std::size_t i = 0; i < all.size(); ++i) { + all[i] = static_cast(i * 13); + } + std::pmr::monotonic_buffer_resource memory; + const auto id = tp::random_id(all, &memory); + BOOST_TEST(id.get_allocator().resource() == &memory); BOOST_TEST_EQ(id.size(), tp::peer_id_size); BOOST_TEST_EQ(id.find_first_not_of(tp::id_alphabet), std::string::npos); } +// An offer's size is a float64 that Trystero accepts up to Number.MAX_SAFE_INTEGER, 2^53 - 1, the +// bytes 43 3f ff ff ff ff ff ff, and refuses from 2^53, 43 40 00 00 00 00 00 00, as any size that +// is not a positive integer: the largest is read whole on every target, a 32-bit one too. +void offer_sizes_at_two_to_the_53() { + using size_bytes = std::array; + const auto offer_of_size = [](const size_bytes& size) { + auto frame = tp::encode_offer("file", tp::payload_format::binary, "", 7, 1); + std::ranges::copy(size, frame.begin() + 40); + return frame; + }; + // The decoded frame's views point into the frame, which is kept while they are read. + const auto frame = offer_of_size({0x43, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}); + const auto largest = tp::decode_action(frame); + if (!BOOST_TEST(largest.frame.has_value())) { + return; + } + const auto& p = std::get(*largest.frame); + BOOST_TEST_EQ(p.size, std::uint64_t{9007199254740991}); + BOOST_TEST_EQ(p.size, tp::max_offer_size); + BOOST_TEST_EQ(p.id, 7U); + const std::array refused{ + size_bytes{0x43, 0x40, 0, 0, 0, 0, 0, 0}, // 2^53 + size_bytes{0x43, 0x40, 0, 0, 0, 0, 0, 1}, // 2^53 + 2 + size_bytes{0x3f, 0xf8, 0, 0, 0, 0, 0, 0}, // 1.5 + size_bytes{0, 0, 0, 0, 0, 0, 0, 0}, // 0 + size_bytes{0xbf, 0xf0, 0, 0, 0, 0, 0, 0}, // -1 + size_bytes{0x7f, 0xf8, 0, 0, 0, 0, 0, 0}, // NaN + }; + for (const auto& size : refused) { + const auto refused_frame = offer_of_size(size); + const auto decoded = tp::decode_action(refused_frame); + BOOST_TEST(!decoded.frame.has_value()); + BOOST_TEST(decoded.error == tp::wire_error::invalid_proposal); + } +} + +// Every field wider than a byte is big-endian, as DataView writes it, high bytes included: the +// oracle's frames have a short metadata, small ids, offsets and sizes, and a token of 64 bytes. +void wide_fields_are_big_endian() { + const std::string metadata(0x0102, 'm'); + const auto offer = + tp::encode_offer("file", tp::payload_format::binary, metadata, 0x01020304, 0x12345678); + // The metadata's length, the transfer's id, and the size as a float64. + const tp::bytes offer_fields{ + 0x01, 0x02, 0x01, 0x02, 0x03, 0x04, 0x41, 0xb2, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, + }; + BOOST_TEST_ALL_EQ(offer.begin() + 34, offer.begin() + 48, offer_fields.begin(), + offer_fields.end()); + const auto decoded = std::get(*tp::decode_action(offer).frame); + BOOST_TEST_EQ(decoded.id, 0x01020304U); + BOOST_TEST_EQ(decoded.size, 0x12345678U); + BOOST_TEST_EQ(decoded.metadata.size(), metadata.size()); + + const tp::bytes data{9}; + const auto chunk = tp::encode_chunk(0x0a0b0c0d, 0x12345678, data); + const tp::bytes expected_chunk{ + 2, 2, 0x0a, 0x0b, 0x0c, 0x0d, 0x41, 0xb2, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 9, + }; + BOOST_TEST_ALL_EQ(chunk.begin(), chunk.end(), expected_chunk.begin(), expected_chunk.end()); + const auto c = std::get(*tp::decode_action(chunk).frame); + BOOST_TEST_EQ(c.id, 0x0a0b0c0dU); + BOOST_TEST_EQ(c.offset, 305419896.0); + const auto accepted = tp::encode_accepted(0xfffefdfc); + const tp::bytes expected_accepted{2, 3, 0xff, 0xfe, 0xfd, 0xfc}; + BOOST_TEST_ALL_EQ(accepted.begin(), accepted.end(), expected_accepted.begin(), + expected_accepted.end()); + + const std::string token(0x012c, 't'); + const auto presence = tp::presence_frame(token, true); + BOOST_TEST_EQ(presence.size(), 4 + token.size()); + BOOST_TEST_EQ(presence[2], 0x01); + BOOST_TEST_EQ(presence[3], 0x2c); + const auto room = tp::room_frame(token, data); + BOOST_TEST_EQ(room.size(), 3 + token.size() + data.size()); + BOOST_TEST_EQ(room[1], 0x01); + BOOST_TEST_EQ(room[2], 0x2c); + const std::string longest(tp::max_room_token_bytes, 't'); + const auto longest_frame = tp::room_frame(longest, data); + const auto envelope = tp::decode_envelope(longest_frame); + if (BOOST_TEST(envelope.has_value())) { + BOOST_TEST_EQ(envelope->token.size(), tp::max_room_token_bytes); + } +} + // Each field of a signal is bounded, and the bound refuses nothing Trystero sends: its longest // candidate, 8192 bytes of plaintext, sealed with the longest IV in decimal, is read. void signal_bounds() { - json::value document; + std::optional document; const auto read = [&document](const tp::signal_message& m) { - document = json::parse(tp::write_signal(m)); - return tp::read_signal(document).has_value(); + auto parsed = parse_text(tp::write_signal(m), tp::max_parsed_signal_bytes); + if (!parsed.has_value()) { + return false; + } + return tp::read_signal(std::as_const(document.emplace(std::move(parsed).value())).root()) + .has_value(); }; std::array iv{}; iv.fill(255); @@ -333,6 +692,462 @@ void signal_bounds() { BOOST_TEST(!read({.peer_id = "p", .offer_id = offer_id + "a", .offer = "x"})); } +// An event message is Trystero's createEvent's, byte for byte, signed with the oracle's key, clock +// and auxiliary bytes: its topic and content hold every control character, `"`, `\`, U+2028, +// U+2029, DEL and astral characters, which document's quoting writes as JSON.stringify does, and +// its id is the one the protocol computes. +void event_messages(const fixture_value& fixture) { + const auto messages = fixture["event_messages"]; + const auto secret = hex(messages["secret_key"]); + const auto aux = hex(messages["aux"]); + if (!BOOST_TEST_EQ(secret.size(), 32U) || !BOOST_TEST_EQ(aux.size(), 32U)) { + return; + } + const auto key = + tp::nostr::signer::from_secret(std::span(secret.data(), 32)); + if (!BOOST_TEST(key.has_value())) { + return; + } + const std::span aux_bytes(aux.data(), 32); + const auto created_at = + std::chrono::sys_seconds(std::chrono::seconds(integer(messages["created_at"]))); + BOOST_TEST_EQ(messages["events"].size(), 6U); + for (const auto e : messages["events"]) { + const auto topic = str(e["topic"]); + const auto content = str(e["content"]); + BOOST_TEST_EQ(tp::nostr::event_message(*key, created_at, topic, content, aux_bytes), + str(e["message"])); + const auto id = tp::nostr::event_id(key->pubkey(), created_at, tp::nostr::topic_kind(topic), + topic, content); + BOOST_TEST_EQ(tp::to_hex(id), str(e["id"])); + } +} + +// A signal's text is JSON.stringify's of Trystero's object, member for member, with the same +// strings, every byte of their quoting included, and the protocol reads the same fields back. +void signal_texts(const fixture_value& fixture) { + BOOST_TEST_EQ(fixture["signal_texts"].size(), 7U); + for (const auto entry : fixture["signal_texts"]) { + const auto s = entry["signal"]; + // The answerer's messages are those whose second member is the answer or the candidate. + std::string_view second; + std::size_t at = 0; + for (const std::string_view key : s.keys()) { + if (at++ == 1) { + second = key; + } + } + const tp::signal_message m{ + .peer_id = str(s["peerId"]), + .offer_id = str(s["offerId"]), + .offer = str(s["offer"]), + .answer = str(s["answer"]), + .candidate = str(s["candidate"]), + .passive = s["passive"].value_or(false), + .answering = + second == "answer" || (second == "candidate" && !s["offerId"].is_undefined()), + }; + const auto text = str(entry["text"]); + BOOST_TEST_EQ(tp::write_signal(m, str(s["nonce"])), text); + const auto document = parse_text(text, tp::max_parsed_signal_bytes).value(); + const auto read = tp::read_signal(document.root()); + if (!BOOST_TEST(read.has_value())) { + continue; + } + BOOST_TEST_EQ(read->peer_id, m.peer_id); + BOOST_TEST_EQ(read->offer_id, m.offer_id); + BOOST_TEST_EQ(read->offer, m.offer); + BOOST_TEST_EQ(read->answer, m.answer); + BOOST_TEST_EQ(read->candidate, m.candidate); + BOOST_TEST_EQ(read->passive, m.passive); + } +} + +/** `text` read as an action of JSON reads its payload, then written back as one sends it: once + * into an owned document, as a webcpp::document::document, and once into a resource, as a + * webcpp::document::pmr::document; the two writings, which must agree. */ +std::pmr::string payload_written(std::string_view text) { + const auto owned = wd::parse(text); + const auto in_resource = + wd::parse(text, wd::parse_options(), + std::pmr::polymorphic_allocator(std::pmr::get_default_resource())); + if (!BOOST_TEST(owned.has_value() && in_resource.has_value())) { + return {}; + } + std::pmr::string written; + tp::json::append_value(written, owned->root()); + std::pmr::string written_in_resource; + tp::json::append_value(written_in_resource, in_resource->root()); + BOOST_TEST_EQ(written, written_in_resource); + return written; +} + +// A JSON payload's text is JSON.stringify's of the same value for every value a double holds: its +// numbers as JavaScript writes them, its keys in JavaScript's order, array indices first in +// increasing order. A number a double cannot hold is written exact, as webcpp::document holds it, +// where Trystero JS writes the nearest double, or null for Infinity. +void payload_texts(const fixture_value& fixture) { + BOOST_TEST_EQ(fixture["payload_texts"].size(), 5U); + for (const auto entry : fixture["payload_texts"]) { + BOOST_TEST_EQ(payload_written(str(entry["text"])), str(entry["written"])); + } + const auto beyond = fixture["payload_beyond_doubles"]; + if (!BOOST_TEST_EQ(beyond.size(), 1U)) { + return; + } + const auto written = payload_written(str(beyond[0]["text"])); + BOOST_TEST_NE(written, str(beyond[0]["written"])); + BOOST_TEST_EQ(written, + "[9007199254740993,-9223372036854775808,0.1000000000000000055511151231257827," + "1e+400]"); +} + +/** + * The sender of a relay's event that a room acts on as the oracle's room did: an event of the + * room's root topic whose content is a signal with an answer. Empty when the room ignores it. + */ +std::string answer_sender(std::string_view text, std::string_view root_topic) { + const auto document = parse_text(text, tp::nostr::max_parsed_relay_text_bytes); + if (!document.has_value()) { + return {}; + } + const auto message = tp::nostr::read_relay_message(document->root()); + const auto* e = message.has_value() ? std::get_if(&*message) : nullptr; + if (e == nullptr || e->topic != root_topic) { + return {}; + } + const auto signal_document = parse_text(e->content, tp::max_parsed_signal_bytes); + if (!signal_document.has_value()) { + return {}; + } + const auto signal = tp::read_signal(signal_document->root()); + if (!signal.has_value() || signal->answer.empty()) { + return {}; + } + return std::string(signal->peer_id); +} + +// A key written twice keeps its last value, as JSON.parse keeps it, an escaped key included: a +// signal reads what Trystero's own signal handler read from the same text, and a relay's event is +// acted on, with the same sender, exactly when Trystero's room acted on it. +void duplicate_keys(const fixture_value& fixture) { + const auto cases = fixture["duplicate_keys"]; + BOOST_TEST_EQ(cases["signals"].size(), 13U); + for (const auto entry : cases["signals"]) { + const auto document = parse_text(str(entry["text"]), tp::max_parsed_signal_bytes).value(); + const auto read = tp::read_signal(document.root()); + const auto expected = entry["read"]; + if (expected.is_null()) { + BOOST_TEST(!read.has_value()); + continue; + } + if (!BOOST_TEST(read.has_value())) { + continue; + } + BOOST_TEST_EQ(read->peer_id, str(expected["peer_id"])); + BOOST_TEST_EQ(read->offer, str(expected["offer"])); + BOOST_TEST_EQ(read->answer, str(expected["answer"])); + BOOST_TEST_EQ(read->candidate, str(expected["candidate"])); + BOOST_TEST_EQ(read->passive, expected["passive"].value_or(false)); + // Trystero shows an offer's id, which it keeps to answer with. + if (expected.contains("offer_id")) { + BOOST_TEST_EQ(read->offer_id, str(expected["offer_id"])); + } + } + const auto root_topic = str(cases["root_topic"]); + BOOST_TEST_EQ(cases["events"].size(), 6U); + for (const auto entry : cases["events"]) { + BOOST_TEST_EQ(answer_sender(str(entry["text"]), root_topic), str(entry["acted"])); + } +} + +/** `text` with spaces after its value, which JSON allows, up to `size` bytes. */ +std::string padded(std::string_view text, std::size_t size) { + std::string out(text); + out.resize(size, ' '); + return out; +} + +/** The longest signal the bounds of its fields admit: a passive room's sealed offer. */ +std::string longest_signal() { + const std::string peer(tp::max_peer_id_bytes, 'p'); + const std::string offer_id(tp::max_offer_id_bytes, 'o'); + const std::string description(tp::max_sealed_description_bytes, 'a'); + return std::string(tp::write_signal( + {.peer_id = peer, .offer_id = offer_id, .offer = description, .passive = true})); +} + +// The bounds a room parses with refuse no text Trystero sends, and the relay's is under the length +// that closes a relay's connection, so that a text between the two is dropped and the room goes on. +static_assert(tp::max_parsed_signal_bytes == tp::max_sealed_description_bytes + 1024); +static_assert(tp::max_parsed_signal_bytes == 66560); +static_assert(tp::max_sealed_description_bytes + tp::max_peer_id_bytes + tp::max_offer_id_bytes + + 64 <= + tp::max_parsed_signal_bytes); +static_assert(tp::nostr::max_parsed_relay_text_bytes == tp::max_parsed_signal_bytes + 2048); +static_assert(tp::nostr::max_parsed_relay_text_bytes == 68608); +static_assert(tp::nostr::max_parsed_relay_text_bytes < tp::max_relay_message_bytes); +static_assert(tp::max_handshake_bytes == 1024); +// A parse reads at most its bound of text, into an image of at most twice that and 64 KiB more. +static_assert(tp::json::protocol_limits(1000).max_bytes == 1000); +static_assert(tp::json::protocol_limits(1000).max_document_bytes == 2000 + 65536); +// A protocol text nests at most 16 deep; a payload as deep as document's default. +static_assert(tp::json::protocol_limits(1000).max_depth == 16); +static_assert(tp::json::payload_limits(1000, std::uint64_t{64} << 20U).max_depth == + wd::parse_options().max_depth); +// A payload's image grows to 96 times its text and 64 KiB, at most the room's bound. +static_assert(tp::json::payload_limits(1000, std::uint64_t{64} << 20U).max_bytes == 1000); +static_assert(tp::json::payload_limits(1000, std::uint64_t{64} << 20U).max_document_bytes == + 96000 + 65536); +static_assert(tp::json::payload_limits(1000, 100000).max_document_bytes == 100000); +static_assert(tp::json::payload_limits(1'000'000, std::uint64_t{64} << 20U).max_document_bytes == + std::uint64_t{64} << 20U); +static_assert(tp::json::payload_limits(0, 1000).max_document_bytes == 1000); + +// Each text a room parses is read up to its bound, to the byte, and one byte more is refused +// before anything of it is read: no buffer is made, and a text that is not JSON at all is refused +// for its length, not its syntax. The relay's bound reads an event that carries the longest +// signal, which the signal's bound reads in turn, and the handshake's reads Trystero's message. +void parse_bounds() { + const auto refused_unread = [](std::string_view text, std::size_t max_bytes) { + counting_resource memory; + const auto refused = parse_text(text, max_bytes, &memory); + const auto garbage = parse_text(std::string(text.size(), 'x'), max_bytes, &memory); + return !refused.has_value() && refused.error() == wd::errc::capacity && + !garbage.has_value() && garbage.error() == wd::errc::capacity && + memory.allocations == 0; + }; + + const auto signal = longest_signal(); + const auto longest = padded(signal, tp::max_parsed_signal_bytes); + if (!BOOST_TEST_LT(signal.size(), longest.size())) { + return; + } + { + const auto document = parse_text(longest, tp::max_parsed_signal_bytes).value(); + const auto read = tp::read_signal(document.root()); + BOOST_TEST(read.has_value() && read->offer.size() == tp::max_sealed_description_bytes && + read->peer_id.size() == tp::max_peer_id_bytes && read->passive); + } + BOOST_TEST(refused_unread(longest + " ", tp::max_parsed_signal_bytes)); + + // A relay's echo of an event that carries it, with a subscription id of Trystero's 64 + // characters. + std::array secret{}; + secret.fill(7); + const auto key = tp::nostr::signer::from_secret(secret); + if (!BOOST_TEST(key.has_value())) { + return; + } + const std::array aux{}; + const auto topic = tp::peer_topic("my-app", "room-1", std::string(tp::max_peer_id_bytes, 'p')); + const auto message = tp::nostr::event_message( + *key, std::chrono::sys_seconds(std::chrono::seconds(1759700000)), topic, signal, aux); + const std::string_view written = message; + std::string echo = R"(["EVENT",")" + std::string(64, 's') + R"(",)"; + echo += written.substr(9, written.size() - 10); + echo += ']'; + const auto event_text = padded(echo, tp::nostr::max_parsed_relay_text_bytes); + if (!BOOST_TEST_LT(echo.size(), event_text.size())) { + return; + } + { + const auto document = + parse_text(event_text, tp::nostr::max_parsed_relay_text_bytes).value(); + const auto message_read = tp::nostr::read_relay_message(document.root()); + const auto* e = + message_read.has_value() ? std::get_if(&*message_read) : nullptr; + if (BOOST_TEST(e != nullptr)) { + BOOST_TEST_EQ(e->topic, topic); + BOOST_TEST_EQ(e->content, signal); + } + } + BOOST_TEST(refused_unread(event_text + " ", tp::nostr::max_parsed_relay_text_bytes)); + + // Trystero's handshake message: `{"__trystero_pw":"response","h":"<64 hexadecimal digits>"}`. + const auto proof = tp::handshake_proof("ch4ll3ng3", "secret", "my-app", "room-1"); + const auto handshake = + padded(R"({"__trystero_pw":"response","h":")" + std::string(proof) + "\"}", + tp::max_handshake_bytes); + { + const auto document = parse_text(handshake, tp::max_handshake_bytes).value(); + BOOST_TEST_EQ(tp::json::text_of(document.root()["h"]), proof); + } + BOOST_TEST(refused_unread(handshake + " ", tp::max_handshake_bytes)); +} + +/** `["EVENT","sub",]` whose event holds `members` more after its tags and content. */ +std::string event_with(std::string_view members) { + std::string text = R"(["EVENT","sub",{"id":"i","tags":[["x","topic"]],"content":"c")"; + text += members; + return text + "}]"; +} + +// No text costs a room more than a few times its bound to read. An event of 256 distinct keys of +// 128 bytes, which collided in Boost.JSON's hashed objects (chapter 18's draft), is read as any +// text is: document's objects are ordered indices. A text of thousands of values, each a node of +// some 200 bytes of image for 2 of text, is refused once its image has grown to the bound; and the +// resource never has more out at once than the image grown to the bound, with the image it grew +// from. +void parse_cost() { + const auto limits = tp::json::protocol_limits(tp::nostr::max_parsed_relay_text_bytes); + const auto bound = static_cast(limits.max_document_bytes); + const auto parse = [&limits](std::string_view text, counting_resource& memory) { + return wd::parse(text, limits, std::pmr::polymorphic_allocator(&memory)); + }; + + std::string keys; + for (std::size_t i = 0; i < 256; ++i) { + std::string key = std::to_string(i); + key.resize(128, 'k'); + keys += ",\"" + key + "\":0"; + } + counting_resource keyed; + { + const auto document = parse(event_with(keys), keyed); + if (BOOST_TEST(document.has_value())) { + BOOST_TEST_EQ(document->root()[2].size(), 3U + 256U); + const auto message = tp::nostr::read_relay_message(document->root()); + const auto* e = + message.has_value() ? std::get_if(&*message) : nullptr; + BOOST_TEST(e != nullptr && e->topic == "topic" && e->content == "c"); + } + } + BOOST_TEST_LE(keyed.largest, bound); + BOOST_TEST_LT(keyed.peak, 2 * bound); + BOOST_TEST(keyed.live.empty()); + + const auto values = [](std::size_t n) { + std::string text = R"(,"values":[0)"; + for (std::size_t i = 1; i < n; ++i) { + text += ",0"; + } + return event_with(text + "]"); + }; + counting_resource few; + BOOST_TEST(parse(values(100), few).has_value()); + // 4,000 values in 8 KB of text, and the most the bound reads: some 34,000 in 68 KB. + const auto longest = + values(((tp::nostr::max_parsed_relay_text_bytes - event_with("").size()) / 2) - 8); + BOOST_TEST_LE(longest.size(), tp::nostr::max_parsed_relay_text_bytes); + for (const auto& text : {values(4000), longest}) { + counting_resource many; + const auto refused = parse(text, many); + BOOST_TEST(!refused.has_value() && refused.error() == wd::errc::capacity); + BOOST_TEST_EQ(many.largest, bound); + BOOST_TEST_LT(many.peak, 2 * bound); + BOOST_TEST(many.live.empty()); + } +} + +// A protocol text nested past its depth is refused: Boost.JSON's parser stops at the 17th level, +// and the resource has nothing out after it. +void parse_depth() { + const auto limits = tp::json::protocol_limits(tp::nostr::max_parsed_relay_text_bytes); + const auto depth = static_cast(limits.max_depth); + BOOST_TEST_EQ(depth, 16U); + const auto nested = [](std::size_t levels) { + std::string text(levels, '['); + text.append(levels, ']'); + return text; + }; + counting_resource deepest; + BOOST_TEST( + wd::parse(nested(depth), limits, std::pmr::polymorphic_allocator(&deepest)) + .has_value()); + BOOST_TEST(deepest.live.empty()); + counting_resource deeper; + const auto refused = + wd::parse(nested(depth + 1), limits, std::pmr::polymorphic_allocator(&deeper)); + BOOST_TEST(!refused.has_value() && refused.error() == wd::errc::capacity); + BOOST_TEST(deeper.live.empty()); +} + +// Every valid payload fits the image its own length allows, 96 bytes a byte of text: a value of one +// character with its comma or bracket, two bytes, is a node of 192, whether a number, an array of +// one or an array nested 255 deep. The factor is tight: 95 bytes a byte refuses an array of zeros. +void payload_image_per_text_byte() { + const auto parses = [](const std::string& text, std::uint64_t image) { + wd::parse_options o; + o.max_document_bytes = image; + return wd::parse( + text, o, + std::pmr::polymorphic_allocator(std::pmr::get_default_resource())) + .has_value(); + }; + const auto array_of = [](std::string_view value, std::size_t n) { + std::string text = "["; + for (std::size_t i = 0; i < n; ++i) { + text += i == 0 ? "" : ","; + text += value; + } + return text + "]"; + }; + const std::string deep = std::string(255, '[') + std::string(255, ']'); + for (const auto& text : { + array_of("0", 1000), + array_of("[0]", 1000), + array_of("[0,0]", 1000), + array_of(deep, 10), + array_of("{}", 1000), + array_of("\"\"", 1000), + }) { + const auto n = static_cast(text.size()); + const auto limits = tp::json::payload_limits(n, std::uint64_t{64} << 20U); + BOOST_TEST(parses(text, limits.max_document_bytes)); + // Within 1 KiB of the 96 bytes a byte: the 64 KiB the limits add are spare. + BOOST_TEST(parses(text, (tp::json::image_bytes_per_text_byte * n) + 1024)); + } + const std::string zeros = array_of("0", 1000); + BOOST_TEST(!parses(zeros, ((tp::json::image_bytes_per_text_byte - 1) * zeros.size()) + 1024)); +} + +// A parse's image is one allocation of the resource it is given, the only thing the resource has +// out once the parse succeeds: the strings read from it point into it, a move construction takes +// it with the allocator, and the resource has nothing out once the document goes. A handle refers +// to the document object, so the moved-to document is read through its own. +void parse_resource() { + constexpr std::string_view text = + R"(["EVENT","sub",{"id":"abc","tags":[["x","topic-a"]],"content":"{\"peerId\":\"p\"}"}])"; + counting_resource memory; + { + auto parsed = parse_text(text, tp::nostr::max_parsed_relay_text_bytes, &memory); + if (!BOOST_TEST(parsed.has_value())) { + return; + } + wd::pmr::document document = std::move(parsed).value(); + BOOST_TEST(document.get_allocator().resource() == &memory); + const auto image = document.image(); + if (!BOOST_TEST_EQ(memory.live.size(), 1U)) { + return; + } + BOOST_TEST(memory.live.begin()->first == static_cast(image.data())); + BOOST_TEST_EQ(memory.live.begin()->second, document.capacity()); + const auto* begin = reinterpret_cast(image.data()); + const auto* end = begin + image.size(); + const auto inside = [begin, end](std::string_view s) { + return std::less_equal<>()(begin, s.data()) && + std::less_equal<>()(s.data() + s.size(), end); + }; + const auto message = tp::nostr::read_relay_message(std::as_const(document).root()); + const auto* e = message.has_value() ? std::get_if(&*message) : nullptr; + if (BOOST_TEST(e != nullptr)) { + BOOST_TEST_EQ(e->content, R"({"peerId":"p"})"); + BOOST_TEST(inside(e->subscription) && inside(e->id) && inside(e->topic) && + inside(e->content)); + } + const wd::pmr::document moved = std::move(document); + // A document moved from holds no image. + BOOST_TEST(document.image().empty()); // NOLINT(bugprone-use-after-move) + BOOST_TEST(moved.get_allocator().resource() == &memory); + BOOST_TEST(static_cast(moved.image().data()) == + static_cast(image.data())); + BOOST_TEST_EQ(tp::json::text_of(moved.root()[2]["content"]), R"({"peerId":"p"})"); + BOOST_TEST_EQ(memory.live.size(), 1U); + } + BOOST_TEST(memory.live.empty()); +} + void text() { BOOST_TEST_EQ(tp::base64_encode(tp::bytes{}), ""); BOOST_TEST_EQ(tp::base64_encode(tp::bytes{'f'}), "Zg=="); @@ -353,16 +1168,33 @@ int main(int argc, char* argv[]) { return boost::report_errors(); } const auto loaded = load(argv[1]); - const auto& fixture = loaded.as_object(); + if (!BOOST_TEST(loaded.has_value())) { + return boost::report_errors(); + } + const auto fixture = loaded->root(); topics(fixture); relays(fixture); handshake_and_sealing(fixture); nostr_events(fixture); + nostr_message_fields(fixture); + event_ids_are_their_own(fixture); inline_frames(fixture); chunked_frames(fixture); envelopes(fixture); + offer_sizes_at_two_to_the_53(); + wide_fields_are_big_endian(); signals(); + random_ids(); signal_bounds(); + event_messages(fixture); + signal_texts(fixture); + payload_texts(fixture); + duplicate_keys(fixture); + parse_bounds(); + parse_cost(); + parse_depth(); + payload_image_per_text_byte(); + parse_resource(); text(); return boost::report_errors(); } diff --git a/test/provider/Jamfile b/test/provider/Jamfile index 1edf242..5b7fb42 100644 --- a/test/provider/Jamfile +++ b/test/provider/Jamfile @@ -10,7 +10,6 @@ webcpp.original python3 ; # The common executable names all three public dependency aliases. webcpp.drive combined : ../../../../tools/openssl/test//combined_provider - : release multi on - 60 + : release multi 60 : driver.py : : native ; webcpp.lane provider-integration : combined : native ; diff --git a/test/room_test.cpp b/test/room_test.cpp index 2a733f5..c34daf2 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -9,16 +9,21 @@ // log on the standard error. #include +#include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include + +#include +#include +#include + #include -#include -#include +#include #include #include @@ -30,17 +35,20 @@ #include #include #include +#include #include #include #include +#include #include #include +#include "cases.hpp" #include "require.hpp" #include "support/memory_backend.hpp" #include "support/rooms.hpp" -namespace asio = boost::asio; +namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; using namespace std::chrono_literals; @@ -50,6 +58,7 @@ using trystero::test::advance; using trystero::test::app_config; using trystero::test::app_id; using trystero::test::counting_resource; +using trystero::test::document_of; using trystero::test::fixture; using trystero::test::flooder; using trystero::test::join; @@ -101,16 +110,18 @@ void two_peers_join_and_exchange_every_payload_format() { auto chat_a = a.make_action("chat"); auto chat_z = z.make_action("chat"); - auto drink_z = z.make_action("drink"); + auto drink_z = z.make_action("drink"); auto pic_z = z.make_action("pic"); std::vector> chats_z; - boost::json::value drink; + std::optional drink; trystero::bytes pic; chat_z.on_message([&](std::string text, const trystero::message_info& info) { chats_z.emplace_back(std::move(text), info); }); + // tag::json-receive[] drink_z.on_message( - [&](boost::json::value v, const trystero::message_info&) { drink = std::move(v); }); + [&](webcpp::document::document v, const trystero::message_info&) { drink = std::move(v); }); + // end::json-receive[] pic_z.on_message([&](trystero::bytes b, const trystero::message_info&) { pic = std::move(b); }); BOOST_TEST(run_until(f.io, [&] { return joined_a.size() == 1 && joined_z.size() == 1; })); @@ -123,14 +134,17 @@ void two_peers_join_and_exchange_every_payload_format() { std::vector sent; chat_a.async_send("hello", trystero::send_options{.targets = {}, .metadata = R"({"n":1})"}, [&](boost::system::error_code ec) { sent.push_back(ec); }); - a.make_action("drink").async_send( - boost::json::object{{"drink", "negroni"}}, - [&](boost::system::error_code ec) { sent.push_back(ec); }); + // tag::json-send[] + if (auto negroni = webcpp::document::parse(R"({"drink":"negroni"})")) { + a.make_action("drink").async_send( + std::move(*negroni), [&](boost::system::error_code ec) { sent.push_back(ec); }); + } + // end::json-send[] a.make_action("pic").async_send( trystero::bytes{0, 1, 255}, [&](boost::system::error_code ec) { sent.push_back(ec); }); BOOST_TEST(run_until( - f.io, [&] { return chats_z.size() == 1 && !drink.is_null() && pic.size() == 3; })); + f.io, [&] { return chats_z.size() == 1 && drink.has_value() && pic.size() == 3; })); BOOST_TEST_EQ(sent.size(), 3U); for (const auto& ec : sent) { BOOST_TEST(!ec); @@ -138,9 +152,14 @@ void two_peers_join_and_exchange_every_payload_format() { BOOST_TEST_EQ(chats_z.at(0).first, "hello"); BOOST_TEST_EQ(chats_z.at(0).second.from, "AAAAAAAAAAAAAAAAAAAA"); BOOST_TEST_EQ(chats_z.at(0).second.metadata, R"({"n":1})"); - BOOST_TEST_EQ(drink.at("drink").as_string(), "negroni"); const trystero::bytes sent_pic{0, 1, 255}; BOOST_TEST_ALL_EQ(pic.begin(), pic.end(), sent_pic.begin(), sent_pic.end()); + if (!BOOST_TEST(drink.has_value())) { + return; + } + // tag::json-read[] + BOOST_TEST_EQ((*drink)["drink"].value_or(std::string_view()), "negroni"); + // end::json-read[] } void large_payloads_travel_in_chunks_both_ways() { @@ -166,7 +185,7 @@ void large_payloads_travel_in_chunks_both_ways() { for (std::size_t i = 0; i < big.size(); ++i) { big[i] = static_cast(i * 31); } - int done = 0; + std::size_t done = 0; file_a.async_send(big, trystero::send_options{.targets = {}, .metadata = R"({"name":"big.bin"})"}, [&](boost::system::error_code ec) { @@ -206,26 +225,32 @@ void ping_measures_a_round_trip() { } void the_same_password_joins_and_another_does_not() { - fixture f; + fixture f{true}; trystero::app a_app(f.io.get_executor(), f.net, app_config("FFFFFFFFFFFFFFFFFFFF", "s3cret")); auto a = join(a_app, "private"); trystero::app b_app(f.io.get_executor(), f.net, app_config("GGGGGGGGGGGGGGGGGGGG", "s3cret")); auto b = join(b_app, "private"); - BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })); + BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })); - // The intruder's signals cannot be opened with the room key, so it never connects; both sides - // report it. + // A and B, whose ids are lower, offer to the intruder, which cannot open their offers with its + // room key, so it never connects. It reports both: the first at once, with its peer, and the + // other with their number when the interval of its reports ends, 10 s later. std::vector errors; + std::size_t refused = 0; trystero::app intruder_app(f.io.get_executor(), f.net, app_config("HHHHHHHHHHHHHHHHHHHH", "guess")); auto intruder = join(intruder_app, "private"); - intruder.on_error([&](std::string_view, boost::system::error_code ec, std::string_view) { - errors.push_back(ec); - }); + intruder.on_error( + [&](std::string_view peer, boost::system::error_code ec, std::string_view what) { + errors.push_back(ec); + if (ec == trystero::error::wrong_password) { + refused += peer.empty() ? std::stoul(std::string(what)) : 1; + } + }); a.on_error([&](std::string_view, boost::system::error_code ec, std::string_view) { errors.push_back(ec); }); - run_until(f.io, [] { return false; }, 1500ms); + BOOST_TEST(run_until(f, [&] { return refused == 2; }, 20'000ms)); BOOST_TEST(intruder.peers().empty()); BOOST_TEST_EQ(a.peers().size(), 1U); BOOST_TEST(!errors.empty()); @@ -384,8 +409,14 @@ void a_refused_peer_connection_is_reported_and_tried_again() { // Announcements are not sealed: anyone who knows the app and the room ids can announce any number // of fresh ids. A room offers to at most max_unconnected_peers of them at once, its memory and the // page's connections stay bounded, the peer it is connected to keeps working, and once the offers -// to the flooders expire their negotiations are gone and a new peer joins. The clock runs 100 -// times faster, so that offers expire in about 0.6 s. +// to the flooders expire their negotiations are gone and a new peer joins. +// +// The case runs on the virtual clock, so that it sees the same on every machine: the clock stands +// still while the rooms handle a thousand announcements, and moves a minute before the next. On +// the wall clock, a thousand left several thousand relay texts queued ahead of the message that +// must go through, which a loaded machine took longer to handle than the case could wait, and the +// slower it ran, the more often the rooms' timers fired meanwhile, which changed the connections +// and the memory the case compares. // // The memory is bounded by the room's own limits, not by the flood: the negotiations under way, // the event ids, offers and answers, and refused peers it remembers, each up to a count of its @@ -396,9 +427,10 @@ void a_refused_peer_connection_is_reported_and_tried_again() { void a_flood_of_announcements_is_bounded() { constexpr std::size_t flood = trystero::detail::nostr_strategy::remembered_events + 1000; constexpr std::size_t bound = trystero::detail::signaling::max_unconnected_peers; + // Longer than an offer lasts (57.3 s): a thousand finds the offers to the one before expired. + constexpr std::chrono::milliseconds minute = 1min; counting_resource memory; // first: the io_context's pending operations free into it - fixture f; - f.net.time_scale = 100; + fixture f{true}; auto c = app_config("00000000000000000000"); // lower than every flooder: it offers to each c.memory = &memory; trystero::app a_app(f.io.get_executor(), f.net, std::move(c)); @@ -413,49 +445,54 @@ void a_flood_of_announcements_is_bounded() { chat_b.on_message([&](const std::string& text, const trystero::message_info& /*info*/) { heard.push_back(text); }); - webcpp::test::require(BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; }))); + webcpp::test::require(BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }))); const std::size_t joined_in_use = memory.in_use; const std::size_t joined_connections = f.net.live_connections(); - // Announces `count` fresh ids, a thousand at a time, each thousand passed by the relay before - // the next, then has a message go through, and returns what the room holds then, beyond what - // it held once joined. The memory relay queues what it forwards in each room's resource, and - // a flood sent at once would hold it all there, more than Emscripten's 16 MiB. The page's - // connections are counted from those it holds when the flood starts, the late peer's among - // them in the second. The flood adds at most `2 * bound`: the offers of the negotiations under - // way, and those of the ones just expired, closed but held by the completions queued for them - // until the executor reaches them, behind the relays' messages on a loaded machine. + // Announces `count` fresh ids, a thousand a minute, each thousand handled by the relay and the + // rooms before the clock moves, then has a message go through, and returns what the room holds + // then, beyond what it held once joined. The memory relay queues what it forwards in each + // room's resource, and a flood sent at once would hold it all there, more than Emscripten's + // 16 MiB. The page's connections are counted from those it holds when the flood starts, the + // late peer's among them in the second. The flood adds at most `bound`, the offers of the + // negotiations under way: the clock moves only once every queued completion ran, so that the + // connection of an offer that expired is gone before the next thousand. Without the bound on + // negotiations, the room fills its window, 64 connections (measured). flooder attacker(f, "flood"); const auto flooded = [&](std::size_t count, std::string_view prefix) { const std::size_t held = f.net.live_connections(); f.net.peak_connections = held; constexpr std::size_t batch = 1000; for (std::size_t sent = 0; sent < count; sent += batch) { + if (sent > 0) { + advance(f, minute); + } const std::size_t now = std::min(batch, count - sent); const auto before = f.net.relay(relay_a).events_seen; attacker.announce(now, prefix); BOOST_TEST( - run_until(f.io, [&] { return f.net.relay(relay_a).events_seen >= before + now; })); + run_until(f, [&] { return f.net.relay(relay_a).events_seen >= before + now; })); } const std::size_t messages = heard.size() + 1; chat_a.async_send("after the flood", [](boost::system::error_code) {}); - BOOST_TEST(run_until(f.io, [&] { return heard.size() == messages; })); - BOOST_TEST_LE(f.net.peak_connections, held + (2 * bound)); + BOOST_TEST(run_until(f, [&] { return heard.size() == messages; })); + BOOST_TEST_LE(f.net.peak_connections, held + bound); return memory.in_use - joined_in_use; }; const std::size_t first = flooded(flood, "1flood"); // Once every offer to a flooder expired, its negotiation is gone, and a new peer joins. - BOOST_TEST(run_until(f.io, [&] { return f.net.live_connections() == joined_connections; })); + BOOST_TEST( + run_until(f, [&] { return f.net.live_connections() == joined_connections; }, minute)); trystero::app late_app(f.io.get_executor(), f.net, app_config("CCCCCCCCCCCCCCCCCCCC")); const auto late = join(late_app, "flood"); - BOOST_TEST(run_until(f.io, [&] { return joined.size() == 2; })); + BOOST_TEST(run_until(f, [&] { return joined.size() == 2; })); BOOST_TEST_EQ(heard.size(), 1U); // A flood twice as large keeps the room as bounded, and the room working. The half of // `first` allows for the late peer, joined since, and for the records not yet full after the // first flood; without the bound on negotiations, the second flood leaves 2.6 times as much, - // and 2.8 times without the one on the event ids remembered (measured). + // and 2.95 times without the one on the event ids remembered (measured). const std::size_t second = flooded(2 * flood, "1again"); BOOST_TEST_EQ(heard.size(), 2U); BOOST_TEST_LE(second, first + (first / 2)); @@ -477,20 +514,10 @@ void a_forged_answer_changes_nothing() { std::string_view /*what*/) { errors.push_back(ec); }); flooder attacker(f, "forged"); const auto a_topic = trystero::protocol::peer_topic(app_id, "forged", a_id); - int forged = 0; + std::size_t forged = 0; attacker.on_text = [&](std::string_view text) { - boost::system::error_code ec; - const auto document = boost::json::parse(text, ec); - const auto message = - ec ? std::nullopt : trystero::protocol::nostr::read_relay_message(document); - const auto* event = - message ? std::get_if(&*message) : nullptr; - if (event == nullptr) { - return; - } - const auto content = boost::json::parse(event->content, ec); - const auto signal = ec ? std::nullopt : trystero::protocol::read_signal(content); - if (signal && signal->peer_id == a_id && !signal->offer.empty()) { + const auto signal = relayed_signal(text); + if (signal && signal->peer == a_id && !signal->offer.empty()) { attacker.publish( a_topic, {.peer_id = b_id, .offer_id = signal->offer_id, .answer = "not a sealed answer"}); @@ -501,37 +528,209 @@ void a_forged_answer_changes_nothing() { trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); const auto b = join(b_app, "forged"); BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; })); - BOOST_TEST_GE(forged, 1); + BOOST_TEST_GE(forged, 1U); BOOST_TEST_LE(errors.size(), 1U); } // Offers from fresh ids that are not sealed with the room key make no connection: a negotiation -// changes only once its offer opened. +// changes only once its offer opened. The case counts the offers the room could not open, each +// logged once, and looks at the connections once it has every one. void forged_offers_make_no_connection() { - fixture f; - trystero::app a_app(f.io.get_executor(), f.net, app_config("zzzzzzzzzzzzzzzzzzzz")); + constexpr std::size_t flood = 200; + fixture f{true}; + auto c = app_config("zzzzzzzzzzzzzzzzzzzz"); + std::size_t refused = 0; + c.log = [&](std::string_view /*category*/, std::string_view text) { + refused += text.starts_with("could not open the offer from 0offer") ? 1 : 0; + }; + trystero::app a_app(f.io.get_executor(), f.net, std::move(c)); const auto a = join(a_app, "offers"); flooder attacker(f, "offers"); const auto a_topic = trystero::protocol::peer_topic(app_id, "offers", "zzzzzzzzzzzzzzzzzzzz"); - const auto before = f.net.relay(relay_a).events_seen; - for (int i = 0; i < 200; ++i) { + // Twenty at a time, all at one instant, each twenty refused before the next comes. A new id + // beyond the room's 32 negotiations takes the place of one already refused, which is idle: one + // whose offer is being opened keeps its place. More than 32 at once would have the later ids + // refused at the bound, unopened (a_flood_of_offers_at_one_instant_is_bounded). + const auto instant = f.net.steady_now(); + for (std::size_t i = 0; i < flood; ++i) { const std::string id = "0offer" + std::to_string(i); attacker.publish(a_topic, {.peer_id = id, .offer_id = "offer", .offer = "not a sealed offer"}); + if (i % 20 == 19 && !BOOST_TEST(run_until(f, [&] { return refused == i + 1; }))) { + break; + } + } + BOOST_TEST_EQ(refused, flood); + BOOST_TEST_EQ(f.net.made_connections, 0U); + BOOST_TEST(f.net.steady_now() == instant); +} + +// Two peers offer to a room at one instant, and the room's sealer takes its time to open their +// offers, as Web Crypto's does in a page; meanwhile, at the same instant, as many new ids announce +// as the room holds negotiations (max_unconnected_peers): they fill every other place, and the last +// two take the places of idle negotiations. One whose offer is being opened is not idle, so both +// peers join at that instant, as with Trystero, which bounds nothing. At one instant no negotiation +// has been idle longer than another, and the peers' ids sort before the others'. When a +// negotiation was idle as soon as it held no connection, the tie went to the first in id order: +// the last two ids took the peers' places, the room dropped both offers unopened, and the peers +// joined only when they offered again, 2 s later (measured). +void an_offer_being_opened_keeps_its_place() { + constexpr std::size_t bound = trystero::detail::signaling::max_unconnected_peers; + fixture f{true}; + trystero::app a_app(f.io.get_executor(), f.net, app_config("0aaaaaaaaaaaaaaaaaaa")); + const auto a = join(a_app, "opening"); + trystero::app b_app(f.io.get_executor(), f.net, app_config("0bbbbbbbbbbbbbbbbbbb")); + const auto b = join(b_app, "opening"); + webcpp::test::require( + BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }))); + + // From here on the clock stands still: only what is ready runs. + const auto instant = f.net.steady_now(); + const auto settle = [&] { webcpp::test::require(BOOST_TEST(f.net.poll_ready())); }; + f.net.hold_sealer_opens = true; + auto c = app_config("zzzzzzzzzzzzzzzzzzzz"); + std::size_t refusals = 0; + c.log = [&](std::string_view /*category*/, std::string_view text) { + refusals += text.starts_with("refusing ") ? 1 : 0; + }; + trystero::app z_app(f.io.get_executor(), f.net, std::move(c)); + auto z = join(z_app, "opening"); + std::vector joined; + z.on_peer_join([&](std::string_view p) { joined.emplace_back(p); }); + // Its announcement reaches both peers, whose ids are below its own: each offers to it and sends + // its candidate, and the room's opens of the two offers and the two candidates wait. (Each + // signal comes through both relays, as one event, which the room acts on once.) + settle(); + BOOST_TEST_EQ(f.net.held_sealer_opens(), 4U); + flooder crowd(f, "opening"); + crowd.announce(bound, "1crowd"); + settle(); + f.net.hold_sealer_opens = false; + f.net.release_sealer_opens(); + settle(); + BOOST_TEST(f.net.steady_now() == instant); + std::ranges::sort(joined); + const std::vector both{"0aaaaaaaaaaaaaaaaaaa", "0bbbbbbbbbbbbbbbbbbb"}; + BOOST_TEST_ALL_EQ(joined.begin(), joined.end(), both.begin(), both.end()); + BOOST_TEST_EQ(refusals, 0U); +} + +// Forged offers from fresh ids, all at one instant, while the room's sealer takes its time to open +// them: the room opens the offers of at most max_unconnected_peers negotiations, and refuses every +// other id, each logged once, so that each offer is accounted for, refused for not opening or at +// the bound. None makes a connection, and a peer who comes next takes the place of a refused one. +// When each new id could take the place of a negotiation whose offer was being opened, the room +// opened all 200 at once, and dropped 168 of them unopened, with no log (measured). +void a_flood_of_offers_at_one_instant_is_bounded() { + constexpr std::size_t flood = 200; + constexpr std::size_t bound = trystero::detail::signaling::max_unconnected_peers; + fixture f{true}; + const std::string_view z_id = "zzzzzzzzzzzzzzzzzzzz"; + auto c = app_config(z_id); + std::size_t not_opened = 0; + std::size_t refused = 0; + c.log = [&](std::string_view /*category*/, std::string_view text) { + not_opened += text.starts_with("could not open the offer from 0offer") ? 1 : 0; + refused += text.starts_with("refusing 0offer") ? 1 : 0; + }; + trystero::app z_app(f.io.get_executor(), f.net, std::move(c)); + auto z = join(z_app, "instant"); + std::vector joined; + z.on_peer_join([&](std::string_view p) { joined.emplace_back(p); }); + flooder attacker(f, "instant"); + const auto z_topic = trystero::protocol::peer_topic(app_id, "instant", z_id); + const auto instant = f.net.steady_now(); + f.net.hold_sealer_opens = true; + for (std::size_t i = 0; i < flood; ++i) { + attacker.publish(z_topic, { + .peer_id = "0offer" + std::to_string(i), + .offer_id = "offer", + .offer = "not a sealed offer", + }); } - BOOST_TEST(run_until(f.io, [&] { return f.net.relay(relay_a).events_seen >= before + 200; })); - run_until(f.io, [] { return false; }, 200ms); // the opens complete + webcpp::test::require(BOOST_TEST(f.net.poll_ready())); + BOOST_TEST_EQ(f.net.held_sealer_opens(), bound); + BOOST_TEST_EQ(refused, flood - bound); + f.net.hold_sealer_opens = false; + f.net.release_sealer_opens(); + webcpp::test::require(BOOST_TEST(f.net.poll_ready())); + BOOST_TEST_EQ(not_opened, bound); BOOST_TEST_EQ(f.net.made_connections, 0U); + BOOST_TEST(f.net.steady_now() == instant); + + trystero::app a_app(f.io.get_executor(), f.net, app_config("0aaaaaaaaaaaaaaaaaaa")); + const auto a = join(a_app, "instant"); + BOOST_TEST(run_until(f, [&] { return joined.size() == 1; })); +} + +// Offers in one peer's name, all at one instant, while the room's sealer takes its time to open +// them: first one sealed with the room key, then 40 others, each a text of its own and 48 KiB +// long, and the first again, as an event of its own through the other relay. The room opens one +// offer of a peer at a time, as Trystero answers one at a time, and ignores the others in that name +// until it is opened: one open, and one copy of an offer, the first, in the room's resource. The +// first again has the answer sent through its relay too, as Trystero's replay records the relay. +// When each offer started an open of its own, holding its copy, only the relays' rate bounded +// them: 42 opens, some 1.9 MiB, and an answer through the first relay alone (measured). +void offers_in_one_name_are_opened_one_at_a_time() { + constexpr std::size_t offers = 40; + const std::string padding(std::size_t{48} * 1024, 'x'); + counting_resource memory; // first: the io_context's pending operations free into it + fixture f{true}; + const std::string_view z_id = "zzzzzzzzzzzzzzzzzzzz"; + auto c = app_config(z_id); + c.memory = &memory; + trystero::app z_app(f.io.get_executor(), f.net, std::move(c)); + const auto z = join(z_app, "one"); + const auto z_topic = trystero::protocol::peer_topic(app_id, "one", z_id); + // Two sockets in the name of 0name, one on each relay, which see the room's answers to it. + std::set answered_through; + flooder on_a(f, "one"); + flooder on_b(f, "one", relay_b); + for (auto [socket, relay] : {std::pair{&on_a, relay_a}, std::pair{&on_b, relay_b}}) { + socket->on_text = [&answered_through, relay, z_id](std::string_view text) { + const auto signal = relayed_signal(text); + if (signal && signal->peer == z_id && !signal->answer.empty()) { + answered_through.emplace(relay); + } + }; + socket->watch(trystero::protocol::peer_topic(app_id, "one", "0name")); + } + webcpp::test::require(BOOST_TEST(f.net.poll_ready())); + const std::size_t joined = memory.in_use; + f.net.hold_sealer_opens = true; + const auto sealed = flooder::sealed("one", "mem:999"); + const trystero::protocol::signal_message first{ + .peer_id = "0name", + .offer_id = "first", + .offer = sealed, + }; + on_a.publish(z_topic, first); + for (std::size_t i = 0; i < offers; ++i) { + on_a.publish(z_topic, { + .peer_id = "0name", + .offer_id = "o" + std::to_string(i), + .offer = padding + std::to_string(i), + }); + } + on_b.publish(z_topic, first, "again"); + webcpp::test::require(BOOST_TEST(f.net.poll_ready())); + BOOST_TEST_EQ(f.net.held_sealer_opens(), 1U); + BOOST_TEST_LT(memory.in_use - joined, padding.size()); + f.net.hold_sealer_opens = false; + f.net.release_sealer_opens(); + webcpp::test::require(BOOST_TEST(f.net.poll_ready())); + BOOST_TEST_EQ(f.net.made_connections, 1U); + const std::set both{relay_a, relay_b}; + BOOST_TEST_ALL_EQ(answered_through.begin(), answered_through.end(), both.begin(), both.end()); } // Unsealed offers from 2000 fresh ids, which anyone who reads the relays can send: the room reports // the first at once, with its peer, and the rest together, at most once per interval, with no peer -// and their number, so that the application is not handed one report per id. The clock runs 10 -// times faster. +// and their number, so that the application is not handed one report per id. On the virtual +// clock, the flood spans two and a half intervals. void signals_that_do_not_open_are_reported_once_per_interval() { - constexpr int flood = 2000; - fixture f; - f.net.time_scale = 10; + constexpr std::size_t flood = 2000; + fixture f{true}; const std::string a_id = "zzzzzzzzzzzzzzzzzzzz"; trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id)); auto a = join(a_app, "reports"); @@ -549,22 +748,22 @@ void signals_that_do_not_open_are_reported_once_per_interval() { }); flooder attacker(f, "reports"); const auto a_topic = trystero::protocol::peer_topic(app_id, "reports", a_id); - const auto started = f.net.now_ms(); + const auto started = f.net.steady_now(); const auto before = f.net.relay(relay_a).events_seen; - // Paced, so that each offer's open completes before later ids evict its negotiation: every - // twenty, the executor runs until nothing is left to run, the relay, the room and the sealer's - // opens, however slowly the machine runs them. - for (int i = 0; i < flood; ++i) { + // Paced, twenty at a time, fewer than the room's 32 negotiations, so that every offer is opened + // rather than refused at the bound: every twenty, everything ready runs, the relay, the room + // and the sealer's opens, and then the clock moves 250 ms, 25 s for the whole flood. + for (std::size_t i = 0; i < flood; ++i) { attacker.publish(a_topic, { .peer_id = "0garbage" + std::to_string(i), .offer_id = "o", .offer = "not a sealed offer", }); if (i % 20 == 19) { - f.io.poll(); + advance(f, 250ms); } } - BOOST_TEST(run_until(f.io, [&] { return f.net.relay(relay_a).events_seen >= before + flood; })); + BOOST_TEST(run_until(f, [&] { return f.net.relay(relay_a).events_seen >= before + flood; })); // Every failed open is counted once its interval ends. const auto counted = [&] { std::size_t sum = 0; @@ -573,9 +772,9 @@ void signals_that_do_not_open_are_reported_once_per_interval() { } return sum; }; - BOOST_TEST(run_until(f.io, [&] { return counted() == flood; })); - const double elapsed = f.net.now_ms() - started; - BOOST_TEST_LE(static_cast(reports.size()), 2 + (elapsed / 10'000)); + BOOST_TEST(run_until(f, [&] { return counted() == flood; })); + const auto elapsed = f.net.steady_now() - started; + BOOST_TEST_LE(reports.size(), 2 + static_cast(elapsed / 10s)); if (BOOST_TEST(!reports.empty())) { BOOST_TEST_EQ(reports.front().peer, "0garbage0"); } @@ -589,17 +788,19 @@ void sealed_offers_that_fail_at_once_are_bounded() { constexpr std::size_t bound = trystero::detail::signaling::max_connections_per_window; fixture f; auto c = app_config("zzzzzzzzzzzzzzzzzzzz"); - int refusals = 0; + std::size_t refusals = 0; c.log = [&](std::string_view /*category*/, std::string_view text) { - refusals += text.find(" connections were made in the last ") != std::string_view::npos; + refusals += + text.find(" connections were made in the last ") != std::string_view::npos ? 1 : 0; }; trystero::app a_app(f.io.get_executor(), f.net, std::move(c)); const auto a = join(a_app, "churn"); flooder member(f, "churn"); const auto a_topic = trystero::protocol::peer_topic(app_id, "churn", "zzzzzzzzzzzzzzzzzzzz"); // One at a time, each once the previous one made its connection or was refused: sent at once, - // the offers would evict each other's negotiations before they open. Each is a text of its - // own, as a member makes them: the room refuses an offer it used before. + // the ids beyond the room's 32 negotiations would be refused at the bound before their offers + // open, and the window would go untested. Each is a text of its own, as a member makes them: + // the room refuses an offer it used before. for (std::size_t i = 0; i < flood; ++i) { const auto offer = flooder::sealed("churn", "not an SDP the connection takes " + std::to_string(i)); @@ -633,20 +834,12 @@ void announcements_with_forged_answers_are_bounded() { std::map> owners; // peer topic -> its peer id std::size_t forged = 0; attacker.on_text = [&](std::string_view text) { - boost::system::error_code ec; - const auto document = boost::json::parse(text, ec); - const auto message = - ec ? std::nullopt : trystero::protocol::nostr::read_relay_message(document); - const auto* event = - message ? std::get_if(&*message) : nullptr; - const auto topic = event == nullptr ? std::string_view() : event->topic; - const auto owner = owners.find(topic); + const auto signal = relayed_signal(text); + const auto owner = signal ? owners.find(signal->topic) : owners.end(); if (owner == owners.end()) { return; } - const auto content = boost::json::parse(event->content, ec); - const auto signal = ec ? std::nullopt : trystero::protocol::read_signal(content); - if (signal && signal->peer_id == a_id && !signal->offer.empty()) { + if (signal->peer == a_id && !signal->offer.empty()) { attacker.publish(a_topic, { .peer_id = owner->second, .offer_id = signal->offer_id, @@ -686,6 +879,197 @@ void the_replay_cache_remembers_the_last_ones() { BOOST_TEST(!none.contains("one")); } +/** A NIP-01 event id, 64 lowercase hexadecimal digits, all `digit`. */ +std::string event_id_of(char digit) { + std::string id(trystero::detail::recent_event_ids::id_size, digit); + return id; +} + +// A relay may repeat an event, and every relay carries the events of the room: the strategy acts on +// an event id once among the newest it remembers, and on the oldest again once forgotten. +void recent_event_ids_drop_a_repeat_and_forget_the_oldest() { + counting_resource memory; + { + const std::array key{}; + trystero::detail::recent_event_ids ids(3, key, &memory); + const auto a = event_id_of('a'); + const auto b = event_id_of('b'); + const auto c = event_id_of('c'); + const auto d = event_id_of('d'); + BOOST_TEST(ids.remember(a)); + BOOST_TEST(!ids.remember(a)); + BOOST_TEST(ids.remember(b)); + BOOST_TEST(ids.remember(c)); + BOOST_TEST(!ids.remember(a)); + BOOST_TEST(ids.remember(d)); + BOOST_TEST_EQ(ids.size(), 3U); + BOOST_TEST(ids.remember(a)); + BOOST_TEST(!ids.remember(c)); + BOOST_TEST(!ids.remember(d)); + BOOST_TEST(ids.remember(b)); + BOOST_TEST_EQ(ids.size(), 3U); + BOOST_TEST_GT(memory.in_use, 0U); + } + BOOST_TEST_EQ(memory.in_use, 0U); +} + +// Trystero takes every event a relay sends, repeats included. The port drops a repeat only of an +// id NIP-01 defines, 64 lowercase hexadecimal digits: any other id, of any length, is acted on as +// Trystero acts on it, every time, and never stored, so that a relay cannot fill the room's +// resource with the 4096 ids remembered. What the index holds once made is its own: libstdc++'s +// deque and MSVC's debug containers allocate even when empty. +void event_ids_other_than_nip01_ones_are_never_remembered() { + counting_resource memory; + const std::array key{}; + trystero::detail::recent_event_ids ids(3, key, &memory); + const std::size_t empty = memory.in_use; + std::string uppercase = event_id_of('a'); + uppercase.back() = 'A'; + std::string not_hex = event_id_of('a'); + not_hex.front() = 'g'; + for (const std::string& id : { + std::string(), + std::string(63, 'a'), + std::string(65, 'a'), + uppercase, + not_hex, + std::string(std::size_t{1} << 20U, 'a'), + }) { + BOOST_TEST(ids.remember(id)); + BOOST_TEST(ids.remember(id)); + } + BOOST_TEST_EQ(ids.size(), 0U); + BOOST_TEST_EQ(memory.in_use, empty); +} + +// The ids are whatever a relay sends, so the index hashes them with SipHash under a key of the +// strategy's: under another key, an id hashes elsewhere, so that ids a relay chose to collide under +// one key do not under the next. +void the_event_id_hash_is_keyed() { + std::array one{}; + one.fill(1); + std::array two{}; + two.fill(2); + const trystero::detail::recent_event_ids::keyed_hash under_one(one); + const trystero::detail::recent_event_ids::keyed_hash under_two(two); + const auto id = event_id_of('e'); + BOOST_TEST_NE(under_one(id), under_two(id)); + BOOST_TEST_EQ(under_one(id), trystero::detail::recent_event_ids::keyed_hash(one)(id)); +} + +// A strategy draws its index's key from the backend's randomness when it is made, after its +// signer's secret: a relay cannot know it. Its index hashes under those 16 bytes, read again from +// a twin of the backend's stream, so that strategies over other streams hash an id elsewhere. +void a_strategy_draws_the_key_of_its_event_ids() { + constexpr std::size_t key_size = trystero::detail::recent_event_ids::key_size; + const auto id = event_id_of('e'); + std::vector hashes; + for (const std::uint64_t seed : {1U, 2U}) { + asio::io_context io; + trystero::test::memory_network net(io, seed); + const auto strategy = std::make_shared( + net, std::span(), std::pmr::vector(), "topic", + trystero::handler(), + trystero::detail::nostr_strategy::message_handler(), trystero::detail::logger(), + std::pmr::get_default_resource()); + BOOST_TEST_EQ(net.random_bytes, 32U + key_size); // the secret, the key + asio::io_context twin_io; + trystero::test::memory_network twin(twin_io, seed); + std::array secret{}; + twin.random(secret); + std::array key{}; + twin.random(key); + const std::size_t hash = strategy->seen().hash_function()(id); + BOOST_TEST_EQ(hash, trystero::detail::recent_event_ids::keyed_hash(key)(id)); + hashes.push_back(hash); + } + BOOST_TEST_NE(hashes.at(0), hashes.at(1)); +} + +/** A client of the relay `url` of `f`, once it is open: another user of the relay, to a room. */ +std::shared_ptr client_of(fixture& f, std::string_view url) { + const auto open = std::make_shared(false); + auto socket = f.net.connect(url, {.open = [open] { *open = true; }, .message = {}, .close = {}}, + std::pmr::get_default_resource()); + webcpp::test::require(BOOST_TEST(run_until(f, [&open] { return *open; }))); + return socket; +} + +/** Where a client's `["EVENT",{...}]`, as event_message writes it, holds its id. */ +std::size_t id_position(std::string_view message) { + constexpr std::string_view key = R"("id":")"; + return message.find(key) + key.size(); +} + +// A relay chooses the id it sends with an event, and a strategy acts on an id once. A relay on a +// peer's list sends a forged event under a genuine event's id before an honest relay carries the +// genuine one, as it can for a counter-announcement, whose text holds no nonce. The strategy +// remembers only an id it checked to be its event's own, so it acts on both, as Trystero, which +// remembers none, does: on the forged one each time it comes, and on the genuine one once. +void a_forged_event_under_a_genuine_id_hides_nothing() { + fixture f(true); + const std::string_view topic = "a-topic-of-the-room"; + std::vector heard; + const std::array urls{ + std::pmr::string(relay_a), + std::pmr::string(relay_b), + }; + std::pmr::vector topics; + topics.emplace_back(topic); + const auto strategy = std::make_shared( + f.net, urls, std::move(topics), "another-topic", + trystero::handler([] { return std::pmr::string("{}"); }), + trystero::detail::nostr_strategy::message_handler( + [&heard](std::size_t /*relay*/, std::string_view /*topic*/, std::string_view content) { + heard.emplace_back(content); + }), + trystero::detail::logger(), std::pmr::get_default_resource()); + strategy->start(); + // A relay that saw the strategy's first announcement saw its subscription, sent before it. + webcpp::test::require(BOOST_TEST(run_until(f, [&f] { + return f.net.relay(relay_a).events_seen > 0 && f.net.relay(relay_b).events_seen > 0; + }))); + const auto dishonest = client_of(f, relay_a); + const auto honest = client_of(f, relay_b); + std::array secret{}; + secret.fill(5); + const auto key = trystero::protocol::nostr::signer::from_secret(secret); + webcpp::test::require(BOOST_TEST(key.has_value())); + const auto event = [&](std::string_view content) { + const std::array aux{}; + return std::string(trystero::protocol::nostr::event_message( + *key, trystero::detail::unix_now(f.net), topic, content, aux)); + }; + const std::string genuine = event("genuine"); + std::string forged = event("forged"); + const std::size_t id_at = id_position(genuine); + forged.replace(id_position(forged), trystero::detail::recent_event_ids::id_size, genuine, id_at, + trystero::detail::recent_event_ids::id_size); + dishonest->send(forged); + webcpp::test::require(BOOST_TEST(run_until(f, [&heard] { return heard.size() == 1; }))); + honest->send(genuine); + BOOST_TEST(run_until(f, [&heard] { return heard.size() == 2; })); + dishonest->send(genuine); + dishonest->send(forged); + dishonest->send(event("later")); + BOOST_TEST(run_until(f, [&heard] { return !heard.empty() && heard.back() == "later"; })); + const std::array expected{"forged", "genuine", "forged", "later"}; + BOOST_TEST_ALL_EQ(heard.begin(), heard.end(), expected.begin(), expected.end()); + strategy->stop(); +} + +// A boost::circular_buffer moves by swapping its allocators, which std::pmr's cannot: the classes +// that hold one over the room's resource say they cannot move, rather than fail to compile when +// moved. +void classes_over_a_pmr_circular_buffer_do_not_move() { + BOOST_TEST(!std::is_move_constructible_v); + BOOST_TEST(!std::is_move_assignable_v); + BOOST_TEST(!std::is_move_constructible_v); + BOOST_TEST(!std::is_move_assignable_v); + BOOST_TEST(!std::is_move_constructible_v); + BOOST_TEST(!std::is_move_assignable_v); +} + /** Joins B to A, records what `record` keeps of the relays meanwhile, and has B leave; B's app goes * with it, so that B's return negotiates again. */ void join_and_leave(fixture& f, std::string_view b_id, std::string_view room_id, @@ -694,24 +1078,22 @@ void join_and_leave(fixture& f, std::string_view b_id, std::string_view room_id, trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); auto b = join(b_app, room_id); webcpp::test::require( - BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1 && recorded(); }))); + BOOST_TEST(run_until(f, [&] { return joined.size() == 1 && recorded(); }))); bool done = false; b.async_leave([&](boost::system::error_code) { done = true; }); - webcpp::test::require(BOOST_TEST(run_until(f.io, [&] { return done && left.size() == 1; }))); + webcpp::test::require(BOOST_TEST(run_until(f, [&] { return done && left.size() == 1; }))); } // A watcher without the room key records B's sealed answer to A. Once B has left and come back with // the same id, as a Trystero JS page does after a network drop, it sends that answer in B's name // with each of A's new offers to B, before B's own answer. The answer opens with the room key, but -// A used it before: A refuses it, blames no one, and B joins again. The clock runs 10 times -// faster. +// A used it before: A refuses it, blames no one, and B joins again. // // The watcher is armed as A sees B leave: an announcement B made before leaving may still reach A // after it, and A's offer to that announcement is the one the returning B answers, on a relay // where A does not send it again. void a_replayed_answer_is_refused() { - fixture f; - f.net.time_scale = 10; + fixture f{true}; const std::string a_id = "00000000000000000000"; const std::string b_id = "BBBBBBBBBBBBBBBBBBBB"; trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id)); @@ -731,7 +1113,7 @@ void a_replayed_answer_is_refused() { const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "replay", a_id)); const auto b_topic = std::string(trystero::protocol::peer_topic(app_id, "replay", b_id)); std::string recorded; - int replays = 0; + std::size_t replays = 0; watcher.on_text = [&](std::string_view text) { const auto s = relayed_signal(text); if (!s) { @@ -751,20 +1133,18 @@ void a_replayed_answer_is_refused() { join_and_leave(f, b_id, "replay", joined, left, [&] { return !recorded.empty(); }); trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); const auto b = join(b_app, "replay"); - BOOST_TEST(run_until(f.io, [&] { return joined.size() == 2; })); - BOOST_TEST_GE(replays, 1); + BOOST_TEST(run_until(f, [&] { return joined.size() == 2; })); + BOOST_TEST_GE(replays, 1U); BOOST_TEST(std::ranges::none_of(errors, [](boost::system::error_code ec) { return ec == trystero::error::wrong_password; })); } // The same for an offer: B is lower and offers. The watcher records B's sealed offer to A, and once -// B is back, sends it in B's name every 0.5 s of the rooms' time, with fresh offer ids. A answered -// that offer before, so it refuses each replay, and B's own offer joins them. The clock runs 10 -// times faster. +// B is back, sends it in B's name every 0.5 s of the virtual clock, with fresh offer ids. A +// answered that offer before, so it refuses each replay, and B's own offer joins them. void a_replayed_offer_is_refused() { - fixture f; - f.net.time_scale = 10; + fixture f{true}; const std::string a_id = "zzzzzzzzzzzzzzzzzzzz"; const std::string b_id = "BBBBBBBBBBBBBBBBBBBB"; trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id)); @@ -786,18 +1166,18 @@ void a_replayed_offer_is_refused() { join_and_leave(f, b_id, "replayo", joined, left, [&] { return !recorded.empty(); }); trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); const auto b = join(b_app, "replayo"); - int replays = 0; - const auto end = std::chrono::steady_clock::now() + 10s; - while (joined.size() < 2 && std::chrono::steady_clock::now() < end) { + std::size_t replays = 0; + const auto end = f.net.steady_now() + 10s; + while (joined.size() < 2 && f.net.steady_now() < end) { watcher.publish(a_topic, { .peer_id = b_id, .offer_id = "replay" + std::to_string(replays++), .offer = recorded, }); - run_until(f.io, [] { return false; }, 50ms); + advance(f, 500ms); } BOOST_TEST_EQ(joined.size(), 2U); - BOOST_TEST_GE(replays, 1); + BOOST_TEST_GE(replays, 1U); } // A watcher without the room key sends A's own sealed offer to B back to A, at once, as B's answer @@ -813,7 +1193,7 @@ void a_reflected_offer_is_refused_as_an_answer() { flooder watcher(f, "reflect"); const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "reflect", a_id)); const auto b_topic = std::string(trystero::protocol::peer_topic(app_id, "reflect", b_id)); - int reflected = 0; + std::size_t reflected = 0; watcher.on_text = [&](std::string_view text) { const auto s = relayed_signal(text); if (s && s->topic == b_topic && s->peer == a_id && !s->offer.empty()) { @@ -826,21 +1206,19 @@ void a_reflected_offer_is_refused_as_an_answer() { trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); const auto b = join(b_app, "reflect"); BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; })); - BOOST_TEST_GE(reflected, 1); + BOOST_TEST_GE(reflected, 1U); } // A watcher without the room key announces a decoy id above A, records A's sealed offer to it, and // sends that offer to A in B's name whenever B announces itself, before B's own offer. A made that // offer: A refuses it, never answers one in B's name but B's own, and B's own offer joins them. -// The clock runs 10 times faster. void a_reflected_offer_is_refused_as_an_offer() { - fixture f; - f.net.time_scale = 10; + fixture f{true}; const std::string a_id = "yyyyyyyyyyyyyyyyyyyy"; const std::string b_id = "BBBBBBBBBBBBBBBBBBBB"; const std::string decoy = "zzzzzzzzzzzzzzzzzzzz"; auto c = app_config(a_id); - int answered_reflections = 0; + std::size_t answered_reflections = 0; c.log = [&](std::string_view /*category*/, std::string_view text) { answered_reflections += text.starts_with("offer reflected") ? 1 : 0; }; @@ -853,7 +1231,7 @@ void a_reflected_offer_is_refused_as_an_offer() { const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "reflecto", a_id)); const auto decoy_topic = std::string(trystero::protocol::peer_topic(app_id, "reflecto", decoy)); std::string recorded; - int reflected = 0; + std::size_t reflected = 0; watcher.on_text = [&](std::string_view text) { const auto s = relayed_signal(text); if (!s) { @@ -873,12 +1251,12 @@ void a_reflected_offer_is_refused_as_an_offer() { watcher.watch(root); watcher.watch(decoy_topic); watcher.announce_as(decoy, 1); - webcpp::test::require(BOOST_TEST(run_until(f.io, [&] { return !recorded.empty(); }))); + webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !recorded.empty(); }))); trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); const auto b = join(b_app, "reflecto"); - BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; })); - BOOST_TEST_GE(reflected, 1); - BOOST_TEST_EQ(answered_reflections, 0); + BOOST_TEST(run_until(f, [&] { return joined.size() == 1; })); + BOOST_TEST_GE(reflected, 1U); + BOOST_TEST_EQ(answered_reflections, 0U); } // A answers B (B's id is lower), then offers to C (C's id is higher). A watcher without the room @@ -903,7 +1281,7 @@ void a_reflected_answer_is_refused_as_an_answer() { const auto b_topic = std::string(trystero::protocol::peer_topic(app_id, "reflans", b_id)); const auto c_topic = std::string(trystero::protocol::peer_topic(app_id, "reflans", c_id)); std::string a_answer; - int reflected = 0; + std::size_t reflected = 0; watcher.on_text = [&](std::string_view text) { const auto s = relayed_signal(text); if (!s) { @@ -927,23 +1305,23 @@ void a_reflected_answer_is_refused_as_an_answer() { trystero::app peer_c_app(f.io.get_executor(), f.net, app_config(c_id)); const auto peer_c = join(peer_c_app, "reflans"); BOOST_TEST(run_until(f.io, [&] { return joined.size() == 2; })); - BOOST_TEST_GE(reflected, 1); + BOOST_TEST_GE(reflected, 1U); BOOST_TEST(refused); } // A relay that closes each connection right after its subscription, as one does after a text // longer than a room reads, is tried again within a bound that doubles every time, to 60 s; the -// bound comes back to 3.3 s only after a connection that stayed open for 60 s. The clock runs 100 -// times faster. +// bound comes back to 3.3 s only after a connection that stayed open for 60 s. On the virtual +// clock the close comes at the instant of the open: on a wall clock 100 times faster, the process +// paused for 0.6 s between the two made the connection one that had lasted 60 s. void a_relay_that_closes_at_once_is_tried_less_and_less_often() { - fixture f; - f.net.time_scale = 100; + fixture f{true}; auto& relay = f.net.relay(relay_a); relay.close_after_subscribe = true; auto c = app_config("AAAAAAAAAAAAAAAAAAAA"); c.relay_urls = {relay_a}; - std::vector bounds; - int reconnections = 0; + std::vector bounds; + std::size_t reconnections = 0; c.log = [&](std::string_view /*category*/, std::string_view text) { constexpr std::string_view within = ", next attempt within "; if (const auto at = text.find(within); at != std::string_view::npos) { @@ -953,23 +1331,24 @@ void a_relay_that_closes_at_once_is_tried_less_and_less_often() { }; trystero::app a_app(f.io.get_executor(), f.net, std::move(c)); const auto a = join(a_app, "backoff"); - BOOST_TEST(run_until(f.io, [&] { return bounds.size() >= 6; })); - const std::vector growing{3333, 6666, 13332, 26664, 53328, 60000}; + BOOST_TEST(run_until(f, [&] { return bounds.size() >= 6; }, 2min)); + const std::vector growing{3333, 6666, 13332, 26664, 53328, 60000}; BOOST_TEST_ALL_EQ(bounds.begin(), bounds.begin() + std::min(6, std::ssize(bounds)), growing.begin(), growing.end()); - // A connection that lasts: the 60 s announcement after it opened is on the relay, then the - // relay goes away. + // A connection that lasts: once the first of the steady announcements, 60 s after the warm-up, + // is on the relay, the relay goes away. relay.close_after_subscribe = false; - const int before = reconnections; - BOOST_TEST(run_until(f.io, [&] { return reconnections > before; })); + const std::size_t before = reconnections; + BOOST_TEST(run_until(f, [&] { return reconnections > before; }, 1min)); + // The warm-up's first announcement went as the connection opened, before the clock moved: its + // four others, then the first steady one. const auto seen = relay.events_seen; - // the warm-up's five announcements, then the first of the steady ones, 60 s later - BOOST_TEST(run_until(f.io, [&] { return relay.events_seen >= seen + 6; })); + BOOST_TEST(run_until(f, [&] { return relay.events_seen >= seen + 5; }, 2min)); const auto lost = bounds.size(); relay.close_all(); - BOOST_TEST(run_until(f.io, [&] { return bounds.size() > lost; })); + BOOST_TEST(run_until(f, [&] { return bounds.size() > lost; })); if (bounds.size() > lost) { BOOST_TEST_EQ(bounds[lost], 3333); } @@ -977,9 +1356,11 @@ void a_relay_that_closes_at_once_is_tried_less_and_less_often() { // A flood of fresh ids below ours asks the room for a counter-announcement each: the room sends // at most one per relay in 5.3 s, Trystero's announce interval, so that no relay rate-limits it. +// On the virtual clock the interval is checked at its end: a flood at once asks once, an id 1 ms +// before the interval ends asks nothing, and one as it ends asks again. void counter_announcements_are_paced() { constexpr std::size_t flood = 300; - fixture f; + fixture f{true}; auto c = app_config("zzzzzzzzzzzzzzzzzzzz"); std::size_t asked = 0; c.log = [&](std::string_view /*category*/, std::string_view text) { @@ -988,14 +1369,22 @@ void counter_announcements_are_paced() { trystero::app a_app(f.io.get_executor(), f.net, std::move(c)); const auto a = join(a_app, "counter"); flooder attacker(f, "counter"); - const auto start = std::chrono::steady_clock::now(); - const auto before = f.net.relay(relay_a).events_seen; - attacker.announce(flood, "0low"); - BOOST_TEST(run_until(f.io, [&] { return f.net.relay(relay_a).events_seen >= before + flood; })); - f.io.poll(); // the room handles what the relay forwarded, posted behind every event it took - const auto elapsed = std::chrono::steady_clock::now() - start; - BOOST_TEST_GE(asked, 1U); - BOOST_TEST_LE(asked, 1 + static_cast(elapsed / 5333ms)); + // Announces `count` fresh ids, and returns once the relay took them and the room handled them, + // the clock still. + const auto announced = [&](std::size_t count, std::string_view prefix) { + const auto before = f.net.relay(relay_a).events_seen; + attacker.announce(count, prefix); + BOOST_TEST( + run_until(f, [&] { return f.net.relay(relay_a).events_seen >= before + count; })); + }; + announced(flood, "0low"); + BOOST_TEST_EQ(asked, 1U); + advance(f, 5332ms); + announced(1, "0early"); + BOOST_TEST_EQ(asked, 1U); + advance(f, 1ms); + announced(1, "0due"); + BOOST_TEST_EQ(asked, 2U); } // Beyond the bound, a new peer is refused, and one refused again and again is logged once: the @@ -1003,8 +1392,8 @@ void counter_announcements_are_paced() { void a_refused_peer_is_logged_once() { fixture f; auto c = app_config("00000000000000000000"); - int refusals_of_one = 0; - int refusals = 0; + std::size_t refusals_of_one = 0; + std::size_t refusals = 0; c.log = [&](std::string_view /*category*/, std::string_view text) { refusals += text.starts_with("refusing ") ? 1 : 0; refusals_of_one += text.starts_with("refusing 1same") ? 1 : 0; @@ -1019,7 +1408,7 @@ void a_refused_peer_is_logged_once() { BOOST_TEST(run_until( f.io, [&] { return f.net.relay(relay_a).events_seen >= before + bound + 8 + 5; })); BOOST_TEST(run_until(f.io, [&] { return refusals == 9; })); - BOOST_TEST_EQ(refusals_of_one, 1); + BOOST_TEST_EQ(refusals_of_one, 1U); BOOST_TEST_LE(f.net.live_connections(), 2 * bound); } @@ -1028,11 +1417,23 @@ void a_refused_peer_is_logged_once() { void long_peer_ids_are_bounded() { const std::string longest(trystero::protocol::max_peer_id_bytes, 'x'); const std::string too_long(trystero::protocol::max_peer_id_bytes + 1, 'x'); + // {"peerId":}, read as a room reads a signal. const auto signal = [](std::string_view id) { - return boost::json::value(boost::json::object{{"peerId", id}}); + std::pmr::string text("{"); + trystero::protocol::json::append_key(text, "peerId"); + webcpp::test::require(BOOST_TEST(trystero::protocol::json::append_string(text, id))); + text += '}'; + auto parsed = webcpp::document::parse( + text, + trystero::protocol::json::protocol_limits(trystero::protocol::max_parsed_signal_bytes), + std::pmr::polymorphic_allocator(std::pmr::get_default_resource())); + webcpp::test::require(BOOST_TEST(parsed.has_value())); + return std::move(*parsed); }; - BOOST_TEST(trystero::protocol::read_signal(signal(longest)).has_value()); - BOOST_TEST(!trystero::protocol::read_signal(signal(too_long)).has_value()); + const auto longest_signal = signal(longest); + const auto too_long_signal = signal(too_long); + BOOST_TEST(trystero::protocol::read_signal(longest_signal.root()).has_value()); + BOOST_TEST(!trystero::protocol::read_signal(too_long_signal.root()).has_value()); fixture f; trystero::app a_app(f.io.get_executor(), f.net, app_config(too_long)); @@ -1062,7 +1463,7 @@ void three_peers_form_a_mesh() { })); // A broadcast reaches both others. auto shout = rooms[0].make_action("shout"); - int heard = 0; + std::size_t heard = 0; for (std::size_t i = 1; i < rooms.size(); ++i) { rooms[i].make_action("shout").on_message( [&](const std::string& text, const trystero::message_info& /*info*/) { @@ -1084,7 +1485,7 @@ void async_receive_works_in_a_coroutine() { asio::co_spawn( f.io, [&]() -> asio::awaitable { - for (int i = 0; i < 2; ++i) { + for (std::size_t i = 0; i < 2; ++i) { auto [ec, value, info] = co_await inbox.async_receive(asio::as_tuple(asio::use_awaitable)); if (ec) { @@ -1092,18 +1493,142 @@ void async_receive_works_in_a_coroutine() { } seen.push_back(std::holds_alternative(value) ? std::get(value) - : boost::json::serialize(std::get(value))); + : std::get(value).stringify()); } }, asio::detached); BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; })); a.make_action("any").async_send("text", asio::detached); - a.make_action("any").async_send(boost::json::array{1, 2}, asio::detached); + a.make_action("any").async_send(document_of("[1,2]"), + asio::detached); BOOST_TEST(run_until(f.io, [&] { return seen.size() == 2; })); const std::vector both{"text", "[1,2]"}; BOOST_TEST_ALL_EQ(seen.begin(), seen.end(), both.begin(), both.end()); } +// A JSON payload is parsed in the receiving room's resource, as a webcpp::document::pmr::document, +// into an image of at most the room's max_json_document_bytes, whatever type receives it: an array +// of 1,000 zeros is delivered, as is the longest array of zeros whose document fits the bound, +// and the one a zero longer is not, while the messages after it are. +void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() { + constexpr std::uint64_t bound = std::uint64_t{256} << 10U; + std::pmr::unsynchronized_pool_resource z_memory; // outlives the io_context + fixture f; + trystero::app a_app(f.io.get_executor(), f.net, app_config("TTTTTTTTTTTTTTTTTTTT")); + auto a = join(a_app, "json"); + trystero::app z_app(f.io.get_executor(), f.net, app_config("UUUUUUUUUUUUUUUUUUUU")); + auto z = join(z_app, "json", + trystero::room_options{.max_json_document_bytes = bound, .memory = &z_memory}); + std::vector in_resource; + std::vector in_heap; + std::size_t elsewhere = 0; + z.make_action("pmr").on_message( + [&](const webcpp::document::pmr::document& v, const trystero::message_info&) { + elsewhere += v.get_allocator().resource() == &z_memory ? 0 : 1; + in_resource.push_back(v.root().size()); + }); + z.make_action("std").on_message( + [&](const webcpp::document::document& v, const trystero::message_info&) { + in_heap.push_back(v.root().size()); + }); + BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; })); + const auto zeros = [](std::size_t n) { + std::string text = "[0"; + for (std::size_t i = 1; i < n; ++i) { + text += ",0"; + } + return text + "]"; + }; + // The longest array of zeros whose document fits the bound, found by parsing as the room does. + const auto fits = [&zeros](std::size_t n) { + webcpp::document::parse_options o; + o.max_document_bytes = bound; + return webcpp::document::parse(zeros(n), o).has_value(); + }; + // Each zero is a node of 192 bytes, so no more than bound / 192 of them fit. + std::size_t at_bound = 1000; + std::size_t past_bound = (bound / 192) + 1; + while (past_bound - at_bound > 1) { + const std::size_t middle = at_bound + ((past_bound - at_bound) / 2); + (fits(middle) ? at_bound : past_bound) = middle; + } + BOOST_TEST(fits(at_bound) && !fits(at_bound + 1)); + for (const char* name : {"pmr", "std"}) { + auto to_z = a.make_action(name); + for (const std::size_t n : {std::size_t{1000}, at_bound, at_bound + 1, std::size_t{3}}) { + to_z.async_send(document_of(zeros(n)), asio::detached); + } + } + // A data channel keeps its order: the last of each action arrives after the other three. + BOOST_TEST(run_until(f.io, [&] { return in_resource.size() >= 3 && in_heap.size() >= 3; })); + const std::vector delivered{1000, at_bound, 3}; + BOOST_TEST_ALL_EQ(in_resource.begin(), in_resource.end(), delivered.begin(), delivered.end()); + BOOST_TEST_ALL_EQ(in_heap.begin(), in_heap.end(), delivered.begin(), delivered.end()); + BOOST_TEST_EQ(elsewhere, 0U); +} + +// A JSON payload nested as deep as webcpp::document's default, 256, is delivered, to either +// document type: its parse recurses once a level, on the room's executor, on every target and in +// both suspension variants, within the engine's default stack (doc: #trystero-protocol-json). +void a_json_payload_nested_256_deep_is_delivered() { + fixture f; + trystero::app a_app(f.io.get_executor(), f.net, app_config("XXXXXXXXXXXXXXXXXXXX")); + auto a = join(a_app, "deep"); + trystero::app z_app(f.io.get_executor(), f.net, app_config("YYYYYYYYYYYYYYYYYYYY")); + auto z = join(z_app, "deep"); + std::size_t delivered = 0; + z.make_action("pmr").on_message( + [&](const webcpp::document::pmr::document& v, const trystero::message_info&) { + delivered += v.root().is_array() ? 1 : 0; + }); + z.make_action("std").on_message( + [&](const webcpp::document::document& v, const trystero::message_info&) { + delivered += v.root().is_array() ? 1 : 0; + }); + BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; })); + const std::string deepest = std::string(256, '[') + std::string(256, ']'); + for (const char* name : {"pmr", "std"}) { + a.make_action(name).async_send(document_of(deepest), + asio::detached); + } + BOOST_TEST(run_until(f.io, [&] { return delivered == 2; })); +} + +// A message of another format than a document action's completes its receive with +// error::transfer_rejected and a document that holds nothing, which allocates nothing: its root +// reads undefined and it has no image, in the room's resource for a pmr::document. +void a_rejected_document_receive_holds_nothing() { + std::pmr::unsynchronized_pool_resource z_memory; // outlives the io_context + fixture f; + trystero::app a_app(f.io.get_executor(), f.net, app_config("VVVVVVVVVVVVVVVVVVVV")); + auto a = join(a_app, "rejected"); + trystero::app z_app(f.io.get_executor(), f.net, app_config("WWWWWWWWWWWWWWWWWWWW")); + auto z = join(z_app, "rejected", trystero::room_options{.memory = &z_memory}); + std::size_t completed = 0; + z.make_action("pmr").async_receive( + [&](boost::system::error_code ec, webcpp::document::pmr::document v, + const trystero::message_info& info) { + ++completed; + BOOST_TEST(ec == trystero::error::transfer_rejected); + BOOST_TEST(v.root().is_undefined()); + BOOST_TEST(v.image().empty()); + BOOST_TEST(v.get_allocator().resource() == &z_memory); + BOOST_TEST_EQ(info.from, "VVVVVVVVVVVVVVVVVVVV"); + }); + z.make_action("std").async_receive( + [&](boost::system::error_code ec, webcpp::document::document v, + const trystero::message_info& /*info*/) { + ++completed; + BOOST_TEST(ec == trystero::error::transfer_rejected); + BOOST_TEST(v.root().is_undefined()); + BOOST_TEST(v.image().empty()); + }); + BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; })); + a.make_action("pmr").async_send("not JSON", asio::detached); + a.make_action("std").async_send("not JSON", asio::detached); + BOOST_TEST(run_until(f.io, [&] { return completed == 2; })); +} + void view_handlers_read_the_frame_without_copying() { fixture f; trystero::app a_app(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR")); @@ -1142,13 +1667,13 @@ void a_rate_limited_relay_does_not_stop_discovery() { BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })); // Backoff: after the first refusal each peer stops publishing on relay A, so it sees only a // handful of attempts. - BOOST_TEST_LT(1000 - f.net.relay(relay_a).rate_limit_next, 12); + BOOST_TEST_LT(1000 - f.net.relay(relay_a).rate_limit_next, 12U); } // A connection's end is every room's (one room here): a forced failure, a frame that does not // decode, and a 65th advertised token each end it; the peers then meet again over a new one. void a_connections_end_is_seen_and_the_peers_meet_again() { - for (int way = 0; way < 3; ++way) { + for (std::size_t way = 0; way < 3; ++way) { fixture f{true}; trystero::app a_app(f.io.get_executor(), f.net, app_config("NNNNNNNNNNNNNNNNNNNN")); auto a = join(a_app, "ends"); @@ -1158,8 +1683,8 @@ void a_connections_end_is_seen_and_the_peers_meet_again() { }; trystero::app b_app(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO")); const auto b = join(b_app, "ends"); - int joins = 0; - int leaves = 0; + std::size_t joins = 0; + std::size_t leaves = 0; a.on_peer_join([&](std::string_view) { ++joins; }); a.on_peer_leave([&](std::string_view) { ++leaves; }); webcpp::test::require(BOOST_TEST(run_until(f, [&] { return joins == 1; }))); @@ -1174,7 +1699,7 @@ void a_connections_end_is_seen_and_the_peers_meet_again() { const std::array bad{3, 0, 1, 'x'}; f.net.inject(a_end, bad); } else { - for (int i = 0; i < 65; ++i) { + for (std::size_t i = 0; i < 65; ++i) { f.net.inject(a_end, trystero::protocol::presence_frame("X" + std::to_string(i), true)); } @@ -1199,17 +1724,17 @@ void a_frame_of_an_unknown_token_is_dropped() { }; trystero::app b_app(f.io.get_executor(), f.net, app_config("QQQQQQQQQQQQQQQQQQQQ")); const auto b = join(b_app, "unknown"); - int leaves = 0; + std::size_t leaves = 0; a.on_peer_leave([&](std::string_view) { ++leaves; }); webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }))); const std::vector action(4'000, 2); advance(f, 300ms); const auto before = memory.in_use; - for (int i = 0; i < 1000; ++i) { + for (std::size_t i = 0; i < 1000; ++i) { f.net.inject(pcs.front(), trystero::protocol::room_frame("unknown-token", action)); } advance(f, 300ms); - BOOST_TEST_EQ(leaves, 0); + BOOST_TEST_EQ(leaves, 0U); BOOST_TEST_EQ(a.peers().size(), 1U); BOOST_TEST_LT(memory.in_use, before + (std::size_t{64} * 1024)); } @@ -1232,7 +1757,7 @@ void malformed_envelopes_end_the_connection() { }; trystero::app b_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS")); const auto b = join(b_app, "bad"); - int leaves = 0; + std::size_t leaves = 0; a.on_peer_leave([&](std::string_view) { ++leaves; }); webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }))); f.net.inject(pcs.front(), bad); @@ -1247,14 +1772,14 @@ void malformed_envelopes_end_the_connection() { }; trystero::app b_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS")); const auto b = join(b_app, "bad"); - int leaves = 0; + std::size_t leaves = 0; a.on_peer_leave([&](std::string_view) { ++leaves; }); webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }))); std::vector largest{1, 0, 1, 'x'}; largest.resize(16'515, 0); f.net.inject(pcs.front(), largest); advance(f, 300ms); - BOOST_TEST_EQ(leaves, 0); + BOOST_TEST_EQ(leaves, 0U); } // A room acts on the end of the connection its peer is bound to, and on no other: a late end of @@ -1269,8 +1794,8 @@ void a_late_end_of_another_connection_keeps_the_peer() { }; trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); auto b = join(b_app, "late"); - int b_joins = 0; - int b_leaves = 0; + std::size_t b_joins = 0; + std::size_t b_leaves = 0; b.on_peer_join([&](std::string_view) { ++b_joins; }); b.on_peer_leave([&](std::string_view) { ++b_leaves; }); webcpp::test::require(BOOST_TEST( @@ -1285,7 +1810,7 @@ void a_late_end_of_another_connection_keeps_the_peer() { a.room->connection_ended(first, b_id, "a late end of the first connection"); advance(f, 5000ms); BOOST_TEST_EQ(a.room->active_peers().size(), 1U); - BOOST_TEST_EQ(b_leaves, 1); + BOOST_TEST_EQ(b_leaves, 1U); second->end("test"); BOOST_TEST(a.room->active_peers().empty()); a.room->abandon(); @@ -1297,7 +1822,7 @@ void a_withdrawn_presence_is_a_departure() { fixture f{true}; const std::string b_id = "WWWWWWWWWWWWWWWWWWWW"; const auto a = make_app_room(f, "VVVVVVVVVVVVVVVVVVVV", "withdraw"); - int leaves = 0; + std::size_t leaves = 0; a.room->on_peer_leave( a.room->bind([&](std::string_view) { ++leaves; })); std::vector pcs; @@ -1362,7 +1887,7 @@ void a_room_left_with_no_idle_time_sends_its_presence() { run_until(f, [&] { return a.room->active_peers().size() == 1 && b.peers().size() == 1; }))); const auto absent = trystero::protocol::presence_frame( trystero::protocol::room_token(app_id, "no-idle"), false); - int seen = 0; + std::size_t seen = 0; f.net.filter = [&](std::size_t, std::size_t, std::span frame) { if (std::ranges::equal(frame, absent)) { ++seen; @@ -1371,7 +1896,7 @@ void a_room_left_with_no_idle_time_sends_its_presence() { }; a.room->abandon(); advance(f, 1000ms); - BOOST_TEST_EQ(seen, 1); + BOOST_TEST_EQ(seen, 1U); } // The errors' values are fixed and never reused; their messages name what failed. @@ -1389,42 +1914,64 @@ void the_errors_have_their_values() { } // namespace int main() { - two_peers_join_and_exchange_every_payload_format(); - large_payloads_travel_in_chunks_both_ways(); - ping_measures_a_round_trip(); - the_same_password_joins_and_another_does_not(); - leaving_is_seen_by_the_others_and_a_return_reconnects(); - moving_a_room_over_a_joined_one_leaves_it(); - ice_urls_are_checked_as_webrtc_checks_them(); - unusable_ice_servers_are_dropped_and_reported(); - a_refused_peer_connection_is_reported_and_tried_again(); - a_flood_of_announcements_is_bounded(); - long_peer_ids_are_bounded(); - a_refused_peer_is_logged_once(); - a_forged_answer_changes_nothing(); - forged_offers_make_no_connection(); - signals_that_do_not_open_are_reported_once_per_interval(); - sealed_offers_that_fail_at_once_are_bounded(); - announcements_with_forged_answers_are_bounded(); - the_replay_cache_remembers_the_last_ones(); - a_replayed_answer_is_refused(); - a_replayed_offer_is_refused(); - a_reflected_offer_is_refused_as_an_answer(); - a_reflected_offer_is_refused_as_an_offer(); - a_reflected_answer_is_refused_as_an_answer(); - a_relay_that_closes_at_once_is_tried_less_and_less_often(); - counter_announcements_are_paced(); - three_peers_form_a_mesh(); - async_receive_works_in_a_coroutine(); - view_handlers_read_the_frame_without_copying(); - a_rate_limited_relay_does_not_stop_discovery(); - a_connections_end_is_seen_and_the_peers_meet_again(); - a_frame_of_an_unknown_token_is_dropped(); - malformed_envelopes_end_the_connection(); - a_late_end_of_another_connection_keeps_the_peer(); - a_withdrawn_presence_is_a_departure(); - a_kick_by_the_last_room_ends_the_connection(); - a_room_left_with_no_idle_time_sends_its_presence(); - the_errors_have_their_values(); - return boost::report_errors(); + // Some forty cases of two or three apps each: under Asyncify a debug build takes 54 s of the + // processor, more than a third of node's default bound of 120 s, and 74 to 168 s on a loaded + // machine, past it (measured on 2026-11-15 with 18 cores at load averages of 50 to 230; under + // JSPI 34 s, and 44 to 51 s). + webcpp::test::bound(std::chrono::seconds(300)); + // Each case in a frame of its own, which main's never holds (cases.hpp). + using webcpp::test::run_case; + // First, while the parser has run least: a WebAssembly engine compiles a function with its + // baseline tier first, whose frames are the largest, and a peer's first payload meets it so. + run_case(a_json_payload_nested_256_deep_is_delivered); + run_case(two_peers_join_and_exchange_every_payload_format); + run_case(large_payloads_travel_in_chunks_both_ways); + run_case(ping_measures_a_round_trip); + run_case(the_same_password_joins_and_another_does_not); + run_case(leaving_is_seen_by_the_others_and_a_return_reconnects); + run_case(moving_a_room_over_a_joined_one_leaves_it); + run_case(ice_urls_are_checked_as_webrtc_checks_them); + run_case(unusable_ice_servers_are_dropped_and_reported); + run_case(a_refused_peer_connection_is_reported_and_tried_again); + run_case(a_flood_of_announcements_is_bounded); + run_case(long_peer_ids_are_bounded); + run_case(a_refused_peer_is_logged_once); + run_case(a_forged_answer_changes_nothing); + run_case(forged_offers_make_no_connection); + run_case(an_offer_being_opened_keeps_its_place); + run_case(a_flood_of_offers_at_one_instant_is_bounded); + run_case(offers_in_one_name_are_opened_one_at_a_time); + run_case(signals_that_do_not_open_are_reported_once_per_interval); + run_case(sealed_offers_that_fail_at_once_are_bounded); + run_case(announcements_with_forged_answers_are_bounded); + run_case(the_replay_cache_remembers_the_last_ones); + run_case(recent_event_ids_drop_a_repeat_and_forget_the_oldest); + run_case(event_ids_other_than_nip01_ones_are_never_remembered); + run_case(the_event_id_hash_is_keyed); + run_case(a_strategy_draws_the_key_of_its_event_ids); + run_case(a_forged_event_under_a_genuine_id_hides_nothing); + run_case(classes_over_a_pmr_circular_buffer_do_not_move); + run_case(a_replayed_answer_is_refused); + run_case(a_replayed_offer_is_refused); + run_case(a_reflected_offer_is_refused_as_an_answer); + run_case(a_reflected_offer_is_refused_as_an_offer); + run_case(a_reflected_answer_is_refused_as_an_answer); + run_case(a_relay_that_closes_at_once_is_tried_less_and_less_often); + run_case(counter_announcements_are_paced); + run_case(three_peers_form_a_mesh); + run_case(async_receive_works_in_a_coroutine); + run_case(json_payloads_are_read_in_the_rooms_resource_up_to_its_bound); + run_case(a_rejected_document_receive_holds_nothing); + run_case(view_handlers_read_the_frame_without_copying); + run_case(a_rate_limited_relay_does_not_stop_discovery); + run_case(a_connections_end_is_seen_and_the_peers_meet_again); + run_case(a_frame_of_an_unknown_token_is_dropped); + run_case(malformed_envelopes_end_the_connection); + run_case(a_late_end_of_another_connection_keeps_the_peer); + run_case(a_withdrawn_presence_is_a_departure); + run_case(a_kick_by_the_last_room_ends_the_connection); + run_case(a_room_left_with_no_idle_time_sends_its_presence); + run_case(the_errors_have_their_values); + // Under Asyncify, a main that suspended loses what it returns: the status goes first. + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/shared_test.cpp b/test/shared_test.cpp index 0facfb1..9dc7486 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -16,8 +16,10 @@ #include "support/memory_backend.hpp" #include "support/rooms.hpp" -#include +#include + #include +#include #include #include @@ -94,7 +96,7 @@ void joining_is_refused_twice_and_beyond_64() { const auto again = a.join("r"); BOOST_TEST(!again && again.error() == trystero::error::already_joined); std::vector rooms; - for (int i = 1; i < 64; ++i) { + for (std::size_t i = 1; i < 64; ++i) { rooms.push_back(join(a, "x" + std::to_string(i))); } const auto too_many = a.join("x64"); @@ -211,7 +213,7 @@ void a_moved_from_app_releases_nothing() { trystero::app b(f.io.get_executor(), f.net, app_config("MMMMMMMMMMMMMMMMMMMM")); auto ra = join(*a, "r"); auto rb = join(b, "r"); - int leaves = 0; + std::size_t leaves = 0; rb.on_peer_leave([&](std::string_view) { ++leaves; }); webcpp::test::require( BOOST_TEST(run_until(f, [&] { return ra.peers().size() == 1 && rb.peers().size() == 1; }))); @@ -225,7 +227,7 @@ void a_moved_from_app_releases_nothing() { BOOST_TEST_EQ(moved.self_id(), "LLLLLLLLLLLLLLLLLLLL"); } webcpp::trystero::test::advance(f, 1000ms); - BOOST_TEST_EQ(leaves, 0); + BOOST_TEST_EQ(leaves, 0U); BOOST_TEST_EQ(f.net.made_connections, made); BOOST_TEST_EQ(ra.peers().size(), 1U); } @@ -239,14 +241,14 @@ void an_app_destroyed_leaves_its_rooms_going() { trystero::app b(f.io.get_executor(), f.net, app_config("TTTTTTTTTTTTTTTTTTTT")); std::optional ra(join(*a, "r")); auto rb = join(b, "r"); - int leaves = 0; + std::size_t leaves = 0; rb.on_peer_leave([&](std::string_view) { ++leaves; }); webcpp::test::require(BOOST_TEST( run_until(f, [&] { return ra->peers().size() == 1 && rb.peers().size() == 1; }))); const auto made = f.net.made_connections; a.reset(); webcpp::trystero::test::advance(f, 1000ms); - BOOST_TEST_EQ(leaves, 0); + BOOST_TEST_EQ(leaves, 0U); BOOST_TEST_EQ(f.net.made_connections, made); BOOST_TEST_EQ(ra->peers().size(), 1U); ra.reset(); @@ -261,7 +263,7 @@ void an_app_assigned_over_releases_its_state() { trystero::app b(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO")); std::optional ra(join(a, "r")); auto rb = join(b, "r"); - int leaves = 0; + std::size_t leaves = 0; rb.on_peer_leave([&](std::string_view) { ++leaves; }); webcpp::test::require(BOOST_TEST( run_until(f, [&] { return ra->peers().size() == 1 && rb.peers().size() == 1; }))); @@ -269,7 +271,7 @@ void an_app_assigned_over_releases_its_state() { a = trystero::app(f.io.get_executor(), f.net, app_config("PPPPPPPPPPPPPPPPPPPP")); BOOST_TEST_EQ(a.self_id(), "PPPPPPPPPPPPPPPPPPPP"); webcpp::trystero::test::advance(f, 1000ms); - BOOST_TEST_EQ(leaves, 0); + BOOST_TEST_EQ(leaves, 0U); BOOST_TEST_EQ(f.net.made_connections, made); BOOST_TEST_EQ(ra->peers().size(), 1U); ra.reset(); @@ -363,36 +365,37 @@ void corrupt_r2_responses(two_apps& t) { } // Frames of r2 that reach A before B's presence, as a Trystero JS peer sends its handshake before -// its presence: A keeps them, and once B's presence binds r2 it delivers them after making B's -// state, so the handshake completes. B's own `@_hsready` of r2 never reaches A, so only the kept -// one can complete it. B, whose join finds A's presence for r2, binds during the join, as Trystero -// JS does: its handshake goes out first, then its presence. The 64-frame bound and the 10 s expiry -// are the connection's, tested in connection_test.cpp. -void frames_before_presence_are_kept() { +// its presence: the first is B's own advertisement of r2, on which A binds, and A delivers it after +// making B's state, so the handshake completes on it. B's presence is held until both have joined, +// so the frame alone bound A. B, whose join finds A's presence for r2, binds during the join, as +// Trystero JS does: its handshake goes out first, then its presence. The 64-frame bound and the +// 10 s expiry are the connection's, tested in connection_test.cpp. +void frames_before_presence_bind_their_room() { two_apps t("HHHHHHHHHHHHHHHHHHHH", "IIIIIIIIIIIIIIIIIIII"); const ends e(t); joined_in(t, {"r1"}); t.a_rooms.push_back(join(t.a, "r2")); webcpp::trystero::test::advance(t.f, 200ms); - t.f.net.inject(e.a(), internal_frame("r2", "@_hsready")); - webcpp::trystero::test::advance(t.f, 50ms); - BOOST_TEST(t.a_rooms[1].peers().empty()); // kept, not bound: B never advertised r2 std::vector b_sent; t.f.net.filter = [&](std::size_t, std::size_t to, std::span frame) { if (to != e.a()) { return trystero::test::memory_network::verdict::deliver; } - if (auto what = what_of(frame, "r2"); !what.empty()) { + auto what = what_of(frame, "r2"); + const bool presence = what == "presence(1)"; + if (!what.empty()) { b_sent.push_back(std::move(what)); } - return internal_name(frame, "r2") == "@_hsready" - ? trystero::test::memory_network::verdict::drop - : trystero::test::memory_network::verdict::deliver; + return presence ? trystero::test::memory_network::verdict::hold + : trystero::test::memory_network::verdict::deliver; }; t.b_rooms.push_back(join(t.b, "r2")); BOOST_TEST((b_sent == std::vector{"@_hsready", "presence(1)"})); - BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); })); + BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 1ms)); t.f.net.filter = nullptr; // the rooms' farewells go through the network after `e` is gone + t.f.net.release(e.a()); + webcpp::trystero::test::advance(t.f, 1000ms); + BOOST_TEST(t.all_joined()); } // A kept frame that makes A kick B while A binds (an undecodable action frame of r2, then B's @@ -466,11 +469,11 @@ void a_leaving_room_binds_no_one() { // A forced failure, a frame that does not decode, and a 65th advertised token each end the // connection for both rooms, which then meet again over one new connection. void a_connections_end_is_every_rooms() { - for (int way = 0; way < 3; ++way) { + for (std::size_t way = 0; way < 3; ++way) { two_apps t("JJJJJJJJJJJJJJJJJJJ1", "KKKKKKKKKKKKKKKKKKK2"); const ends e(t); joined_in(t, {"r1", "r2"}); - int leaves = 0; + std::size_t leaves = 0; for (auto& r : t.a_rooms) { r.on_peer_leave([&leaves](std::string_view) { ++leaves; }); } @@ -480,7 +483,7 @@ void a_connections_end_is_every_rooms() { const std::array bad{3, 0, 1, 'x'}; t.f.net.inject(e.a(), bad); } else { - for (int i = 0; i < 65; ++i) { + for (std::size_t i = 0; i < 65; ++i) { t.f.net.inject(e.a(), trystero::protocol::presence_frame("X" + std::to_string(i), true)); } @@ -583,12 +586,12 @@ bool is_presence(std::span frame, std::string_view room, boo // room sees the peer go, presence(0, r1) arrives, r2 keeps exchanging, the connection stays, and a // send in the room left completes with room_left. void one_room_leaves() { - for (int way = 0; way < 3; ++way) { + for (std::size_t way = 0; way < 3; ++way) { two_apps t("RRRRRRRRRRRRRRRRRRRR", "SSSSSSSSSSSSSSSSSSSS"); const ends e(t); joined_in(t, {"r1", "r2"}); - int b_r1_leaves = 0; - int b_r2_leaves = 0; + std::size_t b_r1_leaves = 0; + std::size_t b_r2_leaves = 0; t.b_rooms[0].on_peer_leave([&](std::string_view) { ++b_r1_leaves; }); t.b_rooms[1].on_peer_leave([&](std::string_view) { ++b_r2_leaves; }); bool withdrawn = false; @@ -608,7 +611,7 @@ void one_room_leaves() { } BOOST_TEST(run_until(t.f, [&] { return b_r1_leaves == 1 && withdrawn; })); webcpp::trystero::test::advance(t.f, 1s); - BOOST_TEST_EQ(b_r2_leaves, 0); + BOOST_TEST_EQ(b_r2_leaves, 0U); BOOST_TEST_EQ(t.f.net.live_connections(), 2U); std::vector got; auto in_r2 = t.b_rooms[1].make_action("chat"); @@ -681,7 +684,7 @@ void an_action_level_kick_is_per_room() { two_apps t("CCCCCCCCCCCCCCCCCCC1", "DDDDDDDDDDDDDDDDDDD2"); const ends e(t); joined_in(t, {"r1", "r2"}); - int r2_leaves = 0; + std::size_t r2_leaves = 0; t.a_rooms[1].on_peer_leave([&](std::string_view) { ++r2_leaves; }); const std::array garbage{9, 9, 9}; t.f.net.inject(e.a(), trystero::protocol::room_frame( @@ -708,7 +711,7 @@ void a_connection_failing_under_a_waiting_transfer() { joined_in(t, {"r1", "r2"}); auto receiver = t.b_rooms[1].make_action("big"); receiver.on_message([](const trystero::bytes&, const trystero::message_info&) {}); - int completions = 0; + std::size_t completions = 0; std::optional sent; t.a_rooms[1].make_action("big").async_send( trystero::bytes(1'000'000, std::uint8_t{4}), [&](boost::system::error_code ec) { @@ -718,7 +721,7 @@ void a_connection_failing_under_a_waiting_transfer() { webcpp::test::require(BOOST_TEST(poll_until(t.f, [&] { return t.f.net.buffered(e.a()) > std::size_t{64} * 1024; // a chunk waits on the drain }))); - int leaves = 0; + std::size_t leaves = 0; for (auto& r : t.a_rooms) { r.on_peer_leave([&leaves](std::string_view) { ++leaves; }); } @@ -726,7 +729,7 @@ void a_connection_failing_under_a_waiting_transfer() { BOOST_TEST(run_until(t.f, [&] { return leaves == 2 && sent.has_value(); })); BOOST_TEST(*sent == trystero::error::peer_disconnected); BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 30s)); - BOOST_TEST_EQ(completions, 1); + BOOST_TEST_EQ(completions, 1U); } // A kick is per room. B sends an incorrect r2 proof and A is the lower id: @@ -758,13 +761,13 @@ void a_kick_is_per_room() { drop_first_challenge(t); std::vector b_errors; t.a_rooms.push_back(join(t.a, "r2", {.handshake_timeout = 30s})); - const double joined = t.f.net.now_ms(); + const auto joined = t.f.net.steady_now(); t.b_rooms.push_back(join(t.b, "r2")); t.b_rooms[1].on_error([&](std::string_view, boost::system::error_code ec, std::string_view) { b_errors.push_back(ec); }); BOOST_TEST(run_until(t.f, [&] { return !b_errors.empty(); }, 11s)); BOOST_TEST(b_errors.at(0) == trystero::error::handshake_timed_out); - BOOST_TEST_EQ(t.f.net.now_ms() - joined, 10'000.0); + BOOST_TEST(t.f.net.steady_now() - joined == 10s); BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U); BOOST_TEST_EQ(t.f.net.live_connections(), 2U); } @@ -800,20 +803,20 @@ void join_and_leave_sequences_on_one_id() { }; std::vector others; others.reserve(62); - for (int i = 0; i < 62; ++i) { + for (std::size_t i = 0; i < 62; ++i) { others.push_back(join(t.a, "x" + std::to_string(i))); // with lobby and r: 64 rooms } std::optional r(join(t.a, "r")); t.b_rooms.push_back(join(t.b, "r")); webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return r->peers().size() == 1; }))); - int first = 0; - int second = 0; + std::size_t first = 0; + std::size_t second = 0; r->async_leave([&](boost::system::error_code ec) { first += ec ? 100 : 1; }); r->async_leave([&](boost::system::error_code ec) { second += ec ? 100 : 1; }); const auto refused = t.a.join("x62"); BOOST_TEST(!refused && refused.error() == trystero::error::too_many_rooms); // r still counts webcpp::trystero::test::advance(t.f, 50ms); - BOOST_TEST_EQ(first + second, 0); // the second leave waits for the farewell with the first + BOOST_TEST_EQ(first + second, 0U); // the second leave waits for the farewell with the first BOOST_TEST((presences == std::vector{true})); auto again = t.a.join("r"); // finishes r's farewell at once webcpp::test::require(BOOST_TEST(again.has_value())); @@ -822,7 +825,7 @@ void join_and_leave_sequences_on_one_id() { r.reset(); // the old handle, its room ended: nothing more std::optional r2(std::move(*again)); BOOST_TEST(run_until(t.f, [&] { return r2->peers().size() == 1; })); - int third = 0; + std::size_t third = 0; r2->async_leave([&](boost::system::error_code ec) { third += ec ? 100 : 1; }); r2.reset(); // destroyed during its farewell: the farewell ends at once BOOST_TEST((presences == std::vector{true, false, true, false})); @@ -830,9 +833,9 @@ void join_and_leave_sequences_on_one_id() { BOOST_TEST(last_join.has_value()); BOOST_TEST((presences == std::vector{true, false, true, false, true})); webcpp::trystero::test::advance(t.f, 1s); - BOOST_TEST_EQ(first, 1); - BOOST_TEST_EQ(second, 1); - BOOST_TEST_EQ(third, 1); + BOOST_TEST_EQ(first, 1U); + BOOST_TEST_EQ(second, 1U); + BOOST_TEST_EQ(third, 1U); } // during a room's 99 ms farewell, B's presence and B's frames for it bind nothing @@ -845,14 +848,14 @@ void the_farewell_binds_nothing() { t.a_rooms.push_back(join(t.a, "r2")); bool left = false; t.a_rooms[1].async_leave([&](boost::system::error_code) { left = true; }); - int b_joins = 0; + std::size_t b_joins = 0; t.b_rooms.push_back(join(t.b, "r2")); // B's presence, announcement and handshake now t.b_rooms[1].on_peer_join([&](std::string_view) { ++b_joins; }); BOOST_TEST(run_until(t.f, [&] { return left; })); webcpp::trystero::test::advance(t.f, 1s); BOOST_TEST(t.a_rooms[1].peers().empty()); BOOST_TEST(t.b_rooms[1].peers().empty()); - BOOST_TEST_EQ(b_joins, 0); + BOOST_TEST_EQ(b_joins, 0U); BOOST_TEST_EQ(t.f.net.live_connections(), 2U); } { @@ -989,12 +992,12 @@ void check_incorrect_proof_rebinding(bool a_lower) { watcher.watch(trystero::protocol::root_topic(app_id, "r2")); watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.a.self_id())); watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.b.self_id())); - std::vector a_reports; - std::vector b_reports; - const auto recorder = [&t](std::vector& to) { + std::vector a_reports; + std::vector b_reports; + const auto recorder = [&t](std::vector& to) { return [&t, &to](std::string_view, boost::system::error_code ec, std::string_view) { if (ec == trystero::error::wrong_password) { - to.push_back(t.f.net.now_ms()); + to.push_back(t.f.net.steady_now()); } }; }; @@ -1005,19 +1008,18 @@ void check_incorrect_proof_rebinding(bool a_lower) { const auto& lower = a_lower ? a_reports : b_reports; const auto& higher = a_lower ? b_reports : a_reports; webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !lower.empty(); }, 1s))); - const double first = lower.front(); - webcpp::trystero::test::advance( - t.f, - std::chrono::milliseconds(static_cast(first + 100'000 - t.f.net.now_ms()))); + const auto first = lower.front(); + webcpp::trystero::test::advance(t.f, std::chrono::duration_cast( + first + 100s - t.f.net.steady_now())); const std::size_t announced_in_100_s = r2_announcements; webcpp::trystero::test::advance(t.f, 64'999ms); // to 164.999 s after the first BOOST_TEST_EQ(lower.size(), 4U); - const std::array expected{0, 11'000, 33'000, 77'000}; + const std::array expected{0s, 11s, 33s, 77s}; for (std::size_t i = 0; i < std::min(lower.size(), 4); ++i) { - BOOST_TEST_EQ(lower[i] - first, expected[i]); + BOOST_TEST(lower[i] - first == expected[i]); } BOOST_TEST(run_until(t.f, [&] { return lower.size() == 5; }, 1ms)); - BOOST_TEST_EQ(lower.back() - first, 165'000.0); + BOOST_TEST(lower.back() - first == 165s); BOOST_TEST(higher.empty()); BOOST_TEST(!offer_or_answer); // Each room's regular cadence on the relay the watcher reads: at once, after 233, 533, @@ -1040,13 +1042,13 @@ void an_incorrect_proof_rebinds_at_the_steps() { // before the 11 s a kept count would impose. void a_kick_that_closes_the_connection() { { - std::optional kicked_connection_at; + std::optional kicked_connection_at; two_apps t("AAAAAAAAAAAAAAAAAAK1", "BBBBBBBBBBBBBBBBBBK2", "pw"); auto a_config = app_config("AAAAAAAAAAAAAAAAAAK1", "pw"); a_config.log = [&](std::string_view category, std::string_view text) { if (!kicked_connection_at && category == "webrtc" && text.ends_with("ended: its last room kicked the peer")) { - kicked_connection_at = t.f.net.now_ms(); + kicked_connection_at = t.f.net.steady_now(); } }; t.a = trystero::app(t.f.io.get_executor(), t.f.net, std::move(a_config)); @@ -1060,12 +1062,12 @@ void a_kick_that_closes_the_connection() { }; joined_in(t, {"r1"}); corrupt_r2_responses(t); - std::vector kicks; + std::vector kicks; t.a_rooms.push_back(join(t.a, "r2")); t.a_rooms[1].on_error( [&](std::string_view, boost::system::error_code ec, std::string_view) { if (ec == trystero::error::wrong_password) { - kicks.push_back(t.f.net.now_ms()); + kicks.push_back(t.f.net.steady_now()); } }); t.b_rooms.push_back(join(t.b, "r2")); @@ -1075,8 +1077,8 @@ void a_kick_that_closes_the_connection() { const auto b_made_before = b_made; BOOST_TEST(run_until(t.f, [&] { return kicked_connection_at.has_value(); }, 12s)); webcpp::test::require(BOOST_TEST_GE(kicks.size(), 2U)); - BOOST_TEST_EQ(kicks[1] - kicks.front(), 11'000.0); - BOOST_TEST_EQ(kicked_connection_at.value_or(-1) - kicks.front(), 11'000.0); + BOOST_TEST(kicks[1] - kicks.front() == 11s); + BOOST_TEST(kicked_connection_at && *kicked_connection_at - kicks.front() == 11s); webcpp::trystero::test::advance(t.f, 60s); BOOST_TEST_GT(b_made, b_made_before); BOOST_TEST(t.a_rooms[0].peers().empty()); @@ -1084,13 +1086,13 @@ void a_kick_that_closes_the_connection() { { two_apps t("BBBBBBBBBBBBBBBBBBL1", "AAAAAAAAAAAAAAAAAAL2", "pw"); // B the lower id drop_first_challenge(t); - std::vector b_timeouts; + std::vector b_timeouts; t.a_rooms.push_back(join(t.a, "r2", {.handshake_timeout = 30s})); t.b_rooms.push_back(join(t.b, "r2")); t.b_rooms[0].on_error( [&](std::string_view, boost::system::error_code ec, std::string_view) { if (ec == trystero::error::handshake_timed_out) { - b_timeouts.push_back(t.f.net.now_ms()); + b_timeouts.push_back(t.f.net.steady_now()); } }); webcpp::test::require( @@ -1098,7 +1100,7 @@ void a_kick_that_closes_the_connection() { const auto made = t.f.net.made_connections; webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !b_timeouts.empty(); }, 30s))); BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 5s)); - BOOST_TEST_LT(t.f.net.now_ms() - b_timeouts.front(), 5'000.0); + BOOST_TEST(t.f.net.steady_now() - b_timeouts.front() < 5s); BOOST_TEST_GE(t.f.net.made_connections, made + 2); // a new pair, adopted BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2U; }, 1ms)); BOOST_TEST_EQ(b_timeouts.size(), 1U); @@ -1125,23 +1127,26 @@ void hold_first(two_apps& t, std::size_t from, std::string message, std::size_t }; } -// binding needs the peer's own presence. The filter drops B's presence(1, r2) while B -// joins r2, A having joined it first: B binds at its join, on A's presence, and its handshake -// frames reach A, which keeps them and does not bind; B's announcements in r2 bind nothing and -// start no negotiation. B's handshake times out 10 s after its join and B, the higher id, kicks; -// at its rebinding time, 21 s after its join, B binds again and sends its presence, which goes -// through now: A binds at that instant. -void binding_needs_the_peers_own_presence() { +// a lost presence is replaced by the peer's own frames. Trystero JS advertises a room once per +// connection, and Chrome can drop what a page sends on an answering channel as it opens (its log +// says "Send failed INVALID_STATE"; the interop test measured it), so the filter drops every +// presence(1, r2) of B, which joins r2 after A: B binds at its join, on A's presence, and its +// handshake frames reach A, which binds on the first, as on B's presence. Both join at once, with +// no handshake timed out on either side; B's announcements in r2 still bind nothing and start no +// negotiation. +void a_lost_presence_is_replaced_by_the_peers_frames() { two_apps t("NNNNNNNNNNNNNNNNNNNN", "OOOOOOOOOOOOOOOOOOOO"); const ends e(t); joined_in(t, {"r1"}); t.a_rooms.push_back(join(t.a, "r2")); webcpp::trystero::test::advance(t.f, 300ms); - bool drop = true; + std::size_t dropped = 0; t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) { - return drop && from != e.a() && is_presence(frame, "r2", true) - ? trystero::test::memory_network::verdict::drop - : trystero::test::memory_network::verdict::deliver; + if (from != e.a() && is_presence(frame, "r2", true)) { + ++dropped; + return trystero::test::memory_network::verdict::drop; + } + return trystero::test::memory_network::verdict::deliver; }; flooder watcher(t.f, "r2"); bool offer_or_answer = false; @@ -1152,19 +1157,17 @@ void binding_needs_the_peers_own_presence() { }; watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.a.self_id())); watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.b.self_id())); - std::vector b_errors; - const double joined = t.f.net.now_ms(); + std::vector errors; + const auto recorder = [&errors](std::string_view, boost::system::error_code ec, + std::string_view) { errors.push_back(ec); }; + t.a_rooms[1].on_error(recorder); t.b_rooms.push_back(join(t.b, "r2")); - t.b_rooms[1].on_error([&](std::string_view, boost::system::error_code ec, std::string_view) { - b_errors.push_back(ec); - }); - webcpp::trystero::test::advance(t.f, 10'999ms); - BOOST_TEST(t.a_rooms[1].peers().empty()); - BOOST_TEST((b_errors == std::vector{ - make_error_code(trystero::error::handshake_timed_out)})); - drop = false; - BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 11s)); - BOOST_TEST_EQ(t.f.net.now_ms() - joined, 21'000.0); + t.b_rooms[1].on_error(recorder); + BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 1ms)); + webcpp::trystero::test::advance(t.f, 11s); // past both handshake timeouts + BOOST_TEST(t.all_joined()); + BOOST_TEST(errors.empty()); + BOOST_TEST_EQ(dropped, 1U); BOOST_TEST(!offer_or_answer); } @@ -1194,14 +1197,14 @@ void check_transient_failure(bool password, bool lower_times_out, bool release_a }); const auto& timed_out = lower_times_out ? a_errors : b_errors; webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !timed_out.empty(); }, 11s))); - const double kick = t.f.net.now_ms(); + const auto kick = t.f.net.steady_now(); const std::chrono::milliseconds release_after = release_after_rebinding ? 13s : 2s; webcpp::trystero::test::advance(t.f, release_after); t.f.net.filter = {}; t.f.net.release(lower_times_out ? a_end : b_end); // held at the receiving end BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 12s)); - BOOST_TEST_EQ(t.f.net.now_ms() - kick, - static_cast(std::max(11'000, release_after.count()))); + BOOST_TEST(t.f.net.steady_now() - kick == + std::max(11s, release_after)); BOOST_TEST_EQ(timed_out.size(), 1U); BOOST_TEST(timed_out.at(0) == trystero::error::handshake_timed_out); BOOST_TEST_EQ(a_errors.size() + b_errors.size(), 1U); // no other report @@ -1262,18 +1265,18 @@ void a_corrected_response_rejoins() { two_apps t("AAAAAAAAAAAAAAAAAAB1", "ZZZZZZZZZZZZZZZZZZB2", "pw"); joined_in(t, {"r1"}); corrupt_r2_responses(t); - std::vector a_kicks; + std::vector a_kicks; t.a_rooms.push_back(join(t.a, "r2")); t.a_rooms[1].on_error( [&](std::string_view, boost::system::error_code ec, std::string_view) { if (ec == trystero::error::wrong_password) { - a_kicks.push_back(t.f.net.now_ms()); + a_kicks.push_back(t.f.net.steady_now()); } }); std::optional b2(join(t.b, "r2")); webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return a_kicks.size() == 3; }, 40s))); - const double first = a_kicks.front(); - BOOST_TEST_EQ(a_kicks.back() - first, 33'000.0); + const auto first = a_kicks.front(); + BOOST_TEST(a_kicks.back() - first == 33s); webcpp::trystero::test::advance(t.f, 2s); b2.reset(); t.f.net.filter = {}; @@ -1283,7 +1286,7 @@ void a_corrected_response_rejoins() { b_errors.push_back(ec); }); BOOST_TEST(run_until(t.f, [&] { return b2->peers().size() == 1; }, 45s)); - BOOST_TEST_EQ(t.f.net.now_ms() - first, 77'000.0); + BOOST_TEST(t.f.net.steady_now() - first == 77s); BOOST_TEST_LE(std::ranges::count(b_errors, trystero::error::handshake_timed_out), 2); BOOST_TEST_EQ(a_kicks.size(), 3U); } @@ -1306,9 +1309,10 @@ void a_corrected_response_rejoins() { } } -// before A's r2 binds B, inject delivers on A's end B's @_hsready and @_leave of r2; then -// B's presence is let through: A binds, discards both, and the handshake completes on B's next -// frames, with no leave: A's log names no peer gone. +// A, the lower id, kicks B from r2 (an action frame of r2 that does not decode) and refuses it +// until its rebinding time; meanwhile inject delivers on A's end B's @_hsready and @_leave of r2, +// which A keeps without binding. At its rebinding time A binds, discards both, and the handshake +// completes on what follows, with no second leave: A's log names B gone once, for the kick. void a_kept_leave_discards_what_came_before() { std::vector a_log; auto a_config = app_config("AAAAAAAAAAAAAAAAAAE1"); @@ -1316,26 +1320,21 @@ void a_kept_leave_discards_what_came_before() { two_apps t("AAAAAAAAAAAAAAAAAAE1", "ZZZZZZZZZZZZZZZZZZE2"); t.a = trystero::app(t.f.io.get_executor(), t.f.net, std::move(a_config)); const ends e(t); - joined_in(t, {"r1"}); - bool hold_presence = true; - t.f.net.filter = [&](std::size_t, std::size_t, std::span frame) { - return hold_presence && is_presence(frame, "r2", true) - ? trystero::test::memory_network::verdict::hold - : trystero::test::memory_network::verdict::deliver; - }; - t.a_rooms.push_back(join(t.a, "r2")); - t.b_rooms.push_back(join(t.b, "r2")); + joined_in(t, {"r1", "r2"}); + const std::array garbage{9, 9, 9}; + t.f.net.inject(e.a(), trystero::protocol::room_frame( + trystero::protocol::room_token(app_id, "r2"), garbage)); + webcpp::test::require( + BOOST_TEST(run_until(t.f, [&] { return t.a_rooms[1].peers().empty(); }, 1ms))); for (const auto* name : {"@_hsready", "@_leave"}) { t.f.net.inject(e.a(), internal_frame("r2", name)); } webcpp::trystero::test::advance(t.f, 200ms); - BOOST_TEST(t.a_rooms[1].peers().empty()); - hold_presence = false; - t.f.net.release(e.a()); - t.f.net.release(t.f.net.peer_of(e.a())); - BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 1ms)); - BOOST_TEST(std::ranges::none_of( - a_log, [](const std::string& line) { return line.find(" gone: ") != std::string::npos; })); + BOOST_TEST(t.a_rooms[1].peers().empty()); // refused, and kept + BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 11s)); + const auto gone = std::ranges::count_if( + a_log, [](const std::string& line) { return line.find(" gone: ") != std::string::npos; }); + BOOST_TEST_EQ(gone, 1); } // crossed connections recover: A's end of r1's pair and B's end of r2's open first; both @@ -1373,7 +1372,7 @@ void crossed_connections_recover() { f.net.open(b_r1); f.net.open(a_r2); f.net.defer_opens = false; - const double opened = f.net.now_ms(); + const auto opened = f.net.steady_now(); BOOST_TEST(run_until( f, [&] { @@ -1381,7 +1380,7 @@ void crossed_connections_recover() { b2.peers().size() == 1; }, 15s)); - BOOST_TEST_LE(f.net.now_ms() - opened, 15'000.0); + BOOST_TEST(f.net.steady_now() - opened <= 15s); BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 2U; })); } @@ -1428,7 +1427,7 @@ void a_flood_in_one_room_does_not_starve_another() { const auto b_end = t.f.net.peer_of(e.a()); static_cast(t.a_rooms[0].make_action("unread")); // made, no handler: queued auto flood = t.b_rooms[0].make_action("unread"); - for (int i = 0; i < 10'000; ++i) { + for (std::size_t i = 0; i < 10'000; ++i) { flood.async_send("x", [](boost::system::error_code) {}); } std::vector r2_got; @@ -1436,11 +1435,11 @@ void a_flood_in_one_room_does_not_starve_another() { r2_in.on_message( [&](const std::string& s, const trystero::message_info&) { r2_got.push_back(s); }); auto r2_out = t.b_rooms[1].make_action("chat"); - for (int i = 0; i < 100; ++i) { + for (std::size_t i = 0; i < 100; ++i) { r2_out.async_send(std::to_string(i), [](boost::system::error_code) {}); } std::vector pings; - for (int i = 0; i < 5; ++i) { + for (std::size_t i = 0; i < 5; ++i) { t.b_rooms[1].async_ping(t.a.self_id(), [&](boost::system::error_code ec, std::chrono::milliseconds rtt) { if (!ec) { @@ -1464,7 +1463,7 @@ void a_flood_in_one_room_does_not_starve_another() { poll_until(t.f, [&] { return t.f.net.buffered(b_end) > std::size_t{64} * 1024; }))); r2_got.clear(); const auto full = t.f.net.buffered(b_end); - for (int i = 0; i < 20; ++i) { + for (std::size_t i = 0; i < 20; ++i) { r2_out.async_send("c", [&](boost::system::error_code) { if (++chats_done == 20) { chats_first = !transfer_done; @@ -1493,7 +1492,7 @@ void a_passwordless_room_is_open_to_the_apps_other_rooms() { secret_broadcasts += from == e.a() && internal_name(frame, "secret") == "chat" ? 1 : 0; return trystero::test::memory_network::verdict::deliver; }; - int secret_joins = 0; + std::size_t secret_joins = 0; t.a_rooms[1].on_peer_join([&](std::string_view) { ++secret_joins; }); t.f.net.inject(e.a(), trystero::protocol::presence_frame( trystero::protocol::room_token(app_id, "secret"), true)); @@ -1519,12 +1518,12 @@ void invalid_room_proofs_fail_within_one_password_domain() { std::vector errors; t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec, std::string_view) { errors.push_back(ec); }); - const double joined = t.f.net.now_ms(); + const auto joined = t.f.net.steady_now(); t.b_rooms.push_back(join(t.b, "r2", {.handshake_timeout = 30s})); webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !errors.empty(); }, 11s))); BOOST_TEST(errors.front() == (wrong_response ? trystero::error::wrong_password : trystero::error::handshake_timed_out)); - BOOST_TEST_EQ(t.f.net.now_ms() - joined, wrong_response ? 0.0 : 10'000.0); + BOOST_TEST(t.f.net.steady_now() - joined == (wrong_response ? 0s : 10s)); BOOST_TEST(t.a_rooms[1].peers().empty()); BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U); } @@ -1608,7 +1607,7 @@ void a_leaving_log_can_finish_the_farewell_by_rejoining() { }; app.emplace(f.io.get_executor(), f.net, std::move(config)); auto room = join(*app, "r"); - int completions = 0; + std::size_t completions = 0; room.async_leave([&](boost::system::error_code ec) { BOOST_TEST(!ec); ++completions; @@ -1616,7 +1615,7 @@ void a_leaving_log_can_finish_the_farewell_by_rejoining() { BOOST_TEST(acted); BOOST_TEST_EQ(f.net.scheduled(), timers_after_rejoin); webcpp::trystero::test::advance(f, 200ms); - BOOST_TEST_EQ(completions, 1); + BOOST_TEST_EQ(completions, 1U); BOOST_TEST(replacement.has_value()); } @@ -1625,7 +1624,7 @@ void a_leaving_log_can_finish_the_farewell_by_rejoining() { void check_leaving_from_join_log(bool destroy) { fixture f{true}; bool acted = false; - int joins = 0; + std::size_t joins = 0; std::optional room; auto config = app_config("AAAAAAAAAAAAAAAAAAQ1"); config.log = [&](std::string_view, std::string_view text) { @@ -1645,7 +1644,7 @@ void check_leaving_from_join_log(bool destroy) { const auto remote = join(b, "r"); webcpp::test::require(BOOST_TEST(run_until(f, [&] { return acted; }))); webcpp::trystero::test::advance(f, 200ms); - BOOST_TEST_EQ(joins, 0); + BOOST_TEST_EQ(joins, 0U); BOOST_TEST(remote.peers().empty()); } @@ -1659,8 +1658,8 @@ void a_join_log_can_leave_or_destroy_its_room() { // destroys the offending binding. A replacement callback installed by the sink takes effect. void check_leaving_from_error_log(bool destroy) { bool acted = false; - int old_errors = 0; - int new_errors = 0; + std::size_t old_errors = 0; + std::size_t new_errors = 0; std::optional room; two_apps t("AAAAAAAAAAAAAAAAAAR1", "ZZZZZZZZZZZZZZZZZZR2", "pw"); auto config = app_config("AAAAAAAAAAAAAAAAAAR1", "pw"); @@ -1690,8 +1689,8 @@ void check_leaving_from_error_log(bool destroy) { t.b_rooms.push_back(join(t.b, "r2")); webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return acted; }))); webcpp::trystero::test::advance(t.f, 200ms); - BOOST_TEST_EQ(old_errors, 0); - BOOST_TEST_EQ(new_errors, 1); + BOOST_TEST_EQ(old_errors, 0U); + BOOST_TEST_EQ(new_errors, 1U); BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U); } @@ -1728,7 +1727,7 @@ void check_draining_from_queue_log(bool leave) { run_until(f, [&] { return room->peers().size() == 1 && remote.peers().size() == 1; }))); inbox.emplace(room->make_action("unread")); auto out = remote.make_action("unread"); - for (int i = 0; i < 1025; ++i) { + for (std::size_t i = 0; i < 1025; ++i) { out.async_send("x", [](boost::system::error_code) {}); } webcpp::test::require(BOOST_TEST(run_until(f, [&] { return acted; }))); @@ -1766,16 +1765,16 @@ void a_log_sink_can_leave_during_adoption() { const auto survivor = join(a, "survivor"); leaving = join(a, "departing"); auto remote = join(b, "departing"); - int remote_joins = 0; + std::size_t remote_joins = 0; remote.on_peer_join([&](std::string_view) { ++remote_joins; }); webcpp::test::require(BOOST_TEST(run_until(f, [&] { return acted; }, 1s))); webcpp::trystero::test::advance(f, 1ms); if (leaving) { BOOST_TEST(leaving->peers().empty()); } - BOOST_TEST_EQ(remote_joins, 0); + BOOST_TEST_EQ(remote_joins, 0U); webcpp::trystero::test::advance(f, 200ms); - BOOST_TEST_EQ(remote_joins, 0); + BOOST_TEST_EQ(remote_joins, 0U); webcpp::trystero::test::advance(f, 200ms); BOOST_TEST_EQ(f.net.live_connections(), 0U); auto other = join(b, "survivor"); @@ -1854,6 +1853,56 @@ void a_password_challenge_requires_a_string() { } } +// A handshake message of protocol::max_handshake_bytes, a challenge with spaces before its closing +// brace, is read and answered: A, the higher id, whose end is the other of the first connection +// made, sends its proof and reports nothing. One byte longer fails the handshake before it is +// read, as a message of the wrong shape does. +void a_handshake_message_past_its_bound_fails() { + constexpr std::string_view challenge = R"({"__trystero_pw":"challenge","c":"nonce"})"; + for (const std::size_t size : + {trystero::protocol::max_handshake_bytes, trystero::protocol::max_handshake_bytes + 1}) { + two_apps t("ZZZZZZZZZZZZZZZZZZN1", "AAAAAAAAAAAAAAAAAAN2", "pw"); + const ends e(t); + joined_in(t, {"r1"}); + std::size_t proofs = 0; + t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) { + if (internal_name(frame, "r2") != "@_hsdata") { + return trystero::test::memory_network::verdict::deliver; + } + const std::string_view text(reinterpret_cast(frame.data()), frame.size()); + if (from == t.f.net.peer_of(e.a()) && + text.find(R"("__trystero_pw":"response")") != std::string_view::npos) { + ++proofs; + } + return trystero::test::memory_network::verdict::drop; + }; + t.a_rooms.push_back(join(t.a, "r2")); + std::vector errors; + t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec, + std::string_view) { errors.push_back(ec); }); + t.b_rooms.push_back(join(t.b, "r2")); + webcpp::trystero::test::advance(t.f, 1ms); + std::string message(challenge.substr(0, challenge.size() - 1)); + message.append(size - challenge.size(), ' '); + message += '}'; + BOOST_TEST_EQ(message.size(), size); + t.f.net.inject(t.f.net.peer_of(e.a()), internal_frame("r2", "@_hsdata", message)); + webcpp::trystero::test::advance(t.f, 1ms); + if (size == trystero::protocol::max_handshake_bytes) { + BOOST_TEST_EQ(proofs, 1U); + BOOST_TEST(errors.empty()); + } else { + BOOST_TEST_EQ(proofs, 0U); + BOOST_TEST_EQ(errors.size(), 1U); + if (!errors.empty()) { + BOOST_TEST(errors.front() == trystero::error::wrong_password); + } + BOOST_TEST(t.a_rooms[1].peers().empty()); + } + BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U); + } +} + // Connections and room tokens from a passwordless app never reach a protected app's registry, // in either peer-id order. Different password domains have distinct app states and peer ids. void check_public_connection_isolation(bool protected_lower) { @@ -1925,6 +1974,7 @@ int main(int argc, const char* const argv[]) { {"an_error_log_can_leave_or_destroy_its_room", an_error_log_can_leave_or_destroy_its_room}, {"a_queue_log_can_drain_or_destroy_its_room", a_queue_log_can_drain_or_destroy_its_room}, {"a_password_challenge_requires_a_string", a_password_challenge_requires_a_string}, + {"a_handshake_message_past_its_bound_fails", a_handshake_message_past_its_bound_fails}, { "invalid_room_proofs_fail_within_one_password_domain", invalid_room_proofs_fail_within_one_password_domain, @@ -1966,7 +2016,7 @@ int main(int argc, const char* const argv[]) { {"an_app_destroyed_leaves_its_rooms_going", an_app_destroyed_leaves_its_rooms_going}, {"an_app_assigned_over_releases_its_state", an_app_assigned_over_releases_its_state}, {"an_app_assigned_to_itself_keeps_its_state", an_app_assigned_to_itself_keeps_its_state}, - {"frames_before_presence_are_kept", frames_before_presence_are_kept}, + {"frames_before_presence_bind_their_room", frames_before_presence_bind_their_room}, {"a_kept_frame_that_kicks_during_a_binding", a_kept_frame_that_kicks_during_a_binding}, {"a_kept_frame_binds_its_room", a_kept_frame_binds_its_room}, {"a_leaving_room_binds_no_one", a_leaving_room_binds_no_one}, @@ -1995,7 +2045,10 @@ int main(int argc, const char* const argv[]) { {"the_rebinding_step", the_rebinding_step}, {"an_incorrect_proof_rebinds_at_the_steps", an_incorrect_proof_rebinds_at_the_steps}, {"a_kick_that_closes_the_connection", a_kick_that_closes_the_connection}, - {"binding_needs_the_peers_own_presence", binding_needs_the_peers_own_presence}, + { + "a_lost_presence_is_replaced_by_the_peers_frames", + a_lost_presence_is_replaced_by_the_peers_frames, + }, {"a_transient_failure_converges", a_transient_failure_converges}, {"an_answer_to_an_old_challenge", an_answer_to_an_old_challenge}, {"a_corrected_response_rejoins", a_corrected_response_rejoins}, @@ -2009,5 +2062,6 @@ int main(int argc, const char* const argv[]) { } } BOOST_TEST(ran != 0); - return boost::report_errors(); + // Under Asyncify, a main that suspended loses what it returns: the status goes first. + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/signaling_test.cpp b/test/signaling_test.cpp new file mode 100644 index 0000000..32d4302 --- /dev/null +++ b/test/signaling_test.cpp @@ -0,0 +1,492 @@ +// 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) + +// Tests the signaling and the Nostr strategy alone, over the memory backend, on both targets. As +// an answerer, the signaling publishes the bytes Trystero JS 0.26.0's own signal handler published +// for the same offers, which the original's oracle wrote into fixtures/expected/expected.json, the +// test's one argument: its sealer gives Trystero's sealed texts, and its peer connections the +// oracle's answer and candidate. Each text a strategy or a signaling reads is bounded: a relay's +// text or a signal at its bound is read, one byte longer is dropped. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "support/memory_backend.hpp" + +#include + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "require.hpp" + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +namespace backend = trystero::backend; +namespace detail = trystero::detail; +namespace tp = trystero::protocol; +using trystero::test::memory_network; +using trystero::test::post_in; +using webcpp::test::require; + +namespace { + +/** A value of the fixture: a read-only handle of an owned document. */ +using fixture_value = webcpp::document::basic_const_value<>; + +/** The fixture at `path`, read with webcpp::document; nothing when it does not parse. */ +std::optional load(const char* path) { + const std::ifstream file(path); + std::stringstream text; + text << file.rdbuf(); + auto parsed = webcpp::document::parse(text.str()); + if (!parsed.has_value()) { + return std::nullopt; + } + return std::move(parsed).unsafe_value(); +} + +std::string_view str(const fixture_value& v) { + return v.value_or(std::string_view()); +} + +/** The resource of everything the test makes. */ +std::pmr::memory_resource* memory() { + return std::pmr::get_default_resource(); +} + +/** + * An answering peer connection that gives the oracle's answer, then its one candidate, each + * posted, as a browser's arrive after the call; it opens no channel. + */ +class answering_connection final : public backend::peer_connection, + public std::enable_shared_from_this { +public: + answering_connection(asio::io_context& io, std::string_view answer, std::string_view candidate) + : io_(io), answer_(answer), candidate_(candidate) {} + + void set_handlers(handlers h) override { h_ = std::move(h); } + + std::shared_ptr create_data_channel( + std::string_view /*label*/) override { + return nullptr; + } + + void set_local_description( + trystero::handler done) + override { + post_in(io_, memory(), [self = shared_from_this(), done = std::move(done)]() mutable { + done({}, "answer", self->answer_); + post_in(self->io_, memory(), [self] { + if (self->h_.ice_candidate) { + self->h_.ice_candidate(self->candidate_); + } + }); + }); + } + + void set_remote_description(std::string_view type, std::string_view sdp, + trystero::handler done) override { + remote_type = type; + remote_sdp = sdp; + post_in(io_, memory(), [done = std::move(done)]() mutable { done({}); }); + } + + void add_ice_candidate(std::string_view /*candidate_json*/, + trystero::handler done) override { + post_in(io_, memory(), [done = std::move(done)]() mutable { done({}); }); + } + + [[nodiscard]] bool has_remote_description() const override { return !remote_sdp.empty(); } + + void close() override {} + + /** The description the signaling applied: the offer it opened. */ + std::string remote_type; + /** Its text. */ + std::string remote_sdp; + +private: + asio::io_context& io_; + std::string answer_; + std::string candidate_; + handlers h_; +}; + +/** The memory network, whose peer connections answer as the oracle's answering peer does. */ +class answering_network final : public memory_network { +public: + answering_network(asio::io_context& io, std::string_view answer, std::string_view candidate) + : memory_network(io), answer_(answer), candidate_(candidate) { + virtual_clock = true; + } + + std::shared_ptr make_peer_connection( + std::span /*servers*/, + std::pmr::memory_resource* /*memory*/) override { + auto made = std::make_shared(io(), answer_, candidate_); + connections.push_back(made); + return made; + } + + /** Every connection made, in order. */ + std::vector> connections; + +private: + std::string answer_; + std::string candidate_; +}; + +/** + * A sealer that seals and opens as Trystero JS did for the oracle: each plaintext the oracle + * sealed becomes the text Trystero's encrypt made of it, and that text opens to it again. Any + * other text fails, as one sealed under another key does, and is counted. + */ +class oracle_sealer final : public backend::sealer { +public: + oracle_sealer(asio::io_context& io, const fixture_value& sealed) : io_(io) { + for (const auto entry : sealed) { + table_.emplace_back(str(entry["plaintext"]), str(entry["text"])); + } + } + + void seal(std::string_view plaintext, + trystero::handler done) override { + reply(find(plaintext, true), std::move(done)); + } + + void open(std::string_view sealed, + trystero::handler done) override { + ++opened; + reply(find(sealed, false), std::move(done)); + } + + /** How many texts it was asked to open. */ + std::size_t opened = 0; + /** How many texts it did not know, which a test of Trystero's texts never gives. */ + std::size_t unknown = 0; + +private: + /** The sealed text of a plaintext, or the plaintext of a sealed text; nothing for another. */ + [[nodiscard]] std::optional find(std::string_view text, bool plaintext) const { + for (const auto& [plain, sealed] : table_) { + if ((plaintext ? plain : sealed) == text) { + return plaintext ? sealed : plain; + } + } + return std::nullopt; + } + + void reply(std::optional text, + trystero::handler done) { + if (!text) { + ++unknown; + } + post_in(io_, memory(), [text = std::move(text), done = std::move(done)]() mutable { + if (text) { + done({}, *text); + } else { + done(make_error_code(trystero::error::wrong_password), {}); + } + }); + } + + asio::io_context& io_; + std::vector> table_; +}; + +/** A signal the signaling published. */ +struct published_signal { + std::size_t relay; + std::string topic; + std::string text; +}; + +/** A signaling of the oracle's room and self id, over its sealer and an answering network. */ +struct answerer { + asio::io_context io; + answering_network net; + std::shared_ptr sealer; + std::vector published; + std::vector failures; + std::shared_ptr signaling; + + explicit answerer(const fixture_value& oracle) + : net(io, str(oracle["answer_sdp"]), str(oracle["candidate"])), + sealer(std::make_shared(io, oracle["sealed"])) { + signaling = std::make_shared( + net, sealer, str(oracle["app_id"]), str(oracle["room_id"]), str(oracle["self_id"]), + std::span(), + detail::signaling::callbacks{ + .claim = {}, + .publish = + [this](std::size_t relay, std::string_view topic, std::string_view content) { + published.push_back({ + .relay = relay, + .topic = std::string(topic), + .text = std::string(content), + }); + }, + .connected = {}, + .failed = [this](std::string_view, boost::system::error_code ec, + std::string_view) { failures.push_back(ec); }, + }, + detail::logger(), memory(), memory()); + } + + /** Hands `text` to the signaling, as a relay's on the room's self topic, then runs what is + * ready, the virtual clock standing still. */ + void receive(std::string_view text) { + signaling->handle(0, text); + require(BOOST_TEST(net.poll_ready())); + } +}; + +// For each offer, the signaling opens it, applies it to an answering connection, and publishes the +// answer, then the candidate it held, on the offerer's topic, each written as Trystero's answerer +// writes it: {peerId, answer, offerId} and {peerId, candidate, offerId}, its offerId last, or none +// for an offer that had none. The bytes are Trystero's, member for member. +void an_answerers_signals_are_trysteros(const fixture_value& oracle) { + const auto cases = oracle["cases"]; + BOOST_TEST_EQ(cases.size(), 2U); + for (const auto c : cases) { + answerer a(oracle); + a.receive(str(c["offer"])); + BOOST_TEST_EQ(a.net.connections.size(), 1U); + if (!a.net.connections.empty()) { + BOOST_TEST_EQ(a.net.connections[0]->remote_type, "offer"); + BOOST_TEST_EQ(a.net.connections[0]->remote_sdp, str(oracle["sealed"][0]["plaintext"])); + } + const auto expected = c["published"]; + BOOST_TEST_EQ(a.published.size(), expected.size()); + std::size_t i = 0; + for (const auto signal : expected) { + if (i < a.published.size()) { + BOOST_TEST_EQ(a.published[i].relay, 0U); + BOOST_TEST_EQ(a.published[i].topic, str(signal["topic"])); + BOOST_TEST_EQ(a.published[i].text, str(signal["text"])); + } + ++i; + } + BOOST_TEST_EQ(a.sealer->unknown, 0U); + BOOST_TEST(a.failures.empty()); + } +} + +/** `text`, an object's JSON, with spaces before its closing brace, to `size` bytes. */ +std::string padded(std::string_view text, std::size_t size) { + require(BOOST_TEST(text.ends_with('}') && text.size() <= size)); + std::string out(text.substr(0, text.size() - 1)); + out.append(size - text.size(), ' '); + out += '}'; + return out; +} + +// A signal of protocol::max_parsed_signal_bytes, the oracle's first offer with spaces, is read and +// answered; one byte longer is dropped before it is read: nothing is opened, made or published. +void a_signal_past_its_bound_is_dropped(const fixture_value& oracle) { + const auto offer = str(oracle["cases"][0]["offer"]); + { + answerer a(oracle); + a.receive(padded(offer, tp::max_parsed_signal_bytes)); + BOOST_TEST_EQ(a.sealer->opened, 1U); + BOOST_TEST_EQ(a.net.connections.size(), 1U); + BOOST_TEST_EQ(a.published.size(), 2U); + } + { + answerer a(oracle); + a.receive(padded(offer, tp::max_parsed_signal_bytes + 1)); + BOOST_TEST_EQ(a.sealer->opened, 0U); + BOOST_TEST(a.net.connections.empty()); + BOOST_TEST(a.published.empty()); + } +} + +/** A relay's connection that keeps what the strategy sends it. */ +class recording_socket final : public backend::websocket { +public: + void send(std::string_view text) override { sent.emplace_back(text); } + + void close() override { closed = true; } + + /** Every text sent, in order. */ + std::vector sent; + /** Whether the strategy closed it. */ + bool closed = false; +}; + +/** The memory network, whose relay connections are the test's: it keeps the handlers of the last + * one made, to hand the strategy texts as a relay's. */ +class relaying_network final : public memory_network { +public: + explicit relaying_network(asio::io_context& io) : memory_network(io) { virtual_clock = true; } + + std::shared_ptr connect(std::string_view /*url*/, + backend::websocket::handlers h, + std::pmr::memory_resource* /*memory*/) override { + handlers = std::move(h); + socket = std::make_shared(); + return socket; + } + + /** The handlers of the last connection made. */ + backend::websocket::handlers handlers; + /** That connection. */ + std::shared_ptr socket; +}; + +/** A relay's `["EVENT", , ]` of `topic` whose content is `size` bytes in + * all, padded with letters, under the id `id`. */ +std::string relay_event(std::string_view subscription, std::string_view topic, std::string_view id, + std::size_t size) { + std::pmr::string head(R"(["EVENT",)", memory()); + require(BOOST_TEST(webcpp::document::quote(subscription, head).has_value())); + head += R"(,{"id":")"; + head += id; + head += R"(","tags":[["x",)"; + require(BOOST_TEST(webcpp::document::quote(topic, head).has_value())); + head += R"(]],"content":")"; + constexpr std::string_view tail = R"("}])"; + require(BOOST_TEST(head.size() + tail.size() <= size)); + std::string out(head); + out.append(size - head.size() - tail.size(), 'a'); + out += tail; + return out; +} + +// A relay's text of protocol::nostr::max_parsed_relay_text_bytes, an event of the room's +// subscription and topic, reaches the room; one byte longer is dropped before it is read. +void a_relay_text_past_its_bound_is_dropped() { + asio::io_context io; + relaying_network net(io); + const std::pmr::string url("wss://relay.test", memory()); + const std::string_view topic = "the-room-topic"; + std::vector contents; + const auto strategy = std::make_shared( + net, std::span(&url, 1), + std::pmr::vector({std::pmr::string(topic, memory())}, memory()), topic, + [] { return std::pmr::string(R"({"peerId":"p"})", memory()); }, + [&contents](std::size_t, std::string_view, std::string_view content) { + contents.push_back(content.size()); + }, + detail::logger(), memory()); + strategy->start(); + require(BOOST_TEST(net.socket != nullptr && static_cast(net.handlers.open))); + net.handlers.open(); + require(BOOST_TEST(net.poll_ready())); + // The subscription the strategy asked for, ["REQ", , ]. + require(BOOST_TEST(!net.socket->sent.empty())); + const auto request = webcpp::document::parse(net.socket->sent.front()); + require(BOOST_TEST(request.has_value() && str(request->root()[0]) == "REQ")); + const auto subscription = str(request->root()[1]); + const std::size_t bound = tp::nostr::max_parsed_relay_text_bytes; + const auto at_bound = relay_event(subscription, topic, std::string(64, '1'), bound); + const auto past_bound = relay_event(subscription, topic, std::string(64, '2'), bound + 1); + BOOST_TEST_EQ(at_bound.size(), bound); + BOOST_TEST_EQ(past_bound.size(), bound + 1); + net.handlers.message(at_bound); + BOOST_TEST_EQ(contents.size(), 1U); + net.handlers.message(past_bound); + BOOST_TEST_EQ(contents.size(), 1U); + BOOST_TEST(!net.socket->closed); + strategy->stop(); +} + +/** A relay's `["EVENT", , ]` of `topic` under the id `id`, its event holding + * a member nested so that the whole text nests `depth` deep. */ +std::string nested_event(std::string_view subscription, std::string_view topic, std::string_view id, + std::size_t depth) { + std::pmr::string text(R"(["EVENT",)", memory()); + require(BOOST_TEST(webcpp::document::quote(subscription, text).has_value())); + text += R"(,{"id":")"; + text += id; + text += R"(","tags":[["x",)"; + require(BOOST_TEST(webcpp::document::quote(topic, text).has_value())); + // The text's array and its event are two levels; the member's arrays are the rest. + text += R"(]],"content":"c","deep":)"; + text.append(depth - 2, '['); + text.append(depth - 2, ']'); + text += "}]"; + return std::string(text); +} + +// A relay's text nested as deep as a protocol text may, protocol::json::max_protocol_depth, reaches +// the room; one level deeper is dropped as a malformed one is, before the parse recurses further. +void a_relay_text_past_its_depth_is_dropped() { + asio::io_context io; + relaying_network net(io); + const std::pmr::string url("wss://relay.test", memory()); + const std::string_view topic = "the-room-topic"; + std::vector contents; + const auto strategy = std::make_shared( + net, std::span(&url, 1), + std::pmr::vector({std::pmr::string(topic, memory())}, memory()), topic, + [] { return std::pmr::string(R"({"peerId":"p"})", memory()); }, + [&contents](std::size_t, std::string_view, std::string_view content) { + contents.emplace_back(content); + }, + detail::logger(), memory()); + strategy->start(); + require(BOOST_TEST(net.socket != nullptr && static_cast(net.handlers.open))); + net.handlers.open(); + require(BOOST_TEST(net.poll_ready())); + require(BOOST_TEST(!net.socket->sent.empty())); + const auto request = webcpp::document::parse(net.socket->sent.front()); + require(BOOST_TEST(request.has_value() && str(request->root()[0]) == "REQ")); + const auto subscription = str(request->root()[1]); + const std::size_t depth = tp::json::max_protocol_depth; + BOOST_TEST_EQ(depth, 16U); + net.handlers.message(nested_event(subscription, topic, std::string(64, '1'), depth)); + BOOST_TEST_EQ(contents.size(), 1U); + net.handlers.message(nested_event(subscription, topic, std::string(64, '2'), depth + 1)); + BOOST_TEST_EQ(contents.size(), 1U); + BOOST_TEST(!net.socket->closed); + strategy->stop(); +} + +} // namespace + +int main(int argc, char* argv[]) { + if (!BOOST_TEST_EQ(argc, 2)) { + BOOST_LIGHTWEIGHT_TEST_OSTREAM + << "usage: signaling_test \n"; + return webcpp::test::exit_status(boost::report_errors()); + } + const auto fixture = load(argv[1]); + if (!BOOST_TEST(fixture.has_value() && (*fixture)["answerer"].is_object())) { + return webcpp::test::exit_status(boost::report_errors()); + } + const auto oracle = fixture->root()["answerer"]; + an_answerers_signals_are_trysteros(oracle); + a_signal_past_its_bound_is_dropped(oracle); + a_relay_text_past_its_bound_is_dropped(); + a_relay_text_past_its_depth_is_dropped(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index e95a103..4004e01 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -10,18 +10,18 @@ #include #include #include -#include #include #include +#include #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include + +#include #include #include @@ -53,8 +53,8 @@ * each factory method is given; the network's own state (its relays, their subscriptions, its * record of the connections) is in the resource the network is constructed with, and changes only * when a room joins, connects or leaves. The state of the hooks a test drives (held frames, - * deferred opens, a buffering channel's queue, the virtual clock) is in the default resource and is - * made only when the test sets the hook. + * deferred opens, held sealer opens, a buffering channel's queue, the virtual clock) is in the + * default resource and is made only when the test sets the hook. */ namespace webcpp::trystero::test { @@ -62,9 +62,9 @@ class memory_network; /** Posts `f` to `io`, allocated in `memory`. */ template -void post_in(boost::asio::io_context& io, std::pmr::memory_resource* memory, F&& f) { - boost::asio::post(io, boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), - std::forward(f))); +void post_in(webcpp::asio::io_context& io, std::pmr::memory_resource* memory, F&& f) { + webcpp::asio::post(io, webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), + std::forward(f))); } class memory_timer; @@ -74,24 +74,23 @@ class memory_timer; * that nothing keeps it, or its memory in the resource of the room or connection that made it, * past that call. */ struct virtual_clock_state { - using key = std::pair; + using key = std::pair; std::map due; std::uint64_t scheduled = 0; - double now_ms = 0; + std::chrono::steady_clock::time_point now{}; }; -/** An Asio timer, as the native backend's: a wait cancelled, replaced or destroyed never fires, +/** An Asio timer, as the platform backend's: a wait cancelled, replaced or destroyed never fires, * even when Asio had already queued its expiry. On the virtual clock, it waits there instead, until * the test moves the clock past its due time. */ class memory_timer : public backend::timer { public: /** A timer on the virtual clock `clock`, or on Asio's when `clock` is empty. */ - memory_timer(boost::asio::io_context& io, std::pmr::memory_resource* memory, int time_scale = 1, + memory_timer(webcpp::asio::io_context& io, std::pmr::memory_resource* memory, std::weak_ptr clock = {}) : io_(io), timer_(io), memory_(memory), - time_scale_(time_scale), on_clock_(!clock.expired()), clock_(std::move(clock)), waits_( @@ -108,15 +107,14 @@ class memory_timer : public backend::timer { unschedule(); // a restart replaces the pending expiry fire_ = std::move(fire); if (const auto c = clock_.lock()) { - key_ = virtual_clock_state::key{c->now_ms + static_cast(delay.count()), - c->scheduled++}; + key_ = virtual_clock_state::key{c->now + delay, c->scheduled++}; c->due.emplace(*key_, this); } return; } const std::uint64_t wait = ++*waits_; - timer_.expires_after(delay / time_scale_); - timer_.async_wait(boost::asio::bind_allocator( + timer_.expires_after(delay); + timer_.async_wait(webcpp::asio::bind_allocator( std::pmr::polymorphic_allocator<>(memory_), [waits = std::weak_ptr(waits_), wait, fire = std::move(fire)](boost::system::error_code ec) mutable { @@ -156,10 +154,9 @@ class memory_timer : public backend::timer { key_.reset(); } - boost::asio::io_context& io_; - boost::asio::steady_timer timer_; + webcpp::asio::io_context& io_; + webcpp::asio::steady_timer timer_; std::pmr::memory_resource* memory_; - int time_scale_; bool on_clock_; std::weak_ptr clock_; std::optional key_; @@ -198,8 +195,12 @@ class memory_relay { void close_all(); std::size_t events_seen = 0; + /** How many texts went through the relay: each text it received from a socket, and each text + * a socket of it handed to its room. A test that measures a window of a room's life reads it + * to know whether relay traffic, which parses JSON at both ends, happened in that window. */ + std::size_t texts = 0; /** Answers this many EVENTs with "rate-limited:", to exercise the strategy's backoff. */ - int rate_limit_next = 0; + std::size_t rate_limit_next = 0; /** Closes each connection right after its subscription, as a relay does after a text longer * than a room reads. */ bool close_after_subscribe = false; @@ -214,15 +215,12 @@ class memory_relay { class memory_websocket : public backend::websocket, public std::enable_shared_from_this { public: - memory_websocket(boost::asio::io_context& io, memory_relay* relay, handlers h, + memory_websocket(webcpp::asio::io_context& io, memory_relay* relay, handlers h, std::pmr::memory_resource* memory) - : io_(io), relay_(relay), h_(std::move(h)), memory_(memory), json_(memory) {} + : io_(io), relay_(relay), h_(std::move(h)), memory_(memory) {} std::pmr::memory_resource* memory() const { return memory_; } - /** A storage over this socket's resource, for a value parsed and dropped during one call. */ - boost::json::storage_ptr json() { return {&json_}; } - void open() { post_in(io_, memory_, [self = shared_from_this()] { if (self->closed_) { @@ -250,10 +248,14 @@ class memory_websocket : public backend::websocket, }); } - /** Delivers a text the relay made in this socket's resource. */ + /** Delivers a text the relay made in this socket's resource; the relay counts it in its + * `texts` once the socket hands it to its room. */ void deliver(std::pmr::string text) { post_in(io_, memory_, [self = shared_from_this(), text = std::move(text)] { if (self->open_ && self->h_.message) { + if (self->relay_ != nullptr) { + ++self->relay_->texts; + } self->h_.message(text); } }); @@ -279,11 +281,10 @@ class memory_websocket : public backend::websocket, } } - boost::asio::io_context& io_; + webcpp::asio::io_context& io_; memory_relay* relay_; handlers h_; std::pmr::memory_resource* memory_; - json_resource json_; bool open_ = false; bool closed_ = false; }; @@ -300,47 +301,60 @@ inline void memory_relay::close_all() { } } +/** A subscription of `socket` to the kinds and topics a NIP-01 filter names, in `memory`. */ +inline memory_relay::subscription subscription_of(const std::shared_ptr& socket, + const protocol::json::const_value& filter, + std::pmr::memory_resource* memory) { + memory_relay::subscription s{ + .socket = socket, + .kinds = std::pmr::set(memory), + .topics = std::pmr::set>(memory), + }; + for (const protocol::json::const_value k : filter["kinds"]) { + if (const auto kind = k.get(); kind.has_value()) { + s.kinds.insert(*kind); + } + } + for (const protocol::json::const_value t : filter["#x"]) { + s.topics.emplace(protocol::json::text_of(t)); + } + return s; +} + inline void memory_relay::receive(const std::shared_ptr& from, std::string_view text) { - boost::system::error_code ec; - const auto value = protocol::json::parse(text, from->json(), ec); - const auto* message = ec ? nullptr : value.if_array(); - if (message == nullptr || message->empty() || !message->at(0).is_string()) { + ++texts; + // The text is read into the sender's resource, as a room reads a relay's, within the longest + // text a relay's connection carries. + const auto parsed = webcpp::document::parse( + text, protocol::json::protocol_limits(protocol::max_relay_message_bytes), + std::pmr::polymorphic_allocator(from->memory())); + if (!parsed.has_value()) { return; } - const std::string_view type = message->at(0).get_string(); - if (type == "REQ" && message->size() >= 3) { - subscription s{ - .socket = from, - .kinds = std::pmr::set(memory_), - .topics = std::pmr::set>(memory_), - }; - const auto& filter = message->at(2).as_object(); - for (const auto& k : filter.at("kinds").as_array()) { - s.kinds.insert(k.as_int64()); - } - for (const auto& t : filter.at("#x").as_array()) { - s.topics.emplace(std::string_view(t.as_string())); - } + const protocol::json::const_value message = parsed->root(); + if (!message.at(0).is_string()) { + return; + } + const std::string_view type = protocol::json::text_of(message.at(0)); + if (type == "REQ" && message.size() >= 3) { subscriptions_.insert_or_assign( - key{from.get(), - std::pmr::string(std::string_view(message->at(1).as_string()), memory_)}, - std::move(s)); + key{from.get(), std::pmr::string(protocol::json::text_of(message.at(1)), memory_)}, + subscription_of(from, message.at(2), memory_)); std::pmr::string eose(R"(["EOSE",)", from->memory()); - protocol::json::append_value(eose, message->at(1)); + protocol::json::append_value(eose, message.at(1)); eose += ']'; from->deliver(std::move(eose)); if (close_after_subscribe) { from->close(); } - } else if (type == "CLOSE" && message->size() >= 2) { - subscriptions_.erase( - key{from.get(), - std::pmr::string(std::string_view(message->at(1).as_string()), from->memory())}); - } else if (type == "EVENT" && message->size() >= 2) { - const auto& event = message->at(1).as_object(); + } else if (type == "CLOSE" && message.size() >= 2) { + subscriptions_.erase(key{ + from.get(), std::pmr::string(protocol::json::text_of(message.at(1)), from->memory())}); + } else if (type == "EVENT" && message.size() >= 2) { + const protocol::json::const_value event = message.at(1); std::pmr::string ok(R"(["OK",)", from->memory()); - protocol::json::append_value(ok, event.at("id")); + protocol::json::append_value(ok, event["id"]); if (rate_limit_next > 0) { --rate_limit_next; ok += R"(,false,"rate-limited: slow down"])"; @@ -350,22 +364,25 @@ inline void memory_relay::receive(const std::shared_ptr& from, ++events_seen; ok += R"(,true,""])"; from->deliver(std::move(ok)); - const auto kind = event.at("kind").as_int64(); + const auto kind = event["kind"].get(); + if (!kind.has_value()) { + return; + } // The event's first tag, ["x", ]. - const auto& tags = event.at("tags").as_array(); - const auto& tag = tags.at(0).as_array(); - const std::string_view topic = tag.at(1).as_string(); + const std::string_view topic = protocol::json::text_of(event["tags"].at(0).at(1)); for (auto& [subscribed, s] : subscriptions_) { const auto socket = s.socket.lock(); - if (!socket || !s.kinds.contains(kind) || !s.topics.contains(topic)) { + if (!socket || !s.kinds.contains(*kind) || !s.topics.contains(topic)) { continue; } - // ["EVENT", , ], as boost::json::serialize writes it, in the - // receiver's resource. + // ["EVENT", , ], as JSON.stringify writes it, in the receiver's + // resource: the event's bytes are the ones the room sent, since none of its keys is + // an integer, which JavaScript's order would move first. std::pmr::string forwarded(R"(["EVENT",)", socket->memory()); - protocol::json::append_string(forwarded, subscribed.second); + // The subscription's id was read from the REQ's JSON, so it is UTF-8. + protocol::json::detail::append_utf8(forwarded, subscribed.second); forwarded += ','; - protocol::json::append_value(forwarded, message->at(1)); + protocol::json::append_value(forwarded, event); forwarded += ']'; socket->deliver(std::move(forwarded)); } @@ -416,7 +433,7 @@ struct node_allocator { class memory_data_channel : public backend::data_channel, public std::enable_shared_from_this { public: - memory_data_channel(boost::asio::io_context& io, std::pmr::memory_resource* memory) + memory_data_channel(webcpp::asio::io_context& io, std::pmr::memory_resource* memory) : io_(io), memory_(memory), queue_(node_allocator(memory)) {} void set_handlers(handlers h) override { h_ = std::move(h); } @@ -482,7 +499,7 @@ class memory_data_channel : public backend::data_channel, * receives each frame whose last byte it moved. */ void drain(); - boost::asio::io_context& io_; + webcpp::asio::io_context& io_; std::pmr::memory_resource* memory_; std::weak_ptr remote_; handlers h_; @@ -505,7 +522,7 @@ class memory_data_channel : public backend::data_channel, class memory_peer_connection : public backend::peer_connection, public std::enable_shared_from_this { public: - memory_peer_connection(boost::asio::io_context& io, memory_network& net, + memory_peer_connection(webcpp::asio::io_context& io, memory_network& net, std::weak_ptr registry, std::size_t id, std::pmr::memory_resource* memory) : io_(io), @@ -629,7 +646,7 @@ class memory_peer_connection : public backend::peer_connection, private: void try_connect(); - boost::asio::io_context& io_; + webcpp::asio::io_context& io_; memory_network& net_; std::weak_ptr registry_; std::size_t id_; @@ -655,7 +672,7 @@ class memory_peer_connection : public backend::peer_connection, */ class memory_network : public backend::factory { public: - explicit memory_network(boost::asio::io_context& io, std::uint64_t seed = 1, + explicit memory_network(webcpp::asio::io_context& io, std::uint64_t seed = 1, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) : io_(io), random_(seed), @@ -714,13 +731,13 @@ class memory_network : public backend::factory { std::shared_ptr make_timer(std::pmr::memory_resource* memory) override { if (!virtual_clock) { return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), - io_, memory, time_scale); + io_, memory); } if (!clock_) { clock_ = std::make_shared(); } return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), io_, - memory, time_scale, + memory, std::weak_ptr(clock_)); } @@ -728,22 +745,26 @@ class memory_network : public backend::factory { std::pmr::memory_resource* memory) override; void random(std::span out) override { + random_bytes += out.size(); for (auto& b : out) { b = static_cast(random_()); } } - std::int64_t unix_seconds() override { - return 1'759'700'000 + static_cast(now_ms() / 1000); + /** A wall clock that moves with steady_now(), from 2025-10-05T21:33:20Z at its origin, in whole + * seconds. */ + std::chrono::sys_seconds unix_now() override { + return std::chrono::sys_seconds(std::chrono::seconds(1'759'700'000)) + + std::chrono::floor(steady_now().time_since_epoch()); } - double now_ms() override { + /** The virtual clock's time, or the time since the network was made; from the steady clock's + * epoch. */ + std::chrono::steady_clock::time_point steady_now() override { if (virtual_clock) { - return clock_ ? clock_->now_ms : 0.0; + return clock_ ? clock_->now : std::chrono::steady_clock::time_point(); } - return std::chrono::duration(std::chrono::steady_clock::now() - start_) - .count() * - time_scale; + return std::chrono::steady_clock::time_point(std::chrono::steady_clock::now() - start_); } std::shared_ptr find(std::size_t id) { @@ -751,7 +772,7 @@ class memory_network : public backend::factory { return it == connections_->end() ? nullptr : it->second->shared_from_this(); } - boost::asio::io_context& io() { return io_; } + webcpp::asio::io_context& io() { return io_; } /** How many peer connections are open now. */ [[nodiscard]] std::size_t live_connections() const { return connections_->size(); } @@ -760,10 +781,10 @@ class memory_network : public backend::factory { std::size_t made_connections = 0; /** The most peer connections that were open at once. */ std::size_t peak_connections = 0; - /** How much faster than real time the timers and the clock run, for tests of long timeouts. */ - int time_scale = 1; + /** How many random bytes were drawn. */ + std::size_t random_bytes = 0; /** How many of the next peer connections to refuse, as a browser at its limit does. */ - int refuse_peer_connections = 0; + std::size_t refuse_peer_connections = 0; /** Whether to record the URL of every ICE server a peer connection is made with. */ bool record_servers = false; /** The URLs recorded, in the default resource: only a test that records them allocates. */ @@ -789,6 +810,15 @@ class memory_network : public backend::factory { void open(std::size_t pc); /** Delivers `frame` on the channel of `pc`, as if its other end had sent it. */ void inject(std::size_t pc, std::span frame); + /** When true, every sealer's opens wait until release_sealer_opens(), as Web Crypto's take + * their time in a page while the relays' texts keep coming. */ + bool hold_sealer_opens = false; + /** Completes the sealer opens held, in the order they were asked for. */ + void release_sealer_opens(); + + /** How many sealer opens wait to be released. */ + [[nodiscard]] std::size_t held_sealer_opens() const { return held_sealer_opens_.size(); } + /** Reports `failed` on `pc`, then closes its channel. */ void fail(std::size_t pc); /** Reports `disconnected` on `pc`; its channel stays open. */ @@ -806,8 +836,8 @@ class memory_network : public backend::factory { /** The buffered_amount() of the channel of `pc`, or 0 when it has none. */ [[nodiscard]] std::size_t buffered(std::size_t pc) const; - /** Whether the timers made from now on run on the virtual clock, which now_ms() and - * unix_seconds() then read, and which moves only through advance() and step(). */ + /** Whether the timers made from now on run on the virtual clock, which steady_now() and + * unix_now() then read, and which moves only through advance() and step(). */ bool virtual_clock = false; /** How many timers one advance() fires at most before it gives up. */ std::size_t max_steps = 1'000'000; @@ -819,15 +849,16 @@ class memory_network : public backend::factory { bool poll_ready(); /** A ready-handler budget was exhausted; the caller must report a test failure. */ bool handlers_exhausted = false; - /** Runs the io_context's ready work, then fires the earliest timer due at or before - * `until_ms`, moving the clock to it; false, with the clock at `until_ms`, when none is due. */ - bool step(double until_ms); + /** Runs the io_context's ready work, then fires the earliest timer due at or before `until`, + * moving the clock to it; false, with the clock at `until`, when none is due. */ + bool step(std::chrono::steady_clock::time_point until); /** How many timers wait on the virtual clock. */ [[nodiscard]] std::size_t scheduled() const; private: friend class memory_data_channel; friend class memory_peer_connection; + friend class memory_sealer; /** A frame held by the filter, and every frame its sending end sent after it. */ struct held_frame { @@ -835,15 +866,24 @@ class memory_network : public backend::factory { std::vector bytes; }; + /** A sealer's open held by `hold_sealer_opens`: its result, made when it was asked for, and + * what it completes, in the resource of the room that asked. */ + struct held_open { + std::pmr::memory_resource* memory; + bool ours; + std::pmr::string plain; + handler done; + }; + /** Holds, drops or delivers `frame`, as the filter and the frames held before it say. */ void route(std::size_t from, std::size_t to, std::span frame); /** Hands `frame` to the other end of the channel of `from`, or to that channel's queue when * channels buffer. */ void deliver(std::size_t from, std::span frame); - /** Whether a timer of the virtual clock is due at or before `until_ms`. */ - [[nodiscard]] bool due_by(double until_ms) const; + /** Whether a timer of the virtual clock is due at or before `until`. */ + [[nodiscard]] bool due_by(std::chrono::steady_clock::time_point until) const; - boost::asio::io_context& io_; + webcpp::asio::io_context& io_; std::mt19937_64 random_; std::chrono::steady_clock::time_point start_; std::pmr::memory_resource* memory_; @@ -853,6 +893,7 @@ class memory_network : public backend::factory { std::size_t next_pc_ = 0; std::map> held_; // by the receiving end std::map> deferred_; // ends waiting for open() + std::deque held_sealer_opens_; std::shared_ptr clock_; }; @@ -981,9 +1022,9 @@ inline void memory_data_channel::drain() { } draining_ = !queue_.empty(); if (draining_) { - boost::asio::post( - io_, boost::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory_), - [self = shared_from_this()] { self->drain(); })); + webcpp::asio::post( + io_, webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory_), + [self = shared_from_this()] { self->drain(); })); } // Last, since the handler may send again, which queues behind what is left. if (above && buffered_ <= low_threshold && h_.buffered_amount_low) { @@ -1091,8 +1132,8 @@ inline std::size_t memory_network::buffered(std::size_t pc) const { return channel ? channel->buffered_amount() : 0; } -inline bool memory_network::due_by(double until_ms) const { - return clock_ && !clock_->due.empty() && clock_->due.begin()->first.first <= until_ms; +inline bool memory_network::due_by(std::chrono::steady_clock::time_point until) const { + return clock_ && !clock_->due.empty() && clock_->due.begin()->first.first <= until; } inline bool memory_network::poll_ready() { @@ -1109,7 +1150,7 @@ inline bool memory_network::poll_ready() { return false; } -inline bool memory_network::step(double until_ms) { +inline bool memory_network::step(std::chrono::steady_clock::time_point until) { // The clock moves from the first step, before any timer is made. if (virtual_clock && !clock_) { clock_ = std::make_shared(); @@ -1117,14 +1158,14 @@ inline bool memory_network::step(double until_ms) { if (!poll_ready()) { return false; } - if (!due_by(until_ms)) { + if (!due_by(until)) { if (clock_) { - clock_->now_ms = std::max(clock_->now_ms, until_ms); + clock_->now = std::max(clock_->now, until); } return false; } const auto it = clock_->due.begin(); - clock_->now_ms = std::max(clock_->now_ms, it->first.first); + clock_->now = std::max(clock_->now, it->first.first); memory_timer* const timer = it->second; clock_->due.erase(it); timer->expire(); @@ -1132,7 +1173,7 @@ inline bool memory_network::step(double until_ms) { } inline bool memory_network::advance(std::chrono::milliseconds by) { - const double until = now_ms() + static_cast(by.count()); + const auto until = steady_now() + by; // A run of exactly max_steps timers is finite: only one more due timer stops it. for (std::size_t fired = 0;; ++fired) { if (!poll_ready()) { @@ -1155,9 +1196,18 @@ inline std::size_t memory_network::scheduled() const { * opens it. */ class memory_sealer : public backend::sealer { public: - memory_sealer(boost::asio::io_context& io, std::array key, + memory_sealer(memory_network& net, std::array key, std::pmr::memory_resource* memory) - : io_(io), key_(key), memory_(memory) {} + : net_(net), io_(net.io()), key_(key), memory_(memory) {} + + /** Posts the completion of an open whose result is known: `plain` when the text was `ours`. */ + static void complete(webcpp::asio::io_context& io, std::pmr::memory_resource* memory, bool ours, + std::pmr::string plain, + handler done) { + post_in(io, memory, [ours, plain = std::move(plain), done = std::move(done)]() mutable { + done(ours ? backend::error_code{} : make_error_code(error::wrong_password), plain); + }); + } void seal(std::string_view plaintext, handler done) override { @@ -1179,21 +1229,36 @@ class memory_sealer : public backend::sealer { if (ours) { plain.assign(parts->ciphertext.begin(), parts->ciphertext.end()); } - post_in(io_, memory_, [ours, plain = std::move(plain), done = std::move(done)]() mutable { - done(ours ? backend::error_code{} : make_error_code(error::wrong_password), plain); - }); + if (net_.hold_sealer_opens) { + net_.held_sealer_opens_.push_back({ + .memory = memory_, + .ours = ours, + .plain = std::move(plain), + .done = std::move(done), + }); + return; + } + complete(io_, memory_, ours, std::move(plain), std::move(done)); } private: - boost::asio::io_context& io_; + memory_network& net_; + webcpp::asio::io_context& io_; std::array key_; std::pmr::memory_resource* memory_; }; inline std::shared_ptr memory_network::make_sealer( std::array key, std::pmr::memory_resource* memory) { - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), io_, key, - memory); + return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), *this, + key, memory); +} + +inline void memory_network::release_sealer_opens() { + for (auto& held : std::exchange(held_sealer_opens_, {})) { + memory_sealer::complete(io_, held.memory, held.ours, std::move(held.plain), + std::move(held.done)); + } } } // namespace webcpp::trystero::test diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp index a50a783..321a698 100644 --- a/test/support/rooms.hpp +++ b/test/support/rooms.hpp @@ -13,14 +13,19 @@ #include #include +#include +#include #include +#include #include #include -#include +#include + +#include +#include + #include -#include -#include #include #include @@ -39,9 +44,9 @@ #include // The rooms' shared test helpers: a memory network with two relays, an app over them and a join -// that must succeed, a watcher of a room's relay traffic, a flood of announcements, and the virtual -// clock's own waits. A case of room_test.cpp, connection_test.cpp or shared_test.cpp includes this -// header for them. +// that must succeed, a watcher of a room's relay traffic, a flood of announcements, the virtual +// clock's own waits, and a JSON document to send. A case of room_test.cpp, connection_test.cpp or +// shared_test.cpp includes this header for them. namespace webcpp::trystero::test { using namespace std::chrono_literals; @@ -66,6 +71,14 @@ inline trystero::app_config app_config(std::string_view self_id, std::string_vie return c; } +/** The owned document of a JSON text, as an action of JSON sends it; a text that does not parse + * ends the test. */ +inline webcpp::document::document document_of(std::string_view text) { + auto parsed = webcpp::document::parse(text); + webcpp::test::require(BOOST_TEST(parsed.has_value())); + return std::move(*parsed); +} + /** Joins `room_id`, which must succeed: a failure ends the test. */ inline trystero::room join(trystero::app& a, std::string_view room_id, trystero::room_options options = {}) { @@ -75,7 +88,7 @@ inline trystero::room join(trystero::app& a, std::string_view room_id, } /** Runs the io_context until `done` holds or `limit` passes; whether `done` held. */ -inline bool run_until(boost::asio::io_context& io, const std::function& done, +inline bool run_until(webcpp::asio::io_context& io, const std::function& done, std::chrono::milliseconds limit = 10s) { const auto end = std::chrono::steady_clock::now() + limit; while (!done() && std::chrono::steady_clock::now() < end) { @@ -88,7 +101,7 @@ inline bool run_until(boost::asio::io_context& io, const std::function& } struct fixture { - boost::asio::io_context io; + webcpp::asio::io_context io; memory_network net{io}; /** A memory network with two relays; with `virtual_time`, on the virtual clock. */ @@ -108,7 +121,7 @@ inline bool run_until(fixture& f, const std::function& done, if (!f.net.virtual_clock) { return run_until(f.io, done, limit); } - const double end = f.net.now_ms() + static_cast(limit.count()); + const auto end = f.net.steady_now() + limit; for (std::size_t steps = 0; !done(); ++steps) { if (steps == f.net.max_steps) { BOOST_ERROR("the virtual clock fired max_steps timers without moving past them"); @@ -160,11 +173,13 @@ class counting_resource final : public std::pmr::memory_resource { } }; -/** Announcements of fresh peer ids on a room's topic, signed, through a socket of their own. */ +/** Announcements of fresh peer ids on a room's topic, signed, through a socket of their own to one + * relay, the first unless another is named. */ class flooder { public: - flooder(fixture& f, std::string_view room) : f_(f), topic_(protocol::root_topic(app_id, room)) { - socket_ = f.net.connect(relay_a, + flooder(fixture& f, std::string_view room, std::string_view relay = relay_a) + : f_(f), topic_(protocol::root_topic(app_id, room)) { + socket_ = f.net.connect(relay, { .open = [this] { open_ = true; }, .message = @@ -189,14 +204,15 @@ class flooder { void watch(std::string_view topic) { const std::array topics{std::pmr::string(topic)}; socket_->send( - protocol::nostr::subscribe_message("watch" + std::to_string(next_++), topics, 0)); + protocol::nostr::subscribe_message("watch" + std::to_string(next_++), topics, {})); } - /** Publishes a signal on a topic, in any peer's name. */ - void publish(std::string_view topic, const protocol::signal_message& m) { + /** Publishes a signal on a topic, in any peer's name; with a nonce, as an event of its own. */ + void publish(std::string_view topic, const protocol::signal_message& m, + std::string_view nonce = {}) { const std::array aux{}; - socket_->send(protocol::nostr::event_message(*signer_, f_.net.unix_seconds(), topic, - protocol::write_signal(m), aux)); + socket_->send(protocol::nostr::event_message(*signer_, detail::unix_now(f_.net), topic, + protocol::write_signal(m, nonce), aux)); } /** `plain` sealed under the room key of `room`, with no password, as the memory sealer seals. @@ -209,12 +225,12 @@ class flooder { } /** Announces one id `times` times. */ - void announce_as(std::string_view id, int times) { + void announce_as(std::string_view id, std::size_t times) { const std::array aux{}; - for (int i = 0; i < times; ++i) { + for (std::size_t i = 0; i < times; ++i) { const auto nonce = std::to_string(next_++); const auto content = protocol::write_signal({.peer_id = id}, nonce); - socket_->send(protocol::nostr::event_message(*signer_, f_.net.unix_seconds(), topic_, + socket_->send(protocol::nostr::event_message(*signer_, detail::unix_now(f_.net), topic_, content, aux)); } } @@ -226,7 +242,7 @@ class flooder { std::pmr::string id(prefix); id += std::to_string(next_++); const auto content = protocol::write_signal({.peer_id = id}); - socket_->send(protocol::nostr::event_message(*signer_, f_.net.unix_seconds(), topic_, + socket_->send(protocol::nostr::event_message(*signer_, detail::unix_now(f_.net), topic_, content, aux)); } } @@ -250,17 +266,21 @@ struct relayed { bool announcement = false; }; -/** The topic and the signal of a relay's text, when it is an event that carries one. */ +/** The topic and the signal of a relay's text, when it is an event that carries one. Both texts + * are read within the relay's bound, wider than a room's, so that the watcher sees whatever a room + * could be sent. */ inline std::optional relayed_signal(std::string_view text) { - boost::system::error_code ec; - const auto document = boost::json::parse(text, ec); - const auto message = ec ? std::nullopt : protocol::nostr::read_relay_message(document); + const auto limits = protocol::json::protocol_limits(protocol::max_relay_message_bytes); + const std::pmr::polymorphic_allocator memory(std::pmr::get_default_resource()); + const auto parsed = webcpp::document::parse(text, limits, memory); + const auto message = + parsed.has_value() ? protocol::nostr::read_relay_message(parsed->root()) : std::nullopt; const auto* event = message ? std::get_if(&*message) : nullptr; if (event == nullptr) { return std::nullopt; } - const auto content = boost::json::parse(event->content, ec); - const auto signal = ec ? std::nullopt : protocol::read_signal(content); + const auto content = webcpp::document::parse(event->content, limits, memory); + const auto signal = content.has_value() ? protocol::read_signal(content->root()) : std::nullopt; if (!signal) { return std::nullopt; } diff --git a/test/timer_test.cpp b/test/timer_test.cpp new file mode 100644 index 0000000..1b312a6 --- /dev/null +++ b/test/timer_test.cpp @@ -0,0 +1,135 @@ +// 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) + +// Tests the timer over webcpp::asio's steady_timer, on both targets: a wait fires once; a wait +// that is cancelled, restarted or destroyed never calls its handler, even when its expiry was +// already queued, which Asio cannot take back; and its waits are allocated in the resource it is +// given. On emscripten the io_context's run family suspends into node's event loop, where the +// reactor's one setTimeout wakes it. + +#include + +#include + +#include +#include + +#include +#include +#include +#include + +#include "cases.hpp" + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +namespace { + +/** A resource that counts what it gives, and what is still out. */ +class counting_resource final : public std::pmr::memory_resource { +public: + /** How many allocations it made. */ + std::size_t allocations = 0; + /** How many of them are not yet returned. */ + std::size_t outstanding = 0; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations; + ++outstanding; + return std::pmr::new_delete_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + --outstanding; + 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::shared_ptr make_timer(asio::io_context& io, + std::pmr::memory_resource* memory) { + return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), + io.get_executor(), memory); +} + +/** + * Starts `first`, then `second`, both at 0 ms, so that both have expired when the io_context first + * looks: Asio then queues both completions as successes in one pass, `first`'s ahead, and what + * `first` does to `second` comes after `second`'s expiry was queued. + */ +template +void both_expired(asio::io_context& io, trystero::detail::timer& first, + trystero::detail::timer& second, std::size_t& second_fired, Then then) { + first.start(0ms, then); + second.start(0ms, [&second_fired] { ++second_fired; }); + io.run_for(100ms); // lint-run: the timers' expiries are the events under test + io.restart(); +} + +void an_uncancelled_wait_fires_once() { + asio::io_context io; + counting_resource memory; + const auto timer = make_timer(io, &memory); + const std::size_t made = memory.allocations; + std::size_t fired = 0; + timer->start(1ms, [&] { ++fired; }); + io.run_for(100ms); // lint-run: the wait expires + BOOST_TEST_EQ(fired, 1U); + // The wait was allocated in the timer's resource, and given back once it completed. + BOOST_TEST_GT(memory.allocations, made); + BOOST_TEST_EQ(memory.outstanding, 2U); // the timer, and its count of waits +} + +void a_cancelled_wait_never_fires() { + asio::io_context io; + std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); + const auto first = make_timer(io, memory); + const auto second = make_timer(io, memory); + std::size_t fired = 0; + both_expired(io, *first, *second, fired, [&] { second->cancel(); }); + BOOST_TEST_EQ(fired, 0U); +} + +void a_destroyed_timer_never_fires() { + asio::io_context io; + std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); + const auto first = make_timer(io, memory); + auto second = make_timer(io, memory); + std::size_t fired = 0; + both_expired(io, *first, *second, fired, [&] { second.reset(); }); + BOOST_TEST_EQ(fired, 0U); +} + +void a_restarted_timer_fires_only_its_new_wait() { + asio::io_context io; + std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); + const auto first = make_timer(io, memory); + const auto second = make_timer(io, memory); + std::size_t fired = 0; + std::size_t restarted = 0; + both_expired(io, *first, *second, fired, [&] { second->start(10ms, [&] { ++restarted; }); }); + io.run_for(100ms); // lint-run: the restarted wait expires + BOOST_TEST_EQ(fired, 0U); + BOOST_TEST_EQ(restarted, 1U); +} + +} // namespace + +int main() { + // Each case in a frame of its own, which main's never holds (cases.hpp). + using webcpp::test::run_case; + run_case(an_uncancelled_wait_fires_once); + run_case(a_cancelled_wait_never_fires); + run_case(a_destroyed_timer_never_fires); + run_case(a_restarted_timer_fires_only_its_new_wait); + return webcpp::test::exit_status(boost::report_errors()); +}