From 979374950060fa5ff6f44d3f3054597f6a83a547 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 15:36:01 -0300 Subject: [PATCH 001/116] trystero: the native backend's WebRTC over webcpp::webrtc, without exceptions The backend's peer connection and data channel are now one implementation over webcpp::webrtc for both targets (include/webcpp/trystero/webrtc/), holding webrtc::basic_peer_connection and basic_data_channel over a polymorphic allocator on the app's resource. native/peer_connection.hpp and native/data_channel.hpp, over libdatachannel's C++ API, are gone. trystero's policies stay over it, on the executor: text messages and binaries larger than a room frame are dropped after async_receive, frames no handler has read wait in a FIFO of 64 frames for 10 s, the connection and ICE states are merged, the per-minute window stays the native backend's. The native backend owns a webcpp::webrtc runtime, or uses the program's, and every connection and channel keeps it alive. A URL libdatachannel cannot parse is still left out, as before. The native backend no longer needs exceptions: build.jam names /webcpp/webrtc//webrtc, and native_peer_connection and native_room also run with exception-handling=off. --- build.jam | 18 +- include/webcpp/trystero/config.hpp | 9 +- include/webcpp/trystero/native/backend.hpp | 156 ++++-- .../webcpp/trystero/native/data_channel.hpp | 302 ----------- .../trystero/native/peer_connection.hpp | 384 -------------- .../webcpp/trystero/webrtc/data_channel.hpp | 389 ++++++++++++++ .../trystero/webrtc/peer_connection.hpp | 489 ++++++++++++++++++ test/Jamfile | 36 +- test/native_peer_connection_test.cpp | 325 ++++++++++-- 9 files changed, 1321 insertions(+), 787 deletions(-) delete mode 100644 include/webcpp/trystero/native/data_channel.hpp delete mode 100644 include/webcpp/trystero/native/peer_connection.hpp create mode 100644 include/webcpp/trystero/webrtc/data_channel.hpp create mode 100644 include/webcpp/trystero/webrtc/peer_connection.hpp diff --git a/build.jam b/build.jam index 6bc8db5..86edbc3 100644 --- a/build.jam +++ b/build.jam @@ -10,8 +10,9 @@ project /webcpp/trystero ; -# Only libsecp256k1 is externally installed. Native WebRTC and OpenSSL are -# pinned source dependencies, built together for the consumer's B2 variant. +# Only libsecp256k1 is externally installed. 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 ; import webcpp ; @@ -40,7 +41,8 @@ rule trystero-dependencies ( properties * ) } # The native backend's own dependencies, checked only when a target that -# uses it is built. +# uses it is built: its WebRTC, libdatachannel's through webcpp::webrtc, runs +# on worker threads. rule native-dependencies ( properties * ) { if single in $(properties) @@ -62,12 +64,10 @@ alias trystero : : @trystero-dependencies emscripten:-lembind ; # 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. +# The native backend: its WebRTC is webcpp::webrtc's, which brings the pinned +# libdatachannel and OpenSSL, and works with exceptions on and off, through +# libdatachannel's C API; so does the backend. # tag::native[] alias native : : @native-dependencies - : : trystero /webcpp/third_party//libdatachannel ; + : : trystero /webcpp/webrtc//webrtc ; # end::native[] diff --git a/include/webcpp/trystero/config.hpp b/include/webcpp/trystero/config.hpp index b59fd2f..4a0c1dd 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,10 +24,9 @@ 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, both backends 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. */ diff --git a/include/webcpp/trystero/native/backend.hpp b/include/webcpp/trystero/native/backend.hpp index e8a42c8..6c478bf 100644 --- a/include/webcpp/trystero/native/backend.hpp +++ b/include/webcpp/trystero/native/backend.hpp @@ -12,36 +12,39 @@ #include #include #include -#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 +#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. + * The native target: the backend interface over webcpp::webrtc for WebRTC, natively + * libdatachannel's, 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`. @@ -67,6 +70,13 @@ struct backend_config { */ 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 libdatachannel's threads. A backend given the program's runtime + * does not use it. + */ + ::webcpp::webrtc::runtime_options runtime = {}; + /** What the relays' WebSockets tolerate of a relay that stops reading or answering. */ websocket_limits relay_limits = {}; }; @@ -77,30 +87,48 @@ struct backend_config { * 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. + * OpenSSL allocate stays theirs. + * + * 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. A process holds one runtime at a time, since libdatachannel's state is the process's: + * a program with several native backends at once, or that uses webcpp::webrtc beside trystero, + * makes one runtime and gives it to each. * * @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. + * A backend with a runtime of its own, made with `backend_config::runtime`, 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. + * context or load the system's certificate authorities; without exceptions, Boost's + * `throw_exception`, which the program defines, is called instead. */ 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); - } + : backend(std::move(ex), nullptr, std::move(config)) {} + + /** + * A backend whose peer connections the program's runtime counts. + * + * @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 are made with; its `runtime` is not used. + * @throws std::exception As the other constructor. + */ + backend(boost::asio::any_io_executor ex, ::webcpp::webrtc::runtime& runtime, + backend_config config = {}) + // An empty owner: the pointer does not own the program's runtime. + : backend(std::move(ex), + std::shared_ptr<::webcpp::webrtc::runtime>( + std::shared_ptr<::webcpp::webrtc::runtime>(), &runtime), + std::move(config)) {} /** * The TLS configuration of the relays' connections, for an application with authorities of its @@ -110,6 +138,13 @@ class backend : public trystero::backend::factory { */ boost::asio::ssl::context& tls_context() { 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 Boost.Beast, with @ref connect_websocket. * @@ -126,14 +161,18 @@ class backend : public trystero::backend::factory { } /** - * Makes a peer connection of libdatachannel, bound to `backend_config::bind_address`. + * Makes a peer connection of webcpp::webrtc, bound to `backend_config::bind_address`. + * + * A room has dropped every server WebRTC refuses when it joined; a URL libdatachannel still + * cannot parse, as a `stuns:` one, a scheme it does not know, is left out here, where a + * browser refuses the connection. * * @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. + * `backend_config::max_peer_connections_per_minute` in the last minute, when its runtime holds + * as many connections as it allows, or when libdatachannel refuses to make one. */ std::shared_ptr make_peer_connection( std::span servers, @@ -141,11 +180,13 @@ class backend : public trystero::backend::factory { if (!constructions_.take(now_ms())) { return nullptr; } - try { - return peer_connection::create(ex_, servers, config_.bind_address, memory); - } catch (...) { - return nullptr; + auto made = webrtc::peer_connection::make(runtime_, ex_, servers, config_.bind_address, + *this, memory); + if (!made && made.error() == ::webcpp::webrtc::error::syntax_error) { + made = webrtc::peer_connection::make(runtime_, ex_, parsed(servers, memory), + config_.bind_address, *this, memory); } + return made ? *made : nullptr; } /** @@ -207,14 +248,67 @@ class backend : public trystero::backend::factory { } private: + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + backend(boost::asio::any_io_executor ex, std::shared_ptr<::webcpp::webrtc::runtime> runtime, + backend_config config) + // NOLINTEND(performance-unnecessary-value-param) + : ex_(std::move(ex)), + config_(std::move(config)), + runtime_(runtime ? std::move(runtime) : own_runtime(config_.runtime)), + 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); + } + + /** A runtime of the backend's own, which its connections share with it. */ + static std::shared_ptr<::webcpp::webrtc::runtime> own_runtime( + const ::webcpp::webrtc::runtime_options& options) { + return std::allocate_shared<::webcpp::webrtc::runtime>( + std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), options); + } + + /** + * 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; + } + boost::asio::any_io_executor ex_; backend_config config_; + std::shared_ptr<::webcpp::webrtc::runtime> runtime_; 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/webrtc/data_channel.hpp b/include/webcpp/trystero/webrtc/data_channel.hpp new file mode 100644 index 0000000..4d7ccb0 --- /dev/null +++ b/include/webcpp/trystero/webrtc/data_channel.hpp @@ -0,0 +1,389 @@ +// 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 native and the browser backends make their 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. + * + * 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, and which outlives + * every operation of the channel. + * @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. + static_cast(channel_.send(webcpp::asio::buffer(frame.data(), frame.size()))); + 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: natively + // libdatachannel cuts a longer one to it, so that no message is left in the queue. + 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(); + if (ec == ::webcpp::webrtc::error::message_too_large) { + // The platform dropped a message larger than it accepts: none can be a frame. + receive(); + return; + } + if (ec == webcpp::asio::error::operation_aborted || ec == ::webcpp::webrtc::error::closed) { + return; // closed or destroyed: its close event reports it + } + 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..4daffcf --- /dev/null +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -0,0 +1,489 @@ +// 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 { + +/** + * 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 + 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. + */ + 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, + }; + return connection_type::make(runtime, ex, config, ::webcpp::webrtc::options{}, + 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), + json_(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( + {*kind, 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. + * @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 { + 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* text = object != nullptr ? object->if_contains("candidate") : nullptr; + if (text == nullptr || !text->is_string()) { + post([done = std::move(done)]() mutable { + done(make_error_code(error::backend_failure)); + }); + return; + } + ::webcpp::webrtc::ice_candidate_view candidate{.candidate = text->get_string()}; + if (const auto* mid = object->if_contains("sdpMid"); mid != nullptr && mid->is_string()) { + candidate.sdp_mid = std::string_view(mid->get_string()); + } + if (const auto* index = object->if_contains("sdpMLineIndex"); index != nullptr) { + if (const auto value = index->to_number(parse_error); + !parse_error && value >= 0 && value <= 65535) { + candidate.sdp_m_line_index = static_cast(value); + } + } + if (const auto* fragment = object->if_contains("usernameFragment"); + fragment != nullptr && fragment->is_string()) { + candidate.username_fragment = fragment->get_string(); + } + 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. */ + void on_candidate(const connection_type::ice_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":)"; + if (candidate.sdp_mid.empty()) { + json += "null"; + } else { + protocol::json::append_string(json, candidate.sdp_mid); + } + json += R"(,"sdpMLineIndex":)"; + if (candidate.sdp_m_line_index) { + protocol::json::append_integer(json, *candidate.sdp_m_line_index); + } else { + json += "null"; + } + if (!candidate.username_fragment.empty()) { + json += R"(,"usernameFragment":)"; + protocol::json::append_string(json, candidate.username_fragment); + } + json += '}'; + 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_; + json_resource json_; + 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/test/Jamfile b/test/Jamfile index 849bc69..1098ea3 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -16,22 +16,16 @@ 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. +# The headers that build on both targets, the native backend's and the +# backend's WebRTC over webcpp::webrtc, against libdatachannel and OpenSSL, +# and the browser backend's, 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 + : trystero/native/*.hpp trystero/webrtc/*.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 ; # config.hpp defines WEBCPP_TRYSTERO_NO_EXCEPTIONS exactly when webcpp has no @@ -48,10 +42,8 @@ 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's tests, over webcpp::webrtc's libdatachannel and OpenSSL, run +# natively only. # tag::both-targets[] webcpp.run protocol : protocol_test.cpp : fixtures/expected/expected.json ; webcpp.run room : room_test.cpp ; @@ -83,11 +75,19 @@ webcpp.run native_websocket : native_websocket_test.cpp _GLIBCXX_ASSERTIONS : native ; webcpp.run native_timer : native_timer_test.cpp : /webcpp/trystero//native multi : native ; +# The backend's WebRTC over webcpp::webrtc, and whole rooms over it, as the +# build asks and without exceptions: webcpp::webrtc calls libdatachannel's C +# API, which catches what libdatachannel throws, so the native backend needs +# none. # tag::native[] webcpp.run native_peer_connection : native_peer_connection_test.cpp - : /webcpp/trystero//native multi on : native ; + : /webcpp/trystero//native multi : native ; webcpp.run native_room : native_room_test.cpp - : /webcpp/trystero//native multi on : native ; + : /webcpp/trystero//native multi : native ; +webcpp.run native_peer_connection_no_exceptions : native_peer_connection_test.cpp + : /webcpp/trystero//native multi off : native ; +webcpp.run native_room_no_exceptions : native_room_test.cpp + : /webcpp/trystero//native multi off : native ; # end::native[] # Every allocation of two rooms that exchange a payload goes through the diff --git a/test/native_peer_connection_test.cpp b/test/native_peer_connection_test.cpp index 7f203bc..99c2eed 100644 --- a/test/native_peer_connection_test.cpp +++ b/test/native_peer_connection_test.cpp @@ -4,19 +4,25 @@ // 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. +// Tests the native backend's peer connection, 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 @@ -59,14 +65,19 @@ bool run_until(asio::io_context& io, const std::function& done, 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::native::backend factory{io.get_executor(), runtime, {.bind_address = loopback}}; 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 offerer; + std::shared_ptr answerer; std::shared_ptr offer_end; std::shared_ptr answer_end; std::vector at_offerer, at_answerer; @@ -74,14 +85,44 @@ struct pair { std::vector answerer_states; int 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(std::pmr::memory_resource* channel_memory = nullptr, - const std::optional& channel_executor = {}) { + void connect() { offerer->set_handlers({ .ice_candidate = [this](std::string_view c) { @@ -109,16 +150,8 @@ struct pair { 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"); - } + 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) { @@ -164,8 +197,9 @@ struct pair { } }; -// Observes the native channel's posted callbacks without running them. This lets a test -// install a receiver after a real message is queued and before that message is dispatched. +// 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; @@ -175,6 +209,20 @@ struct queued_tasks { 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; @@ -225,11 +273,33 @@ class queued_executor { } }; +/** A pair whose offerer posts to a queue the test runs, in `memory`. */ struct queued_pair : pair { - std::shared_ptr tasks = std::make_shared(); + 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. */ + ~queued_pair() { + reset(); + tasks->run(); + const std::scoped_lock lock(tasks->mutex); + tasks->ready.clear(); + } - void connect(std::pmr::memory_resource* memory = nullptr) { - pair::connect(memory, asio::any_io_executor(queued_executor(io.get_executor(), tasks))); + void connect() { + pair::connect(); require(BOOST_TEST(until([&] { return offer_open && answer_open; }))); } @@ -243,9 +313,15 @@ struct queued_pair : pair { limit); } + /** Runs the offerer's events until its channel keeps `count` frames for a receiver. */ void receive(std::size_t count) { - require(BOOST_TEST(run_until(io, [&] { return tasks->size() >= count; }))); - tasks->run(); + 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(); } }; @@ -314,9 +390,12 @@ void a_full_pending_queue_drains_in_order_and_uses_replacement_handlers() { } p.receive(64); std::vector received; - // The 65th callback is already queued before set_handlers posts its flush. + // 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({ @@ -455,8 +534,8 @@ class pending_memory : public std::pmr::memory_resource { void pending_frames_and_delivery_use_the_channels_resource() { pending_memory memory; { - queued_pair p; - p.connect(&memory); + queued_pair p(&memory); + p.connect(); 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) { @@ -488,14 +567,25 @@ void pending_frames_and_delivery_use_the_channels_resource() { 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(); }))) { + trystero::native::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; } - BOOST_TEST(*result == trystero::error::backend_failure); + for (const auto& ec : results) { + BOOST_TEST(ec == trystero::error::backend_failure); + } } void the_backend_makes_at_most_its_budget_in_a_minute() { @@ -517,6 +607,162 @@ void the_backend_makes_at_most_its_budget_in_a_minute() { 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::native::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::native::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) { + return boost::json::serialize(boost::json::object{ + {"candidate", c.candidate}, + {"sdpMid", c.sdp_mid}, + {"sdpMLineIndex", c.sdp_m_line_index.value_or(0)}, + }); +} + +// 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() { + webcpp::webrtc::runtime runtime; + asio::io_context io; + trystero::native::backend factory(io.get_executor(), runtime, {.bind_address = loopback}); + const auto local = factory.make_peer_connection({}, std::pmr::get_default_resource()); + 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())); + webcpp::webrtc::peer_connection& remote = *made; + + // Candidates wait until the side they go to has both descriptions. + bool negotiated = false; + std::vector to_remote; + std::vector to_local; + const auto add_to_remote = [&remote](std::string_view json) { + const auto v = boost::json::parse(json).as_object(); + const std::string_view text = v.at("candidate").as_string(); + const std::string_view mid = v.at("sdpMid").as_string(); + remote.async_add_ice_candidate({.candidate = text, .sdp_mid = mid}, + [](webcpp::webrtc::detail::error_code) {}); + }; + local->set_handlers({ + .ice_candidate = + [&](std::string_view json) { + if (negotiated) { + add_to_remote(json); + } else { + to_remote.emplace_back(json); + } + }, + .data_channel = {}, + .state = {}, + }); + std::function trickle = [&] { + remote.async_wait_ice_candidate( + [&](webcpp::webrtc::detail::error_code ec, const webcpp::webrtc::ice_candidate& c) { + if (ec || c.candidate.empty()) { + return; + } + if (negotiated) { + local->add_ice_candidate(json_of(c), [](backend::error_code) {}); + } else { + to_local.push_back(json_of(c)); + } + trickle(); + }); + }; + trickle(); + std::optional sender; + remote.async_accept_data_channel( + [&](webcpp::webrtc::detail::error_code ec, webcpp::webrtc::data_channel c) { + if (!ec) { + sender.emplace(std::move(c)); + } + }); + const auto channel = local->create_data_channel("data"); + require(BOOST_TEST(channel != nullptr)); + std::vector received; + channel->set_handlers({ + .open = {}, + .message = [&](backend::bytes frame) { received.push_back(std::move(frame)); }, + .close = {}, + .buffered_amount_low = {}, + }); + local->set_local_description( + [&](backend::error_code ec, std::string_view, std::string_view offer) { + require(BOOST_TEST(!ec)); + remote.async_set_remote_description( + {.type = webcpp::webrtc::sdp_type::offer, .sdp = offer}, + [&](webcpp::webrtc::detail::error_code ec) { + require(BOOST_TEST(!ec)); + remote.async_set_local_description( + [&](webcpp::webrtc::detail::error_code ec, + const webcpp::webrtc::session_description& answer) { + require(BOOST_TEST(!ec)); + local->set_remote_description( + "answer", answer.sdp, [&](backend::error_code ec) { + require(BOOST_TEST(!ec)); + 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) {}); + } + }); + }); + }); + }); + require(BOOST_TEST(run_until(io, [&] { + return channel->is_open() && sender && + sender->ready_state() == webcpp::webrtc::data_channel_state::open; + }))); + const std::vector before{1, 2, 3}; + const std::vector after{4, 5}; + BOOST_TEST(!sender->send(asio::buffer(before))); + BOOST_TEST(!sender->send_text("1e300")); + BOOST_TEST(!sender->send(asio::buffer(after))); + require(BOOST_TEST(run_until(io, [&] { return received.size() == 2; }))); + BOOST_TEST_ALL_EQ(received[0].begin(), received[0].end(), before.begin(), before.end()); + BOOST_TEST_ALL_EQ(received[1].begin(), received[1].end(), after.begin(), after.end()); + // Nothing more arrives: the text was dropped, not delivered late. + run_until(io, [] { return false; }, 200ms); + BOOST_TEST_EQ(received.size(), 2U); + sender.reset(); + remote.close(); +} + } // namespace int main() { @@ -529,6 +775,9 @@ int main() { 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(); + 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(); } From 6a39d7705b0a1ca852d453e884c74efdc715190d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 15:54:12 -0300 Subject: [PATCH 002/116] trystero: the browser backend's WebRTC over webcpp::webrtc, on webcpp::asio The browser backend's peer connection and data channel, and its census of the page's connections, are gone: it makes the same connection over webcpp::webrtc as the native backend, whose browser runtime counts the page's connections against browser::backend::max_peer_connections (256), now runtime_options::max_peer_connections of the runtime it owns. webcpp::webrtc's browser objects deliver through webcpp::asio's bridge, a service of their executor's io_context, so trystero names Asio as webcpp::asio throughout what builds on emscripten: natively it is Boost.Asio itself, unchanged; on emscripten it is webcpp::asio's backend, which browser::event_loop polls as before. /webcpp/trystero//trystero brings /webcpp/asio//asio, and /webcpp/webrtc//webrtc on emscripten, instead of BOOST_ASIO_DISABLE_THREADS: a program on emscripten is built in webcpp::asio's two suspension variants, jspi and asyncify. The tests whose main runs the io_context end with webcpp::test::exit_status, which a main that suspended under Asyncify needs; the allocation test counts Asyncify's unwind data apart, as webcpp::asio's own allocation test does. browser_peer_connection and browser_data_channel test the backend's WebRTC over webcpp::webrtc's browser objects, with a page's RTCPeerConnection of their own under node. The chat site copies the program webcpp::asio names after its variant as chat-program.js. The interop native peer and the native example no longer ask for exceptions. --- build.jam | 20 +- example/Jamfile | 4 +- example/chat/Jamfile | 13 +- example/chat/chat.cpp | 5 +- example/quick_start.cpp | 12 +- include/webcpp/trystero/app.hpp | 5 +- include/webcpp/trystero/browser/backend.hpp | 456 ++---------------- .../webcpp/trystero/browser/event_loop.hpp | 49 +- include/webcpp/trystero/browser/js.hpp | 9 - include/webcpp/trystero/browser/src.hpp | 24 - include/webcpp/trystero/detail/app_impl.hpp | 5 +- include/webcpp/trystero/detail/post.hpp | 22 +- include/webcpp/trystero/room.hpp | 90 ++-- .../webcpp/trystero/webrtc/data_channel.hpp | 20 +- meta/include-boundaries.json | 4 +- test/Jamfile | 6 +- test/allocation_test.cpp | 92 +++- test/app_impl_test.cpp | 9 +- test/browser_data_channel_test.cpp | 57 ++- test/browser_event_loop_test.cpp | 15 +- test/browser_peer_connection_test.cpp | 58 ++- test/browser_sealer_test.cpp | 5 +- test/browser_websocket_bound_test.cpp | 5 +- test/browser_websocket_late_events_test.cpp | 5 +- test/browser_websocket_test.cpp | 5 +- test/connection_test.cpp | 9 +- test/memory_backend_test.cpp | 9 +- test/oracle/Jamfile | 11 +- test/oracle/interop/peer.cpp | 5 +- test/room_test.cpp | 17 +- test/shared_test.cpp | 7 +- test/support/memory_backend.hpp | 53 +- test/support/rooms.hpp | 7 +- 33 files changed, 418 insertions(+), 695 deletions(-) diff --git a/build.jam b/build.jam index 86edbc3..0e39364 100644 --- a/build.jam +++ b/build.jam @@ -6,7 +6,8 @@ # # 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. +# /webcpp/trystero//native for the native backend. Both backends' WebRTC is +# webcpp::webrtc's. project /webcpp/trystero ; @@ -51,16 +52,19 @@ rule native-dependencies ( properties * ) } } -# 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. +# Asio is webcpp::asio: natively Boost.Asio itself, on emscripten the shipped +# backend, without threads (the event loop drives it), whose browser runtime +# webcpp::webrtc's browser objects deliver through. On emscripten the browser +# backend's WebRTC is webcpp::webrtc's, and the 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. # tag::trystero[] alias trystero : : @trystero-dependencies : : include /boost//headers /webcpp//boost_json - /webcpp/config//config secp256k1 - emscripten:BOOST_ASIO_DISABLE_THREADS + /webcpp/config//config /webcpp/asio//asio secp256k1 + emscripten:/webcpp/webrtc//webrtc emscripten:-lembind ; # end::trystero[] diff --git a/example/Jamfile b/example/Jamfile index 3b5593f..fed3412 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -14,11 +14,9 @@ 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 ; + : /webcpp/trystero//native multi : native ; # end::native[] # tag::browser[] webcpp.link quick_start : quick_start.cpp diff --git a/example/chat/Jamfile b/example/chat/Jamfile index 64209e6..7efaeb8 100644 --- a/example/chat/Jamfile +++ b/example/chat/Jamfile @@ -35,15 +35,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..f60fee1 100644 --- a/example/chat/chat.cpp +++ b/example/chat/chat.cpp @@ -11,9 +11,10 @@ #include #include // once per program: the JavaScript export +#include + #include #include -#include #include #include @@ -25,7 +26,7 @@ namespace { // tag::state[] struct chat { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; trystero::browser::backend backend{loop}; std::unique_ptr app; // made at the first join, with that join's app id diff --git a/example/quick_start.cpp b/example/quick_start.cpp index 867e988..7fa057b 100644 --- a/example/quick_start.cpp +++ b/example/quick_start.cpp @@ -13,18 +13,18 @@ #include #include // once per program -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include #include -namespace asio = boost::asio; +namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; // end::includes[] diff --git a/include/webcpp/trystero/app.hpp b/include/webcpp/trystero/app.hpp index 9b98060..47bfae4 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. */ diff --git a/include/webcpp/trystero/browser/backend.hpp b/include/webcpp/trystero/browser/backend.hpp index 73ecfcc..1d55e23 100644 --- a/include/webcpp/trystero/browser/backend.hpp +++ b/include/webcpp/trystero/browser/backend.hpp @@ -17,11 +17,16 @@ #include #include #include +#include + +#include +#include + +#include // lint-world: binds an allocator only +#include // lint-world: posts handlers only #include -#include // lint-world: getentropy, the page's entropy -#include // lint-world: binds an allocator only -#include // lint-world: posts handlers only +#include // lint-world: getentropy, the page's entropy #include #include @@ -33,9 +38,10 @@ #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. + * The browser target: the backend interface over the page's own `WebSocket`, `setTimeout` and + * `crypto.subtle`, through `emscripten::val`, and over its `RTCPeerConnection` and + * `RTCDataChannel` through webcpp::webrtc. 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` @@ -69,9 +75,9 @@ inline backend::bytes from_js(const val& buffer, std::pmr::memory_resource* memo */ 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))); + webcpp::asio::post(loop.io(), + webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), + std::forward(f))); loop.schedule_poll(); } @@ -312,394 +318,6 @@ class websocket : public backend::websocket { 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. @@ -907,17 +525,12 @@ class sealer : public backend::sealer, public std::enable_shared_from_this( + std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), + ::webcpp::webrtc::runtime_options{.max_peer_connections = max_peer_connections, + .thread_pool_size = 0})) {} + /** * Opens a WebSocket to a relay, with the page's `WebSocket`. * @@ -943,22 +569,21 @@ class backend : public trystero::backend::factory { } /** - * Makes a peer connection, with the page's `RTCPeerConnection`. + * Makes a peer connection of webcpp::webrtc, over 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. + * browser refuses to make one: it throws for a server it cannot use, and when the page holds as + * many connections as it allows. */ 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); + auto made = webrtc::peer_connection::make(runtime_, loop_.get_executor(), servers, {}, + *this, memory); + return made ? *made : nullptr; } /** @@ -1019,6 +644,7 @@ class backend : public trystero::backend::factory { private: event_loop& loop_; + std::shared_ptr<::webcpp::webrtc::runtime> runtime_; }; } // namespace webcpp::trystero::browser diff --git a/include/webcpp/trystero/browser/event_loop.hpp b/include/webcpp/trystero/browser/event_loop.hpp index a376430..2482502 100644 --- a/include/webcpp/trystero/browser/event_loop.hpp +++ b/include/webcpp/trystero/browser/event_loop.hpp @@ -12,12 +12,13 @@ #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 // 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 @@ -40,7 +41,7 @@ class event_loop; * * 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`. + * in the browser is constructed with it, through `webcpp::asio::any_io_executor`. * * @see "The browser backend", in the guide. */ @@ -58,16 +59,16 @@ class executor { * * @return The loop's io_context. */ - [[nodiscard]] boost::asio::execution_context& query( - boost::asio::execution::context_t /*context*/) const noexcept; + [[nodiscard]] webcpp::asio::execution_context& query( + webcpp::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 { + static constexpr webcpp::asio::execution::blocking_t::never_t query( + webcpp::asio::execution::blocking_t /*blocking*/) noexcept { return {}; } @@ -77,7 +78,7 @@ class executor { * @return A copy of this executor. */ [[nodiscard]] executor require( - boost::asio::execution::blocking_t::never_t /*never*/) const noexcept { + webcpp::asio::execution::blocking_t::never_t /*never*/) const noexcept { return executor(*loop_); } @@ -145,10 +146,10 @@ class event_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, + explicit event_loop(webcpp::asio::io_context& io, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) : io_(io), - work_(boost::asio::make_work_guard(io)), + work_(webcpp::asio::make_work_guard(io)), token_(emscripten::val::object()), decoder_(emscripten::val::global("TextDecoder").new_()), encoder_(emscripten::val::global("TextEncoder").new_()), @@ -228,7 +229,7 @@ class event_loop { * * @return The io_context it was constructed with. */ - boost::asio::io_context& io() noexcept { return io_; } + webcpp::asio::io_context& io() noexcept { return io_; } /** * An executor of this loop, what a room in the browser is constructed with. @@ -325,11 +326,11 @@ class event_loop { } 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)); - })); + webcpp::asio::post(io_, webcpp::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)); } @@ -390,8 +391,8 @@ class event_loop { static constexpr int poll_id = 0; - boost::asio::io_context& io_; - boost::asio::executor_work_guard work_; + webcpp::asio::io_context& io_; + webcpp::asio::executor_work_guard work_; emscripten::val token_; emscripten::val decoder_; emscripten::val encoder_; @@ -401,14 +402,14 @@ class event_loop { bool poll_scheduled_ = false; }; -inline boost::asio::execution_context& executor::query( - boost::asio::execution::context_t /*context*/) const noexcept { +inline webcpp::asio::execution_context& executor::query( + webcpp::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)); + webcpp::asio::post(loop_->io(), std::forward(f)); loop_->schedule_poll(); } diff --git a/include/webcpp/trystero/browser/js.hpp b/include/webcpp/trystero/browser/js.hpp index c7d11c8..096d1d8 100644 --- a/include/webcpp/trystero/browser/js.hpp +++ b/include/webcpp/trystero/browser/js.hpp @@ -41,15 +41,6 @@ emscripten::EM_VAL webcpp_trystero_js_try(emscripten::EM_VAL target, emscripten: */ 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 { diff --git a/include/webcpp/trystero/browser/src.hpp b/include/webcpp/trystero/browser/src.hpp index e7326d2..1d7eaa9 100644 --- a/include/webcpp/trystero/browser/src.hpp +++ b/include/webcpp/trystero/browser/src.hpp @@ -64,30 +64,6 @@ EM_JS(emscripten::EM_VAL, webcpp_trystero_js_handler, }); }); -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 diff --git a/include/webcpp/trystero/detail/app_impl.hpp b/include/webcpp/trystero/detail/app_impl.hpp index f59e6d2..d6df7e2 100644 --- a/include/webcpp/trystero/detail/app_impl.hpp +++ b/include/webcpp/trystero/detail/app_impl.hpp @@ -21,7 +21,8 @@ #include #include -#include // lint-world: names the executor only +#include // lint-world: names the executor only + #include #include @@ -81,7 +82,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. */ 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/room.hpp b/include/webcpp/trystero/room.hpp index 9c2f8a9..f886d85 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -29,13 +29,14 @@ #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 @@ -408,17 +409,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,7 +444,7 @@ 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; @@ -841,8 +842,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 +851,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 +864,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 +887,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; } @@ -1546,7 +1547,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; @@ -1705,8 +1706,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 +1730,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))); @@ -1820,7 +1821,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( @@ -1859,30 +1860,31 @@ 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)); - }))); + webcpp::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)); + }))); }, token); } diff --git a/include/webcpp/trystero/webrtc/data_channel.hpp b/include/webcpp/trystero/webrtc/data_channel.hpp index 4d7ccb0..45fc0b9 100644 --- a/include/webcpp/trystero/webrtc/data_channel.hpp +++ b/include/webcpp/trystero/webrtc/data_channel.hpp @@ -59,7 +59,9 @@ using allocator_type = std::pmr::polymorphic_allocator; * 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. + * 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. @@ -233,8 +235,9 @@ class data_channel : public backend::data_channel, /** 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: natively - // libdatachannel cuts a longer one to it, so that no message is left in the queue. + // 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_, @@ -248,14 +251,13 @@ class data_channel : public backend::data_channel, void on_received(boost::system::error_code ec, bool text) { buffer_.reset(); - if (ec == ::webcpp::webrtc::error::message_too_large) { - // The platform dropped a message larger than it accepts: none can be a frame. - receive(); + // 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 == webcpp::asio::error::operation_aborted || ec == ::webcpp::webrtc::error::closed) { - return; // closed or destroyed: its close event reports it - } if (ec) { // A message no buffer can take stays queued, and the platform's failure stays too: the // channel cannot go on. diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 32fe954..9b5632c 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -10,11 +10,13 @@ "must-not-include": [ "webcpp/trystero/native", "webcpp/trystero/browser", + "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 backends' WebRTC (webcpp::webrtc, natively libdatachannel), OpenSSL or Emscripten" } ] } diff --git a/test/Jamfile b/test/Jamfile index 1098ea3..5ae5ef9 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -18,9 +18,9 @@ webcpp.targets native emscripten ; # The headers that build on both targets, the native backend's and the # backend's WebRTC over webcpp::webrtc, against libdatachannel and OpenSSL, -# and the browser backend's, on emscripten. Every one compiles with -# exceptions and without them, as the build asks, so the lint analyses them -# so too. +# and the browser backend's, on emscripten, which includes that WebRTC there. +# 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 diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 57f3ddb..951a4f6 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -15,14 +15,16 @@ #include "require.hpp" #include "support/memory_backend.hpp" -#include -#include -#include -#include +#include +#include +#include +#include + #include #include #include #include +#include #include #include @@ -44,6 +46,7 @@ #include #endif #ifdef __EMSCRIPTEN__ +#include #include #include #include @@ -72,6 +75,15 @@ bool counting = false; // counts nothing: that allocation is operator new's, counted once. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool inside_operator_new = false; +// 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) +unsigned char 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; #ifdef _MSC_VER /** Whether the calling thread is the one the test counts on: MSVC counts every thread. */ @@ -144,7 +156,7 @@ namespace { void* counted(void* pointer) { if (on_counted_thread() && counting && !inside_operator_new) { - ++c_allocations; + ++(inside_runtime != 0 ? runtime_allocations : c_allocations); } return pointer; } @@ -389,7 +401,7 @@ class counting_resource final : public std::pmr::memory_resource { /** 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) { +bool run_until(webcpp::asio::io_context& io, Predicate done) { for (int slice = 0; slice < 500 && !done(); ++slice) { io.restart(); io.run_for(std::chrono::milliseconds(10)); // lint-run: the memory relays post to it @@ -466,7 +478,7 @@ void exchange_allocates_through_the_rooms_resources(Make make) { // 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. @@ -496,8 +508,8 @@ void exchange_allocates_through_the_rooms_resources(Make make) { [&](const Payload& /*payload*/, const trystero::message_info& /*info*/) { ++received; }); 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*/) {})); + 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. @@ -525,7 +537,7 @@ void exchange_allocates_through_the_rooms_resources(Make make) { } /** Runs io for about `milliseconds`, whatever happens. */ -void run_for(boost::asio::io_context& io, int milliseconds) { +void run_for(webcpp::asio::io_context& io, int milliseconds) { for (int slice = 0; slice < milliseconds / 10; ++slice) { io.restart(); io.run_for(std::chrono::milliseconds(10)); // lint-run: the memory relays post to it @@ -537,16 +549,16 @@ 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; +void warm(webcpp::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))); + 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, [] {}); + webcpp::asio::post(io, [] {}); run_for(io, 20); } @@ -590,7 +602,7 @@ 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); @@ -633,16 +645,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 +665,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"); @@ -708,7 +721,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,16 +754,16 @@ 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 } @@ -804,8 +817,37 @@ void operator delete(void* pointer, std::size_t /*size*/, std::align_val_t /*ali release(pointer); } +/** + * 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 __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 +} + int main() { count_this_thread(); + mark_the_runtime_allocations(); #if defined(WEBCPP_TEST_TRYSTERO_COUNTS_C_ALLOCATIONS) && defined(__APPLE__) && \ !defined(__EMSCRIPTEN__) malloc_logger = &count_c_allocation; @@ -827,5 +869,5 @@ int main() { }); a_room_allocates_through_its_resource_from_join_to_destruction(); rooms_of_one_app_allocate_through_their_resources(); - return boost::report_errors(); + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/app_impl_test.cpp b/test/app_impl_test.cpp index ac32574..a154081 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 @@ -35,7 +37,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; @@ -692,5 +694,6 @@ int main() { 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(); + // 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/browser_data_channel_test.cpp b/test/browser_data_channel_test.cpp index a39dc47..2e811f7 100644 --- a/test/browser_data_channel_test.cpp +++ b/test/browser_data_channel_test.cpp @@ -4,11 +4,12 @@ // 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. +// Tests the browser backend's data channels, 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 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. @@ -16,14 +17,18 @@ #include #include // once per program: the JavaScript export +#include + +#include #include -#include #include #include #include #include +#include "require.hpp" + namespace trystero = webcpp::trystero; using emscripten::val; @@ -50,11 +55,12 @@ class watching_resource final : public std::pmr::memory_resource { }; struct state { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; + trystero::browser::backend backend{loop}; watching_resource memory; - val channel = val::object(); - std::shared_ptr wrapper; + std::shared_ptr connection; + std::shared_ptr wrapper; int messages = 0; std::size_t last_size = 0; val deadline = val::undefined(); @@ -73,15 +79,40 @@ void set_exit_code(int code) { void deliver(const val& data) { val event = val::object(); event.set("data", data); - val::global("setTimeout")(the_state().channel["onmessage"], val(0), event); + val::global("setTimeout")(val::global("lastChannel")["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); + // 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 = @@ -91,7 +122,7 @@ int main() { 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}); + BOOST_TEST_LE(s.memory.largest, std::size_t{20'000}); val::global("clearTimeout")(s.deadline); set_exit_code(boost::report_errors()); }, diff --git a/test/browser_event_loop_test.cpp b/test/browser_event_loop_test.cpp index 1cfa284..ed99fac 100644 --- a/test/browser_event_loop_test.cpp +++ b/test/browser_event_loop_test.cpp @@ -27,11 +27,12 @@ #include #include // once per program: the JavaScript exports +#include +#include // lint-world: posts handlers only + #include #include #include -#include -#include // lint-world: posts handlers only #include #include @@ -50,7 +51,7 @@ namespace { constexpr int escapes = 3000; struct state { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; val deadline = val::undefined(); std::uintptr_t stack_before = 0; @@ -106,7 +107,7 @@ void cpp_escapes_free_their_exceptions() { return; } s.heap_after = in_use; - boost::asio::post(s.loop.get_executor(), [] { + webcpp::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); @@ -166,7 +167,7 @@ void nested_recovery() { BOOST_TEST_EQ(loop.depth(), 1); loop.recover(loop.depth()); BOOST_TEST_EQ(loop.depth(), 1); - boost::asio::post(loop.get_executor(), [] { + webcpp::asio::post(loop.get_executor(), [] { BOOST_TEST_EQ(the_state().loop.depth(), 1); // the poll that runs it after_nested_recovery(); }); @@ -200,7 +201,7 @@ void many_escapes() { } s.stack_after = emscripten_stack_get_current(); ++s.served_after; - boost::asio::post(s.loop.get_executor(), [] { + webcpp::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); @@ -238,7 +239,7 @@ 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); + webcpp::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*/) { diff --git a/test/browser_peer_connection_test.cpp b/test/browser_peer_connection_test.cpp index 64f54a0..36a376e 100644 --- a/test/browser_peer_connection_test.cpp +++ b/test/browser_peer_connection_test.cpp @@ -4,26 +4,29 @@ // 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. +// Tests the browser backend's peer connections, 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 `backend::max_peer_connections` of them, counted from their construction +// The page holds at most `backend::max_peer_connections` of them, 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. // -// 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. +// main runs the checks that need no event, and starts the collection; the verdict comes once the +// census counts a connection less, which a timer looks for, 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 @@ -36,7 +39,7 @@ using emscripten::val; namespace { struct state { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; trystero::browser::backend backend{loop}; val deadline = val::undefined(); @@ -48,8 +51,11 @@ state& the_state() { return s; } -val census() { - return val::take_ownership(webcpp_trystero_js_census()); +/** The connections webcpp::webrtc's census of the page counts. */ +double held() { + const val census = val::global( + "globalThis")[val::global("Symbol").call("for", val("webcpp.webrtc.census"))]; + return census.isUndefined() ? 0 : census["held"].as(); } /** Calls `setTimeout` with a function that runs `f` through the loop, as the page's events do. */ @@ -63,10 +69,15 @@ 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) { +/** Once a collection released a connection, the backend makes one again; until then, it looks + * again a little later. */ +void on_release(int /*slot*/, const val& /*event*/) { auto& s = the_state(); - if (s.done || held.as() >= trystero::browser::backend::max_peer_connections) { + if (s.done) { + return; + } + if (held() >= trystero::browser::backend::max_peer_connections) { + after(10, on_release); return; } s.done = true; @@ -91,11 +102,17 @@ int main() { }; }); BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); - BOOST_TEST_EQ(census()["held"].as(), 0); + 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() {} }; @@ -123,16 +140,17 @@ int main() { pc->close(); } } - BOOST_TEST_EQ(census()["held"].as(), static_cast(budget)); + BOOST_TEST_EQ(held(), 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)); + // A collection frees them: node's gc, exposed for this test, from an event after this one; + // the census counts the release once the FinalizationRegistry has seen it. after(0, [](int /*slot*/, const val& /*event*/) { EM_ASM({ require('v8').setFlagsFromString('--expose-gc'); require('vm').runInNewContext('gc')(); }); + after(10, on_release); }); s.deadline = after(10'000, [](int /*slot*/, const val& /*event*/) { BOOST_ERROR("no collection released a connection"); diff --git a/test/browser_sealer_test.cpp b/test/browser_sealer_test.cpp index 73a242e..0e8e8d3 100644 --- a/test/browser_sealer_test.cpp +++ b/test/browser_sealer_test.cpp @@ -17,8 +17,9 @@ #include #include // once per program: the JavaScript exports +#include + #include -#include #include #include @@ -42,7 +43,7 @@ struct outcome { }; struct state { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; trystero::browser::backend backend{loop}; std::shared_ptr sealer; diff --git a/test/browser_websocket_bound_test.cpp b/test/browser_websocket_bound_test.cpp index e96ca68..e6e5f83 100644 --- a/test/browser_websocket_bound_test.cpp +++ b/test/browser_websocket_bound_test.cpp @@ -17,9 +17,10 @@ #include // once per program: the JavaScript exports #include +#include + #include #include -#include #include #include @@ -64,7 +65,7 @@ namespace { constexpr int texts = 100; struct state { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; trystero::browser::backend backend{loop}; std::shared_ptr socket; diff --git a/test/browser_websocket_late_events_test.cpp b/test/browser_websocket_late_events_test.cpp index f8218c6..0a3aacc 100644 --- a/test/browser_websocket_late_events_test.cpp +++ b/test/browser_websocket_late_events_test.cpp @@ -20,9 +20,10 @@ #include // once per program: the JavaScript exports #include +#include + #include #include -#include #include #include @@ -71,7 +72,7 @@ EM_JS(void, install_late_websocket, (), { namespace { struct state { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; trystero::browser::backend backend{loop}; std::shared_ptr stalled; diff --git a/test/browser_websocket_test.cpp b/test/browser_websocket_test.cpp index 43d1033..65228af 100644 --- a/test/browser_websocket_test.cpp +++ b/test/browser_websocket_test.cpp @@ -19,8 +19,9 @@ #include #include // once per program: the JavaScript exports +#include + #include -#include #include #include @@ -45,7 +46,7 @@ constexpr std::array urls{ }; struct state { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; trystero::browser::backend backend{loop}; std::array, urls.size()> sockets; diff --git a/test/connection_test.cpp b/test/connection_test.cpp index 1928971..b175685 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; @@ -855,5 +857,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/memory_backend_test.cpp b/test/memory_backend_test.cpp index f76997a..580146c 100644 --- a/test/memory_backend_test.cpp +++ b/test/memory_backend_test.cpp @@ -10,8 +10,10 @@ #include "support/memory_backend.hpp" -#include +#include + #include +#include #include #include @@ -24,7 +26,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; @@ -543,5 +545,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/oracle/Jamfile b/test/oracle/Jamfile index f081437..d4eac81 100644 --- a/test/oracle/Jamfile +++ b/test/oracle/Jamfile @@ -19,11 +19,10 @@ webcpp.lane oracle : 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 webcpp::webrtc. 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. @@ -32,7 +31,7 @@ webcpp.drive interop_browser : interop/peer.cpp : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH 2400 : interop/run.mjs : --browser : emscripten ; webcpp.drive interop_native : interop/native_peer.cpp - : /webcpp/trystero//native multi on 2400 + : /webcpp/trystero//native multi 2400 _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS : interop/run.mjs : --native : native ; diff --git a/test/oracle/interop/peer.cpp b/test/oracle/interop/peer.cpp index fc90aeb..e501ab8 100644 --- a/test/oracle/interop/peer.cpp +++ b/test/oracle/interop/peer.cpp @@ -26,9 +26,10 @@ #include #include // once per program: the JavaScript export +#include + #include #include -#include #include #include @@ -56,7 +57,7 @@ struct extra_room { /** Everything the page keeps alive: the io_context, the event loop, the backend, the app, the room * and its actions. */ struct page { - boost::asio::io_context io; + webcpp::asio::io_context io; trystero::browser::event_loop loop{io}; trystero::browser::backend backend{loop}; std::unique_ptr app; diff --git a/test/room_test.cpp b/test/room_test.cpp index 2a733f5..b075472 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -11,14 +11,16 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include + #include #include #include +#include #include #include @@ -40,7 +42,7 @@ #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; @@ -1426,5 +1428,6 @@ int main() { 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(); + // 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..d92b262 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 @@ -2009,5 +2011,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/support/memory_backend.hpp b/test/support/memory_backend.hpp index e95a103..af95e65 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -16,10 +16,11 @@ #include #include -#include -#include -#include -#include +#include +#include +#include +#include + #include #include @@ -62,9 +63,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; @@ -86,8 +87,8 @@ struct virtual_clock_state { 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, - std::weak_ptr clock = {}) + memory_timer(webcpp::asio::io_context& io, std::pmr::memory_resource* memory, + int time_scale = 1, std::weak_ptr clock = {}) : io_(io), timer_(io), memory_(memory), @@ -116,7 +117,7 @@ class memory_timer : public backend::timer { } const std::uint64_t wait = ++*waits_; timer_.expires_after(delay / time_scale_); - 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 { @@ -156,8 +157,8 @@ 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_; @@ -214,7 +215,7 @@ 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) {} @@ -279,7 +280,7 @@ 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_; @@ -416,7 +417,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 +483,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 +506,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 +630,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 +656,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), @@ -751,7 +752,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(); } @@ -843,7 +844,7 @@ class memory_network : public backend::factory { /** Whether a timer of the virtual clock is due at or before `until_ms`. */ [[nodiscard]] bool due_by(double until_ms) 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_; @@ -981,9 +982,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) { @@ -1155,7 +1156,7 @@ 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(webcpp::asio::io_context& io, std::array key, std::pmr::memory_resource* memory) : io_(io), key_(key), memory_(memory) {} @@ -1185,7 +1186,7 @@ class memory_sealer : public backend::sealer { } private: - boost::asio::io_context& io_; + webcpp::asio::io_context& io_; std::array key_; std::pmr::memory_resource* memory_; }; diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp index a50a783..07645f4 100644 --- a/test/support/rooms.hpp +++ b/test/support/rooms.hpp @@ -17,7 +17,8 @@ #include #include -#include +#include + #include #include #include @@ -75,7 +76,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 +89,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. */ From 0d9e5ed40360469aab61910cd1bccdc426a00c8d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 16:04:53 -0300 Subject: [PATCH 003/116] trystero: webcpp::webrtc in the documentation, the changelog and the metadata The page's backends, design, building, allocation and testing say what the backends' WebRTC is now: webcpp::webrtc's, on both targets, with trystero's policies over it (the merged states, the dropped texts and oversized binaries, the 64 frames and 10 s, the per-minute window, the runtime's cap), and no exception asked for natively. The Unreleased lines name what a user sees; meta/libraries.json, which has no field for a dependency, names webcpp::webrtc in its description; AGENTS.md records the backend interface kept for the memory relays, webcpp::asio on emscripten and the runtime. --- AGENTS.md | 184 ++++++++++++++++++---------- README.md | 58 +++++---- doc/Jamfile | 5 +- doc/acknowledgements.adoc | 3 +- doc/allocation.adoc | 40 ++++-- doc/browser.adoc | 57 ++++++--- doc/building.adoc | 40 +++--- doc/changelog.adoc | 14 +++ doc/design.adoc | 104 +++++++++++++--- doc/differences.adoc | 5 +- doc/native.adoc | 111 +++++++++-------- doc/overview.adoc | 29 +++-- doc/quick-start.adoc | 4 +- doc/roadmap.adoc | 3 +- doc/testing.adoc | 38 +++--- doc/usage.adoc | 7 +- meta/libraries.json | 2 +- test/CONVERSION.md | 7 ++ test/oracle/interop/native_peer.cpp | 2 +- 19 files changed, 470 insertions(+), 243 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0d31605..29d2d1f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,35 +22,56 @@ holds only what is specific to trystero. and the examples' app ids `webcpp-trystero-quick-start` and `webcpp-trystero-chat`. `LICENSE-TRYSTERO.txt` is Trystero's notice, unchanged, and the README names what derives from Trystero. -- **The core and the two backends.** ``, the headers +- **The core and the backends.** ``, 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 backends, of the + backend's WebRTC and webcpp::webrtc, of libdatachannel, OpenSSL and + Emscripten, and the lint fails an include that crosses it. `webrtc/` is the + backend's WebRTC, over webcpp::webrtc, on both targets: one peer + connection and one data channel that both backends make, 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. `browser/` is the browser backend, over the + page's WebSocket, timers and Web Crypto 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 Boost.Beast and OpenSSL, which builds only natively. + `test/Jamfile` compiles each header alone on the targets that build it, in + three calls; `webrtc/` natively, and on emscripten through + `browser/backend.hpp`. +- **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 native 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. +- **Exceptions.** trystero's WebRTC is webcpp::webrtc's, which natively calls + libdatachannel's C API, where no exception crosses: every part of trystero, + both backends included, works with exceptions and without them, and no + program or test asks for `on`. `native_peer_connection` + and `native_room` also run with `exception-handling=off`, as the evidence. + trystero raises nothing of its own; a raise would go through + `boost::throw_exception`, as the native backend's TLS context does when + OpenSSL cannot make it. +- **webcpp::asio.** trystero names Asio as `webcpp::asio` wherever it builds + on emscripten (the core, the browser 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 native backend + keeps Boost.Asio's names, which Boost.Beast takes. `/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 (`quick_start-60-d-jspi.js`), and the suites run in both. + `browser::event_loop` polls the `io_context` as before and never runs it, + but a test whose `main` runs it, as the tests over the memory relays do, + suspends there under Asyncify, which loses what a `main` that suspended + returns: those end with `webcpp::test::exit_status`. - **The dependencies.** libsecp256k1 (every room) remains an external installation, found through `webcpp.external` and `webcpp.external-found` at `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=`, then @@ -58,7 +79,9 @@ holds only what is specific to trystero. fallback outside Windows is allowed only for this dependency. A missing installation leaves trystero out unless `webcpp-require-external=on`. MSVC links its static `libsecp256k1.lib` with `SECP256K1_STATIC`. - The native backend instead names `/webcpp/third_party//libdatachannel`, + Both backends' WebRTC is webcpp::webrtc's, `/webcpp/webrtc//webrtc`, which + `/webcpp/trystero//native` names, and `/webcpp/trystero//trystero` on + emscripten; 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 @@ -75,17 +98,38 @@ holds only what is specific to trystero. 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; +- **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. `native::backend` makes one of its own + (`backend_config::runtime`, 256 connections) or takes the program's + (`backend(ex, runtime, config)`), 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. + `browser::backend` owns one capped at `max_peer_connections` (256); + webcpp::webrtc's census of the page counts every runtime's connections. +- **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, as before; in the browser a refused server refuses the connection. + The per-minute window stays `native::backend`'s. +- **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. `native_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. - **embind.** Every program on emscripten links `-lembind`, which @@ -93,7 +137,7 @@ holds only what is specific to trystero. 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 + `send`, a 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++ @@ -101,10 +145,14 @@ holds only what is specific to trystero. 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. + frees it: one that reached JavaScript would keep its object for good. + webcpp::webrtc's JavaScript catches the page's WebRTC exceptions the same + way, and its events come through webcpp::asio's bridge, which posts to the + loop's executor. 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 browser tests 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. @@ -144,12 +192,14 @@ holds only what is specific to trystero. refused and logged once. - 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). + `browser::backend::max_peer_connections` (256), the cap of its + 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 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), and holds at + most its runtime's `max_peer_connections` (256) alive at once. - 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 @@ -411,11 +461,14 @@ 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. + - **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 @@ -465,21 +518,23 @@ holds only what is specific to trystero. `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 + 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; the JSON storage's counter, 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); 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 + 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; 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 + below), and under Asyncify the unwind data of a call that suspends, which + webcpp::asio's run family does (the test counts it apart, 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. @@ -521,7 +576,12 @@ 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. + 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. - **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 diff --git a/README.md b/README.md index 7bec36d..68c83ef 100644 --- a/README.md +++ b/README.md @@ -11,21 +11,21 @@ A room runs on two targets, through a backend of each: | 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 | +| the browser's | `` | emscripten | the page's `WebSocket` and `crypto.subtle`, through embind, and webcpp::webrtc over its `RTCPeerConnection` | +| the native one | `` | native | webcpp::webrtc over libdatachannel for WebRTC, Boost.Beast for the relays' WebSockets, OpenSSL for TLS and AES-GCM | `` 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 include neither backend. Both backends' 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. 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, both backends 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 +45,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,13 +65,16 @@ send a wrong room proof, reported by the lower id only. ## Building inside the superproject trystero is developed inside the webcpp superproject, as a Boost library is -developed inside Boost. Its TLS and WebRTC dependencies are built from +developed inside Boost. It builds on webcpp::asio and webcpp::webrtc, two +libraries of the superproject; its TLS and WebRTC dependencies are built from pinned sources; only libsecp256k1 needs an external installation: | Library | Needed by | Found where | | --- | --- | --- | | libsecp256k1 0.8.0, with its `schnorrsig` and `extrakeys` modules | every room: it signs the Nostr events peers meet through | `-sSECP256K1_ROOT=` natively, `-sSECP256K1_EMSCRIPTEN_ROOT=` for its emscripten build, else `.local/secp256k1-native` and `.local/secp256k1-emscripten` | -| libdatachannel 0.24.6 | the native backend | `/webcpp/third_party//libdatachannel`, from pinned source submodules | +| webcpp::asio | every room | `/webcpp/asio//asio` | +| webcpp::webrtc | both backends' WebRTC | `/webcpp/webrtc//webrtc` | +| libdatachannel 0.24.6 | the native backend, through webcpp::webrtc | `/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 | The libsecp256k1 `-s` option, on b2's command line, names a directory with the library's @@ -92,11 +96,12 @@ 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`. +webcpp::asio, libsecp256k1 and Boost.JSON's definitions, compiled once per +variant, and on emscripten webcpp::webrtc and embind; a program there is +built in webcpp::asio's suspension variant, `webcpp-suspend=jspi` by default +or `asyncify`. A native program uses `/webcpp/trystero//native`, which adds +webcpp::webrtc, with libdatachannel and OpenSSL, and declares +`multi` itself, as `example/Jamfile` does. ## The examples @@ -189,7 +194,7 @@ struct application { ``` webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//native multi on : native ; + : /webcpp/trystero//native multi : native ; ``` @@ -302,7 +307,10 @@ The first build also compiles Boost.JSON's definitions, 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. ### 9. Run them @@ -354,8 +362,8 @@ Every browser tab that joins the same app and room joins the same chat. `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 +backend and the backend's WebRTC natively, against webcpp::webrtc's +libdatachannel and OpenSSL, and the browser backend 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/doc/Jamfile b/doc/Jamfile index 3ac1a63..7ef2708 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -12,8 +12,7 @@ webcpp.doc trystero : trystero.adoc ; # 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. +# brings webcpp::webrtc, libdatachannel and OpenSSL, and Boost.Asio without +# threads, as wasm32 has none, for the native backend's Beast and timers. webcpp.reference trystero : /webcpp/trystero//native multi /webcpp//emscripten-reference BOOST_ASIO_DISABLE_THREADS ; diff --git a/doc/acknowledgements.adoc b/doc/acknowledgements.adoc index eda544c..a61eaab 100644 --- a/doc/acknowledgements.adoc +++ b/doc/acknowledgements.adoc @@ -21,5 +21,6 @@ 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 +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..31e5ccb 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -83,7 +83,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] @@ -151,9 +151,10 @@ A move assignment carries the source's allocator with its target. [#trystero-allocation-asio] === Asio, the backends, Boost.JSON 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 @@ -165,7 +166,11 @@ executor, as the browser's `event_loop` executor, the wrapper stays Asio's. 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. +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. *Boost.JSON* allocates through `json_resource`, a `boost::container::pmr::memory_resource` that forwards to a @@ -186,8 +191,10 @@ 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; @@ -195,16 +202,20 @@ nothing. 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; +* 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`; * 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; * 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. + an array on every call; +* on Emscripten under Asyncify, the unwind data Asyncify allocates when a + call of webcpp::asio's run family suspends, which a program whose + `io_context` the browser's `event_loop` polls never does. 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 @@ -247,8 +258,11 @@ The counting resources also count a return of memory they never gave, a 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`: +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 index 1f8590a..5d61580 100644 --- a/doc/browser.adoc +++ b/doc/browser.adoc @@ -8,8 +8,9 @@ == 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 +page's own `WebSocket`, `setTimeout` and `crypto.subtle`, through embind's +`emscripten::val`, and over its `RTCPeerConnection` and `RTCDataChannel` +through webcpp::webrtc (<>), 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. @@ -22,9 +23,12 @@ 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. + settled promise or a timer, is dispatched to its handler, and is followed + by `io_context::poll()`, which runs everything that became ready. +* webcpp::webrtc's objects receive the page's WebRTC events through + webcpp::asio's bridge, a service of the loop's `io_context`, which posts to + the loop's executor, and so schedules a `poll()` as any work posted outside + an event does. * 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. @@ -42,7 +46,9 @@ wake-ups and up to an interval of latency. The backend's timers are === How JavaScript reaches {cpp} The page calls one function, `trystero_dispatch`, which -`` exports. A JavaScript handler is that +`` exports; webcpp::webrtc's events come +through webcpp::asio's bridge, whose JavaScript `/webcpp/asio//asio` links +into every program on emscripten. 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 @@ -57,10 +63,11 @@ resource: no `std::string` is made to carry either. === 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 +constructor, `JSON.parse`, a `send` or a 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} +that into the error its interface has; webcpp::webrtc's JavaScript catches +the page's WebRTC exceptions the same way. 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, @@ -72,10 +79,12 @@ 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 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 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 @@ -84,11 +93,14 @@ peer's malformed message never stops the page's loop. 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 + 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). It is the cap of the webcpp::webrtc runtime the backend owns, + `runtime_options::max_peer_connections`, and webcpp::webrtc's census of + the page counts every connection it makes, with any runtime. 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; @@ -102,9 +114,14 @@ binds another room without making another peer connection. `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. + trystero uses none. Its Asio is webcpp::asio's, built without threads when + the program has no pthread ABI, and the loop drives it on the page's one + thread. +* A suspension variant of webcpp::asio, which `/webcpp/trystero//trystero` + brings: `webcpp-suspend=jspi`, the default, for a browser with JavaScript + Promise Integration, or `asyncify` for any other. The loop never runs the + `io_context`, so no program of trystero suspends, but webcpp::asio's + runtime is linked either way. * 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`, diff --git a/doc/building.adoc b/doc/building.adoc index 7175d46..13b0c53 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -8,9 +8,10 @@ == 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 are built from pinned sources. Only libsecp256k1 needs an -external installation: +a Boost library is developed inside Boost. It builds on two libraries of +webcpp's: webcpp::asio, and webcpp::webrtc, the WebRTC of both its backends. +Its native TLS and WebRTC dependencies are built from pinned sources. Only +libsecp256k1 needs an external installation: [cols="2,2,3",options="header"] |=== @@ -22,8 +23,16 @@ external installation: `-sSECP256K1_EMSCRIPTEN_ROOT=` for its emscripten build, else `.local/secp256k1-emscripten` +| webcpp::asio +| every room +| `/webcpp/asio//asio`: natively Boost.Asio, on emscripten the backend it ships + +| webcpp::webrtc +| both backends' WebRTC +| `/webcpp/webrtc//webrtc`, the superproject's `libs/webrtc` + | libdatachannel 0.24.6 -| the native backend +| the native backend, through webcpp::webrtc | `/webcpp/third_party//libdatachannel`, built from `third_party/libs/libdatachannel` | OpenSSL 3.5.9 @@ -57,9 +66,8 @@ include::{library-root}/build.jam[tag=dependencies] 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: +webcpp::asio, libsecp256k1 and Boost.JSON's definitions, compiled once per +variant, and, on emscripten, webcpp::webrtc and embind: [listing] ---- @@ -69,9 +77,13 @@ 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. +On emscripten webcpp::asio builds without threads, since the page has none, +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 `quick_start-60-d-jspi.js`. -A native program uses `/webcpp/trystero//native`, which adds libdatachannel -and the same source-built OpenSSL used by Asio and Beast: +A native program uses `/webcpp/trystero//native`, which adds webcpp::webrtc, +with libdatachannel and the same source-built OpenSSL used by Asio and Beast: [listing] ---- @@ -82,17 +94,17 @@ The native backend uses worker threads, so each consumer declares `multi`. Its OpenSSL dependency is the matching threaded variant; a single-threaded native backend is rejected before compilation. -The native backend's WebRTC also needs exceptions (<>), -and b2 lets no usage requirement override a build's -`exception-handling=off`, so each program and test that uses it declares -`on` itself, as the examples do: +The native backend works with exceptions and without them +(<>), so a program builds as it asks, as the +examples do: [listing] ---- include::{examples}/Jamfile[tag=native] ---- -and as trystero's own tests of the native backend's connections do: +and as trystero's own tests of the native backend's connections do, once +without exceptions too: [listing] ---- diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 65033fe..e593d77 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,6 +16,20 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* Changed both backends' WebRTC to webcpp::webrtc, one implementation for +native and the browser. +* Changed the native backend to work without exceptions, as the rest does. +* *Breaking change:* Removed the backends' own peer connection and data +channel classes, and their `native_handle()`; use `native::backend` or +`browser::backend`. +* *Breaking change:* Changed trystero's Asio to webcpp::asio; a browser +program uses `webcpp::asio::io_context`. +* Added `native::backend_config::runtime`: at most 256 native connections +alive at once. +* Added a `native::backend` constructor that takes the program's +webcpp::webrtc runtime. +* Changed browser data channels to keep frames that arrive before a +handler, 64 for 10 s. // end::unreleased[] [#trystero-changelog-0-1-0] diff --git a/doc/design.adoc b/doc/design.adoc index 35dbd34..e2bd67a 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -31,20 +31,29 @@ | `room.hpp`, `detail/*.hpp` | the Nostr strategy, signaling, bindings, action wire and room API +| Backend's WebRTC +| `webrtc/*.hpp` +| webcpp::webrtc's peer connections and data channels, and trystero's + policies over them, on both targets + | Browser backend | `browser/*.hpp` | `emscripten::val` over the browser's APIs, and the event loop | Native backend | `native/*.hpp` -| libdatachannel, Boost.Beast, OpenSSL and Asio's timers +| Boost.Beast, OpenSSL and Asio's timers |=== 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 a 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 @@ -112,13 +121,70 @@ 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. [#trystero-design-webrtc] -=== Why the browser's own 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. +=== Why webcpp::webrtc + +Both backends' 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 +fixtures wrap the native backend's connections. + +[#trystero-design-backend-webrtc] +=== The backend's WebRTC + +Both backends make their peer connections and data channels the same way, 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: + +* 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. Natively it carries `sdpMid` and an + `sdpMLineIndex` of 0, and no user name fragment, as libdatachannel gives + none. +* 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 native backend makes at most + `backend_config::max_peer_connections_per_minute` connections in any + minute, its own policy against floods (<>); and the + connections alive at once are webcpp::webrtc's `runtime`'s to cap, natively + the backend's runtime's (<>), in the browser the + page's census (<>). [#trystero-design-text] === Text is a view, a copy is a decision @@ -141,12 +207,14 @@ The asynchronous operations are the exception, for the reason <> gives. [#trystero-design-dependencies] -=== Optional native 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. +=== Dependencies + +trystero builds on webcpp::asio, and its backends on webcpp::webrtc. +`/webcpp/trystero//trystero` brings `/webcpp/asio//asio`, and on emscripten +`/webcpp/webrtc//webrtc`, the browser's WebRTC; `/webcpp/trystero//native` +brings `/webcpp/webrtc//webrtc` natively, with its libdatachannel, under the +MPL 2.0, and OpenSSL, under the Apache License 2.0. Neither is in a browser +program, as OpenSSL is optional for Asio. [#trystero-design-licensing] === Licensing diff --git a/doc/differences.adoc b/doc/differences.adoc index 95fbcc2..df20c9a 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -115,8 +115,9 @@ handler set right after `join` sees every join; `peers()` lists the joined peers for a handler set later. *`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. +`RTCPeerConnection`. A connection is the backend's, webcpp::webrtc's over a +page's object in the browser and over libdatachannel's natively, and the +room does not hand it out. *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 diff --git a/doc/native.adoc b/doc/native.adoc index dde013c..4a779db 100644 --- a/doc/native.adoc +++ b/doc/native.adoc @@ -8,9 +8,10 @@ == 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 +webcpp::webrtc for WebRTC, which natively is +https://github.com/paullouisageneau/libdatachannel[libdatachannel]'s +(<>), 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 @@ -20,54 +21,33 @@ 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. +trystero raises no exception of its own, and the native backend works with +exceptions and without them, as the rest of trystero does. 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. ``, 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 alone in a build that has them. It changes nothing in trystero's +behaviour. 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; without exceptions Boost calls +the program's `boost::throw_exception` instead. [#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. +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 the browser. An application +that runs the `io_context` on several threads gives the app a strand, shared +by all its rooms. If a transport closes during adoption, before the room obtains a binding, the room forgets that negotiation and restarts announcements. Its later close @@ -76,15 +56,35 @@ 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 (<>). +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 the browser, 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 + browser refuses the whole connection. +* What libdatachannel allocates inside itself is libdatachannel's + (<>). + +[#trystero-native-runtime] +=== The runtime + +webcpp::webrtc's `runtime` holds what libdatachannel keeps for the whole +process, its threads and its global state, and caps the peer connections +alive at once. A native backend makes one of its own, with +`backend_config::runtime`, or takes the program's: `native::backend(ex, +runtime, config)`. 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 process holds one +runtime at a time, since libdatachannel's state is the process's: a program +with several native backends at once, or that uses webcpp::webrtc beside +trystero, makes one `webcpp::webrtc::runtime` before its `io_context` and +gives it to each. [#trystero-native-config] === Its configuration @@ -110,6 +110,15 @@ with, beside the app's `ice_servers`: 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 a connection + gives its place back once it is gone; and `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, `native::websocket_limits` (<>). diff --git a/doc/overview.adoc b/doc/overview.adoc index 202f07a..01c0319 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -30,14 +30,16 @@ The library provides: * 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; + 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. + two implementations, for the browser and for native programs, whose WebRTC + is webcpp::webrtc's on both. [#trystero-overview-targets] === Two backends @@ -52,13 +54,15 @@ Each backend is a header of its own: | `` | emscripten -| the page's `WebSocket`, `RTCPeerConnection`, `RTCDataChannel`, - `setTimeout` and `crypto.subtle`, through embind (<>) +| the page's `WebSocket`, `setTimeout` and `crypto.subtle`, through embind, + and webcpp::webrtc over the page's `RTCPeerConnection` and + `RTCDataChannel` (<>) | `` | native -| libdatachannel for WebRTC, Boost.Beast for the relays' WebSockets, - OpenSSL for TLS and AES-GCM, and Asio's timers (<>) +| webcpp::webrtc over libdatachannel for WebRTC, Boost.Beast for the relays' + WebSockets, OpenSSL for TLS and AES-GCM, and Asio's timers + (<>) |=== Both run the same room, and both meet Trystero JS peers. Every name is in the @@ -70,6 +74,8 @@ namespace `webcpp::trystero`. * A {cpp}20 compiler. * Boost 1.92: Asio, Container (its `pmr` base class), Core, Hash2, JSON and System; and Beast for the native backend. +* webcpp::asio, and webcpp::webrtc for both backends' WebRTC + (<>). * 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. @@ -77,10 +83,9 @@ namespace `webcpp::trystero`. served from a secure context (https, or http on `localhost`), where `crypto.subtle` exists. * 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, both backends included, +compiles and works without exceptions (<>). diff --git a/doc/quick-start.adoc b/doc/quick-start.adoc index 732a7b6..0bb7b6a 100644 --- a/doc/quick-start.adoc +++ b/doc/quick-start.adoc @@ -45,7 +45,7 @@ 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 +`async_send`. `webcpp::asio::as_tuple` turns the error into a value, so leaving the room ends the loop instead of throwing: [source] @@ -63,7 +63,7 @@ the `io_context` (<>). 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: +webcpp::webrtc posts what libdatachannel's threads report to it: [source] ---- diff --git a/doc/roadmap.adoc b/doc/roadmap.adoc index be5ef58..cfe8e39 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 bfb19d3..c571d8c 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -49,8 +49,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 and the +allocation test run on both: [listing] ---- @@ -64,8 +65,9 @@ include::{library-root}/test/Jamfile[tag=allocation] | 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. + native backend and the backend's WebRTC natively, against webcpp::webrtc's + libdatachannel and OpenSSL, and the browser backend, with the backend's + WebRTC it includes, on emscripten. | `config`, `config_developer_defined`, `config_all_off` | `` defines `WEBCPP_TRYSTERO_NO_EXCEPTIONS` @@ -121,24 +123,32 @@ include::{library-root}/test/Jamfile[tag=allocation] 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, - handler replacement and destruction, the 64-frame and 10-second bounds, - and allocation and release through the channel's resource. +| `native_peer_connection`, `native_room`, and each `_no_exceptions` +| Two connections of the backend's WebRTC, over webcpp::webrtc's + libdatachannel, wired to each other, each handler on the executor, and + whole native rooms over 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 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; 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. | `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. + sealer's completions, and, 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, and + webcpp::webrtc's census of them. |=== -The native backend's connections need exceptions whatever the build asks +The native backend's tests run once more without exceptions (<>), and each browser test is also built without exceptions, as a program that uses the browser backend may be: diff --git a/doc/usage.adoc b/doc/usage.adoc index afb8ec6..ffe0753 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -231,9 +231,10 @@ 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, 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..dbd7633 100644 --- a/test/CONVERSION.md +++ b/test/CONVERSION.md @@ -35,6 +35,13 @@ 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. + ## How each form was converted | Old | New | Why | diff --git a/test/oracle/interop/native_peer.cpp b/test/oracle/interop/native_peer.cpp index 0225ec6..8b05d2d 100644 --- a/test/oracle/interop/native_peer.cpp +++ b/test/oracle/interop/native_peer.cpp @@ -152,7 +152,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: From caa01c1d07945a188e9af7f7230f0eb927d98326 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 16:25:13 -0300 Subject: [PATCH 004/116] trystero: keep the backend's WebRTC and its tests to clang-tidy A refused send no longer arms the drain's wait, an empty brace list and a positional session_description_view are written out, and the browser backend's runtime options take their trailing comma. The native peer connection test's mixed pair is a fixture of its own, its queued pair opens with open(), whose destructor says why it raises nothing, and the allocation test keeps Asyncify's counters to emscripten. --- include/webcpp/trystero/browser/backend.hpp | 6 +- .../webcpp/trystero/webrtc/data_channel.hpp | 10 +- .../trystero/webrtc/peer_connection.hpp | 7 +- test/allocation_test.cpp | 10 + test/native_peer_connection_test.cpp | 253 +++++++++++------- 5 files changed, 173 insertions(+), 113 deletions(-) diff --git a/include/webcpp/trystero/browser/backend.hpp b/include/webcpp/trystero/browser/backend.hpp index 1d55e23..6ae9960 100644 --- a/include/webcpp/trystero/browser/backend.hpp +++ b/include/webcpp/trystero/browser/backend.hpp @@ -549,8 +549,10 @@ class backend : public trystero::backend::factory { : loop_(loop), runtime_(std::allocate_shared<::webcpp::webrtc::runtime>( std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), - ::webcpp::webrtc::runtime_options{.max_peer_connections = max_peer_connections, - .thread_pool_size = 0})) {} + ::webcpp::webrtc::runtime_options{ + .max_peer_connections = max_peer_connections, + .thread_pool_size = 0, + })) {} /** * Opens a WebSocket to a relay, with the page's `WebSocket`. diff --git a/include/webcpp/trystero/webrtc/data_channel.hpp b/include/webcpp/trystero/webrtc/data_channel.hpp index 45fc0b9..bea1ec7 100644 --- a/include/webcpp/trystero/webrtc/data_channel.hpp +++ b/include/webcpp/trystero/webrtc/data_channel.hpp @@ -90,8 +90,7 @@ class data_channel : public backend::data_channel, * @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, and which outlives - * every operation of the channel. + * @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. @@ -176,8 +175,11 @@ class data_channel : public backend::data_channel, if (!is_open()) { return; } - // A channel closed in between refuses the frame, and its close event reports it. - static_cast(channel_.send(webcpp::asio::buffer(frame.data(), frame.size()))); + // 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(); } diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp index 4daffcf..f1ffa7c 100644 --- a/include/webcpp/trystero/webrtc/peer_connection.hpp +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -170,8 +170,8 @@ class peer_connection : public backend::peer_connection, .policy = ::webcpp::webrtc::ice_transport_policy::all, .bind_address = bind_address, }; - return connection_type::make(runtime, ex, config, ::webcpp::webrtc::options{}, - allocator_type(memory)); + const ::webcpp::webrtc::options bounds; + return connection_type::make(runtime, ex, config, bounds, allocator_type(memory)); } /** @@ -263,7 +263,8 @@ class peer_connection : public backend::peer_connection, return; } pc_.async_set_remote_description( - {*kind, sdp}, bound([done = std::move(done)](boost::system::error_code ec) mutable { + {.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{}); })); } diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 951a4f6..544b554 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -75,6 +75,7 @@ bool counting = false; // counts nothing: that allocation is operator new's, counted once. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool inside_operator_new = false; +#ifdef __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 @@ -84,6 +85,7 @@ unsigned char 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. */ @@ -156,7 +158,11 @@ namespace { void* counted(void* pointer) { if (on_counted_thread() && counting && !inside_operator_new) { +#ifdef __EMSCRIPTEN__ ++(inside_runtime != 0 ? runtime_allocations : c_allocations); +#else + ++c_allocations; +#endif } return pointer; } @@ -817,6 +823,8 @@ 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 @@ -845,6 +853,8 @@ void mark_the_runtime_allocations() { #endif } +} // namespace + int main() { count_this_thread(); mark_the_runtime_allocations(); diff --git a/test/native_peer_connection_test.cpp b/test/native_peer_connection_test.cpp index 99c2eed..5f7e86e 100644 --- a/test/native_peer_connection_test.cpp +++ b/test/native_peer_connection_test.cpp @@ -291,6 +291,9 @@ struct queued_pair : pair { /** 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(); @@ -298,8 +301,9 @@ struct queued_pair : pair { tasks->ready.clear(); } - void connect() { - pair::connect(); + /** 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; }))); } @@ -366,7 +370,7 @@ void closing_one_end_is_seen_by_the_other() { // 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(); + 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'}; @@ -382,7 +386,7 @@ void messages_wait_for_the_receiver_during_handoff() { void a_full_pending_queue_drains_in_order_and_uses_replacement_handlers() { queued_pair p; - p.connect(); + 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) { @@ -437,7 +441,7 @@ void a_full_pending_queue_drains_in_order_and_uses_replacement_handlers() { void a_pending_queue_overflow_closes_the_channel() { queued_pair p; - p.connect(); + p.open(); require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); bool closed = false; p.offer_end->set_handlers({ @@ -455,7 +459,7 @@ void a_pending_queue_overflow_closes_the_channel() { void pending_messages_expire_without_a_receiver() { queued_pair p; - p.connect(); + p.open(); require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; }))); bool closed = false; p.offer_end->set_handlers({ @@ -472,7 +476,7 @@ void pending_messages_expire_without_a_receiver() { void a_receiver_can_close_and_destroy_its_channel_during_pending_delivery() { queued_pair p; - p.connect(); + 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}); @@ -535,7 +539,7 @@ void pending_frames_and_delivery_use_the_channels_resource() { pending_memory memory; { queued_pair p(&memory); - p.connect(); + p.open(); 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) { @@ -650,117 +654,158 @@ std::string json_of(const webcpp::webrtc::ice_candidate& c) { }); } -// 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() { +/** + * The native 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::native::backend factory(io.get_executor(), runtime, {.bind_address = loopback}); - const auto local = factory.make_peer_connection({}, std::pmr::get_default_resource()); - 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())); - webcpp::webrtc::peer_connection& remote = *made; - - // Candidates wait until the side they go to has both descriptions. + trystero::native::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; - const auto add_to_remote = [&remote](std::string_view json) { + + 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 v = boost::json::parse(json).as_object(); const std::string_view text = v.at("candidate").as_string(); const std::string_view mid = v.at("sdpMid").as_string(); - remote.async_add_ice_candidate({.candidate = text, .sdp_mid = mid}, - [](webcpp::webrtc::detail::error_code) {}); - }; - local->set_handlers({ - .ice_candidate = - [&](std::string_view json) { - if (negotiated) { - add_to_remote(json); - } else { - to_remote.emplace_back(json); - } - }, - .data_channel = {}, - .state = {}, - }); - std::function trickle = [&] { - remote.async_wait_ice_candidate( - [&](webcpp::webrtc::detail::error_code ec, const webcpp::webrtc::ice_candidate& c) { - if (ec || c.candidate.empty()) { - return; - } - if (negotiated) { - local->add_ice_candidate(json_of(c), [](backend::error_code) {}); - } else { - to_local.push_back(json_of(c)); + 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(); } - trickle(); }); - }; - trickle(); - std::optional sender; - remote.async_accept_data_channel( - [&](webcpp::webrtc::detail::error_code ec, webcpp::webrtc::data_channel c) { - if (!ec) { - sender.emplace(std::move(c)); - } + } + + /** 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 = {}, }); - const auto channel = local->create_data_channel("data"); - require(BOOST_TEST(channel != nullptr)); - std::vector received; - channel->set_handlers({ - .open = {}, - .message = [&](backend::bytes frame) { received.push_back(std::move(frame)); }, - .close = {}, - .buffered_amount_low = {}, - }); - local->set_local_description( - [&](backend::error_code ec, std::string_view, std::string_view offer) { - require(BOOST_TEST(!ec)); - remote.async_set_remote_description( - {.type = webcpp::webrtc::sdp_type::offer, .sdp = offer}, - [&](webcpp::webrtc::detail::error_code ec) { - require(BOOST_TEST(!ec)); - remote.async_set_local_description( - [&](webcpp::webrtc::detail::error_code ec, - const webcpp::webrtc::session_description& answer) { - require(BOOST_TEST(!ec)); - local->set_remote_description( - "answer", answer.sdp, [&](backend::error_code ec) { - require(BOOST_TEST(!ec)); - 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) {}); - } - }); - }); - }); + 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 = {}, }); - require(BOOST_TEST(run_until(io, [&] { - return channel->is_open() && sender && - sender->ready_state() == webcpp::webrtc::data_channel_state::open; - }))); + 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(!sender->send(asio::buffer(before))); - BOOST_TEST(!sender->send_text("1e300")); - BOOST_TEST(!sender->send(asio::buffer(after))); - require(BOOST_TEST(run_until(io, [&] { return received.size() == 2; }))); - BOOST_TEST_ALL_EQ(received[0].begin(), received[0].end(), before.begin(), before.end()); - BOOST_TEST_ALL_EQ(received[1].begin(), received[1].end(), after.begin(), after.end()); + 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(io, [] { return false; }, 200ms); - BOOST_TEST_EQ(received.size(), 2U); - sender.reset(); - remote.close(); + run_until(p.io, [] { return false; }, 200ms); + BOOST_TEST_EQ(p.received.size(), 2U); } } // namespace From 528a4e6502052a12a884da4304fe067d0be8f913 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 16:59:20 -0300 Subject: [PATCH 005/116] trystero: a clean page, its reference read for Emscripten's target The guide's reference reads every header for Emscripten's target, where webcpp::asio is not Boost.Asio: the native backend's executor, timer and sealer now name webcpp::asio, which natively is Boost.Asio itself, and its relays' Boost.Beast WebSockets get the same executor through relay_executor, which names none for that parse alone. Three Doc Comments keep their brief to one sentence, a possessive no longer follows a code span, and backend.hpp says which resource a peer connection and its frames are in: the app's. --- AGENTS.md | 8 ++++- doc/design.adoc | 4 +-- include/webcpp/trystero/backend.hpp | 18 +++++----- include/webcpp/trystero/browser/backend.hpp | 8 +++-- include/webcpp/trystero/native/backend.hpp | 35 ++++++++++++++----- include/webcpp/trystero/native/sealer.hpp | 8 ++--- include/webcpp/trystero/native/timer.hpp | 12 +++---- .../webcpp/trystero/webrtc/data_channel.hpp | 4 ++- 8 files changed, 63 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 29d2d1f..3312a7f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,13 @@ holds only what is specific to trystero. 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 native backend - keeps Boost.Asio's names, which Boost.Beast takes. `/webcpp/trystero//trystero` + names it too (its executor, timer and sealer), but for its relays' + WebSockets, which are Boost.Beast's over Boost.Asio: `native::backend`'s + private `relay_executor` hands them the backend's executor, natively the + same type. The guide's reference reads every header for Emscripten's + target, where webcpp::asio is its own and the native backend is never + built: there `relay_executor` names no executor, and the native headers + still parse. `/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 (`quick_start-60-d-jspi.js`), and the suites run in both. diff --git a/doc/design.adoc b/doc/design.adoc index e2bd67a..c072b4e 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -182,8 +182,8 @@ in them, over webcpp::webrtc: * The caps. The native backend makes at most `backend_config::max_peer_connections_per_minute` connections in any minute, its own policy against floods (<>); and the - connections alive at once are webcpp::webrtc's `runtime`'s to cap, natively - the backend's runtime's (<>), in the browser the + `runtime` of webcpp::webrtc caps the connections alive at once, natively + the backend's own (<>), in the browser over the page's census (<>). [#trystero-design-text] diff --git a/include/webcpp/trystero/backend.hpp b/include/webcpp/trystero/backend.hpp index 3fc97a5..0e21c4f 100644 --- a/include/webcpp/trystero/backend.hpp +++ b/include/webcpp/trystero/backend.hpp @@ -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`. */ diff --git a/include/webcpp/trystero/browser/backend.hpp b/include/webcpp/trystero/browser/backend.hpp index 6ae9960..212ba28 100644 --- a/include/webcpp/trystero/browser/backend.hpp +++ b/include/webcpp/trystero/browser/backend.hpp @@ -528,9 +528,11 @@ class backend : public trystero::backend::factory { * The most `RTCPeerConnection` objects the page holds, every program 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. It is the cap of the backend's - * webcpp::webrtc runtime, `runtime_options::max_peer_connections`, whose census of the page - * counts the connections webcpp::webrtc makes. + * counts until a collection the page cannot ask for. + * + * It is the cap of the backend's webcpp::webrtc runtime, + * `runtime_options::max_peer_connections`, whose census of the page counts the connections + * webcpp::webrtc makes. * * 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 diff --git a/include/webcpp/trystero/native/backend.hpp b/include/webcpp/trystero/native/backend.hpp index 6c478bf..9b82422 100644 --- a/include/webcpp/trystero/native/backend.hpp +++ b/include/webcpp/trystero/native/backend.hpp @@ -21,8 +21,10 @@ #include #include +#include // lint-world: posts handlers only + #include -#include // lint-world: posts handlers only +#include // lint-world: the relays' Boost.Beast WebSockets #include // lint-world: the relays' TLS #include @@ -72,8 +74,9 @@ struct backend_config { /** * What the backend's own webcpp::webrtc runtime is made with: the most peer connections alive - * at once, 256 by default, and libdatachannel's threads. A backend given the program's runtime - * does not use it. + * at once, 256 by default, and libdatachannel's threads. + * + * A backend given the program's runtime does not use it. */ ::webcpp::webrtc::runtime_options runtime = {}; @@ -110,7 +113,7 @@ class backend : public trystero::backend::factory { * context or load the system's certificate authorities; without exceptions, Boost's * `throw_exception`, which the program defines, is called instead. */ - explicit backend(boost::asio::any_io_executor ex, backend_config config = {}) + explicit backend(webcpp::asio::any_io_executor ex, backend_config config = {}) : backend(std::move(ex), nullptr, std::move(config)) {} /** @@ -122,7 +125,7 @@ class backend : public trystero::backend::factory { * @param config What its peer connections are made with; its `runtime` is not used. * @throws std::exception As the other constructor. */ - backend(boost::asio::any_io_executor ex, ::webcpp::webrtc::runtime& runtime, + backend(webcpp::asio::any_io_executor ex, ::webcpp::webrtc::runtime& runtime, backend_config config = {}) // An empty owner: the pointer does not own the program's runtime. : backend(std::move(ex), @@ -157,7 +160,8 @@ class backend : public trystero::backend::factory { 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); + return connect_websocket(relay_executor(), tls_, url, std::move(h), memory, + config_.relay_limits); } /** @@ -249,7 +253,7 @@ class backend : public trystero::backend::factory { private: // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - backend(boost::asio::any_io_executor ex, std::shared_ptr<::webcpp::webrtc::runtime> runtime, + backend(webcpp::asio::any_io_executor ex, std::shared_ptr<::webcpp::webrtc::runtime> runtime, backend_config config) // NOLINTEND(performance-unnecessary-value-param) : ex_(std::move(ex)), @@ -262,6 +266,21 @@ class backend : public trystero::backend::factory { tls_.set_verify_mode(boost::asio::ssl::verify_peer); } + /** + * The executor of the relays' WebSockets, which are Boost.Beast's and take Boost.Asio's. + * + * Natively webcpp::asio is Boost.Asio, and the two executors are one: the backend builds + * natively alone. The reference of the guide reads every header for Emscripten's target, + * where webcpp::asio is its own and the backend is never built: it names no executor there. + */ + [[nodiscard]] boost::asio::any_io_executor relay_executor() const { +#ifdef WEBCPP_TARGET_NATIVE + return ex_; +#else + return {}; +#endif + } + /** A runtime of the backend's own, which its connections share with it. */ static std::shared_ptr<::webcpp::webrtc::runtime> own_runtime( const ::webcpp::webrtc::runtime_options& options) { @@ -302,7 +321,7 @@ class backend : public trystero::backend::factory { return out; } - boost::asio::any_io_executor ex_; + webcpp::asio::any_io_executor ex_; backend_config config_; std::shared_ptr<::webcpp::webrtc::runtime> runtime_; trystero::detail::construction_window constructions_; diff --git a/include/webcpp/trystero/native/sealer.hpp b/include/webcpp/trystero/native/sealer.hpp index e61fd6d..e16ac65 100644 --- a/include/webcpp/trystero/native/sealer.hpp +++ b/include/webcpp/trystero/native/sealer.hpp @@ -17,8 +17,8 @@ #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 #include @@ -110,7 +110,7 @@ class sealer : public backend::sealer { * @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, + sealer(webcpp::asio::any_io_executor ex, std::array key, std::pmr::memory_resource* memory) : ex_(std::move(ex)), key_(key), memory_(memory) {} @@ -168,7 +168,7 @@ class sealer : public backend::sealer { complete(std::move(done), make_error_code(e), std::pmr::string(memory_)); } - boost::asio::any_io_executor ex_; + webcpp::asio::any_io_executor ex_; std::array key_; std::pmr::memory_resource* memory_; }; diff --git a/include/webcpp/trystero/native/timer.hpp b/include/webcpp/trystero/native/timer.hpp index f2095a2..ee8624e 100644 --- a/include/webcpp/trystero/native/timer.hpp +++ b/include/webcpp/trystero/native/timer.hpp @@ -11,10 +11,10 @@ #include -#include // lint-world: Trystero's timers -#include // lint-world: allocates timer waits -#include // lint-world: Trystero's timers #include +#include // lint-world: Trystero's timers +#include // lint-world: allocates timer waits +#include // lint-world: Trystero's timers #include #include @@ -42,7 +42,7 @@ class timer : public trystero::backend::timer { * @param memory The room's resource, which each wait is allocated in; it must outlive the * timer's pending waits. */ - timer(const boost::asio::any_io_executor& ex, std::pmr::memory_resource* memory) + timer(const webcpp::asio::any_io_executor& ex, std::pmr::memory_resource* memory) : timer_(ex), memory_(memory), waits_( @@ -58,7 +58,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,7 +75,7 @@ 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_; diff --git a/include/webcpp/trystero/webrtc/data_channel.hpp b/include/webcpp/trystero/webrtc/data_channel.hpp index bea1ec7..6274f34 100644 --- a/include/webcpp/trystero/webrtc/data_channel.hpp +++ b/include/webcpp/trystero/webrtc/data_channel.hpp @@ -138,7 +138,9 @@ class data_channel : public backend::data_channel, /** * 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. + * outlives the call. + * + * A message handler installed while frames wait posts their delivery. * * @param h The new handlers, kept in the channel's resource. */ From f11dd5f7a2fa323a400c953335d153bdf80fa4d0 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:18:08 -0300 Subject: [PATCH 006/116] trystero: Boost for what the core wrote itself: Endian, Unordered with a keyed Hash2, circular_buffer, one random_id The action wire and the envelope read and write their big-endian fields with Boost.Endian, and an offer's size is read in 64 bits: on a 32-bit target an offer of 2^53 - 1 bytes was read as 4294967295 (measured on Emscripten). The strategy's event-id dedup is a boost::unordered_flat_set hashed with SipHash under a key it draws, so ids a relay chose to share a bucket of std::hash cost one probe each. The construction window, the recent challenges and the replay cache are boost::circular_buffer rings. One protocol::random_id maps random bytes to Trystero's characters, in place of four copies and the unused make_id. Comments cite Trystero's dist/ files instead of C/, error.hpp names app::on_error, and differences.adoc no longer says as today. --- doc/differences.adoc | 6 +- doc/protocol.adoc | 16 +- include/webcpp/trystero/app.hpp | 4 +- .../webcpp/trystero/detail/action_wire.hpp | 2 +- include/webcpp/trystero/detail/app_impl.hpp | 26 ++-- include/webcpp/trystero/detail/connection.hpp | 12 +- .../trystero/detail/construction_window.hpp | 15 +- .../webcpp/trystero/detail/nostr_strategy.hpp | 142 ++++++++++++------ include/webcpp/trystero/detail/random_id.hpp | 42 ++++++ include/webcpp/trystero/detail/rebinding.hpp | 19 +-- .../webcpp/trystero/detail/replay_cache.hpp | 29 ++-- include/webcpp/trystero/detail/signaling.hpp | 13 +- include/webcpp/trystero/error.hpp | 4 +- .../webcpp/trystero/protocol/action_wire.hpp | 91 ++++++----- include/webcpp/trystero/protocol/envelope.hpp | 18 ++- include/webcpp/trystero/protocol/topics.hpp | 33 ++-- include/webcpp/trystero/room.hpp | 19 +-- test/protocol_test.cpp | 101 ++++++++++++- test/room_test.cpp | 78 ++++++++++ 19 files changed, 466 insertions(+), 204 deletions(-) create mode 100644 include/webcpp/trystero/detail/random_id.hpp diff --git a/doc/differences.adoc b/doc/differences.adoc index df20c9a..e6e8ac0 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -90,9 +90,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,7 +102,7 @@ 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 diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 000e935..51862ef 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -54,6 +54,14 @@ 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 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 @@ -129,7 +137,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"] |=== diff --git a/include/webcpp/trystero/app.hpp b/include/webcpp/trystero/app.hpp index 47bfae4..e039b64 100644 --- a/include/webcpp/trystero/app.hpp +++ b/include/webcpp/trystero/app.hpp @@ -189,8 +189,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/detail/action_wire.hpp b/include/webcpp/trystero/detail/action_wire.hpp index 93726c1..bcb026f 100644 --- a/include/webcpp/trystero/detail/action_wire.hpp +++ b/include/webcpp/trystero/detail/action_wire.hpp @@ -608,7 +608,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(); diff --git a/include/webcpp/trystero/detail/app_impl.hpp b/include/webcpp/trystero/detail/app_impl.hpp index d6df7e2..2022244 100644 --- a/include/webcpp/trystero/detail/app_impl.hpp +++ b/include/webcpp/trystero/detail/app_impl.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -105,7 +106,7 @@ class app_impl : public std::enable_shared_from_this { set_aside("self_id is longer than any peer accepts, 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(); @@ -275,13 +276,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) { @@ -325,7 +327,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), @@ -415,16 +417,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/connection.hpp b/include/webcpp/trystero/detail/connection.hpp index 4325191..6c7e870 100644 --- a/include/webcpp/trystero/detail/connection.hpp +++ b/include/webcpp/trystero/detail/connection.hpp @@ -473,10 +473,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_)); @@ -540,7 +540,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 +557,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..e222e87 100644 --- a/include/webcpp/trystero/detail/construction_window.hpp +++ b/include/webcpp/trystero/detail/construction_window.hpp @@ -9,11 +9,11 @@ #include +#include + #include #include -#include #include -#include namespace webcpp::trystero::detail { @@ -30,23 +30,20 @@ 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())) {} + : times_(limit, 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_) { + if (times_.capacity() == 0 || (times_.full() && now_ms - times_.front() < window_ms_)) { return false; } - times_[next_] = now_ms; - next_ = (next_ + 1) % times_.size(); + times_.push_back(now_ms); // 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; + boost::circular_buffer> times_; double window_ms_; }; diff --git a/include/webcpp/trystero/detail/nostr_strategy.hpp b/include/webcpp/trystero/detail/nostr_strategy.hpp index 1f01dc1..c79f99d 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -11,28 +11,112 @@ #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. + * + * 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; + + /** 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 + * an empty one is always new and never remembered. */ + bool remember(std::string_view id) { + if (id.empty()) { + 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, for its statistics, which Boost.Unordered keeps with + * `BOOST_UNORDERED_ENABLE_STATS`. */ + [[nodiscard]] const index_type& index() const noexcept { return index_; } + +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 @@ -77,8 +161,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); @@ -142,6 +225,7 @@ class nostr_strategy : public std::enable_shared_from_this { static constexpr double first_retry_ms = 3333; static constexpr double max_retry_ms = 60'000; static constexpr double healthy_ms = 60'000; + static constexpr std::size_t subscription_id_size = 64; struct relay_state { relay_state(std::string_view address, std::pmr::memory_resource* memory) @@ -173,18 +257,15 @@ 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); @@ -244,7 +325,7 @@ class nostr_strategy : public std::enable_shared_from_this { r.open = true; r.opened_ms = factory_.now_ms(); 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_)); @@ -343,23 +424,6 @@ 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); @@ -375,7 +439,7 @@ class nostr_strategy : public std::enable_shared_from_this { if (e->subscription != r.subscription || e->topic.empty()) { return; } - if (std::ranges::find(topics_, e->topic) == topics_.end() || !remember(e->id)) { + if (std::ranges::find(topics_, e->topic) == topics_.end() || !seen_.remember(e->id)) { return; } on_message_(index, e->topic, e->content); @@ -429,15 +493,6 @@ class nostr_strategy : public std::enable_shared_from_this { }}); } - /** 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_; @@ -448,10 +503,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/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..b776c33 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,10 @@ 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(); - } - } + /** 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 +66,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..dddf471 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,10 @@ 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) {} /** 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 +45,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..ba91a95 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -316,16 +317,6 @@ 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; @@ -444,7 +435,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); 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/protocol/action_wire.hpp b/include/webcpp/trystero/protocol/action_wire.hpp index 687baa0..b1f35f7 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 @@ -147,17 +170,16 @@ inline void append_header(bytes& out, frame_kind kind, std::string_view name, pa out[at + 1] = static_cast(static_cast(kind) | (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/topics.hpp b/include/webcpp/trystero/protocol/topics.hpp index 1c2b804..affc011 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,24 @@ 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: the id is as unpredictable as its bytes, not uniform. + * + * @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; } diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index f886d85..cfd46d6 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -586,8 +587,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( @@ -941,16 +944,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()) { @@ -1198,7 +1191,7 @@ 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_)); } diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index e16f221..30127c1 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include @@ -296,14 +296,102 @@ 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() { + const auto offer_of_size = [](const std::array& size) { + auto frame = tp::encode_offer("file", tp::payload_format::binary, "", 7, 1); + std::ranges::copy(size, frame.begin() + 40); + return frame; + }; + const auto largest = + tp::decode_action(offer_of_size({0x43, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})); + 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, 6> refused{{ + {0x43, 0x40, 0, 0, 0, 0, 0, 0}, // 2^53 + {0x43, 0x40, 0, 0, 0, 0, 0, 1}, // 2^53 + 2 + {0x3f, 0xf8, 0, 0, 0, 0, 0, 0}, // 1.5 + {0, 0, 0, 0, 0, 0, 0, 0}, // 0 + {0xbf, 0xf0, 0, 0, 0, 0, 0, 0}, // -1 + {0x7f, 0xf8, 0, 0, 0, 0, 0, 0}, // NaN + }}; + for (const auto& size : refused) { + const auto decoded = tp::decode_action(offer_of_size(size)); + 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); + const std::array 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 envelope = tp::decode_envelope(tp::room_frame(longest, data)); + 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() { @@ -361,7 +449,10 @@ int main(int argc, char* argv[]) { 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(); text(); return boost::report_errors(); diff --git a/test/room_test.cpp b/test/room_test.cpp index b075472..ec82575 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -8,6 +8,10 @@ // support/memory_backend.hpp. WEBCPP_TEST_TRYSTERO_VERBOSE in the environment prints each room's // log on the standard error. +// Boost.Unordered counts the probes and the comparisons of its open-addressing containers, which +// the case of colliding event ids reads; before any of its headers. +#define BOOST_UNORDERED_ENABLE_STATS + #include #include @@ -35,6 +39,7 @@ #include #include #include +#include #include #include @@ -688,6 +693,77 @@ void the_replay_cache_remembers_the_last_ones() { BOOST_TEST(!none.contains("one")); } +// 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); + 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")); + // An event without an id is never taken for a repeat. + BOOST_TEST(ids.remember("")); + BOOST_TEST(ids.remember("")); + BOOST_TEST_EQ(ids.size(), 3U); + BOOST_TEST_GT(memory.in_use, 0U); + } + BOOST_TEST_EQ(memory.in_use, 0U); +} + +// Ids a relay chooses so that the standard library's unseeded hash puts them all in one bucket of a +// std::unordered_set sized for the ids remembered, the strategy's index before, where each lookup +// walks every one of them, cost the index a probe and a comparison each: it hashes them with +// SipHash under a key of its own. The ids are found by search, as an attacker finds them. +void colliding_event_ids_stay_fast() { + constexpr std::size_t count = 2048; + constexpr std::size_t capacity = trystero::detail::nostr_strategy::remembered_events; + std::unordered_set reference; + reference.reserve(capacity); + std::vector colliding; + colliding.reserve(count); + std::string candidate(64, '0'); // the length of a Nostr event id, in hexadecimal + const auto target = reference.bucket(candidate); + for (std::uint64_t n = 0; colliding.size() < count; ++n) { + for (std::size_t i = 0; i < 16; ++i) { + candidate[candidate.size() - 1 - i] = "0123456789abcdef"[(n >> (4 * i)) & 15U]; + } + if (reference.bucket(candidate) == target) { + colliding.push_back(candidate); + } + } + reference.insert(colliding.begin(), colliding.end()); + BOOST_TEST_GE(reference.bucket_count(), capacity); + BOOST_TEST_EQ(reference.bucket_size(target), count); + + std::array key{}; + key.fill(0x5a); + trystero::detail::recent_event_ids ids(capacity, key, std::pmr::get_default_resource()); + const auto fresh = + std::ranges::count_if(colliding, [&](const auto& id) { return ids.remember(id); }); + const auto repeated = + std::ranges::count_if(colliding, [&](const auto& id) { return !ids.remember(id); }); + BOOST_TEST_EQ(static_cast(fresh), count); + BOOST_TEST_EQ(static_cast(repeated), count); + const auto stats = ids.index().get_stats(); + // Measured: 1.08, 1.04, 0.03, 1 and 1.01; a chain of `count` ids would cost about half of them, + // a thousand comparisons, at each lookup. + BOOST_TEST_LE(stats.insertion.probe_length.average, 1.5); + BOOST_TEST_LE(stats.unsuccessful_lookup.probe_length.average, 1.5); + BOOST_TEST_LE(stats.unsuccessful_lookup.num_comparisons.average, 0.5); + BOOST_TEST_LE(stats.successful_lookup.probe_length.average, 1.5); + BOOST_TEST_LE(stats.successful_lookup.num_comparisons.average, 1.5); +} + /** 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, @@ -1409,6 +1485,8 @@ int main() { sealed_offers_that_fail_at_once_are_bounded(); announcements_with_forged_answers_are_bounded(); the_replay_cache_remembers_the_last_ones(); + recent_event_ids_drop_a_repeat_and_forget_the_oldest(); + colliding_event_ids_stay_fast(); a_replayed_answer_is_refused(); a_replayed_offer_is_refused(); a_reflected_offer_is_refused_as_an_answer(); From bb004b1703f38725d8475e0122c62791d28b104c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:20:43 -0300 Subject: [PATCH 007/116] trystero: the native relays on webcpp::beast, their URLs through Boost.URL The relay WebSocket is one session over webcpp::beast's stream, natively Boost.Beast's own, composed of Asio operations whose handlers carry the room's allocator instead of coroutines, so that no coroutine frame and no read buffer stays outside the room's resource; it compiles for Emscripten too, where webcpp::beast's page stream keeps its state in the room's resource. A relay's URL is read with Boost.URL: an IPv6 address reaches the resolver without its brackets, which made such a relay unreachable, a scheme in capitals is a WebSocket's, and userinfo and fragments are refused as a page refuses them. SNI goes through webcpp::beast and names a host name only. The backend's constructors throw nothing: native::make_tls_context makes its context, TLS 1.2 or newer over the system's authorities, as a result, and a backend may take the program's own, webcpp's embedded roots among them; one that holds an error keeps it in tls_context() and its wss:// relays report a close. The relay_executor bridge goes, since the session names webcpp::asio's executor on both targets. --- build.jam | 10 +- doc/building.adoc | 15 +- doc/native.adoc | 62 ++- include/webcpp/trystero/native/backend.hpp | 107 ++-- include/webcpp/trystero/native/websocket.hpp | 536 +++++++++++++------ test/native_websocket_test.cpp | 398 +++++++++++++- 6 files changed, 889 insertions(+), 239 deletions(-) diff --git a/build.jam b/build.jam index 0e39364..01ad84f 100644 --- a/build.jam +++ b/build.jam @@ -70,8 +70,14 @@ alias trystero : : @trystero-dependencies # The native backend: its WebRTC is webcpp::webrtc's, which brings the pinned # libdatachannel and OpenSSL, and works with exceptions on and off, through -# libdatachannel's C API; so does the backend. +# libdatachannel's C API; so does the backend. Its relays' WebSockets are +# webcpp::beast's over the same OpenSSL (//tls), their URLs read with +# Boost.URL, built from Boost's sources once per variant; webcpp::asio's +# //tls adds webcpp's embedded authorities, which a program may trust in +# place of the system's (make_tls_client_context). # tag::native[] alias native : : @native-dependencies - : : trystero /webcpp/webrtc//webrtc ; + : : trystero /webcpp/webrtc//webrtc + /webcpp/beast//tls /webcpp/asio//tls + /webcpp//boost_url ; # end::native[] diff --git a/doc/building.adoc b/doc/building.adoc index 13b0c53..797f6b4 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -31,6 +31,14 @@ libsecp256k1 needs an external installation: | both backends' WebRTC | `/webcpp/webrtc//webrtc`, the superproject's `libs/webrtc` +| webcpp::beast +| the native backend's relays: their WebSockets and TLS +| `/webcpp/beast//tls`: natively Boost.Beast over the source-built OpenSSL + +| Boost.URL +| the native backend's relays: their URLs +| `/webcpp//boost_url`, built from Boost's sources once per variant + | libdatachannel 0.24.6 | the native backend, through webcpp::webrtc | `/webcpp/third_party//libdatachannel`, built from `third_party/libs/libdatachannel` @@ -83,7 +91,12 @@ and links its runtime in the suspension variant the build asks, it, as `quick_start-60-d-jspi.js`. A native program uses `/webcpp/trystero//native`, which adds webcpp::webrtc, -with libdatachannel and the same source-built OpenSSL used by Asio and Beast: +with libdatachannel and the same source-built OpenSSL used by Asio and Beast; +webcpp::beast's TLS over that OpenSSL for the relays' WebSockets; 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 +(<>): [listing] ---- diff --git a/doc/native.adoc b/doc/native.adoc index 4a779db..fd3a373 100644 --- a/doc/native.adoc +++ b/doc/native.adoc @@ -10,8 +10,9 @@ Natively, `native::backend` implements the backend interface over webcpp::webrtc for WebRTC, which natively is https://github.com/paullouisageneau/libdatachannel[libdatachannel]'s -(<>), 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 +(<>), webcpp::beast for the relays' WebSockets, +natively Boost.Beast's, 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 @@ -33,10 +34,10 @@ refuses is not made, and no exception crosses into trystero. (`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. 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; without exceptions Boost calls -the program's `boost::throw_exception` instead. +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-native-threads] === Threads @@ -78,7 +79,8 @@ webcpp::webrtc's `runtime` holds what libdatachannel keeps for the whole process, its threads and its global state, and caps the peer connections alive at once. A native backend makes one of its own, with `backend_config::runtime`, or takes the program's: `native::backend(ex, -runtime, config)`. Each of its connections and channels keeps that runtime +runtime, config)`, or `native::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 process holds one runtime at a time, since libdatachannel's state is the process's: a program @@ -127,15 +129,49 @@ with, beside the app's `ice_servers`: [#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 +The relays are reached over webcpp::beast, natively Boost.Beast's own +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 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, as a page's `WebSocket` reads it: the +scheme in any case, a host name in lower case and with its escapes decoded, +an IPv6 address in brackets (`ws://[2001:db8::1]:7447/`), whose address +without them is what the resolver looks up, and the scheme's port when the URL +names none. A URL of another scheme, without a host, with a user name or a +fragment, or with a port beyond 65535, is refused; the relay reports a close, +as an unreachable one does, and the room retries it later as it would any +other. + +Over TLS the connection names the relay's host to the server (SNI) when it is +a name, never when it is an address, and checks the relay's certificate +against the URL's host, a name or an address. By default the backend makes +its TLS context with `native::make_tls_context()`: TLS 1.2 or newer, and the +system's certificate authorities, those OpenSSL's default verify paths name. +A relay whose certificate does not verify is unreachable, and the room +retries it later. An 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,cpp] +---- +trystero::native::backend backend(io.get_executor(), + webcpp::asio::make_tls_client_context()); +---- + +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. + A relay is a third party, and the backend bounds what one can make the room hold: diff --git a/include/webcpp/trystero/native/backend.hpp b/include/webcpp/trystero/native/backend.hpp index 9b82422..ee3d1f9 100644 --- a/include/webcpp/trystero/native/backend.hpp +++ b/include/webcpp/trystero/native/backend.hpp @@ -22,10 +22,10 @@ #include #include // lint-world: posts handlers only +#include // lint-world: the relays' TLS #include -#include // lint-world: the relays' Boost.Beast WebSockets -#include // lint-world: the relays' TLS +#include #include #include @@ -41,9 +41,9 @@ /** * The native target: the backend interface over webcpp::webrtc for WebRTC, natively - * libdatachannel's, 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. + * libdatachannel's, webcpp::beast for the relays' WebSockets, natively Boost.Beast's, 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 { @@ -105,41 +105,77 @@ class backend : public trystero::backend::factory { public: /** * A backend with a runtime of its own, made with `backend_config::runtime`, whose TLS verifies - * relays against the system's certificate authorities. + * relays against the system's certificate authorities, as @ref make_tls_context makes it. + * + * It throws nothing: when OpenSSL cannot make the TLS context, `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. * @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; without exceptions, Boost's - * `throw_exception`, which the program defines, is called instead. */ explicit backend(webcpp::asio::any_io_executor ex, backend_config config = {}) - : backend(std::move(ex), nullptr, std::move(config)) {} + : backend(std::move(ex), make_tls_context(), nullptr, std::move(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, or a private one. + * + * @param ex The executor everything the backend reports runs on. + * @param tls The TLS context of every `wss://` connection, which should verify peers; 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 are made with. + */ + backend(webcpp::asio::any_io_executor ex, boost::system::result tls, + backend_config config = {}) + : backend(std::move(ex), std::move(tls), nullptr, std::move(config)) {} /** - * A backend whose peer connections the program's runtime counts. + * A backend whose peer connections the program's runtime counts, and whose TLS verifies relays + * against the system's certificate authorities, as the first constructor's does. * * @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 are made with; its `runtime` is not used. - * @throws std::exception As the other constructor. */ backend(webcpp::asio::any_io_executor ex, ::webcpp::webrtc::runtime& runtime, backend_config config = {}) + : backend(std::move(ex), make_tls_context(), runtime, std::move(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 are made with; its `runtime` is not used. + */ + backend(webcpp::asio::any_io_executor ex, boost::system::result tls, + ::webcpp::webrtc::runtime& runtime, backend_config config = {}) // An empty owner: the pointer does not own the program's runtime. - : backend(std::move(ex), + : backend(std::move(ex), std::move(tls), std::shared_ptr<::webcpp::webrtc::runtime>( std::shared_ptr<::webcpp::webrtc::runtime>(), &runtime), std::move(config)) {} /** - * The TLS configuration of the relays' connections, for an application with authorities of its - * own. + * The TLS context of the relays' connections, which an application may still configure before + * the backend connects to a relay. * - * @return The context every `wss://` connection of the backend is made with. + * @return The context every `wss://` connection of the backend is made with, or the error that + * kept it from being made. */ - boost::asio::ssl::context& tls_context() { return tls_; } + boost::system::result tls_context() { + if (!tls_) { + return tls_.error(); + } + return *tls_; + } /** * The runtime that counts the backend's peer connections. @@ -149,18 +185,19 @@ class backend : public trystero::backend::factory { [[nodiscard]] ::webcpp::webrtc::runtime& runtime() const { return *runtime_; } /** - * Opens a WebSocket to a relay over Boost.Beast, with @ref connect_websocket. + * 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 and its queued texts are - * allocated in. - * @return The WebSocket. + * @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(relay_executor(), tls_, url, std::move(h), memory, + return connect_websocket(ex_, tls_ ? &*tls_ : nullptr, url, std::move(h), memory, config_.relay_limits); } @@ -253,33 +290,15 @@ class backend : public trystero::backend::factory { private: // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - backend(webcpp::asio::any_io_executor ex, std::shared_ptr<::webcpp::webrtc::runtime> runtime, - backend_config config) + backend(webcpp::asio::any_io_executor ex, boost::system::result tls, + std::shared_ptr<::webcpp::webrtc::runtime> runtime, backend_config config) // NOLINTEND(performance-unnecessary-value-param) : ex_(std::move(ex)), config_(std::move(config)), runtime_(runtime ? std::move(runtime) : own_runtime(config_.runtime)), 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 executor of the relays' WebSockets, which are Boost.Beast's and take Boost.Asio's. - * - * Natively webcpp::asio is Boost.Asio, and the two executors are one: the backend builds - * natively alone. The reference of the guide reads every header for Emscripten's target, - * where webcpp::asio is its own and the backend is never built: it names no executor there. - */ - [[nodiscard]] boost::asio::any_io_executor relay_executor() const { -#ifdef WEBCPP_TARGET_NATIVE - return ex_; -#else - return {}; -#endif - } + tls_(std::move(tls)) {} /** A runtime of the backend's own, which its connections share with it. */ static std::shared_ptr<::webcpp::webrtc::runtime> own_runtime( @@ -325,7 +344,7 @@ class backend : public trystero::backend::factory { backend_config config_; std::shared_ptr<::webcpp::webrtc::runtime> runtime_; trystero::detail::construction_window constructions_; - boost::asio::ssl::context tls_; + boost::system::result tls_; }; } // namespace webcpp::trystero::native diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp index 2189f6d..6d544d4 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/native/websocket.hpp @@ -10,30 +10,45 @@ #include #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 // 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 +#ifdef WEBCPP_TARGET_NATIVE +#include +#include +#endif +#include +#include +#include +#include +#include +#include + +#include +#include #include #include +#include +#include #include #include #include #include #include #include +#include +#include #include namespace webcpp::trystero::native { @@ -56,100 +71,241 @@ struct websocket_limits { * 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. + * `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 it queued none. */ +inline boost::system::error_code openssl_error() { +#ifdef WEBCPP_TARGET_NATIVE + // Asio's own TLS errors are OpenSSL's codes, in its category, as an int. + if (const auto code = ERR_get_error(); 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. 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. + */ +inline boost::system::result make_tls_context() { +#ifdef WEBCPP_TARGET_NATIVE + SSL_CTX* const raw = SSL_CTX_new(TLS_client_method()); + if (raw == nullptr) { + return detail::openssl_error(); + } + // The context owns the handle from here, and throws only for a null one. + webcpp::asio::ssl::context context(raw); + if (SSL_CTX_set_min_proto_version(raw, TLS1_2_VERSION) != 1) { + return detail::openssl_error(); + } + SSL_CTX_set_options(raw, SSL_OP_NO_COMPRESSION); + boost::system::error_code ec; + context.set_default_verify_paths(ec); // lint-world: the system's certificate authorities + if (ec) { + return ec; + } + context.set_verify_mode(webcpp::asio::ssl::verify_peer, ec); + if (ec) { + return ec; + } + return context; +#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; - /** The host, a name or an address. */ + /** 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, the scheme's default when the URL names none. */ + /** 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; }; -/** The parts of a `ws://` or `wss://` URL, in `memory`; nothing for any other scheme or without a - * host. */ +/** Whether a decoded host name holds a byte that a page's URL parser refuses in a host. */ +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; + }); +} + +/** + * 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, or with a port beyond 65535. + */ 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 = false, + .secure = secure, + .named = view.host_type() == boost::urls::host_type::name, .host = std::pmr::string(memory), .port = std::pmr::string(memory), + .handshake_host = 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 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; + } + 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.append("[").append(out.host).append("]"); + break; + default: // none, or an IPvFuture address, which no resolver knows + 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(), '/'); + 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.append(":").append(out.port); } - 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; + 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, 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. + * One WebSocket connection over webcpp::beast, 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. * - * 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. + * 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; natively Boost.Beast's stream state, the resolver's results and + * OpenSSL's state are theirs. On Emscripten the page's stream keeps its state in the room's + * resource too. */ 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 = boost::asio::ip::tcp; + using tcp = webcpp::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>; + std::conditional_t, + webcpp::beast::tcp_stream>; /** Beast's WebSocket stream. */ - using stream_type = boost::beast::websocket::stream; + using stream_type = webcpp::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) + /** 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)), + 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))), - queue_(memory) {} + buffer_(std::pmr::polymorphic_allocator(memory)), + queue_(memory), + writing_text_(memory) {} - /** Starts the coroutine that connects, shakes hands and reads. */ + /** + * 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() { - boost::asio::co_spawn( - ex_, [self = this->shared_from_this()] { return self->run(); }, boost::asio::detached); + 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); + })); } /** @@ -164,17 +320,15 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()] { return self->write_queue(); }, - boost::asio::detached); + write_next(); } /** Closes with a WebSocket close frame, or drops a connection still being made. */ @@ -184,126 +338,187 @@ class websocket_session : public std::enable_shared_from_thisshared_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); + 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; - boost::beast::get_lowest_layer(ws_).close(); + resolver_.cancel(); + webcpp::beast::get_lowest_layer(ws_).close(); } private: - static stream_type make_stream(const boost::asio::any_io_executor& ex, - boost::asio::ssl::context& tls) { + /** 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 + (void)memory; if constexpr (Secure) { - return stream_type(ex, tls); + return stream_type(ex, *tls); } else { (void)tls; return stream_type(ex); } +#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)); } - 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(); + void on_resolve(const boost::system::error_code& ec, + const tcp::resolver::results_type& results) { + if (ec || closing_) { + end(); + return; } - 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(); + 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) { +#ifdef WEBCPP_TARGET_NATIVE 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(); + // 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 the browser the page's WebSocket sends the name and verifies the certificate. + ws_.next_layer().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(); } - lowest.expires_never(); - auto timeouts = boost::beast::websocket::stream_base::timeout::suggested( - boost::beast::role_type::client); + } + + 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(); + auto timeouts = webcpp::beast::websocket::stream_base::timeout::suggested( + webcpp::beast::role_type::client); +#ifdef WEBCPP_TARGET_NATIVE 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); - 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(); + 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; + ws_.text(true); + // A longer message fails the read, which closes the connection, as a page's does. + ws_.read_message_max(protocol::max_relay_message_bytes); 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()); + read(); + } + + void read() { + ws_.async_read(buffer_, bound([self = this->shared_from_this()]( + const boost::system::error_code& ec, std::size_t size) { + self->on_read(ec, size); + })); + } + + void on_read(const boost::system::error_code& ec, std::size_t size) { + if (ec) { + end(); + return; } - end(); + 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()); + if (closing_) { + end(); + return; + } + read(); } /** - * Writes the queued texts in turn, each moved out of the queue into this frame before its - * write starts. + * 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 it owns, and its completion - * touches only that text. + * text being written is no longer in it, so the write reads a text the session 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; - } + void write_next() { + if (queue_.empty() || !open_ || ended_) { + writing_ = false; + return; } - writing_ = false; + writing_text_ = std::move(queue_.front()); + queue_.pop_front(); + queued_bytes_ -= writing_text_.size(); + ws_.async_write(webcpp::asio::buffer(writing_text_), + bound([self = this->shared_from_this()](const boost::system::error_code& ec, + std::size_t) { + if (ec) { + self->writing_ = false; + return; + } + self->write_next(); + })); } void end() { @@ -320,7 +535,7 @@ class websocket_session : public std::enable_shared_from_this h_; + webcpp::beast::basic_flat_buffer> buffer_; std::pmr::deque queue_; - std::size_t queued_bytes_ = 0; // of the texts in 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; @@ -362,38 +579,43 @@ class websocket_handle : public backend::websocket { } // namespace detail /** - * Connects to a Nostr relay over Boost.Beast: `ws://` in the clear, `wss://` over TLS with `tls`. + * Connects to a Nostr relay over webcpp::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. + * relay that stops reading is dropped once the queue would pass `limits.max_queued_bytes`, and, + * natively, one that stops answering once `limits.idle_timeout` passes with its keep-alive ping + * unanswered; both report a close. The URL is read with Boost.URL: an IPv6 address in brackets, a + * scheme in any case. A URL it cannot parse, one with userinfo or a fragment, and a `wss://` URL + * without `tls`, report a close, as an unreachable relay does. Natively a `wss://` connection + * names the host to the server (SNI) when it is a name, and checks the certificate against the + * URL's host, a name or an address. 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. + * peers, as the context of @ref make_tls_context does; null when the program has none. * @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 memory The room's resource, which the connection, its handlers, its queued texts, its read + * buffer and its operations are allocated in; natively Boost.Beast's stream state and OpenSSL's + * are theirs. * @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 = {}) { +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) { + 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), }; } diff --git a/test/native_websocket_test.cpp b/test/native_websocket_test.cpp index d8cc7b4..5a07aaf 100644 --- a/test/native_websocket_test.cpp +++ b/test/native_websocket_test.cpp @@ -4,20 +4,28 @@ // 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. +// Tests the native WebSocket client, webcpp::beast's, natively 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 @@ -29,6 +37,8 @@ #include #include +#include "require.hpp" + namespace asio = boost::asio; namespace beast = boost::beast; namespace trystero = webcpp::trystero; @@ -37,6 +47,63 @@ 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. * @@ -69,24 +136,79 @@ struct echo_server { if (accepted) { co_return; } - beast::flat_buffer buffer; + 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; + context.use_certificate_chain(asio::buffer(relay_certificate), ec); + webcpp::test::require(BOOST_TEST(!ec)); + context.use_private_key(asio::buffer(relay_key), asio::ssl::context::pem, ec); + webcpp::test::require(BOOST_TEST(!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 [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) { + auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::use_awaitable)); + if (ec) { co_return; } - buffer.consume(buffer.size()); + 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; + std::vector server_names; + int failed_handshakes = 0; }; /** What a hostile relay does once it reads a client's first message. */ @@ -214,21 +336,245 @@ void urls_name_a_scheme_host_port_and_path() { 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::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(!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::native::detail::parse_url("https://example.org").has_value()); BOOST_TEST(!trystero::native::detail::parse_url("wss://").has_value()); } +// 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::native::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::native::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::native::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::native::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::native::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::native::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::native::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::native::detail::parse_url("wss://user:pw@relay.example.org").has_value()); + BOOST_TEST(!trystero::native::detail::parse_url("wss://relay.example.org/#top").has_value()); + BOOST_TEST(!trystero::native::detail::parse_url("wss://relay.example.org:99999").has_value()); + BOOST_TEST(!trystero::native::detail::parse_url("ws:relay.example.org").has_value()); + BOOST_TEST(!trystero::native::detail::parse_url("ws://[v1.x]/").has_value()); + // A name the resolver would read up to its first NUL. + BOOST_TEST(!trystero::native::detail::parse_url("ws://relay%00.example.org/").has_value()); +} + +// 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. +void a_relay_at_an_ipv6_address_opens() { + 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, + "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, 0); +} + +// What a socket reported, recorded by the handlers record() makes. +struct reports { + bool opened = false; + int 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::native::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); +} + +// 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::native::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, 0); + BOOST_TEST_EQ(server.failed_handshakes, 0); + 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::native::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 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::native::make_tls_context(); + if (!BOOST_TEST(tls.has_value())) { + return; + } + reports seen; + const auto socket = + trystero::native::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 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); + tls_echo_server secure(io); + { + trystero::native::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::native::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::native::backend backend(io.get_executor()); + BOOST_TEST(backend.tls_context().has_value()); +} + void opens_sends_in_order_receives_and_closes_once() { asio::io_context io; const echo_server server(io); @@ -237,7 +583,7 @@ void opens_sends_in_order_receives_and_closes_once() { int closes = 0; std::vector received; const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), + io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, .message = [&](std::string_view text) { received.emplace_back(text); }, @@ -272,7 +618,7 @@ void a_message_longer_than_a_relay_sends_closes_the_socket() { int closes = 0; std::vector received; const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), + io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, .message = [&](std::string_view text) { received.push_back(text.size()); }, @@ -301,7 +647,7 @@ void an_unreachable_relay_closes_without_opening() { 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), + io.get_executor(), &tls, "ws://127.0.0.1:" + std::to_string(port), { .open = [&] { opened = true; }, .message = {}, @@ -319,7 +665,7 @@ void a_dropped_socket_reports_nothing() { int events = 0; { const auto socket = - trystero::native::connect_websocket(io.get_executor(), tls, server.url(), + trystero::native::connect_websocket(io.get_executor(), &tls, server.url(), { .open = [&] { ++events; }, .message = [&](std::string_view) { ++events; }, @@ -337,7 +683,7 @@ void closing_right_after_a_send_lets_the_write_finish_first() { 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(), + const auto socket = trystero::native::connect_websocket(io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, .message = {}, @@ -370,7 +716,7 @@ void a_connection_that_ends_during_a_write_closes_once(misbehaviour what) { bool opened = false; int closes = 0; std::shared_ptr socket; - socket = trystero::native::connect_websocket(io.get_executor(), tls, server.url(), + socket = trystero::native::connect_websocket(io.get_executor(), &tls, server.url(), { .open = [&] { @@ -402,7 +748,7 @@ void a_relay_that_stops_reading_is_dropped_at_the_queue_bound() { 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(), + const auto socket = trystero::native::connect_websocket(io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, .message = {}, @@ -431,7 +777,7 @@ void a_relay_that_stops_answering_times_out() { bool opened = false; int closes = 0; const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), + io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, .message = {}, @@ -458,7 +804,7 @@ void a_quiet_relay_that_answers_pings_stays_connected() { int closes = 0; std::vector received; const auto socket = trystero::native::connect_websocket( - io.get_executor(), tls, server.url(), + io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, .message = [&](std::string_view text) { received.emplace_back(text); }, @@ -482,6 +828,14 @@ void a_quiet_relay_that_answers_pings_stays_connected() { int main() { urls_name_a_scheme_host_port_and_path(); + urls_name_ipv6_hosts_and_refuse_what_a_page_refuses(); + a_relay_at_an_ipv6_address_opens(); + the_tls_context_verifies_peers_from_tls_1_2(); + a_relay_over_tls_opens_and_is_sent_its_name(); + a_relay_whose_certificate_names_another_host_closes_without_opening(); + a_relay_of_an_authority_not_trusted_closes_without_opening(); + a_backend_reaches_relays_with_the_tls_context_it_is_given(); + a_backend_makes_its_own_tls_context(); opens_sends_in_order_receives_and_closes_once(); a_message_longer_than_a_relay_sends_closes_the_socket(); an_unreachable_relay_closes_without_opening(); From eec0841f1d22599852d81bc1f56368daeff8cc2d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:30:37 -0300 Subject: [PATCH 008/116] trystero: the browser on webcpp::asio's run family A page's program now runs its io_context from main, under a work guard, as webcpp::asio's model asks: browser::event_loop, browser/js.hpp and browser/src.hpp are gone, and nothing polls the io_context from a JavaScript event. browser::backend takes the io_context's executor; the page's WebSocket events reach it through webcpp::asio's bridge, Web Crypto's promises through browser::async_await, made in an async function so that a synchronous throw becomes a rejection, and its timer is the new detail::timer over webcpp::asio's steady_timer, whose waits are numbered so that one cancelled, restarted or destroyed never fires. A failed getentropy now fails the seal, and ends the program in random(), as the native backend does. The browser tests run their io_context from main and end with webcpp::test::exit_status; browser_event_loop goes, its subject now asio's bridge and run family. New: timer, on both targets, and browser_page, whose work guard keeps a page with no room running and whose exports, called while run is suspended, only post and reach the room. The examples and the interop's browser peer run from main, their page calls posting to the io_context. --- example/chat/chat.cpp | 44 +- example/quick_start.cpp | 19 +- include/webcpp/trystero/browser/backend.hpp | 714 +++++++++++------- .../webcpp/trystero/browser/event_loop.hpp | 496 ------------ include/webcpp/trystero/browser/js.hpp | 100 --- include/webcpp/trystero/browser/src.hpp | 76 -- include/webcpp/trystero/detail/timer.hpp | 88 +++ test/Jamfile | 11 +- test/browser_data_channel_test.cpp | 53 +- test/browser_event_loop_test.cpp | 251 ------ test/browser_page_test.cpp | 137 ++++ test/browser_peer_connection_test.cpp | 87 +-- test/browser_sealer_test.cpp | 99 ++- test/browser_websocket_bound_test.cpp | 69 +- test/browser_websocket_late_events_test.cpp | 84 +-- test/browser_websocket_test.cpp | 102 +-- test/oracle/interop/cpp.html | 2 +- test/oracle/interop/peer.cpp | 44 +- test/timer_test.cpp | 131 ++++ 19 files changed, 1096 insertions(+), 1511 deletions(-) delete mode 100644 include/webcpp/trystero/browser/event_loop.hpp delete mode 100644 include/webcpp/trystero/browser/js.hpp delete mode 100644 include/webcpp/trystero/browser/src.hpp create mode 100644 include/webcpp/trystero/detail/timer.hpp delete mode 100644 test/browser_event_loop_test.cpp create mode 100644 test/browser_page_test.cpp create mode 100644 test/timer_test.cpp diff --git a/example/chat/chat.cpp b/example/chat/chat.cpp index f60fee1..babb762 100644 --- a/example/chat/chat.cpp +++ b/example/chat/chat.cpp @@ -9,15 +9,17 @@ // id are in the same chat. #include #include -#include // once per program: the JavaScript export +#include #include +#include #include #include #include #include +#include using emscripten::val; namespace trystero = webcpp::trystero; @@ -27,8 +29,7 @@ namespace { // tag::state[] struct chat { webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + trystero::browser::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. @@ -39,12 +40,12 @@ struct chat { // end::state[] chat& the_chat() { - static chat c; // the page's one chat; it lives as long as the tab + static chat c; // the page's one chat, which main runs and the page's calls post to return c; } val js(std::string_view text) { - return the_chat().loop.text(text); + return trystero::browser::js_string(text); } val js(bool value) { @@ -69,8 +70,7 @@ void join_room(const std::string& app_id, const std::string& room_id) { 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) { @@ -110,12 +110,38 @@ void send_message(std::string text) { // end::send[] +// tag::calls[] +/** The page's `join`: posted to the io_context, which main runs. */ +void post_join(std::string app_id, std::string room_id) { + webcpp::asio::post(the_chat().io, [app_id = std::move(app_id), room_id = std::move(room_id)] { + join_room(app_id, room_id); + }); +} + +/** The page's `send`: posted to the io_context, which main runs. */ +void post_send(std::string text) { + webcpp::asio::post(the_chat().io, + [text = std::move(text)]() mutable { send_message(std::move(text)); }); +} + +// end::calls[] + } // namespace // tag::bindings[] EMSCRIPTEN_BINDINGS(chat_example) { - emscripten::function("join", &join_room); - emscripten::function("send", &send_message); + emscripten::function("join", &post_join); + emscripten::function("send", &post_send); } // end::bindings[] + +// tag::main[] +int main() { + auto& c = the_chat(); + // 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::main[] diff --git a/example/quick_start.cpp b/example/quick_start.cpp index 7fa057b..89aaf91 100644 --- a/example/quick_start.cpp +++ b/example/quick_start.cpp @@ -11,11 +11,11 @@ // tag::includes[] #include #include -#include // once per program #include #include #include +#include #include #include @@ -38,12 +38,11 @@ struct lobby { trystero::action echo = room.make_action("echo"); }; -/** What the page keeps alive: event loop, backend, app, and the room it joined. */ +/** What the page keeps alive: its io_context, the backend, the 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"}}; + trystero::browser::backend backend{io.get_executor()}; + trystero::app app{io.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 @@ -81,8 +80,8 @@ asio::awaitable echo_back(trystero::action& echo) { // tag::main[] int main() { - auto* app = new application; // a page's program lives as long as the tab - auto* lobby = app->join(); + application app; // lives in main, whose run lasts as long as the tab + auto* lobby = app.join(); if (lobby == nullptr) { return 1; } @@ -98,7 +97,11 @@ int main() { lobby->chat.on_message([](const std::string& text, const trystero::message_info& info) { std::cout << info.from << ": " << text << '\n'; }); - asio::co_spawn(app->loop.get_executor(), echo_back(lobby->echo), asio::detached); + asio::co_spawn(app.io, echo_back(lobby->echo), asio::detached); + + // The page waits for its peers with no work of its own at times: the guard keeps the run going. + const auto guard = asio::make_work_guard(app.io); + app.io.run(); // lint-run: the page's program, suspended into the browser's event loop } // end::main[] diff --git a/include/webcpp/trystero/browser/backend.hpp b/include/webcpp/trystero/browser/backend.hpp index 212ba28..73c31aa 100644 --- a/include/webcpp/trystero/browser/backend.hpp +++ b/include/webcpp/trystero/browser/backend.hpp @@ -10,11 +10,10 @@ #include #include -#include -#include +#include +#include #include #include -#include #include #include #include @@ -22,30 +21,44 @@ #include #include -#include // lint-world: binds an allocator only -#include // lint-world: posts handlers only +#include // lint-world: names the executor only +#include // lint-world: binds an allocator only +#include // lint-world: awaits the page's promises +#include // lint-world: the page's events +#include // lint-world: the bridge of the executor's context +#include // lint-world: the bridge of the executor's context +#include #include #include // lint-world: getentropy, the page's entropy +#include + +#include +#include #include +#include +#include +#include #include #include #include +#include #include #include +#include #include -#include /** - * The browser target: the backend interface over the page's own `WebSocket`, `setTimeout` and - * `crypto.subtle`, through `emscripten::val`, and over its `RTCPeerConnection` and - * `RTCDataChannel` through webcpp::webrtc. It needs a secure context (https, or http on - * localhost), where `crypto.subtle` exists. + * The browser target: the backend interface over the page's own `WebSocket` and `crypto.subtle`, + * over webcpp::asio's timers, and over its `RTCPeerConnection` and `RTCDataChannel` through + * webcpp::webrtc. 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. + * Tip: the page's events reach C++ through webcpp::asio's bridge, a service of the program's + * io_context, which only posts to it: they run while the program runs that io_context, from + * `main`. 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. */ namespace webcpp::trystero::browser { @@ -54,140 +67,210 @@ 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()))); +// The page's WebSocket and 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. JavaScript stays in JavaScript: what can throw is caught +// there, before it can reach a WebAssembly frame, and a Web Crypto call is made inside an async +// function, so that what it throws becomes the rejection of the promise it returns. The functions +// use Emval, HEAPU8 and UTF8ToString, which webcpp::asio's browser runtime has Emscripten link, in +// every program on /webcpp/asio//asio. + +// 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)); } -/** 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; +/** + * The UTF-8 bytes of `text` as a `Uint8Array`, or null for a value that is no string or for a + * text longer than `max` bytes, whose length is checked first in UTF-16 units. + */ +inline emscripten::EM_VAL js_encode(emscripten::EM_VAL text, double max) { + return reinterpret_cast(EM_ASM_PTR(({ + const text = Emval.toValue($0); + const max = $1; + + if (typeof text !== 'string' || text.length > max) return Emval.toHandle(null); + const bytes = new TextEncoder().encode(text); + return Emval.toHandle(bytes.length > max ? null : bytes); + }), text, max)); +} + +/** 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); } /** - * 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. + * A `WebSocket` to `url` whose events call `deliver` with `{kind: 0}`, `{kind: 1, data}` and + * `{kind: 2}`, its open, a message and its close, or null when the constructor throws. */ -template -void defer(event_loop& loop, std::pmr::memory_resource* memory, F&& f) { - webcpp::asio::post(loop.io(), - webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(memory), - std::forward(f))); - loop.schedule_poll(); +inline emscripten::EM_VAL js_websocket(emscripten::EM_VAL url, emscripten::EM_VAL deliver) { + return reinterpret_cast(EM_ASM_PTR(({ + const url = Emval.toValue($0); + const deliver = Emval.toValue($1); + + try { + const socket = new WebSocket(url); + socket.onopen = () => deliver({kind: 0}); + socket.onmessage = event => deliver({kind: 1, data: event.data}); + socket.onclose = () => deliver({kind: 2}); + return Emval.toHandle(socket); + } catch (_) { + return Emval.toHandle(null); + } + }), url, deliver)); } /** - * 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. + * Sends `size` bytes of UTF-8 at `data` as a text when the socket is open, returning 1, with + * nothing sent, when its `bufferedAmount` would pass `bound` with them, else 0. */ -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 int js_send(emscripten::EM_VAL socket, const char* data, std::size_t size, double bound) { + return EM_ASM_INT(({ + const socket = Emval.toValue($0); + const data = $1 >>> 0; + const size = $2 >>> 0; + const bound = $3; + + try { + if (socket.readyState !== 1) return 0; + if (Number(socket.bufferedAmount) + size > bound) return 1; + socket.send(UTF8ToString(data, size, true)); + } catch (_) { + } + return 0; + }), socket, data, size, bound); } -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; +/** Closes a socket, its handlers set to null first with `detach`, so that it reports nothing. */ +inline void js_close(emscripten::EM_VAL socket, bool detach) { + EM_ASM(({ + const socket = Emval.toValue($0); + const detach = $1; + + try { + if (detach) { + socket.onopen = null; + socket.onmessage = null; + socket.onclose = null; + } + socket.close(); + } catch (_) { } - defer(loop, memory, [done = std::move(done), reason = operation.value]() mutable { - done(false, std::move(reason)); - }); + }), socket, detach); } -} // namespace detail +/** + * 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 timer over the page's `setTimeout`. - * - * @see "The browser backend", in the guide. + * 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. */ -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_); - } +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 - /** - * 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()); - } +/** Takes ownership of a handle an import returned. */ +inline val take(emscripten::EM_VAL handle) { + return val::take_ownership(handle); +} - /** 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; +/** + * The UTF-8 bytes of a JavaScript string, copied straight into a string of `memory` when they are + * at most `max_bytes`, and nothing otherwise, nor for a value that is no string. + */ +inline std::optional utf8(const val& text, std::pmr::memory_resource* memory, + std::size_t max_bytes) { + const val encoded = take(js_encode(text.as_handle(), static_cast(max_bytes))); + if (encoded.isNull()) { + return std::nullopt; } + std::pmr::string out(encoded["length"].as(), '\0', memory); + js_copy(encoded.as_handle(), out.data(), out.size()); + return out; +} -private: - void on_fire() { - handle_ = val::undefined(); - auto fire = std::exchange(fire_, nullptr); - if (fire) { - fire(); // may destroy this timer - } - } +/** A copy of an `ArrayBuffer`'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); + js_copy(view.as_handle(), out.data(), out.size()); + return out; +} - event_loop& loop_; - int id_; - val handle_ = val::undefined(); - handler fire_; -}; +/** The bridge of the io_context an executor runs on, which delivers the page's events 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 val js_string(std::string_view utf8) { + return detail::take(detail::js_text(utf8.data(), utf8.size())); +} /** - * A WebSocket over the page's `WebSocket`. + * A WebSocket over the page's `WebSocket`, whose events reach the executor through webcpp::asio's + * bridge. * - * 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. + * Each event of the page's socket, its open, a message or its close, is posted to the executor in + * the order the page delivers them, and reaches the handlers when it runs there. 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 after the call. A page has no idle timeout: its `WebSocket` cannot ping. * * @see "The browser backend", in the guide. */ -class websocket : public backend::websocket { +class websocket : public backend::websocket, public std::enable_shared_from_this { public: /** * Opens a WebSocket to `url`. @@ -196,46 +279,43 @@ class websocket : public backend::websocket { * 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 ex The executor its events are posted to, an io_context's of webcpp::asio, 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. + * @param memory The room's resource, which the WebSocket's handlers, its events and the texts + * it receives are allocated in. */ - websocket(event_loop& loop, std::string_view url, handlers h, std::pmr::memory_resource* memory) - : loop_(loop), + websocket(const webcpp::asio::any_io_executor& ex, std::string_view url, handlers h, + std::pmr::memory_resource* memory) + : ex_(ex), 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; + events_(*this), + bridge_(&detail::bridge_of(ex_)), + key_(bridge_->add(events_)) { + socket_ = detail::take( + detail::js_websocket(js_string(url).as_handle(), bridge_->function(key_).as_handle())); + if (socket_.isNull()) { + socket_ = val::undefined(); + leave_bridge(); + report(close_event, std::pmr::string(memory_)); } - socket_ = made.value; - socket_.set("onopen", loop_.handler(id_, 0)); - socket_.set("onmessage", loop_.handler(id_, 1)); - socket_.set("onclose", loop_.handler(id_, 2)); } + /** Not copyable: the bridge delivers to it by its address. */ + websocket(const websocket&) = delete; + + /** Not copy-assignable: the bridge delivers to it by its address. */ + websocket& operator=(const websocket&) = delete; + /** 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()); + leave_bridge(); + if (!socket_.isUndefined()) { + detail::js_close(socket_.as_handle(), true); } - socket_.call("close"); } /** @@ -243,78 +323,131 @@ class websocket : public backend::websocket { * 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. + * `protocol::max_queued_relay_bytes` drops the socket instead, which reports its close after + * the call. * * @param text The message, read during the call. */ void send(std::string_view text) override { - if (socket_.isUndefined() || socket_["readyState"].as() != 1) { + if (socket_.isUndefined()) { return; } - const auto held = static_cast(socket_["bufferedAmount"].as()); - if (held + text.size() > protocol::max_queued_relay_bytes) { + if (detail::js_send(socket_.as_handle(), text.data(), text.size(), + static_cast(protocol::max_queued_relay_bytes)) != 0) { 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"); + detail::js_close(socket_.as_handle(), false); } } private: + /** What the bridge delivers the page's events of the socket to. */ + class events final : public webcpp::asio::browser::intrusive_registration { + public: + explicit events(websocket& owner) noexcept : owner_(owner) {} + + bool deliver(const val& event) override { return owner_.deliver(event); } + + void shutdown() noexcept override { owner_.shutdown(); } + + private: + websocket& owner_; + }; + + static constexpr int open_event = 0; + static constexpr int message_event = 1; + static constexpr int close_event = 2; + + /** + * Posts an event of the page to the executor, a message copied into the room's resource first, + * or closes the socket for a text too long for a relay; it runs no handler. + */ + bool deliver(const val& event) { + const int kind = event["kind"].as(); + if (kind != message_event) { + report(kind, std::pmr::string(memory_)); + return false; + } + const val data = event["data"]; + if (!data.isString()) { + return false; + } + // 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. + auto text = detail::utf8(data, memory_, protocol::max_relay_message_bytes); + if (!text) { + close(); + return false; + } + report(message_event, std::move(*text)); + return false; + } + + /** The io_context's shutdown: the socket is closed, and reports nothing more. */ + void shutdown() noexcept { + bridge_ = nullptr; + key_ = 0; + if (!socket_.isUndefined()) { + detail::js_close(socket_.as_handle(), true); + socket_ = val::undefined(); + } + } + + /** + * Posts the report of an event to the executor, through the shared handlers: a socket destroyed + * before it runs reports nothing, and a handler may destroy the socket during its own call. + */ + void report(int kind, std::pmr::string text) { + trystero::detail::post( + ex_, memory_, + [weak = std::weak_ptr(h_), kind, text = std::move(text)]() mutable { + const auto h = weak.lock(); + if (!h) { + return; + } + if (kind == open_event) { + if (h->open) { + h->open(); + } + } else if (kind == message_event) { + if (h->message) { + h->message(text); + } + } else if (auto f = std::exchange(h->close, {})) { + f(); + } + }); + } + /** * 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"); + leave_bridge(); + detail::js_close(socket_.as_handle(), true); 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(); - } - } - }); + report(close_event, std::pmr::string(memory_)); } - /** 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(); + /** Removes the registration: an event of the page from now on finds nothing. */ + void leave_bridge() noexcept { + if (bridge_ != nullptr && key_ != 0) { + bridge_->remove(std::exchange(key_, 0)); } } - event_loop& loop_; + webcpp::asio::any_io_executor ex_; std::pmr::memory_resource* memory_; std::shared_ptr h_; - int id_; + events events_; + webcpp::asio::browser::bridge* bridge_; + std::uint64_t key_; val socket_ = val::undefined(); }; @@ -322,9 +455,10 @@ class websocket : public backend::websocket { * 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. + * Each Web Crypto promise is awaited with webcpp::asio's `browser::async_await`, which posts its + * settlement to the executor. 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. */ @@ -336,20 +470,22 @@ class sealer : public backend::sealer, public std::enable_shared_from_this key, std::pmr::memory_resource* memory) - : loop_(loop), raw_key_(key), memory_(memory), waiting_(memory) {} + sealer(const webcpp::asio::any_io_executor& ex, std::array key, + std::pmr::memory_resource* memory) + : ex_(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 or the encryption fails. + * 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) { @@ -392,73 +528,71 @@ class sealer : public backend::sealer, public std::enable_shared_from_this allocator() const { return {memory_}; } + using waiting_operation = handler; - /** 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"]; - } + [[nodiscard]] std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } - 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; + /** 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), {}); + }); } 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_); + if (getentropy(iv.data(), iv.size()) != 0) { // lint-world: a seal's IV + fail(std::move(done), error::backend_failure); + return; + } + webcpp::asio::browser::async_await( + ex_, + 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 val& cipher) mutable { + if (ec) { + done(make_error_code(error::backend_failure), {}); + return; + } + const auto sealed = + protocol::format_sealed(iv, detail::from_js(cipher, memory), 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()) { - detail::defer(loop_, memory_, [done = std::move(done)]() mutable { - done(make_error_code(error::wrong_password), {}); - }); + fail(std::move(done), 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_); + webcpp::asio::browser::async_await( + ex_, + 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 val& plain) mutable { + if (ec) { + 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())); + })); } /** * 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(); + void wait_for_key(waiting_operation op) { + const std::weak_ptr weak = weak_from_this(); if (state_ == key_state::failed) { - detail::defer(loop_, memory_, [weak, op = std::move(op)]() mutable { + trystero::detail::post(ex_, memory_, [weak, op = std::move(op)]() mutable { if (const auto self = weak.lock()) { op(*self, false); } @@ -470,56 +604,50 @@ class sealer : public backend::sealer, public std::enable_shared_from_thiskey_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_); + webcpp::asio::browser::async_await( + ex_, detail::take(detail::js_import_key(raw_key_.data(), raw_key_.size())), + webcpp::asio::bind_allocator(allocator(), + [weak](boost::system::error_code ec, const val& key) { + if (const auto self = weak.lock()) { + self->key_imported(!ec, key); + } + })); } - void key_imported(bool ok, val key) { + void key_imported(bool ok, const val& key) { state_ = ok ? key_state::ready : key_state::failed; - key_ = std::move(key); - for (auto& op : std::exchange(waiting_, {})) { + key_ = key; + std::pmr::deque ready(allocator()); + ready.swap(waiting_); + for (auto& op : ready) { op(*this, ok); } } - enum class key_state { none, importing, ready, failed }; + enum class key_state : std::uint8_t { none, importing, ready, failed }; - event_loop& loop_; + webcpp::asio::any_io_executor ex_; std::array raw_key_; std::pmr::memory_resource* memory_; key_state state_ = key_state::none; val key_ = val::undefined(); - std::pmr::deque> waiting_; + std::pmr::deque waiting_; }; /** - * The browser's factory: one per page, beside the page's `event_loop`. + * The browser's factory: one per page, over the executor of the io_context the program runs. * * 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 + * handlers and their events 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. * + * Tip: every object it makes runs on its executor, whose io_context the program runs from `main` + * (`io.run()`, 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. The app is + * given an executor of the same io_context. + * * @see "The browser backend", in the guide. */ class backend : public trystero::backend::factory { @@ -542,13 +670,14 @@ class backend : public trystero::backend::factory { static constexpr std::size_t max_peer_connections = 256; /** - * Constructs the page's backend, with a webcpp::webrtc runtime of its own: in the browser the - * page's census counts the connections of every runtime alike. + * Constructs the page's backend over `ex`, with a webcpp::webrtc runtime of its own: in the + * browser the page's census counts the connections of every runtime alike. * - * @param loop The page's loop, which must outlive the backend and every object it makes. + * @param ex The executor every object of the backend runs on, an io_context's of + * webcpp::asio, which must outlive the backend and every object it makes. */ - explicit backend(event_loop& loop) - : loop_(loop), + explicit backend(webcpp::asio::any_io_executor ex) + : ex_(std::move(ex)), runtime_(std::allocate_shared<::webcpp::webrtc::runtime>( std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), ::webcpp::webrtc::runtime_options{ @@ -556,6 +685,13 @@ class backend : public trystero::backend::factory { .thread_pool_size = 0, })) {} + /** + * The executor every object of the backend runs on. + * + * @return The executor it was constructed with. + */ + [[nodiscard]] const webcpp::asio::any_io_executor& get_executor() const noexcept { return ex_; } + /** * Opens a WebSocket to a relay, with the page's `WebSocket`. * @@ -568,8 +704,8 @@ class backend : public trystero::backend::factory { 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); + return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), ex_, url, + std::move(h), memory); } /** @@ -585,21 +721,20 @@ class backend : public trystero::backend::factory { std::shared_ptr make_peer_connection( std::span servers, std::pmr::memory_resource* memory) override { - auto made = webrtc::peer_connection::make(runtime_, loop_.get_executor(), servers, {}, - *this, memory); + auto made = webrtc::peer_connection::make(runtime_, ex_, servers, {}, *this, memory); return made ? *made : nullptr; } /** - * Makes a timer, over `setTimeout`. + * Makes a timer, over webcpp::asio's `steady_timer`. * - * @param memory The room's resource, which the timer and its handler are allocated in. + * @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), loop_, - memory); + return std::allocate_shared( + std::pmr::polymorphic_allocator<>(memory), ex_, memory); } /** @@ -612,12 +747,13 @@ class backend : public trystero::backend::factory { */ 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, + return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), ex_, key, memory); } /** - * Fills `out` with the page's entropy, which Emscripten draws from `crypto.getRandomValues`. + * Fills `out` with the page's entropy, which Emscripten draws from `crypto.getRandomValues`, + * and ends the program when the page has none, as the native backend does. * * @param out The bytes to fill. */ @@ -625,7 +761,9 @@ class backend : public trystero::backend::factory { 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 + if (getentropy(out.data() + at, piece) != 0) { // lint-world: Trystero's randomness + std::abort(); // no secure randomness: nothing is safe + } } } @@ -647,7 +785,7 @@ class backend : public trystero::backend::factory { double now_ms() override { return val::global("performance").call("now"); } private: - event_loop& loop_; + webcpp::asio::any_io_executor ex_; std::shared_ptr<::webcpp::webrtc::runtime> runtime_; }; diff --git a/include/webcpp/trystero/browser/event_loop.hpp b/include/webcpp/trystero/browser/event_loop.hpp deleted file mode 100644 index 2482502..0000000 --- a/include/webcpp/trystero/browser/event_loop.hpp +++ /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) - -#ifndef WEBCPP_TRYSTERO_BROWSER_EVENT_LOOP_HPP -#define WEBCPP_TRYSTERO_BROWSER_EVENT_LOOP_HPP - -#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 -#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 `webcpp::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]] webcpp::asio::execution_context& query( - webcpp::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 webcpp::asio::execution::blocking_t::never_t query( - webcpp::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( - webcpp::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(webcpp::asio::io_context& io, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) - : io_(io), - work_(webcpp::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. - */ - webcpp::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. - webcpp::asio::post(io_, webcpp::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; - - webcpp::asio::io_context& io_; - webcpp::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 webcpp::asio::execution_context& executor::query( - webcpp::asio::execution::context_t /*context*/) const noexcept { - return loop_->io(); -} - -template -void executor::execute(F&& f) const { - webcpp::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 096d1d8..0000000 --- a/include/webcpp/trystero/browser/js.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_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); -} - -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 1d7eaa9..0000000 --- a/include/webcpp/trystero/browser/src.hpp +++ /dev/null @@ -1,76 +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); - } - }); -}); - -// 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/detail/timer.hpp b/include/webcpp/trystero/detail/timer.hpp new file mode 100644 index 0000000..22cded7 --- /dev/null +++ b/include/webcpp/trystero/detail/timer.hpp @@ -0,0 +1,88 @@ +// 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_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 + +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * The backend's timer over webcpp::asio's steady_timer, 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. 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 backend::timer { +public: + /** + * Constructs a timer, not started. + * + * @param ex The executor it fires on. + * @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 webcpp::asio::any_io_executor& ex, std::pmr::memory_resource* memory) + : timer_(ex), + memory_(memory), + waits_( + std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), 0)) {} + + /** + * Calls `fire` on the executor once `delay` has passed, in place of a pending expiry. + * + * @param delay How long to wait. + * @param fire What to call when the timer expires; never called once the timer is cancelled, + * started again or destroyed, even when its expiry was already queued. + */ + void start(std::chrono::milliseconds delay, handler fire) override { + const std::uint64_t wait = ++*waits_; + timer_.expires_after(delay); + timer_.async_wait(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 { + if (const auto current = waits.lock(); !ec && current && *current == wait) { + fire(); + } + })); + } + + /** Cancels the pending expiry, if any, whose handler is then never called. */ + void cancel() override { + ++*waits_; + timer_.cancel(); + } + +private: + 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::detail + +#endif diff --git a/test/Jamfile b/test/Jamfile index 5ae5ef9..654c8f1 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -63,6 +63,9 @@ 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 browser backend +# makes: a wait cancelled, restarted or destroyed never fires. +webcpp.run timer : timer_test.cpp ; # end::both-targets[] webcpp.run native_sealer : native_sealer_test.cpp : /webcpp/trystero//native multi fixtures/expected/expected.json : native ; @@ -101,20 +104,20 @@ webcpp.run allocation : allocation_test.cpp : emscripten:-sA # 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 ; +# 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 browser_page : browser_page_test.cpp : : emscripten ; # end::browser[] # The same, built without exceptions, as a program that uses the browser # backend 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 @@ -127,6 +130,8 @@ 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 browser_page_no_exceptions : browser_page_test.cpp + : off : emscripten ; # end::no-exceptions[] # The combined Asio/Beast/Trystero provider has its own recurring native lane. diff --git a/test/browser_data_channel_test.cpp b/test/browser_data_channel_test.cpp index 2e811f7..cad5caa 100644 --- a/test/browser_data_channel_test.cpp +++ b/test/browser_data_channel_test.cpp @@ -11,26 +11,31 @@ // 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 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. +// 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 // once per program: the JavaScript export +#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 { @@ -55,26 +60,16 @@ class watching_resource final : public std::pmr::memory_resource { }; struct state { - webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; watching_resource memory; + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::browser::backend backend{io.get_executor()}; std::shared_ptr connection; 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(); @@ -85,7 +80,7 @@ void deliver(const val& data) { } // namespace int main() { - auto& s = the_state(); + state s; // A connection whose channel is open from the start, and which the test reaches as // lastChannel. EM_ASM({ @@ -116,15 +111,11 @@ int main() { s.wrapper->set_handlers({ .open = {}, .message = - [](const trystero::backend::bytes& frame) { - auto& s = the_state(); + [&s](const trystero::backend::bytes& frame) { ++s.messages; s.last_size = frame.size(); - BOOST_TEST_EQ(s.messages, 1); - BOOST_TEST_EQ(s.last_size, 3U); - BOOST_TEST_LE(s.memory.largest, std::size_t{20'000}); - val::global("clearTimeout")(s.deadline); - set_exit_code(boost::report_errors()); + s.guard.reset(); + s.io.stop(); }, .close = {}, .buffered_amount_low = {}, @@ -135,11 +126,13 @@ int main() { 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*/) { + 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"); - 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; + } + // The first frame to arrive is the last one sent: the run stopped there. + BOOST_TEST_EQ(s.messages, 1); + 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/browser_event_loop_test.cpp b/test/browser_event_loop_test.cpp deleted file mode 100644 index ed99fac..0000000 --- a/test/browser_event_loop_test.cpp +++ /dev/null @@ -1,251 +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 // lint-world: posts handlers only - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; -using emscripten::val; - -namespace { - -constexpr int escapes = 3000; - -struct state { - webcpp::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; - webcpp::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); - webcpp::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; - webcpp::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*/) { - webcpp::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_page_test.cpp b/test/browser_page_test.cpp new file mode 100644 index 0000000..2ce1a2e --- /dev/null +++ b/test/browser_page_test.cpp @@ -0,0 +1,137 @@ +// 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 reaches C++ through functions the program exports, which only post to +// it, as webcpp::asio's model asks (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 export from a JavaScript timer, and its posted work sends on the first +// room's action, which the second room receives. Neither export runs any of that inside its call. +// +// 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 + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +namespace test = webcpp::trystero::test; +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 in_export = false; + bool ran_inside_an_export = false; + bool joined = false; + int met = 0; + bool sent = false; + std::string received; +}; + +/** Records whether posted work runs inside an export's call, which it never should. */ +void handling(page& p) { + if (p.in_export) { + p.ran_inside_an_export = true; + } +} + +/** Schedules the second export from a JavaScript timer, once both rooms met. */ +void met(page& p) { + if (++p.met != 2) { + return; + } + // A function expression: clang-format splits an arrow function's => into = >. + EM_ASM({ setTimeout(function() { _test_page_send($0); }, 0); }, &p); +} + +/** 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 = std::move(text); + p.f.io.stop(); + }); +} + +} // namespace + +/** The page's first call: it posts the join, nothing more. */ +extern "C" EMSCRIPTEN_KEEPALIVE void test_page_join(page* p) { + p->in_export = true; + asio::post(p->f.io, [p] { join(*p); }); + p->in_export = false; +} + +/** The page's second call: it posts a send on the first room's action, nothing more. */ +extern "C" EMSCRIPTEN_KEEPALIVE void test_page_send(page* p) { + p->in_export = true; + asio::post(p->f.io, [p] { + handling(*p); + p->chat_a->async_send("from the page", [p](boost::system::error_code ec) { + BOOST_TEST(!ec); + p->sent = true; + }); + }); + p->in_export = false; +} + +int main() { + page p; + // A function expression: clang-format splits an arrow function's => into = >. + EM_ASM({ setTimeout(function() { _test_page_join($0); }, 50); }, &p); + 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.empty()) { + BOOST_ERROR("the page's send never reached the other room"); + } + BOOST_TEST_EQ(p.received, "from the page"); + BOOST_TEST(!p.ran_inside_an_export); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/browser_peer_connection_test.cpp b/test/browser_peer_connection_test.cpp index 36a376e..626242c 100644 --- a/test/browser_peer_connection_test.cpp +++ b/test/browser_peer_connection_test.cpp @@ -16,41 +16,42 @@ // 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 once the -// census counts a connection less, which a timer looks for, and a deadline fails by name if it -// never comes. Node exits once nothing is pending. +// 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 // once per program: the JavaScript exports #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 { struct state { - webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; - val deadline = val::undefined(); + asio::io_context io; + trystero::browser::backend backend{io.get_executor()}; + asio::steady_timer look{io}; bool done = false; }; -state& the_state() { - static state s; - return s; -} - /** The connections webcpp::webrtc's census of the page counts. */ double held() { const val census = val::global( @@ -58,38 +59,36 @@ double held() { return census.isUndefined() ? 0 : census["held"].as(); } -/** 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)); +/** 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 looks - * again a little later. */ -void on_release(int /*slot*/, const val& /*event*/) { - auto& s = the_state(); - if (s.done) { - return; - } +/** 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() >= trystero::browser::backend::max_peer_connections) { - after(10, on_release); + 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); - val::global("clearTimeout")(s.deadline); - set_exit_code(boost::report_errors()); + s.io.stop(); } } // namespace int main() { - auto& s = the_state(); + state s; std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); // node has no RTCPeerConnection. @@ -143,19 +142,13 @@ int main() { BOOST_TEST_EQ(held(), 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; - // the census counts the release once the FinalizationRegistry has seen it. - after(0, [](int /*slot*/, const val& /*event*/) { - EM_ASM({ - require('v8').setFlagsFromString('--expose-gc'); - require('vm').runInNewContext('gc')(); - }); - after(10, on_release); - }); - s.deadline = after(10'000, [](int /*slot*/, const val& /*event*/) { + // 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"); - set_exit_code(boost::report_errors()); - }); - set_exit_code(1); // until the verdict - return 0; + } + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/browser_sealer_test.cpp b/test/browser_sealer_test.cpp index 0e8e8d3..3560ccf 100644 --- a/test/browser_sealer_test.cpp +++ b/test/browser_sealer_test.cpp @@ -10,19 +10,21 @@ // 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. +// main starts the first step and runs the io_context, which each Web Crypto promise the sealer +// awaits holds; each step starts from the completions of the one before, and the last ends the +// run. A step that does not come within 10 s fails by name. #include -#include // once per program: the JavaScript exports #include #include #include +#include +#include #include +#include #include #include #include @@ -30,8 +32,10 @@ #include #include +namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; using emscripten::val; +using namespace std::chrono_literals; namespace { @@ -43,49 +47,39 @@ struct outcome { }; struct state { - webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + asio::io_context io; + trystero::browser::backend backend{io.get_executor()}; std::shared_ptr sealer; bool in_call = false; + bool judged = 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(); + 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(F f) { - the_state().in_call = true; +void call(state& s, F f) { + s.in_call = true; f(); - the_state().in_call = false; + s.in_call = false; } -std::shared_ptr make_sealer() { +std::shared_ptr make_sealer(state& s) { std::array key{}; key.fill(7); - return the_state().backend.make_sealer(key, std::pmr::get_default_resource()); + return s.backend.make_sealer(key, std::pmr::get_default_resource()); } /** Checks that a completion came, after its call, with `expected`. */ @@ -96,8 +90,7 @@ void expect(const std::optional& got, boost::system::error_code expecte } } -void verdict() { - const auto& s = the_state(); +void verdict(state& s) { expect(s.opened, {}); if (s.opened) { BOOST_TEST_EQ(s.opened->text, "hello"); @@ -105,34 +98,31 @@ void verdict() { 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()); + s.judged = true; + s.io.stop(); } /** 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)); }); +void open_after_failure(state& s) { + call(s, [&s] { s.sealer->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() { +void seal_without_subtle(state& s) { 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)); - }); + s.sealer = make_sealer(s); + call(s, [&s] { s.sealer->seal("hello", record(s, s.without_subtle, open_after_failure)); }); } /** Once both opens completed, the next step. */ -void opened() { - const auto& s = the_state(); +void opened(state& s) { if (s.opened && s.garbage) { - seal_without_subtle(); + seal_without_subtle(s); } } @@ -140,29 +130,26 @@ void opened() { * 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(); +void open_sealed(state& s) { + if (!BOOST_TEST(!s.sealed->ec)) { + verdict(s); 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)); + call(s, [&s] { + s.sealer->open(s.sealed->text, record(s, s.opened, opened)); + s.sealer->open("not a sealed text", record(s, 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*/) { + state s; + s.sealer = make_sealer(s); + call(s, [&s] { s.sealer->seal("hello", record(s, s.sealed, open_sealed)); }); + s.io.run_for(10s); // lint-run: the test's event loop, held by the promises the sealer awaits + if (!s.judged) { 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; + } + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/browser_websocket_bound_test.cpp b/test/browser_websocket_bound_test.cpp index e6e5f83..4cef284 100644 --- a/test/browser_websocket_bound_test.cpp +++ b/test/browser_websocket_bound_test.cpp @@ -7,29 +7,34 @@ // 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. +// protocol::max_queued_relay_bytes the socket is dropped and reports one close, after the call, +// 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. +// 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 // once per program: the JavaScript exports #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. @@ -65,70 +70,60 @@ namespace { constexpr int texts = 100; struct state { - webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::browser::backend backend{io.get_executor()}; std::shared_ptr socket; int closes = 0; bool sent = false; - val deadline = val::undefined(); + bool judged = false; }; -state& the_state() { - static state s; - return s; +std::size_t held() { + return static_cast(val::global("stalledHeld").as()); } -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); -} - -void verdict() { - auto& s = the_state(); +void verdict(state& s) { 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_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()); + s.judged = true; + s.guard.reset(); } } // namespace int main() { install_stalled_websocket(); - auto& s = the_state(); + state s; s.socket = s.backend.connect("wss://relay.test", { .open = - [] { - auto& s = the_state(); + [&s] { const std::string text(std::size_t{64} * 1024, 't'); for (int i = 0; i < texts; ++i) { s.socket->send(text); } + BOOST_TEST_EQ(s.closes, 0); // not inside the call s.sent = true; - verdict(); + verdict(s); }, .message = {}, .close = - [] { - ++the_state().closes; - verdict(); + [&s] { + ++s.closes; + verdict(s); }, }, std::pmr::get_default_resource()); - const int id = s.loop.add([](int /*slot*/, const val& /*event*/) { + 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(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; + BOOST_TEST_LE(held(), trystero::protocol::max_queued_relay_bytes); + } + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/browser_websocket_late_events_test.cpp b/test/browser_websocket_late_events_test.cpp index 0a3aacc..dca164b 100644 --- a/test/browser_websocket_late_events_test.cpp +++ b/test/browser_websocket_late_events_test.cpp @@ -12,28 +12,35 @@ // 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. +// 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 // once per program: the JavaScript exports #include +#include +#include #include #include #include #include +#include +#include // once per program: its EM_JS +#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(). @@ -72,75 +79,65 @@ EM_JS(void, install_late_websocket, (), { namespace { struct state { - webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::browser::backend backend{io.get_executor()}; 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(); + bool judged = false; }; -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(); +void judge(state& s) { 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()); + s.judged = true; + s.guard.reset(); } /** Once both sockets reported their close, judges behind every event the stand-in queued. */ -void closed() { - const auto& s = the_state(); +void closed(state& s) { if (s.stalled_closes == 0 || s.big_closes == 0) { return; } - val::global("setTimeout")(s.loop.handler(s.verdict, 0), val(0), val::undefined()); + 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(); - auto& s = the_state(); - s.verdict = s.loop.add(judge); + state s; s.stalled = s.backend.connect("wss://relay.test", { .open = - [] { - const auto& s = the_state(); + [&s] { 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(); + [&s](std::string_view /*text*/) { if (s.stalled_closes != 0) { ++s.messages_after_close; } }, .close = - [] { - ++the_state().stalled_closes; - closed(); + [&s] { + ++s.stalled_closes; + closed(s); }, }, std::pmr::get_default_resource()); @@ -148,23 +145,20 @@ int main() { "wss://relay.test", { .open = - [] { - const auto& s = the_state(); + [&s] { s.big->send(std::string(trystero::protocol::max_queued_relay_bytes + 1, 'b')); }, .message = {}, .close = - [] { - ++the_state().big_closes; - closed(); + [&s] { + ++s.big_closes; + closed(s); }, }, std::pmr::get_default_resource()); - const int id = s.loop.add([](int /*slot*/, const val& /*event*/) { + 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"); - 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; + } + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/browser_websocket_test.cpp b/test/browser_websocket_test.cpp index 65228af..8f26e20 100644 --- a/test/browser_websocket_test.cpp +++ b/test/browser_websocket_test.cpp @@ -12,26 +12,33 @@ // 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. +// 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 // once per program: the JavaScript exports +#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; namespace { @@ -46,57 +53,57 @@ constexpr std::array urls{ }; struct state { - webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + asio::io_context io; + asio::executor_work_guard guard{io.get_executor()}; + trystero::browser::backend backend{io.get_executor()}; + asio::steady_timer settle{io}; std::array, urls.size()> sockets; std::array closes{}; std::size_t total = 0; - val deadline = val::undefined(); + bool judged = false; }; -state& the_state() { - static state s; - return s; -} - -void set_exit_code(int code) { - val::global("process").set("exitCode", val(code)); +/** Whether node's WebSocket makes a socket of `url`, as the page's own code would see it. */ +bool node_accepts(std::string_view url) { + // clang-format off + return EM_ASM_INT(({ + try { + new WebSocket(UTF8ToString($0, $1)).close(); + return 1; + } catch (_) { + return 0; + } + }), url.data(), url.size()) != 0; + // clang-format on } -/** Ends the test once every URL has reported its close. */ -void closed(std::size_t i) { - auto& s = the_state(); +/** 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()) { + 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()); + 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), 1); + } + s.sockets = {}; // destroyed after the close: nothing more is reported + s.judged = true; + s.guard.reset(); + }); } -/** 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(); +/** Makes a WebSocket of each URL, then sends on it and closes it. */ +void connect_all(state& s) { 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"); - + std::cout << urls.at(i) << (node_accepts(urls.at(i)) ? ": 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); }, + .close = [&s, i] { closed(s, i); }, }, std::pmr::get_default_resource()); s.sockets.at(i)->send("ignored"); @@ -108,14 +115,11 @@ void connect_all(int /*slot*/, const val& /*event*/) { } // 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*/) { + 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"); - 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; + } + return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/oracle/interop/cpp.html b/test/oracle/interop/cpp.html index 64b1cdc..8f7a9dc 100644 --- a/test/oracle/interop/cpp.html +++ b/test/oracle/interop/cpp.html @@ -43,7 +43,7 @@ return super.close() } } -var Module = {onRuntimeInitialized: () => Module.start()} +// The program's main starts the peer and runs it for the page's life; the driver's calls post to it. window.leave = () => Module.leave() // The program run.mjs serves under /build/, as b2 linked it: interop_browser.js, beside its wasm. const program = document.createElement('script') diff --git a/test/oracle/interop/peer.cpp b/test/oracle/interop/peer.cpp index e501ab8..8bd8f7a 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, `leave`, only posts to it. // // | Query parameter | Meaning | // | app, room | the app id and room id | @@ -24,9 +25,10 @@ // | 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 @@ -54,12 +56,11 @@ 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 { webcpp::asio::io_context io; - trystero::browser::event_loop loop{io}; - trystero::browser::backend backend{loop}; + trystero::browser::backend backend{io.get_executor()}; std::unique_ptr app; std::unique_ptr room; std::unique_ptr> chat; @@ -73,7 +74,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; @@ -123,8 +125,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::browser::js_string(category), + trystero::browser::js_string(text)); } /** A checksum the driver can compare without moving the payload: sum of bytes times their position, @@ -264,8 +266,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}}); @@ -359,15 +360,28 @@ void start() { } } -/** Called by the driver: leave the room with Trystero's farewell. */ +/** Called by the driver: posts the leave of the room, with Trystero's farewell. */ void leave() { - the_page().room->async_leave( - [](boost::system::error_code ec) { record("left", {{"error", ec ? ec.message() : ""}}); }); + webcpp::asio::post(the_page().io, [] { + 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); + start(); + app.io.run(); // lint-run: the page's program, suspended into the browser's event loop +} diff --git a/test/timer_test.cpp b/test/timer_test.cpp new file mode 100644 index 0000000..66e6dde --- /dev/null +++ b/test/timer_test.cpp @@ -0,0 +1,131 @@ +// 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 + +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, 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 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; + int fired = 0; + timer->start(1ms, [&] { ++fired; }); + io.run_for(100ms); // lint-run: the wait expires + BOOST_TEST_EQ(fired, 1); + // 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); + 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; + std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); + const auto first = make_timer(io, memory); + auto second = make_timer(io, memory); + 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; + 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); + 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); +} + +} // 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 webcpp::test::exit_status(boost::report_errors()); +} From c150aa89c8e6fdbf405c409fc80dd948989fd52c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:32:46 -0300 Subject: [PATCH 009/116] trystero: the page says a browser program runs its io_context The browser backend's page describes the program webcpp::asio's model asks for: main runs the io_context under a work guard, the page's events reach C++ through webcpp::asio's bridge and only post, Web Crypto's promises are awaited with browser::async_await, the timers are webcpp::asio's, and the page's calls into C++ post too, as the chat's join and send now do. The quick start, the overview, the testing chapter (browser_page and timer in, browser_event_loop out) and the README follow. --- README.md | 19 +++-- doc/browser.adoc | 175 ++++++++++++++++++++++++------------------- doc/overview.adoc | 11 +-- doc/quick-start.adoc | 32 ++++---- doc/testing.adoc | 25 +++++-- 5 files changed, 148 insertions(+), 114 deletions(-) diff --git a/README.md b/README.md index 68c83ef..f777137 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ A room runs on two targets, through a backend of each: | Backend | Header | Target | Built on | | --- | --- | --- | --- | -| the browser's | `` | emscripten | the page's `WebSocket` and `crypto.subtle`, through embind, and webcpp::webrtc over its `RTCPeerConnection` | +| the browser's | `` | emscripten | the page's `WebSocket` and `crypto.subtle`, through webcpp::asio's bridge, webcpp::asio's timers, and webcpp::webrtc over its `RTCPeerConnection` | | the native one | `` | native | webcpp::webrtc over libdatachannel for WebRTC, Boost.Beast for the relays' WebSockets, OpenSSL for TLS and AES-GCM | `` is the rooms themselves, which build on both targets @@ -19,8 +19,11 @@ and include neither backend. Both backends' 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. Every name is in the namespace `webcpp::trystero`. Messages, -binary data and pings are ported; audio and video tracks are not yet. +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. Every part of it, both backends included, compiles and @@ -156,7 +159,8 @@ int main() { } ``` -The browser quick start's app and the room it joins, which a page keeps alive as long as the tab: +The browser quick start's app and the room it joins, which its `main` keeps alive as long as the +tab, running the `io_context` as a native program does: ```cpp @@ -167,12 +171,11 @@ struct lobby { trystero::action echo = room.make_action("echo"); }; -/** What the page keeps alive: event loop, backend, app, and the room it joined. */ +/** What the page keeps alive: its io_context, the backend, the 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"}}; + trystero::browser::backend backend{io.get_executor()}; + trystero::app app{io.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 diff --git a/doc/browser.adoc b/doc/browser.adoc index 5d61580..73e2909 100644 --- a/doc/browser.adoc +++ b/doc/browser.adoc @@ -8,73 +8,77 @@ == The browser backend In the browser, `browser::backend` implements the backend interface over the -page's own `WebSocket`, `setTimeout` and `crypto.subtle`, through embind's -`emscripten::val`, and over its `RTCPeerConnection` and `RTCDataChannel` -through webcpp::webrtc (<>), 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 or a timer, is dispatched to its handler, and is followed - by `io_context::poll()`, which runs everything that became ready. -* webcpp::webrtc's objects receive the page's WebRTC events through - webcpp::asio's bridge, a service of the loop's `io_context`, which posts to - the loop's executor, and so schedules a `poll()` as any work posted outside - an event does. -* 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. +page's own `WebSocket` and `crypto.subtle`, over webcpp::asio's timers, and +over the page's `RTCPeerConnection` and `RTCDataChannel` through +webcpp::webrtc (<>). It is given the +executor of the program's `io_context`, which the program runs from `main`, +as webcpp::asio's model has it. One backend serves every app and room of +the page. Apps with different passwords use distinct self ids and share no +connection or presence. + +[#trystero-browser-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 the functions the program exports to it, + through embind or `EMSCRIPTEN_KEEPALIVE`, and each only posts 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"). + +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-browser-javascript] === How JavaScript reaches {cpp} -The page calls one function, `trystero_dispatch`, which -`` exports; webcpp::webrtc's events come -through webcpp::asio's bridge, whose JavaScript `/webcpp/asio//asio` links -into every program on emscripten. 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. +Every function the page calls with an event 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. 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, 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. +memory a view points into, `browser::js_string`, and text that comes back +is encoded 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` or a 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; webcpp::webrtc's JavaScript catches -the page's WebRTC exceptions the same way. 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. +`WebSocket` constructor or `send`, a Web Crypto method, in JavaScript that +catches what it throws: a socket that cannot be made reports its close, and +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. 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 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 program. [#trystero-browser-bounds] === What a page bounds @@ -89,9 +93,9 @@ peer's malformed message never stops the page's loop. 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 - (<>). + the socket, which reports one close after the call. 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 @@ -104,8 +108,9 @@ peer's malformed message never stops the page's loop. 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. +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-browser-page] === What a page needs @@ -115,15 +120,17 @@ binds another room without making another peer connection. 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 the loop drives it on the page's one + 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//trystero` brings: `webcpp-suspend=jspi`, the default, for a browser with JavaScript - Promise Integration, or `asyncify` for any other. The loop never runs the - `io_context`, so no program of trystero suspends, but webcpp::asio's - runtime is linked either way. -* A program that lives as long as the page: the event loop must outlive - every room and object it serves. + 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` (<>). +* 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. * 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. @@ -132,38 +139,54 @@ binds another room without making another peer connection. === 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: +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 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: +The program joins the app and the room its user typed, 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: +`send_message` 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: +The page calls `join` and `send` from its own events, a form's submission; +each only posts the work to the `io_context`, which `main` runs: + +[source] +---- +include::{examples}/chat/chat.cpp[tag=calls] +---- + +They are what the program exports to the page, through embind: [source] ---- include::{examples}/chat/chat.cpp[tag=bindings] ---- +And `main` runs the `io_context`, under a work guard, for the page's life: + +[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/overview.adoc b/doc/overview.adoc index 01c0319..0c68f1f 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -54,9 +54,9 @@ Each backend is a header of its own: | `` | emscripten -| the page's `WebSocket`, `setTimeout` and `crypto.subtle`, through embind, - and webcpp::webrtc over the page's `RTCPeerConnection` and - `RTCDataChannel` (<>) +| the page's `WebSocket` and `crypto.subtle`, through webcpp::asio's bridge, + webcpp::asio's timers, and webcpp::webrtc over the page's + `RTCPeerConnection` and `RTCDataChannel` (<>) | `` | native @@ -79,9 +79,10 @@ namespace `webcpp::trystero`. * 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. -* 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, through webcpp::webrtc, and OpenSSL 3. diff --git a/doc/quick-start.adoc b/doc/quick-start.adoc index 0bb7b6a..94cf516 100644 --- a/doc/quick-start.adoc +++ b/doc/quick-start.adoc @@ -17,12 +17,11 @@ both. <> builds and runs them. [#trystero-quick-start-browser] === In the browser -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: +A browser program keeps four things alive for as long as its page: an +`io_context`, the `browser::backend` that implements the platform over the +browser's APIs on the executor of that `io_context`, 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: [source] ---- @@ -31,13 +30,9 @@ include::{examples}/quick_start.cpp[tag=includes] include::{examples}/quick_start.cpp[tag=application] ---- -`` 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: +that completes the handshake, prints every `chat` message, starts a +coroutine that answers the `echo` action, and runs the `io_context`: [source] ---- @@ -53,17 +48,20 @@ leaving the room ends the loop instead of throwing: include::{examples}/quick_start.cpp[tag=coroutine] ---- -`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` (<>). +`main` runs the `io_context` for as long as the page lives, as a native +program does, under a work guard, since a page that waits for its peers may +have no work of its own. Nothing blocks the browser: whenever nothing is +ready, `run` suspends into the browser's event loop, and every JavaScript +event that reaches the library is posted to the `io_context`, whose handlers +run when `run` resumes (<>). [#trystero-quick-start-native] === Natively 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 -webcpp::webrtc posts what libdatachannel's threads report to it: +`io_context` as the browser's does, and webcpp::webrtc posts what +libdatachannel's threads report to it: [source] ---- diff --git a/doc/testing.adoc b/doc/testing.adoc index c571d8c..f0a060b 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -115,6 +115,12 @@ include::{library-root}/test/Jamfile[tag=allocation] | Every allocation of two apps and their rooms goes through their resources (<>). +| `timer` +| The timer over webcpp::asio's `steady_timer`, which the browser backend + makes: a wait fires once, in the timer's resource, and one cancelled, + restarted or destroyed never fires, even when its expiry was already + queued. + | `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 @@ -137,15 +143,18 @@ include::{library-root}/test/Jamfile[tag=allocation] once, and leaves out a URL libdatachannel cannot parse. Both run once more without exceptions. -| `browser_event_loop`, `browser_websocket`, `browser_websocket_bound`, `browser_websocket_late_events`, `browser_sealer`, `browser_data_channel`, `browser_peer_connection` +| `browser_websocket`, `browser_websocket_bound`, `browser_websocket_late_events`, `browser_sealer`, `browser_data_channel`, `browser_peer_connection`, `browser_page` | 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, and, 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, and - webcpp::webrtc's census of them. + WebSocket and Web Crypto but no WebRTC, each test's `main` running its + `io_context` as a page's program does: the WebSocket's URLs, its bound on + what a relay holds unsent and its silence once dropped, the sealer's + completions, and, 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, and + webcpp::webrtc's census of them; and the shape of a page's program, whose + work guard keeps a page with no room yet running, and whose exported + functions, called from JavaScript while `run` is suspended, only post, + and reach the room. |=== The native backend's tests run once more without exceptions From 690890bb97f1e8e00b0a8401e1c975085b760154 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:33:54 -0300 Subject: [PATCH 010/116] trystero: the protocol test keeps each decoded frame alive and its lists to clang-tidy --- test/protocol_test.cpp | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index 30127c1..3afa45e 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -319,13 +319,15 @@ void random_ids() { // 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() { - const auto offer_of_size = [](const std::array& size) { + 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; }; - const auto largest = - tp::decode_action(offer_of_size({0x43, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})); + // 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; } @@ -333,16 +335,17 @@ void offer_sizes_at_two_to_the_53() { 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, 6> refused{{ - {0x43, 0x40, 0, 0, 0, 0, 0, 0}, // 2^53 - {0x43, 0x40, 0, 0, 0, 0, 0, 1}, // 2^53 + 2 - {0x3f, 0xf8, 0, 0, 0, 0, 0, 0}, // 1.5 - {0, 0, 0, 0, 0, 0, 0, 0}, // 0 - {0xbf, 0xf0, 0, 0, 0, 0, 0, 0}, // -1 - {0x7f, 0xf8, 0, 0, 0, 0, 0, 0}, // NaN - }}; + 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 decoded = tp::decode_action(offer_of_size(size)); + 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); } @@ -354,8 +357,10 @@ 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); - const std::array offer_fields{0x01, 0x02, 0x01, 0x02, 0x03, 0x04, 0x41, - 0xb2, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00}; + // 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); @@ -365,8 +370,9 @@ void wide_fields_are_big_endian() { 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}; + 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); @@ -386,7 +392,8 @@ void wide_fields_are_big_endian() { BOOST_TEST_EQ(room[1], 0x01); BOOST_TEST_EQ(room[2], 0x2c); const std::string longest(tp::max_room_token_bytes, 't'); - const auto envelope = tp::decode_envelope(tp::room_frame(longest, data)); + 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); } From 443ca988742352f42be247172f01f1f3039a9cca Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:41:11 -0300 Subject: [PATCH 011/116] trystero: keep the relay session to clang-tidy make_tls_context sets the verification and reads the system's authorities through OpenSSL itself, as webcpp::asio's make_tls_client_context does, since Asio's error-code forms also return the code, which bugprone-unused-return-value refuses to discard. The read loop and the writes are loops of asynchronous operations, not recursions: each of their functions states its exemption from misc-no-recursion, with the reason above. The test's TLS server keeps what its callbacks record mutable, so that a test may hold it const. --- include/webcpp/trystero/native/websocket.hpp | 66 +++++++++++--------- test/native_websocket_test.cpp | 15 ++--- 2 files changed, 43 insertions(+), 38 deletions(-) diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp index 6d544d4..10c47f2 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/native/websocket.hpp @@ -109,26 +109,23 @@ inline boost::system::error_code openssl_error() { */ inline boost::system::result make_tls_context() { #ifdef WEBCPP_TARGET_NATIVE - SSL_CTX* const raw = SSL_CTX_new(TLS_client_method()); - if (raw == nullptr) { + std::unique_ptr raw(SSL_CTX_new(TLS_client_method()), + &SSL_CTX_free); + if (!raw) { return detail::openssl_error(); } - // The context owns the handle from here, and throws only for a null one. - webcpp::asio::ssl::context context(raw); - if (SSL_CTX_set_min_proto_version(raw, TLS1_2_VERSION) != 1) { + if (SSL_CTX_set_min_proto_version(raw.get(), TLS1_2_VERSION) != 1) { return detail::openssl_error(); } - SSL_CTX_set_options(raw, SSL_OP_NO_COMPRESSION); - boost::system::error_code ec; - context.set_default_verify_paths(ec); // lint-world: the system's certificate authorities - if (ec) { - return ec; - } - context.set_verify_mode(webcpp::asio::ssl::verify_peer, ec); - if (ec) { - return ec; + 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(); } - return context; + // 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; @@ -470,13 +467,19 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()]( - const boost::system::error_code& ec, std::size_t size) { - self->on_read(ec, size); - })); + // 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. Hence the + // exemptions from misc-no-recursion of read, its handler and on_read, and of write_next and + // its handler, the cycles of the read loop and of the writes. + void read() { // NOLINT(misc-no-recursion) + auto handler = [self = this->shared_from_this()]( // NOLINT(misc-no-recursion) + const boost::system::error_code& ec, std::size_t size) { + self->on_read(ec, size); + }; + ws_.async_read(buffer_, bound(std::move(handler))); } + // NOLINTNEXTLINE(misc-no-recursion) void on_read(const boost::system::error_code& ec, std::size_t size) { if (ec) { end(); @@ -500,9 +503,10 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()](const boost::system::error_code& ec, - std::size_t) { - if (ec) { - self->writing_ = false; - return; - } - self->write_next(); - })); + auto handler = [self = this->shared_from_this()]( // NOLINT(misc-no-recursion) + const boost::system::error_code& ec, std::size_t) { + if (ec) { + self->writing_ = false; + return; + } + self->write_next(); + }; + ws_.async_write(webcpp::asio::buffer(writing_text_), bound(std::move(handler))); } void end() { diff --git a/test/native_websocket_test.cpp b/test/native_websocket_test.cpp index 5a07aaf..21211d2 100644 --- a/test/native_websocket_test.cpp +++ b/test/native_websocket_test.cpp @@ -151,10 +151,10 @@ struct tls_echo_server { : acceptor(io, {asio::ip::make_address("127.0.0.1"), 0}), context(asio::ssl::context::tls_server) { boost::system::error_code ec; - context.use_certificate_chain(asio::buffer(relay_certificate), ec); - webcpp::test::require(BOOST_TEST(!ec)); - context.use_private_key(asio::buffer(relay_key), asio::ssl::context::pem, ec); - webcpp::test::require(BOOST_TEST(!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); @@ -207,8 +207,9 @@ struct tls_echo_server { tcp::acceptor acceptor; asio::ssl::context context; - std::vector server_names; - int failed_handshakes = 0; + // Written by the server's own callbacks, also while a test holds the server const. + mutable std::vector server_names; + mutable int failed_handshakes = 0; }; /** What a hostile relay does once it reads a client's first message. */ @@ -537,7 +538,7 @@ void a_relay_of_an_authority_not_trusted_closes_without_opening() { void a_backend_reaches_relays_with_the_tls_context_it_is_given() { asio::io_context io; const echo_server plain(io); - tls_echo_server secure(io); + const tls_echo_server secure(io); { trystero::native::backend backend(io.get_executor(), webcpp::asio::make_tls_client_context(test_authority)); From 41218bd9097942cf5cef02c67531364cb15b2a7e Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:48:39 -0300 Subject: [PATCH 012/116] trystero: the relay session's OpenSSL branches on every target but Emscripten The session chose OpenSSL's TLS context, SNI, the certificate check and the keep-alive pings when the target is native, and the page's when it is Emscripten. It now chooses the page's on Emscripten alone, as webcpp::asio's make_tls_client_context does, since every other target of webcpp::beast runs OpenSSL in the program. --- include/webcpp/trystero/native/websocket.hpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp index 10c47f2..5580994 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/native/websocket.hpp @@ -24,7 +24,7 @@ #include // lint-world: the relays' WebSockets #include // lint-world: the relays' WebSockets -#ifdef WEBCPP_TARGET_NATIVE +#ifndef WEBCPP_TARGET_EMSCRIPTEN #include #include #endif @@ -80,7 +80,7 @@ namespace detail { /** The error OpenSSL queued last, or `not_enough_memory` when it queued none. */ inline boost::system::error_code openssl_error() { -#ifdef WEBCPP_TARGET_NATIVE +#ifndef WEBCPP_TARGET_EMSCRIPTEN // Asio's own TLS errors are OpenSSL's codes, in its category, as an int. if (const auto code = ERR_get_error(); code != 0) { return {static_cast(code), webcpp::asio::error::get_ssl_category()}; @@ -108,7 +108,7 @@ inline boost::system::error_code openssl_error() { * @see "The relays", in the guide. */ inline boost::system::result make_tls_context() { -#ifdef WEBCPP_TARGET_NATIVE +#ifndef WEBCPP_TARGET_EMSCRIPTEN std::unique_ptr raw(SSL_CTX_new(TLS_client_method()), &SSL_CTX_free); if (!raw) { @@ -405,7 +405,7 @@ class websocket_session : public std::enable_shared_from_this Date: Sat, 14 Nov 2026 17:52:13 -0300 Subject: [PATCH 013/116] trystero: an IPv6 relay's handshake host written without a fluent chain The bracketed address is appended in three statements, as the lint's rule against chains of three calls asks, and the url_parts host's Doc Comment keeps its closing line to itself. --- include/webcpp/trystero/native/websocket.hpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp index 5580994..482c2db 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/native/websocket.hpp @@ -147,7 +147,8 @@ struct url_parts { // NOLINT(bugprone-exception-escape) 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. + /** + * 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. */ @@ -226,7 +227,9 @@ inline std::optional parse_url( break; case boost::urls::host_type::ipv6: out.host.assign(address.data(), address.size()); - out.handshake_host.append("[").append(out.host).append("]"); + out.handshake_host = "["; + out.handshake_host += out.host; + out.handshake_host += "]"; break; default: // none, or an IPvFuture address, which no resolver knows return std::nullopt; From a011d7cc91ef56c4650660c7a1562621ffc5a17c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 17:59:30 -0300 Subject: [PATCH 014/116] trystero: a page calls C++ through browser::page_call Under Asyncify an embind function called while main is suspended in its run returns a promise that never settles, and its second call aborts a debug build (measured with Emscripten 6.0.11): the interop's browser peer failed its two leaving scenarios there, window.leave() never answering, and the chat aborted at its second message. browser::page_call is a function of webcpp::asio's bridge that the program hands to the page; each call posts its work, with the value the page passed, and returns at once in either variant, and a call of one destroyed meanwhile reaches nothing. The chat's main now owns the chat and hands the page joinRoom and sendText, the interop peer's main defines window.leave, and browser_page drives both calls from JavaScript, twice in a row. The backend's constructors take their executor by value, as clang-tidy asks, and two comments no longer name a clock or the run family. --- doc/browser.adoc | 43 ++++---- doc/testing.adoc | 7 +- example/chat/chat.cpp | 47 ++------- example/chat/index.html | 12 ++- include/webcpp/trystero/browser/backend.hpp | 95 ++++++++++++++++-- include/webcpp/trystero/detail/timer.hpp | 4 +- test/Jamfile | 3 +- test/browser_page_test.cpp | 105 ++++++++++++-------- test/oracle/interop/cpp.html | 4 +- test/oracle/interop/peer.cpp | 27 ++--- 10 files changed, 208 insertions(+), 139 deletions(-) diff --git a/doc/browser.adoc b/doc/browser.adoc index 73e2909..a73c8b5 100644 --- a/doc/browser.adoc +++ b/doc/browser.adoc @@ -34,12 +34,16 @@ in either suspension variant). * 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 the functions the program exports to it, - through embind or `EMSCRIPTEN_KEEPALIVE`, and each only posts 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"). +* The page reaches {cpp} through `browser::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). 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` @@ -49,9 +53,9 @@ handlers is followed by a yield, which lets the page render. A handler's [#trystero-browser-javascript] === How JavaScript reaches {cpp} -Every function the page calls with an event 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 +Every function the page calls with an event, or with a call of its own +(`browser::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. A Web Crypto promise is awaited with webcpp::asio's `browser::async_await`, whose settlement is posted the same way and whose @@ -166,22 +170,11 @@ page's log: include::{examples}/chat/chat.cpp[tag=send] ---- -The page calls `join` and `send` from its own events, a form's submission; -each only posts the work to the `io_context`, which `main` runs: - -[source] ----- -include::{examples}/chat/chat.cpp[tag=calls] ----- - -They are what the program exports to the page, through embind: - -[source] ----- -include::{examples}/chat/chat.cpp[tag=bindings] ----- - -And `main` runs the `io_context`, under a work guard, for the page's life: +`main` keeps the chat, makes the page's two calls, each a +`browser::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] ---- diff --git a/doc/testing.adoc b/doc/testing.adoc index f0a060b..ea17f51 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -152,9 +152,10 @@ include::{library-root}/test/Jamfile[tag=allocation] `RTCPeerConnection` of the test's, a data channel's refusal of what is no frame, and the page's peer connections, made or refused, and webcpp::webrtc's census of them; and the shape of a page's program, whose - work guard keeps a page with no room yet running, and whose exported - functions, called from JavaScript while `run` is suspended, only post, - and reach the room. + work guard keeps a page with no room yet running, and whose + `browser::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. |=== The native backend's tests run once more without exceptions diff --git a/example/chat/chat.cpp b/example/chat/chat.cpp index babb762..1698f1d 100644 --- a/example/chat/chat.cpp +++ b/example/chat/chat.cpp @@ -12,9 +12,7 @@ #include #include -#include -#include #include #include @@ -39,11 +37,6 @@ struct chat { // end::state[] -chat& the_chat() { - static chat c; // the page's one chat, which main runs and the page's calls post to - return c; -} - val js(std::string_view text) { return trystero::browser::js_string(text); } @@ -59,8 +52,7 @@ 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(); +void join_room(chat& c, const std::string& app_id, const std::string& room_id) { if (c.room) { return; } @@ -95,8 +87,7 @@ 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(); +void send_message(chat& c, std::string text) { if (!c.room || text.empty()) { return; } @@ -110,35 +101,19 @@ void send_message(std::string text) { // end::send[] -// tag::calls[] -/** The page's `join`: posted to the io_context, which main runs. */ -void post_join(std::string app_id, std::string room_id) { - webcpp::asio::post(the_chat().io, [app_id = std::move(app_id), room_id = std::move(room_id)] { - join_room(app_id, room_id); - }); -} - -/** The page's `send`: posted to the io_context, which main runs. */ -void post_send(std::string text) { - webcpp::asio::post(the_chat().io, - [text = std::move(text)]() mutable { send_message(std::move(text)); }); -} - -// end::calls[] - } // namespace -// tag::bindings[] -EMSCRIPTEN_BINDINGS(chat_example) { - emscripten::function("join", &post_join); - emscripten::function("send", &post_send); -} - -// end::bindings[] - // tag::main[] int main() { - auto& c = the_chat(); + 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::browser::page_call join(c.io.get_executor(), [&c](const val& form) { + join_room(c, form["app"].as(), form["room"].as()); + }); + const trystero::browser::page_call send( + c.io.get_executor(), [&c](const val& text) { send_message(c, text.as()); }); + 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 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/include/webcpp/trystero/browser/backend.hpp b/include/webcpp/trystero/browser/backend.hpp index 73c31aa..3d3d7d7 100644 --- a/include/webcpp/trystero/browser/backend.hpp +++ b/include/webcpp/trystero/browser/backend.hpp @@ -257,6 +257,83 @@ inline val js_string(std::string_view utf8) { return detail::take(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. + * + * @tparam F A callable of one `const emscripten::val&`, the value the page passed. + * @see "The program runs its io_context", in the guide. + */ +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. + * @param memory The resource `f` and each posted call are allocated in. + */ + 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]] val function() const { + return bridge_ != nullptr ? bridge_->function(key_) : val::undefined(); + } + +private: + bool deliver(const 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_; +}; + /** * A WebSocket over the page's `WebSocket`, whose events reach the executor through webcpp::asio's * bridge. @@ -286,9 +363,9 @@ class websocket : public backend::websocket, public std::enable_shared_from_this * @param memory The room's resource, which the WebSocket's handlers, its events and the texts * it receives are allocated in. */ - websocket(const webcpp::asio::any_io_executor& ex, std::string_view url, handlers h, + websocket(webcpp::asio::any_io_executor ex, std::string_view url, handlers h, std::pmr::memory_resource* memory) - : ex_(ex), + : ex_(std::move(ex)), memory_(memory), h_(std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), std::move(h))), @@ -476,9 +553,9 @@ class sealer : public backend::sealer, public std::enable_shared_from_this key, + sealer(webcpp::asio::any_io_executor ex, std::array key, std::pmr::memory_resource* memory) - : ex_(ex), raw_key_(key), memory_(memory), waiting_(memory) {} + : ex_(std::move(ex)), raw_key_(key), memory_(memory), waiting_(memory) {} /** * Seals a text under a fresh random IV, with `crypto.subtle.encrypt`. @@ -643,10 +720,10 @@ class sealer : public backend::sealer, public std::enable_shared_from_thisemscripten:-sA # end::allocation[] # The browser backend's own tests, under node, which has the page's -# WebSocket, Web Crypto and microtasks but no WebRTC. +# WebSocket and Web Crypto but no WebRTC; each main runs its io_context, as +# a page's program does, and suspends in it in either variant. # tag::browser[] webcpp.run browser_websocket : browser_websocket_test.cpp : : emscripten ; webcpp.run browser_websocket_bound : browser_websocket_bound_test.cpp : : emscripten ; diff --git a/test/browser_page_test.cpp b/test/browser_page_test.cpp index 2ce1a2e..ff3a717 100644 --- a/test/browser_page_test.cpp +++ b/test/browser_page_test.cpp @@ -5,16 +5,20 @@ // 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 reaches C++ through functions the program exports, which only post to -// it, as webcpp::asio's model asks (nothing runs the io_context from a JavaScript event). +// a work guard, and the page calls into C++ through `browser::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 export from a JavaScript timer, and its posted work sends on the first -// room's action, which the second room receives. Neither export runs any of that inside its call. +// page calls the second function twice 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 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. @@ -22,14 +26,15 @@ #include "support/rooms.hpp" #include +#include #include +#include #include #include -#include #include -#include +#include #include #include #include @@ -38,10 +43,12 @@ #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 { @@ -57,28 +64,34 @@ struct page { std::optional z; std::optional> chat_a; std::optional> chat_z; - bool in_export = false; - bool ran_inside_an_export = false; + bool ran_inside_a_call = false; bool joined = false; int met = 0; - bool sent = false; - std::string received; + std::vector received; + int late = 0; }; -/** Records whether posted work runs inside an export's call, which it never should. */ +/** Records whether posted work runs inside a call of the page's, which it never should. */ void handling(page& p) { - if (p.in_export) { - p.ran_inside_an_export = true; + if (asio::use_service(p.f.io).delivering()) { + p.ran_inside_a_call = true; } } -/** Schedules the second export from a JavaScript timer, once both rooms met. */ +/** Calls the page's second function twice from a JavaScript timer, once both rooms met. */ void met(page& p) { if (++p.met != 2) { return; } // A function expression: clang-format splits an arrow function's => into = >. - EM_ASM({ setTimeout(function() { _test_page_send($0); }, 0); }, &p); + EM_ASM({ + setTimeout( + function() { + globalThis.pageReturned = globalThis.pageSend("from the page"); + globalThis.pageSend("again"); + }, + 0); + }); } /** Joins a room of each app, and sets their handlers. */ @@ -94,44 +107,52 @@ void join(page& p) { 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 = std::move(text); - p.f.io.stop(); + p.received.push_back(std::move(text)); + if (p.received.size() == 2) { + p.f.io.stop(); + } }); } -} // namespace - -/** The page's first call: it posts the join, nothing more. */ -extern "C" EMSCRIPTEN_KEEPALIVE void test_page_join(page* p) { - p->in_export = true; - asio::post(p->f.io, [p] { join(*p); }); - p->in_export = false; +/** Sends the page's text on the first room's action. */ +void send(page& p, const val& text) { + handling(p); + p.chat_a->async_send(text.as(), + [](boost::system::error_code ec) { BOOST_TEST(!ec); }); } -/** The page's second call: it posts a send on the first room's action, nothing more. */ -extern "C" EMSCRIPTEN_KEEPALIVE void test_page_send(page* p) { - p->in_export = true; - asio::post(p->f.io, [p] { - handling(*p); - p->chat_a->async_send("from the page", [p](boost::system::error_code ec) { - BOOST_TEST(!ec); - p->sent = true; - }); - }); - p->in_export = false; -} +} // namespace int main() { page p; - // A function expression: clang-format splits an arrow function's => into = >. - EM_ASM({ setTimeout(function() { _test_page_join($0); }, 50); }, &p); + const trystero::browser::page_call join_call(p.f.io.get_executor(), + [&p](const val& /*argument*/) { join(p); }); + const trystero::browser::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::browser::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.empty()) { - BOOST_ERROR("the page's send never reached the other room"); + } else if (p.received.size() != 2) { + BOOST_ERROR("the page's sends never reached the other room"); } - BOOST_TEST_EQ(p.received, "from the page"); - BOOST_TEST(!p.ran_inside_an_export); + 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(!p.ran_inside_a_call); + BOOST_TEST_EQ(p.late, 0); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/oracle/interop/cpp.html b/test/oracle/interop/cpp.html index 8f7a9dc..c594cac 100644 --- a/test/oracle/interop/cpp.html +++ b/test/oracle/interop/cpp.html @@ -43,8 +43,8 @@ return super.close() } } -// The program's main starts the peer and runs it for the page's life; the driver's calls post to it. -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/peer.cpp b/test/oracle/interop/peer.cpp index 8bd8f7a..c0573d5 100644 --- a/test/oracle/interop/peer.cpp +++ b/test/oracle/interop/peer.cpp @@ -7,7 +7,7 @@ // 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`. Its main starts the peer and runs the io_context for the page's life, under a -// work guard; the driver's one call, `leave`, only posts to it. +// work guard; the driver's one call, `window.leave`, a `browser::page_call`, only posts to it. // // | Query parameter | Meaning | // | app, room | the app id and room id | @@ -28,9 +28,7 @@ #include #include -#include -#include #include #include #include @@ -360,28 +358,25 @@ void start() { } } -/** Called by the driver: posts the leave of the room, with Trystero's farewell. */ +/** The driver's call, `window.leave`: leaves the room with Trystero's farewell. */ void leave() { - webcpp::asio::post(the_page().io, [] { - if (!the_page().room) { - return; - } - the_page().room->async_leave([](boost::system::error_code ec) { - record("left", {{"error", ec ? ec.message() : ""}}); - }); - }); + 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("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::browser::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 } From 4c36557b3e83206fbe3b1fd94c9dbcde247d671c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 18:20:02 -0300 Subject: [PATCH 015/116] trystero: the guide's embedded-roots backend, included from its test The page's doc-check refuses C++ that no example or tagged test region holds: the backend made with webcpp's embedded Mozilla roots is a case of native_websocket now, which shows the test authority's relay unreachable through those roots, and the page includes its tagged lines. The handshake host takes its single characters as characters. --- doc/native.adoc | 5 ++--- include/webcpp/trystero/native/websocket.hpp | 7 ++++--- test/native_websocket_test.cpp | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/doc/native.adoc b/doc/native.adoc index fd3a373..3a922d3 100644 --- a/doc/native.adoc +++ b/doc/native.adoc @@ -159,10 +159,9 @@ 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,cpp] +[source] ---- -trystero::native::backend backend(io.get_executor(), - webcpp::asio::make_tls_client_context()); +include::{library-root}/test/native_websocket_test.cpp[tag=embedded-roots,indent=0] ---- The backend takes the context as `make_tls_client_context` returns it, a diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp index 482c2db..4eb1aed 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/native/websocket.hpp @@ -227,9 +227,9 @@ inline std::optional parse_url( break; case boost::urls::host_type::ipv6: out.host.assign(address.data(), address.size()); - out.handshake_host = "["; + out.handshake_host.push_back('['); out.handshake_host += out.host; - out.handshake_host += "]"; + out.handshake_host.push_back(']'); break; default: // none, or an IPvFuture address, which no resolver knows return std::nullopt; @@ -238,7 +238,8 @@ inline std::optional parse_url( 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.append(":").append(out.port); + out.handshake_host.push_back(':'); + out.handshake_host += out.port; } const auto target = view.encoded_target(); if (target.empty() || target.front() != '/') { diff --git a/test/native_websocket_test.cpp b/test/native_websocket_test.cpp index 21211d2..693a198 100644 --- a/test/native_websocket_test.cpp +++ b/test/native_websocket_test.cpp @@ -576,6 +576,23 @@ void a_backend_makes_its_own_tls_context() { 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-native-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::native::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); @@ -837,6 +854,7 @@ int main() { a_relay_of_an_authority_not_trusted_closes_without_opening(); 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(); an_unreachable_relay_closes_without_opening(); From 9835abaff8b5c1f2bb48b231a33a891a76aaa18d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:25:44 -0300 Subject: [PATCH 016/116] trystero: interop judges the public connection by the page's negotiations The interop scenario of a public app beside a protected one, in both id orders, counted every connection the public app made and failed when the count grew between its snapshot before the page's injection and the one after: natively 4 of 59 runs at a load average of 51 to 178 failed so, always with the protected app the higher id and "cppMade" 1, then 2. The two apps share the public app's first room, and whatever the passwords the lower id offers to a higher one it sees announced, as Trystero JS does: the public app, when it has the lower id, makes a connection for the protected app when they meet, and another each time its unanswered offer expires (57 s). The three peers started together, so the two apps met a few hundred ms from the first snapshot, on either side of it, though the public app's connection with the page never changed. The protected app now joins once the public connection is up and the first snapshot taken, and the scenario waits until the two apps met (the higher id could not open the lower id's offer or candidate), so that the public app's connection for the protected app falls inside the window in every run. The check counts the negotiations the public app opened with the page, by its log (the offers it sent the page, the page's offers it answered), and fails when there is none before, and the page still holds one connected connection. Natively, in batches that ran each variant at once under 100 busy loops (load average 250 to 340), the restructured scenario with the old check failed 20 of 20 runs, "cppMade" 1, then 2, with one negotiation with the page before and after, and with the new check passed 20 of 20; beside the old scenario at a load average of 72 to 178 it passed 45 of 45. In headless Chromium, where the count is Chromium's, the old check failed 4 of 4 runs the same way and the new one passed 4 of 4. --- test/oracle/interop/run.mjs | 42 ++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 8 deletions(-) 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)}` } } From ea01925dd7a5e6f3656791f8af2f4711b6b57b81 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:34:35 -0300 Subject: [PATCH 017/116] trystero: one platform backend for both targets, platform::backend native::backend and browser::backend become platform::backend, in include/webcpp/trystero/platform/, built through /webcpp/trystero//platform on both targets: webcpp::webrtc, webcpp::beast's relay session (in a page over its WebSocket, bounded by queue_limits::send), detail::timer, std::chrono clocks, and per target only the sealer and one checked source of randomness. backend_config::memory holds the backend's own state. A page's page_call and js_string are in platform/page.hpp. The tests become platform_* tests on each target that builds them. --- build.jam | 58 +- doc/Jamfile | 15 +- doc/browser.adoc | 185 ---- doc/native.adoc | 191 ---- doc/platform.adoc | 438 +++++++++ doc/trystero.adoc | 4 +- example/Jamfile | 5 +- example/chat/Jamfile | 2 +- example/chat/chat.cpp | 11 +- example/native_quick_start.cpp | 8 +- example/quick_start.cpp | 4 +- include/webcpp/trystero.hpp | 8 +- include/webcpp/trystero/backend.hpp | 6 +- include/webcpp/trystero/browser/backend.hpp | 871 ------------------ include/webcpp/trystero/config.hpp | 9 +- include/webcpp/trystero/native/sealer.hpp | 178 ---- include/webcpp/trystero/native/timer.hpp | 86 -- .../trystero/{native => platform}/backend.hpp | 177 ++-- include/webcpp/trystero/platform/entropy.hpp | 59 ++ include/webcpp/trystero/platform/page.hpp | 150 +++ include/webcpp/trystero/platform/sealer.hpp | 458 +++++++++ .../{native => platform}/websocket.hpp | 75 +- include/webcpp/trystero/protocol/relays.hpp | 4 +- .../webcpp/trystero/webrtc/data_channel.hpp | 4 +- meta/include-boundaries.json | 5 +- test/CONVERSION.md | 7 + test/Jamfile | 151 +-- test/browser_sealer_test.cpp | 155 ---- test/native_sealer_test.cpp | 117 --- test/native_timer_test.cpp | 92 -- test/oracle/Jamfile | 11 +- test/oracle/interop/native_peer.cpp | 14 +- test/oracle/interop/peer.cpp | 15 +- test/platform_backend_test.cpp | 147 +++ ...pp => platform_page_data_channel_test.cpp} | 7 +- ...=> platform_page_peer_connection_test.cpp} | 58 +- ...r_page_test.cpp => platform_page_test.cpp} | 16 +- ...=> platform_page_websocket_bound_test.cpp} | 57 +- ...tform_page_websocket_late_events_test.cpp} | 34 +- ....cpp => platform_peer_connection_test.cpp} | 19 +- ...e_room_test.cpp => platform_room_test.cpp} | 15 +- test/platform_sealer_test.cpp | 231 +++++ ...t_test.cpp => platform_websocket_test.cpp} | 159 ++-- ...> platform_websocket_unreachable_test.cpp} | 48 +- test/support/memory_backend.hpp | 2 +- 45 files changed, 2062 insertions(+), 2304 deletions(-) delete mode 100644 doc/browser.adoc delete mode 100644 doc/native.adoc create mode 100644 doc/platform.adoc delete mode 100644 include/webcpp/trystero/browser/backend.hpp delete mode 100644 include/webcpp/trystero/native/sealer.hpp delete mode 100644 include/webcpp/trystero/native/timer.hpp rename include/webcpp/trystero/{native => platform}/backend.hpp (63%) create mode 100644 include/webcpp/trystero/platform/entropy.hpp create mode 100644 include/webcpp/trystero/platform/page.hpp create mode 100644 include/webcpp/trystero/platform/sealer.hpp rename include/webcpp/trystero/{native => platform}/websocket.hpp (88%) delete mode 100644 test/browser_sealer_test.cpp delete mode 100644 test/native_sealer_test.cpp delete mode 100644 test/native_timer_test.cpp create mode 100644 test/platform_backend_test.cpp rename test/{browser_data_channel_test.cpp => platform_page_data_channel_test.cpp} (95%) rename test/{browser_peer_connection_test.cpp => platform_page_peer_connection_test.cpp} (64%) rename test/{browser_page_test.cpp => platform_page_test.cpp} (91%) rename test/{browser_websocket_bound_test.cpp => platform_page_websocket_bound_test.cpp} (65%) rename test/{browser_websocket_late_events_test.cpp => platform_page_websocket_late_events_test.cpp} (78%) rename test/{native_peer_connection_test.cpp => platform_peer_connection_test.cpp} (97%) rename test/{native_room_test.cpp => platform_room_test.cpp} (91%) create mode 100644 test/platform_sealer_test.cpp rename test/{native_websocket_test.cpp => platform_websocket_test.cpp} (84%) rename test/{browser_websocket_test.cpp => platform_websocket_unreachable_test.cpp} (66%) diff --git a/build.jam b/build.jam index 01ad84f..90044e6 100644 --- a/build.jam +++ b/build.jam @@ -5,9 +5,9 @@ # 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. Both backends' WebRTC is -# webcpp::webrtc's. +# 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 ; @@ -41,43 +41,41 @@ rule trystero-dependencies ( properties * ) return [ webcpp.external-found trystero : libsecp256k1 : $(properties) ] ; } -# The native backend's own dependencies, checked only when a target that -# uses it is built: its WebRTC, libdatachannel's through webcpp::webrtc, runs -# on worker threads. -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." ; } } -# Asio is webcpp::asio: natively Boost.Asio itself, on emscripten the shipped -# backend, without threads (the event loop drives it), whose browser runtime -# webcpp::webrtc's browser objects deliver through. On emscripten the browser -# backend's WebRTC is webcpp::webrtc's, and the 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. # tag::trystero[] alias trystero : : @trystero-dependencies : : include /boost//headers /webcpp//boost_json - /webcpp/config//config /webcpp/asio//asio secp256k1 - emscripten:/webcpp/webrtc//webrtc - emscripten:-lembind ; + /webcpp/config//config /webcpp/asio//asio secp256k1 ; # end::trystero[] -# The native backend: its WebRTC is webcpp::webrtc's, which brings the pinned -# libdatachannel and OpenSSL, and works with exceptions on and off, through -# libdatachannel's C API; so does the backend. Its relays' WebSockets are -# webcpp::beast's over the same OpenSSL (//tls), their URLs read with -# Boost.URL, built from Boost's sources once per variant; webcpp::asio's -# //tls adds webcpp's embedded authorities, which a program may trust in -# place of the system's (make_tls_client_context). -# tag::native[] -alias native : : @native-dependencies +# 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. +# tag::platform[] +alias platform : : emscripten + : : trystero /webcpp/webrtc//webrtc + /webcpp/beast//browser /webcpp//boost_url ; +alias platform : : @platform-dependencies : : trystero /webcpp/webrtc//webrtc /webcpp/beast//tls /webcpp/asio//tls /webcpp//boost_url ; -# end::native[] +# end::platform[] diff --git a/doc/Jamfile b/doc/Jamfile index 7ef2708..6160e42 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -8,11 +8,12 @@ import webcpp ; webcpp.doc trystero : trystero.adoc ; -# No single target builds every header: the browser backend's build 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 webcpp::webrtc, libdatachannel and OpenSSL, and Boost.Asio without -# threads, as wasm32 has none, for the native backend's Beast and timers. -webcpp.reference trystero : /webcpp/trystero//native multi +# No single target builds every header: a page's build 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 platform backend's target, built +# natively, which brings webcpp::webrtc, libdatachannel and OpenSSL, and +# Boost.Asio without threads, as wasm32 has none, for the relays' Beast and +# the timers. +webcpp.reference trystero : /webcpp/trystero//platform multi /webcpp//emscripten-reference BOOST_ASIO_DISABLE_THREADS ; diff --git a/doc/browser.adoc b/doc/browser.adoc deleted file mode 100644 index a73c8b5..0000000 --- a/doc/browser.adoc +++ /dev/null @@ -1,185 +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` and `crypto.subtle`, over webcpp::asio's timers, and -over the page's `RTCPeerConnection` and `RTCDataChannel` through -webcpp::webrtc (<>). It is given the -executor of the program's `io_context`, which the program runs from `main`, -as webcpp::asio's model has it. One backend serves every app and room of -the page. Apps with different passwords use distinct self ids and share no -connection or presence. - -[#trystero-browser-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 `browser::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). - -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-browser-javascript] -=== How JavaScript reaches {cpp} - -Every function the page calls with an event, or with a call of its own -(`browser::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. 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, `browser::js_string`, and text that comes back -is encoded 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 -`WebSocket` constructor or `send`, a Web Crypto method, in JavaScript that -catches what it throws: a socket that cannot be made reports its close, and -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. 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 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 program. - -[#trystero-browser-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 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 after the call. 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). It is the cap of the webcpp::webrtc runtime the backend owns, - `runtime_options::max_peer_connections`, and webcpp::webrtc's census of - the page counts every connection it makes, with any runtime. 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, their events, timers 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. 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//trystero` - 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` (<>). -* 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. -* 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 `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; a received message goes from its frame straight into a JavaScript -string: - -[source] ----- -include::{examples}/chat/chat.cpp[tag=join] ----- - -`send_message` 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 -`browser::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/native.adoc b/doc/native.adoc deleted file mode 100644 index 3a922d3..0000000 --- a/doc/native.adoc +++ /dev/null @@ -1,191 +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 -webcpp::webrtc for WebRTC, which natively is -https://github.com/paullouisageneau/libdatachannel[libdatachannel]'s -(<>), webcpp::beast for the relays' WebSockets, -natively Boost.Beast's, 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, and the native backend works with -exceptions and without them, as the rest of trystero does. 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. - -``, 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-native-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 the browser. An application -that runs the `io_context` on several threads gives the app a strand, shared -by all its rooms. - -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 - -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 the browser, 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 - browser refuses the whole connection. -* What libdatachannel allocates inside itself is libdatachannel's - (<>). - -[#trystero-native-runtime] -=== The runtime - -webcpp::webrtc's `runtime` holds what libdatachannel keeps for the whole -process, its threads and its global state, and caps the peer connections -alive at once. A native backend makes one of its own, with -`backend_config::runtime`, or takes the program's: `native::backend(ex, -runtime, config)`, or `native::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 process holds one -runtime at a time, since libdatachannel's state is the process's: a program -with several native backends at once, or that uses webcpp::webrtc beside -trystero, makes one `webcpp::webrtc::runtime` before its `io_context` and -gives it to each. - -[#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. - -| `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 a connection - gives its place back once it is gone; and `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, `native::websocket_limits` (<>). -|=== - -[#trystero-native-relays] -=== The relays - -The relays are reached over webcpp::beast, natively Boost.Beast's own -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 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, as a page's `WebSocket` reads it: the -scheme in any case, a host name in lower case and with its escapes decoded, -an IPv6 address in brackets (`ws://[2001:db8::1]:7447/`), whose address -without them is what the resolver looks up, and the scheme's port when the URL -names none. A URL of another scheme, without a host, with a user name or a -fragment, or with a port beyond 65535, is refused; the relay reports a close, -as an unreachable one does, and the room retries it later as it would any -other. - -Over TLS the connection names the relay's host to the server (SNI) when it is -a name, never when it is an address, and checks the relay's certificate -against the URL's host, a name or an address. By default the backend makes -its TLS context with `native::make_tls_context()`: TLS 1.2 or newer, and the -system's certificate authorities, those OpenSSL's default verify paths name. -A relay whose certificate does not verify is unreachable, and the room -retries it later. An 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/native_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. - -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/platform.adoc b/doc/platform.adoc new file mode 100644 index 0000000..fc51268 --- /dev/null +++ b/doc/platform.adoc @@ -0,0 +1,438 @@ +// 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 `getentropy`, which Emscripten draws from +`crypto.getRandomValues`. 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 +(<>); in a page the stream's own state is there too. A +write that fails ends the connection, which reports its close at once. 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, as a page's +`WebSocket` reads it: the scheme in any case, a host name in lower case and +with its escapes decoded, an IPv6 address in brackets +(`ws://[2001:db8::1]:7447/`), whose address without them is what the +resolver looks up, and the scheme's port when the URL names none. A URL of +another scheme, `http://` and `https://` among them, which a page's +`WebSocket` alone would take as `ws://` and `wss://`, without a host, with a +user name or a fragment, or with a port beyond 65535, is refused; the relay +reports a close, as an unreachable one does, and the room retries it later +as it would any other. + +Over TLS, natively, the connection names the relay's host to the server +(SNI) when it is a name, never when it is an address, and checks the relay's +certificate against the URL's host, a name or an address; in a page the +browser does both, against its own authorities. 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. +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. + +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. +* 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 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, `getentropy` in a page. 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. + +[#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). + +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, 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, and 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. +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, and its socket's + `bufferedAmount` and its texts waiting for the executor too + (<>); 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` (<>). +* 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. +* Boost.JSON's and Boost.URL's definitions, which a program links from + `/webcpp//boost_json` 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; a received message goes from its frame straight into a JavaScript +string: + +[source] +---- +include::{examples}/chat/chat.cpp[tag=join] +---- + +`send_message` 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/trystero.adoc b/doc/trystero.adoc index 02367b2..fcd4f06 100644 --- a/doc/trystero.adoc +++ b/doc/trystero.adoc @@ -38,9 +38,7 @@ include::usage.adoc[] include::allocation.adoc[] -include::browser.adoc[] - -include::native.adoc[] +include::platform.adoc[] include::protocol.adoc[] diff --git a/example/Jamfile b/example/Jamfile index fed3412..4fdd2de 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -16,11 +16,12 @@ webcpp.targets native emscripten ; # Each needs the public relays or a browser, so it is linked and never run. # tag::native[] webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//native multi : native ; + : /webcpp/trystero//platform multi : native ; # end::native[] # tag::browser[] webcpp.link quick_start : quick_start.cpp - : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH : emscripten ; + : /webcpp/trystero//platform -sENVIRONMENT=web + -sALLOW_MEMORY_GROWTH : emscripten ; # end::browser[] # The chat page, on emscripten: its program and the site it is served from. diff --git a/example/chat/Jamfile b/example/chat/Jamfile index 7efaeb8..25ab69f 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 ; diff --git a/example/chat/chat.cpp b/example/chat/chat.cpp index 1698f1d..000b1e7 100644 --- a/example/chat/chat.cpp +++ b/example/chat/chat.cpp @@ -8,7 +8,8 @@ // 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 +#include #include #include @@ -27,7 +28,7 @@ namespace { // tag::state[] struct chat { webcpp::asio::io_context io; - trystero::browser::backend backend{io.get_executor()}; + 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. @@ -38,7 +39,7 @@ struct chat { // end::state[] val js(std::string_view text) { - return trystero::browser::js_string(text); + return trystero::platform::js_string(text); } val js(bool value) { @@ -108,10 +109,10 @@ 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::browser::page_call join(c.io.get_executor(), [&c](const val& form) { + const trystero::platform::page_call join(c.io.get_executor(), [&c](const val& form) { join_room(c, form["app"].as(), form["room"].as()); }); - const trystero::browser::page_call send( + const trystero::platform::page_call send( c.io.get_executor(), [&c](const val& text) { send_message(c, text.as()); }); 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. diff --git a/example/native_quick_start.cpp b/example/native_quick_start.cpp index a528d57..0b87822 100644 --- a/example/native_quick_start.cpp +++ b/example/native_quick_start.cpp @@ -5,12 +5,12 @@ // 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. +// tagged regions below: the browser quick start's app and room, over the same platform backend, as +// a native program. Trystero JS and browser peers in the same room are its peers. // tag::program[] #include -#include +#include #include #include @@ -23,7 +23,7 @@ namespace trystero = webcpp::trystero; int main() { boost::asio::io_context io; - trystero::native::backend backend(io.get_executor()); + trystero::platform::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) { diff --git a/example/quick_start.cpp b/example/quick_start.cpp index 89aaf91..d45630e 100644 --- a/example/quick_start.cpp +++ b/example/quick_start.cpp @@ -10,7 +10,7 @@ // tag::includes[] #include -#include +#include #include #include @@ -41,7 +41,7 @@ struct lobby { /** What the page keeps alive: its io_context, the backend, the app, and the room it joined. */ struct application { asio::io_context io; - trystero::browser::backend backend{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; trystero::app app{io.get_executor(), backend, {.app_id = "webcpp-trystero-quick-start"}}; std::optional joined; diff --git a/include/webcpp/trystero.hpp b/include/webcpp/trystero.hpp index 8ea9f2f..45db84a 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 diff --git a/include/webcpp/trystero/backend.hpp b/include/webcpp/trystero/backend.hpp index 0e21c4f..c7e6090 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 diff --git a/include/webcpp/trystero/browser/backend.hpp b/include/webcpp/trystero/browser/backend.hpp deleted file mode 100644 index 3d3d7d7..0000000 --- a/include/webcpp/trystero/browser/backend.hpp +++ /dev/null @@ -1,871 +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 - -#include // lint-world: names the executor only -#include // lint-world: binds an allocator only -#include // lint-world: awaits the page's promises -#include // lint-world: the page's events -#include // lint-world: the bridge of the executor's context -#include // lint-world: the bridge of the executor's context - -#include -#include -#include // lint-world: getentropy, the page's entropy - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * The browser target: the backend interface over the page's own `WebSocket` and `crypto.subtle`, - * over webcpp::asio's timers, and over its `RTCPeerConnection` and `RTCDataChannel` through - * webcpp::webrtc. It needs a secure context (https, or http on localhost), where `crypto.subtle` - * exists. - * - * Tip: the page's events reach C++ through webcpp::asio's bridge, a service of the program's - * io_context, which only posts to it: they run while the program runs that io_context, from - * `main`. 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. - */ -namespace webcpp::trystero::browser { - -/** A JavaScript value, embind's `emscripten::val`. */ -using emscripten::val; - -namespace detail { - -// The page's WebSocket and 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. JavaScript stays in JavaScript: what can throw is caught -// there, before it can reach a WebAssembly frame, and a Web Crypto call is made inside an async -// function, so that what it throws becomes the rejection of the promise it returns. The functions -// use Emval, HEAPU8 and UTF8ToString, which webcpp::asio's browser runtime has Emscripten link, in -// every program on /webcpp/asio//asio. - -// 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)); -} - -/** - * The UTF-8 bytes of `text` as a `Uint8Array`, or null for a value that is no string or for a - * text longer than `max` bytes, whose length is checked first in UTF-16 units. - */ -inline emscripten::EM_VAL js_encode(emscripten::EM_VAL text, double max) { - return reinterpret_cast(EM_ASM_PTR(({ - const text = Emval.toValue($0); - const max = $1; - - if (typeof text !== 'string' || text.length > max) return Emval.toHandle(null); - const bytes = new TextEncoder().encode(text); - return Emval.toHandle(bytes.length > max ? null : bytes); - }), text, max)); -} - -/** 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 `WebSocket` to `url` whose events call `deliver` with `{kind: 0}`, `{kind: 1, data}` and - * `{kind: 2}`, its open, a message and its close, or null when the constructor throws. - */ -inline emscripten::EM_VAL js_websocket(emscripten::EM_VAL url, emscripten::EM_VAL deliver) { - return reinterpret_cast(EM_ASM_PTR(({ - const url = Emval.toValue($0); - const deliver = Emval.toValue($1); - - try { - const socket = new WebSocket(url); - socket.onopen = () => deliver({kind: 0}); - socket.onmessage = event => deliver({kind: 1, data: event.data}); - socket.onclose = () => deliver({kind: 2}); - return Emval.toHandle(socket); - } catch (_) { - return Emval.toHandle(null); - } - }), url, deliver)); -} - -/** - * Sends `size` bytes of UTF-8 at `data` as a text when the socket is open, returning 1, with - * nothing sent, when its `bufferedAmount` would pass `bound` with them, else 0. - */ -inline int js_send(emscripten::EM_VAL socket, const char* data, std::size_t size, double bound) { - return EM_ASM_INT(({ - const socket = Emval.toValue($0); - const data = $1 >>> 0; - const size = $2 >>> 0; - const bound = $3; - - try { - if (socket.readyState !== 1) return 0; - if (Number(socket.bufferedAmount) + size > bound) return 1; - socket.send(UTF8ToString(data, size, true)); - } catch (_) { - } - return 0; - }), socket, data, size, bound); -} - -/** Closes a socket, its handlers set to null first with `detach`, so that it reports nothing. */ -inline void js_close(emscripten::EM_VAL socket, bool detach) { - EM_ASM(({ - const socket = Emval.toValue($0); - const detach = $1; - - try { - if (detach) { - socket.onopen = null; - socket.onmessage = null; - socket.onclose = null; - } - socket.close(); - } catch (_) { - } - }), socket, detach); -} - -/** - * 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 val take(emscripten::EM_VAL handle) { - return val::take_ownership(handle); -} - -/** - * The UTF-8 bytes of a JavaScript string, copied straight into a string of `memory` when they are - * at most `max_bytes`, and nothing otherwise, nor for a value that is no string. - */ -inline std::optional utf8(const val& text, std::pmr::memory_resource* memory, - std::size_t max_bytes) { - const val encoded = take(js_encode(text.as_handle(), static_cast(max_bytes))); - if (encoded.isNull()) { - return std::nullopt; - } - std::pmr::string out(encoded["length"].as(), '\0', memory); - js_copy(encoded.as_handle(), out.data(), out.size()); - return out; -} - -/** A copy of an `ArrayBuffer`'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); - js_copy(view.as_handle(), out.data(), out.size()); - return out; -} - -/** The bridge of the io_context an executor runs on, which delivers the page's events 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 val js_string(std::string_view utf8) { - return detail::take(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. - * - * @tparam F A callable of one `const emscripten::val&`, the value the page passed. - * @see "The program runs its io_context", in the guide. - */ -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. - * @param memory The resource `f` and each posted call are allocated in. - */ - 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]] val function() const { - return bridge_ != nullptr ? bridge_->function(key_) : val::undefined(); - } - -private: - bool deliver(const 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_; -}; - -/** - * A WebSocket over the page's `WebSocket`, whose events reach the executor through webcpp::asio's - * bridge. - * - * Each event of the page's socket, its open, a message or its close, is posted to the executor in - * the order the page delivers them, and reaches the handlers when it runs there. 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 after the call. A page has no idle timeout: its `WebSocket` cannot ping. - * - * @see "The browser backend", in the guide. - */ -class websocket : public backend::websocket, public std::enable_shared_from_this { -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 ex The executor its events are posted to, an io_context's of webcpp::asio, 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, its events and the texts - * it receives are allocated in. - */ - websocket(webcpp::asio::any_io_executor ex, std::string_view url, handlers h, - std::pmr::memory_resource* memory) - : ex_(std::move(ex)), - memory_(memory), - h_(std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), - std::move(h))), - events_(*this), - bridge_(&detail::bridge_of(ex_)), - key_(bridge_->add(events_)) { - socket_ = detail::take( - detail::js_websocket(js_string(url).as_handle(), bridge_->function(key_).as_handle())); - if (socket_.isNull()) { - socket_ = val::undefined(); - leave_bridge(); - report(close_event, std::pmr::string(memory_)); - } - } - - /** Not copyable: the bridge delivers to it by its address. */ - websocket(const websocket&) = delete; - - /** Not copy-assignable: the bridge delivers to it by its address. */ - websocket& operator=(const websocket&) = delete; - - /** Destroys the WebSocket, which closes it without reporting the close. */ - ~websocket() override { - leave_bridge(); - if (!socket_.isUndefined()) { - detail::js_close(socket_.as_handle(), true); - } - } - - /** - * 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 after - * the call. - * - * @param text The message, read during the call. - */ - void send(std::string_view text) override { - if (socket_.isUndefined()) { - return; - } - if (detail::js_send(socket_.as_handle(), text.data(), text.size(), - static_cast(protocol::max_queued_relay_bytes)) != 0) { - drop(); - } - } - - /** Closes the socket, which the handler `close` reports; one never made has reported it. */ - void close() override { - if (!socket_.isUndefined()) { - detail::js_close(socket_.as_handle(), false); - } - } - -private: - /** What the bridge delivers the page's events of the socket to. */ - class events final : public webcpp::asio::browser::intrusive_registration { - public: - explicit events(websocket& owner) noexcept : owner_(owner) {} - - bool deliver(const val& event) override { return owner_.deliver(event); } - - void shutdown() noexcept override { owner_.shutdown(); } - - private: - websocket& owner_; - }; - - static constexpr int open_event = 0; - static constexpr int message_event = 1; - static constexpr int close_event = 2; - - /** - * Posts an event of the page to the executor, a message copied into the room's resource first, - * or closes the socket for a text too long for a relay; it runs no handler. - */ - bool deliver(const val& event) { - const int kind = event["kind"].as(); - if (kind != message_event) { - report(kind, std::pmr::string(memory_)); - return false; - } - const val data = event["data"]; - if (!data.isString()) { - return false; - } - // 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. - auto text = detail::utf8(data, memory_, protocol::max_relay_message_bytes); - if (!text) { - close(); - return false; - } - report(message_event, std::move(*text)); - return false; - } - - /** The io_context's shutdown: the socket is closed, and reports nothing more. */ - void shutdown() noexcept { - bridge_ = nullptr; - key_ = 0; - if (!socket_.isUndefined()) { - detail::js_close(socket_.as_handle(), true); - socket_ = val::undefined(); - } - } - - /** - * Posts the report of an event to the executor, through the shared handlers: a socket destroyed - * before it runs reports nothing, and a handler may destroy the socket during its own call. - */ - void report(int kind, std::pmr::string text) { - trystero::detail::post( - ex_, memory_, - [weak = std::weak_ptr(h_), kind, text = std::move(text)]() mutable { - const auto h = weak.lock(); - if (!h) { - return; - } - if (kind == open_event) { - if (h->open) { - h->open(); - } - } else if (kind == message_event) { - if (h->message) { - h->message(text); - } - } else if (auto f = std::exchange(h->close, {})) { - f(); - } - }); - } - - /** - * 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() { - leave_bridge(); - detail::js_close(socket_.as_handle(), true); - socket_ = val::undefined(); - report(close_event, std::pmr::string(memory_)); - } - - /** Removes the registration: an event of the page from now on finds nothing. */ - void leave_bridge() noexcept { - if (bridge_ != nullptr && key_ != 0) { - bridge_->remove(std::exchange(key_, 0)); - } - } - - webcpp::asio::any_io_executor ex_; - std::pmr::memory_resource* memory_; - std::shared_ptr h_; - events events_; - webcpp::asio::browser::bridge* bridge_; - std::uint64_t key_; - val socket_ = val::undefined(); -}; - -/** - * AES-GCM through `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. 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 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), {}); - }); - } - - void encrypt(std::string_view plaintext, done_handler done) { - std::array iv{}; - if (getentropy(iv.data(), iv.size()) != 0) { // lint-world: a seal's IV - fail(std::move(done), error::backend_failure); - return; - } - webcpp::asio::browser::async_await( - ex_, - 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 val& cipher) mutable { - if (ec) { - done(make_error_code(error::backend_failure), {}); - return; - } - const auto sealed = - protocol::format_sealed(iv, detail::from_js(cipher, memory), 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; - } - webcpp::asio::browser::async_await( - ex_, - 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 val& plain) mutable { - if (ec) { - 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())); - })); - } - - /** - * 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; - webcpp::asio::browser::async_await( - ex_, detail::take(detail::js_import_key(raw_key_.data(), raw_key_.size())), - webcpp::asio::bind_allocator(allocator(), - [weak](boost::system::error_code ec, const val& key) { - if (const auto self = weak.lock()) { - self->key_imported(!ec, key); - } - })); - } - - void key_imported(bool ok, const 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; - val key_ = val::undefined(); - std::pmr::deque waiting_; -}; - -/** - * The browser's factory: one per page, over the executor of the io_context the program runs. - * - * 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 their events 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. - * - * Tip: 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. The app is given an - * executor of the same io_context. - * - * @see "The browser backend", in the guide. - */ -class backend : public trystero::backend::factory { -public: - /** - * The most `RTCPeerConnection` objects the page holds, every program 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. - * - * It is the cap of the backend's webcpp::webrtc runtime, - * `runtime_options::max_peer_connections`, whose census of the page counts the connections - * webcpp::webrtc makes. - * - * 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; - - /** - * Constructs the page's backend over `ex`, with a webcpp::webrtc runtime of its own: in the - * browser the page's census counts the connections of every runtime alike. - * - * @param ex The executor every object of the backend runs on, an io_context's of - * webcpp::asio, which must outlive the backend and every object it makes. - */ - explicit backend(webcpp::asio::any_io_executor ex) - : ex_(std::move(ex)), - runtime_(std::allocate_shared<::webcpp::webrtc::runtime>( - std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), - ::webcpp::webrtc::runtime_options{ - .max_peer_connections = max_peer_connections, - .thread_pool_size = 0, - })) {} - - /** - * The executor every object of the backend runs on. - * - * @return The executor it was constructed with. - */ - [[nodiscard]] const webcpp::asio::any_io_executor& get_executor() const noexcept { return ex_; } - - /** - * 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), ex_, url, - std::move(h), memory); - } - - /** - * Makes a peer connection of webcpp::webrtc, over 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: it throws for a server it cannot use, and when the page holds as - * many connections as it allows. - */ - std::shared_ptr make_peer_connection( - std::span servers, - std::pmr::memory_resource* memory) override { - auto made = webrtc::peer_connection::make(runtime_, ex_, servers, {}, *this, memory); - return made ? *made : nullptr; - } - - /** - * Makes a timer, over the steady timer of webcpp::asio. - * - * @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 `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` with the page's entropy, which Emscripten draws from `crypto.getRandomValues`, - * and ends the program when the page has none, as the native backend does. - * - * @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); - if (getentropy(out.data() + at, piece) != 0) { // lint-world: Trystero's randomness - std::abort(); // no secure randomness: nothing is safe - } - } - } - - /** - * 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: - webcpp::asio::any_io_executor ex_; - std::shared_ptr<::webcpp::webrtc::runtime> runtime_; -}; - -} // namespace webcpp::trystero::browser - -#endif diff --git a/include/webcpp/trystero/config.hpp b/include/webcpp/trystero/config.hpp index 4a0c1dd..22aabc7 100644 --- a/include/webcpp/trystero/config.hpp +++ b/include/webcpp/trystero/config.hpp @@ -24,11 +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, and every part of it, both backends included, - works with exceptions and without them. Its WebRTC is webcpp::webrtc's, which - natively calls libdatachannel's C API, where no exception crosses. + 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/native/sealer.hpp b/include/webcpp/trystero/native/sealer.hpp deleted file mode 100644 index e16ac65..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(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 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_)); - } - - webcpp::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/timer.hpp b/include/webcpp/trystero/native/timer.hpp deleted file mode 100644 index ee8624e..0000000 --- a/include/webcpp/trystero/native/timer.hpp +++ /dev/null @@ -1,86 +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_TIMER_HPP -#define WEBCPP_TRYSTERO_NATIVE_TIMER_HPP - -#include - -#include - -#include -#include // lint-world: Trystero's timers -#include // lint-world: allocates timer waits -#include // lint-world: Trystero's timers - -#include -#include -#include -#include -#include - -namespace webcpp::trystero::native { - -/** - * An Asio timer whose waits are allocated in the room's resource. - * - * Tip: Asio cannot take back an expiry it has already queued, which it then completes as a - * success; so each wait carries its number, and `cancel`, a later `start` and the destructor end - * it, by changing the number or freeing it, before its handler runs. - * - * @see "The native backend", in the guide. - */ -class timer : public trystero::backend::timer { -public: - /** - * Constructs a timer, not started. - * - * @param ex The executor it fires on. - * @param memory The room's resource, which each wait is allocated in; it must outlive the - * timer's pending waits. - */ - timer(const webcpp::asio::any_io_executor& ex, std::pmr::memory_resource* memory) - : timer_(ex), - memory_(memory), - waits_( - std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), 0)) {} - - /** - * Calls `fire` on the executor once `delay` has passed, in place of a pending expiry. - * - * @param delay How long to wait. - * @param fire What to call when the timer expires; never called once the timer is cancelled, - * started again or destroyed, even when its expiry was already queued. - */ - void start(std::chrono::milliseconds delay, handler fire) override { - const std::uint64_t wait = ++*waits_; - timer_.expires_after(delay); - timer_.async_wait(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 { - if (const auto current = waits.lock(); !ec && current && *current == wait) { - fire(); - } - })); - } - - /** Cancels the pending expiry, if any, whose handler is then never called. */ - void cancel() override { - ++*waits_; - timer_.cancel(); - } - -private: - 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 - -#endif diff --git a/include/webcpp/trystero/native/backend.hpp b/include/webcpp/trystero/platform/backend.hpp similarity index 63% rename from include/webcpp/trystero/native/backend.hpp rename to include/webcpp/trystero/platform/backend.hpp index ee3d1f9..b1e18b9 100644 --- a/include/webcpp/trystero/native/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -4,27 +4,27 @@ // 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 +#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 #include #include -#include // lint-world: posts handlers only +#include // lint-world: names the executor only #include // lint-world: the relays' TLS -#include #include #include @@ -37,21 +37,23 @@ #include #include #include +#include #include /** - * The native target: the backend interface over webcpp::webrtc for WebRTC, natively - * libdatachannel's, webcpp::beast for the relays' WebSockets, natively Boost.Beast's, 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. + * 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::native { +namespace webcpp::trystero::platform { /** - * What a native backend makes its peer connections with, beside the app's - * `app_config::ice_servers`. + * 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 native backend", in the guide. + * @see "The platform backend", in the guide. */ struct backend_config { /** @@ -59,7 +61,9 @@ struct backend_config { * 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. + * 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 = {}; @@ -74,32 +78,53 @@ struct backend_config { /** * What the backend's own webcpp::webrtc runtime is made with: the most peer connections alive - * at once, 256 by default, and libdatachannel's threads. + * at once, 256 by default, and, natively, libdatachannel's threads. * - * A backend given the program's runtime does not use it. + * 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 native factory: one per application, beside the executor it runs on. + * 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`. Objects - * and their handlers use the resource supplied to their factory method. What libdatachannel and - * OpenSSL allocate stays theirs. + * 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. A process holds one runtime at a time, since libdatachannel's state is the process's: - * a program with several native backends at once, or that uses webcpp::webrtc beside trystero, - * makes one runtime and gives it to each. + * 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. * - * @see "The native backend", in the guide. + * 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: @@ -110,26 +135,27 @@ class backend : public trystero::backend::factory { * It throws nothing: when OpenSSL cannot make the TLS context, `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. - * @param config What its peer connections are made with; the default binds them to no address. + * @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, backend_config config = {}) - : backend(std::move(ex), make_tls_context(), nullptr, std::move(config)) {} + 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, or a private one. + * `webcpp::asio::make_tls_client_context()` trusts natively, or a private one. * * @param ex The executor everything the backend reports runs on. * @param tls The TLS context of every `wss://` connection, which should verify peers; 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 are made with. + * @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, - backend_config config = {}) - : backend(std::move(ex), std::move(tls), nullptr, std::move(config)) {} + 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 verifies relays @@ -138,11 +164,12 @@ class backend : public trystero::backend::factory { * @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 are made with; its `runtime` is not used. + * @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, - backend_config config = {}) - : backend(std::move(ex), make_tls_context(), runtime, std::move(config)) {} + 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 @@ -153,15 +180,23 @@ class backend : public trystero::backend::factory { * 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 are made with; its `runtime` is not used. + * @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, backend_config config = {}) + ::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), - std::move(config)) {} + 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 @@ -204,16 +239,16 @@ class backend : public trystero::backend::factory { /** * Makes a peer connection of webcpp::webrtc, bound to `backend_config::bind_address`. * - * A room has dropped every server WebRTC refuses when it joined; a URL libdatachannel still - * cannot parse, as a `stuns:` one, a scheme it does not know, is left out here, where a - * browser refuses the connection. + * 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 libdatachannel refuses to make one. + * as many connections as it allows, or when the platform refuses to make one. */ std::shared_ptr make_peer_connection( std::span servers, @@ -223,26 +258,29 @@ class backend : public trystero::backend::factory { } 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 an Asio timer on the backend's executor. + * 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); + return std::allocate_shared( + std::pmr::polymorphic_allocator<>(memory), ex_, memory); } /** - * Makes a sealer over OpenSSL's AES-256-GCM. + * 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 @@ -256,30 +294,29 @@ class backend : public trystero::backend::factory { } /** - * Fills `out` from OpenSSL's random generator; the program aborts when it has no secure - * randomness. + * 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 { - 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 + if (!detail::fill_random(out)) { + std::abort(); // no secure randomness: nothing is safe } } /** - * Seconds since the Unix epoch, from the system's wall clock. + * Seconds since the Unix epoch, from the system's wall clock, in a page `Date.now()`'s. * * @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(); + return std::chrono::floor(now.time_since_epoch()).count(); } /** - * Milliseconds from the standard library's steady clock. + * Milliseconds from the standard library's steady clock, in a page `performance.now()`'s. * * @return The current time, in milliseconds since the clock's epoch. */ @@ -291,22 +328,33 @@ class backend : public trystero::backend::factory { 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, backend_config config) + std::shared_ptr<::webcpp::webrtc::runtime> runtime, const backend_config& config) // NOLINTEND(performance-unnecessary-value-param) : ex_(std::move(ex)), - config_(std::move(config)), - runtime_(runtime ? std::move(runtime) : own_runtime(config_.runtime)), + config_(kept(config)), + runtime_(runtime ? std::move(runtime) : own_runtime(config_)), constructions_(config_.max_peer_connections_per_minute, std::chrono::minutes(1), - std::pmr::get_default_resource()), + config_.memory), tls_(std::move(tls)) {} - /** A runtime of the backend's own, which its connections share with it. */ - static std::shared_ptr<::webcpp::webrtc::runtime> own_runtime( - const ::webcpp::webrtc::runtime_options& options) { + /** 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<>(std::pmr::get_default_resource()), options); + 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. @@ -339,6 +387,7 @@ class backend : public trystero::backend::factory { } return out; } +#endif webcpp::asio::any_io_executor ex_; backend_config config_; @@ -347,6 +396,6 @@ class backend : public trystero::backend::factory { boost::system::result tls_; }; -} // namespace webcpp::trystero::native +} // 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..3f2cac7 --- /dev/null +++ b/include/webcpp/trystero/platform/entropy.hpp @@ -0,0 +1,59 @@ +// 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 // lint-world: getentropy, the page's crypto.getRandomValues +#else +#include +#endif + +#include +#include +#include +#include + +namespace webcpp::trystero::platform::detail { + +/** + * Fills `out` from the platform's one secure source of randomness, its result checked: natively + * OpenSSL's generator, `RAND_bytes`; on emscripten `getentropy`, which Emscripten draws from the + * page's `crypto.getRandomValues`. + * + * @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 + // getentropy fills at most 256 bytes a call. + constexpr std::size_t most = 256; +#else + // RAND_bytes 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 (getentropy(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..a57353f --- /dev/null +++ b/include/webcpp/trystero/platform/page.hpp @@ -0,0 +1,150 @@ +// 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. + * + * @tparam F A callable of one `const emscripten::val&`, the value the page passed. + * @see "The program runs its io_context", in the guide. + */ +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. + * @param memory The resource `f` and each posted call are allocated in. + */ + 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..4fc8d9b --- /dev/null +++ b/include/webcpp/trystero/platform/sealer.hpp @@ -0,0 +1,458 @@ +// 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 +#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 an `ArrayBuffer`'s bytes, in `memory`. */ +inline backend::bytes from_js(const emscripten::val& buffer, std::pmr::memory_resource* memory) { + 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. 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, `getentropy` 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), {}); + }); + } + + 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; + } + webcpp::asio::browser::async_await( + ex_, + 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 { + if (ec) { + done(make_error_code(error::backend_failure), {}); + return; + } + const auto sealed = + protocol::format_sealed(iv, detail::from_js(cipher, memory), 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; + } + webcpp::asio::browser::async_await( + ex_, + 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); + 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; + webcpp::asio::browser::async_await( + ex_, 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/native/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp similarity index 88% rename from include/webcpp/trystero/native/websocket.hpp rename to include/webcpp/trystero/platform/websocket.hpp index 4eb1aed..a5e6008 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -4,8 +4,8 @@ // 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 +#ifndef WEBCPP_TRYSTERO_PLATFORM_WEBSOCKET_HPP +#define WEBCPP_TRYSTERO_PLATFORM_WEBSOCKET_HPP #include @@ -51,18 +51,21 @@ #include #include -namespace webcpp::trystero::native { +namespace webcpp::trystero::platform { /** - * What a native WebSocket tolerates of a relay that stops reading or answering. + * What a relay's WebSocket tolerates of a relay that stops reading or answering. * - * @see "The native backend", in the guide. + * @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; @@ -250,10 +253,11 @@ inline std::optional parse_url( } /** - * One WebSocket connection over webcpp::beast, 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. + * 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 @@ -420,7 +424,7 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()](const boost::system::error_code& error) { @@ -449,6 +453,14 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()](const boost::system::error_code& ec) { @@ -485,7 +497,7 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()]( // NOLINT(misc-no-recursion) const boost::system::error_code& ec, std::size_t) { if (ec) { - self->writing_ = false; + self->fail(); return; } self->write_next(); @@ -529,6 +541,21 @@ class websocket_session : public std::enable_shared_from_this connect_websocket( const webcpp::asio::any_io_executor& ex, webcpp::asio::ssl::context* tls, std::string_view url, @@ -640,6 +669,6 @@ inline std::shared_ptr connect_websocket( return std::allocate_shared>(allocator, session); } -} // namespace webcpp::trystero::native +} // namespace webcpp::trystero::platform #endif diff --git a/include/webcpp/trystero/protocol/relays.hpp b/include/webcpp/trystero/protocol/relays.hpp index 01ac535..f6ba7ba 100644 --- a/include/webcpp/trystero/protocol/relays.hpp +++ b/include/webcpp/trystero/protocol/relays.hpp @@ -35,8 +35,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; diff --git a/include/webcpp/trystero/webrtc/data_channel.hpp b/include/webcpp/trystero/webrtc/data_channel.hpp index 6274f34..465246c 100644 --- a/include/webcpp/trystero/webrtc/data_channel.hpp +++ b/include/webcpp/trystero/webrtc/data_channel.hpp @@ -39,8 +39,8 @@ /** * The backend's WebRTC over webcpp::webrtc, the same on both targets: natively libdatachannel's, - * in the browser the page's own. The native and the browser backends make their peer connections - * here, and what remains of the platform is webcpp::webrtc'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 { diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 9b5632c..4bdb541 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -8,15 +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 the backends' WebRTC (webcpp::webrtc, natively 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/test/CONVERSION.md b/test/CONVERSION.md index dbd7633..074eee6 100644 --- a/test/CONVERSION.md +++ b/test/CONVERSION.md @@ -42,6 +42,13 @@ run as the build asks and once more without them (`native_peer_connection_no_exc (`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 | diff --git a/test/Jamfile b/test/Jamfile index 9ce2ec7..3b46517 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,17 +17,30 @@ import webcpp ; webcpp.targets native emscripten ; -# The headers that build on both targets, the native backend's and the -# backend's WebRTC over webcpp::webrtc, against libdatachannel and OpenSSL, -# and the browser backend's, on emscripten, which includes that WebRTC there. -# Every one compiles with exceptions and without them, as the build asks, so -# the lint analyses them so too. +# 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 ; + +# 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/*.hpp trystero/webrtc/*.hpp - : /webcpp/trystero//native multi : 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 @@ -41,9 +55,7 @@ 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 webcpp::webrtc's libdatachannel and OpenSSL, run -# natively only. +# backend of support/memory_backend.hpp: on both targets. # tag::both-targets[] webcpp.run protocol : protocol_test.cpp : fixtures/expected/expected.json ; webcpp.run room : room_test.cpp ; @@ -63,35 +75,46 @@ 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 browser backend +# 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 ; # 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 + +# 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; and relays it +# cannot reach. 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. -webcpp.run native_websocket : native_websocket_test.cpp - : /webcpp/trystero//native multi - _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE +# touches a container its socket cleared fails at once, not one run in many; +# the backend's WebRTC; and whole rooms over it. Each as the build asks and +# without exceptions: 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 : 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 ; -# The backend's WebRTC over webcpp::webrtc, and whole rooms over it, as the -# build asks and without exceptions: webcpp::webrtc calls libdatachannel's C -# API, which catches what libdatachannel throws, so the native backend needs -# none. -# tag::native[] -webcpp.run native_peer_connection : native_peer_connection_test.cpp - : /webcpp/trystero//native multi : native ; -webcpp.run native_room : native_room_test.cpp - : /webcpp/trystero//native multi : native ; -webcpp.run native_peer_connection_no_exceptions : native_peer_connection_test.cpp - : /webcpp/trystero//native multi off : native ; -webcpp.run native_room_no_exceptions : native_room_test.cpp - : /webcpp/trystero//native multi off : native ; -# end::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_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 @@ -101,38 +124,38 @@ webcpp.run native_room_no_exceptions : native_room_test.cpp 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 and Web Crypto but no WebRTC; each main runs its io_context, as -# a page's program does, and suspends in it in either variant. -# tag::browser[] -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 ; +# 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 ; +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 browser_page : browser_page_test.cpp : : emscripten ; -# end::browser[] +webcpp.run platform_page : platform_page_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_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 browser_page_no_exceptions : browser_page_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_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 ; # end::no-exceptions[] # The combined Asio/Beast/Trystero provider has its own recurring native lane. diff --git a/test/browser_sealer_test.cpp b/test/browser_sealer_test.cpp deleted file mode 100644 index 3560ccf..0000000 --- a/test/browser_sealer_test.cpp +++ /dev/null @@ -1,155 +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 runs the io_context, which each Web Crypto promise the sealer -// awaits holds; each step starts from the completions 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 -#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 { - -/** 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; - trystero::browser::backend backend{io.get_executor()}; - std::shared_ptr sealer; - bool in_call = false; - bool judged = false; - std::optional sealed; - std::optional opened; - std::optional garbage; - std::optional without_subtle; - std::optional after_failure; -}; - -/** 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; -} - -std::shared_ptr make_sealer(state& s) { - std::array key{}; - key.fill(7); - return s.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(state& s) { - 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); - s.judged = true; - s.io.stop(); -} - -/** 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.sealer->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) { - val descriptor = val::object(); - descriptor.set("value", val::object()); - val::global("Object").call("defineProperty", val::global(), val("crypto"), descriptor); - s.sealer = make_sealer(s); - call(s, [&s] { s.sealer->seal("hello", record(s, s.without_subtle, open_after_failure)); }); -} - -/** Once both opens completed, the next step. */ -void opened(state& s) { - if (s.opened && s.garbage) { - seal_without_subtle(s); - } -} - -/** - * 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(state& s) { - if (!BOOST_TEST(!s.sealed->ec)) { - verdict(s); - return; - } - call(s, [&s] { - s.sealer->open(s.sealed->text, record(s, s.opened, opened)); - s.sealer->open("not a sealed text", record(s, s.garbage, opened)); - }); -} - -} // namespace - -int main() { - state s; - s.sealer = make_sealer(s); - call(s, [&s] { s.sealer->seal("hello", record(s, s.sealed, open_sealed)); }); - s.io.run_for(10s); // lint-run: the test's event loop, held by the promises the sealer awaits - if (!s.judged) { - BOOST_ERROR("the steps stopped before the verdict"); - } - return webcpp::test::exit_status(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/oracle/Jamfile b/test/oracle/Jamfile index d4eac81..d1e2b56 100644 --- a/test/oracle/Jamfile +++ b/test/oracle/Jamfile @@ -20,18 +20,19 @@ webcpp.lane oracle : cases-protocol ; # 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, both -# over webcpp::webrtc. 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 +# 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 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/native_peer.cpp b/test/oracle/interop/native_peer.cpp index 8b05d2d..d93604e 100644 --- a/test/oracle/interop/native_peer.cpp +++ b/test/oracle/interop/native_peer.cpp @@ -27,7 +27,7 @@ // | --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 @@ -250,18 +250,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) { diff --git a/test/oracle/interop/peer.cpp b/test/oracle/interop/peer.cpp index c0573d5..4e5cf41 100644 --- a/test/oracle/interop/peer.cpp +++ b/test/oracle/interop/peer.cpp @@ -7,7 +7,7 @@ // 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`. 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 `browser::page_call`, only posts to it. +// 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 | @@ -24,7 +24,8 @@ // | 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 +#include #include #include @@ -58,7 +59,7 @@ struct extra_room { * actions. */ struct page { webcpp::asio::io_context io; - trystero::browser::backend backend{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; std::unique_ptr app; std::unique_ptr room; std::unique_ptr> chat; @@ -123,8 +124,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", trystero::browser::js_string(category), - trystero::browser::js_string(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, @@ -374,8 +375,8 @@ int main() { // 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::browser::page_call leave_call(app.io.get_executor(), - [](const val& /*argument*/) { 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/platform_backend_test.cpp b/test/platform_backend_test.cpp new file mode 100644 index 0000000..3dc415b --- /dev/null +++ b/test/platform_backend_test.cpp @@ -0,0 +1,147 @@ +// 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 a steady clock in milliseconds that a 20 ms wait moves forward. +// - Its randomness fills what it is given, differently each time. +// - 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 + +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; + } +}; + +/** 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 seconds = std::chrono::floor( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + const std::int64_t read = backend.unix_seconds(); + BOOST_TEST_LE(seconds, read); + BOOST_TEST_LE(read, seconds + 1); + + const double start = backend.now_ms(); + asio::steady_timer wait(io, 20ms); + std::optional waited; + wait.async_wait([&](boost::system::error_code) { waited = backend.now_ms() - start; }); + io.run_for(10s); // lint-run: the test's 20 ms wait + if (BOOST_TEST(waited.has_value())) { + BOOST_TEST_GE(*waited, 19.0); // 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; })); +} + +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() { + its_own_state_is_in_its_memory(); + its_clocks_are_the_standard_librarys(); + its_randomness_fills_and_differs(); + its_executor_and_tls_context_are_there(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/browser_data_channel_test.cpp b/test/platform_page_data_channel_test.cpp similarity index 95% rename from test/browser_data_channel_test.cpp rename to test/platform_page_data_channel_test.cpp index cad5caa..33bb32c 100644 --- a/test/browser_data_channel_test.cpp +++ b/test/platform_page_data_channel_test.cpp @@ -4,7 +4,8 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Tests the browser backend's data channels, webcpp::webrtc's, under node, over plain objects in +// 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 @@ -14,7 +15,7 @@ // 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 @@ -63,7 +64,7 @@ struct state { watching_resource memory; asio::io_context io; asio::executor_work_guard guard{io.get_executor()}; - trystero::browser::backend backend{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; std::shared_ptr connection; std::shared_ptr wrapper; int messages = 0; diff --git a/test/browser_peer_connection_test.cpp b/test/platform_page_peer_connection_test.cpp similarity index 64% rename from test/browser_peer_connection_test.cpp rename to test/platform_page_peer_connection_test.cpp index 626242c..0132cb0 100644 --- a/test/browser_peer_connection_test.cpp +++ b/test/platform_page_peer_connection_test.cpp @@ -4,23 +4,29 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Tests the browser backend's peer connections, 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. +// 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 `backend::max_peer_connections` of them, 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 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 @@ -45,9 +51,13 @@ 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::browser::backend backend{io.get_executor()}; + trystero::platform::backend backend{io.get_executor(), + {.max_peer_connections_per_minute = 4 * budget}}; asio::steady_timer look{io}; bool done = false; }; @@ -70,7 +80,7 @@ void collect() { /** 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() >= trystero::browser::backend::max_peer_connections) { + if (held() >= budget) { collect(); s.look.expires_after(10ms); s.look.async_wait([&s](boost::system::error_code ec) { @@ -124,8 +134,24 @@ int main() { } } - // The page's budget: the one above still counts, closed and dropped. - constexpr std::size_t budget = trystero::browser::backend::max_peer_connections; + // 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) { @@ -133,7 +159,7 @@ int main() { made.push_back(std::move(pc)); } } - BOOST_TEST_EQ(made.size(), budget - 1); + BOOST_TEST_EQ(made.size(), budget - 3); BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr); for (const auto& pc : made) { pc->close(); diff --git a/test/browser_page_test.cpp b/test/platform_page_test.cpp similarity index 91% rename from test/browser_page_test.cpp rename to test/platform_page_test.cpp index ff3a717..cc3275f 100644 --- a/test/browser_page_test.cpp +++ b/test/platform_page_test.cpp @@ -5,7 +5,7 @@ // 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 `browser::page_call`, functions of +// 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 @@ -26,7 +26,7 @@ #include "support/rooms.hpp" #include -#include +#include #include #include @@ -125,14 +125,14 @@ void send(page& p, const val& text) { int main() { page p; - const trystero::browser::page_call join_call(p.f.io.get_executor(), - [&p](const val& /*argument*/) { join(p); }); - const trystero::browser::page_call send_call(p.f.io.get_executor(), - [&p](const val& text) { send(p, text); }); + 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::browser::page_call gone(p.f.io.get_executor(), - [&p](const val& /*argument*/) { ++p.late; }); + const trystero::platform::page_call gone(p.f.io.get_executor(), + [&p](const val& /*argument*/) { ++p.late; }); gone.function()(val(1)); } // clang-format off diff --git a/test/browser_websocket_bound_test.cpp b/test/platform_page_websocket_bound_test.cpp similarity index 65% rename from test/browser_websocket_bound_test.cpp rename to test/platform_page_websocket_bound_test.cpp index 4cef284..47ed0cb 100644 --- a/test/browser_websocket_bound_test.cpp +++ b/test/platform_page_websocket_bound_test.cpp @@ -4,21 +4,24 @@ // 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, after the call, -// and holds no more than the bound. Without the bound, the stand-in held all 6.4 MiB and no close -// came. +// 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 @@ -38,19 +41,24 @@ 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({}); + if (this.onopen) this.onopen({type: "open"}); }, 0); } send(text) { @@ -72,9 +80,12 @@ constexpr int texts = 100; struct state { asio::io_context io; asio::executor_work_guard guard{io.get_executor()}; - trystero::browser::backend backend{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'); + int sending = 0; int closes = 0; + bool in_send = false; bool sent = false; bool judged = false; }; @@ -89,12 +100,26 @@ void verdict(state& s) { } BOOST_TEST_EQ(s.closes, 1); BOOST_TEST_LE(held(), trystero::protocol::max_queued_relay_bytes); - BOOST_TEST_EQ(val::global("stalledCloses").as(), 1); + BOOST_TEST_GE(val::global("stalledCloses").as(), 1); 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. */ +void send_next(state& s) { + 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); }); +} + } // namespace int main() { @@ -102,19 +127,11 @@ int main() { state s; s.socket = s.backend.connect("wss://relay.test", { - .open = - [&s] { - const std::string text(std::size_t{64} * 1024, 't'); - for (int i = 0; i < texts; ++i) { - s.socket->send(text); - } - BOOST_TEST_EQ(s.closes, 0); // not inside the call - s.sent = true; - verdict(s); - }, + .open = [&s] { send_next(s); }, .message = {}, .close = [&s] { + BOOST_TEST(!s.in_send); // not inside a send ++s.closes; verdict(s); }, diff --git a/test/browser_websocket_late_events_test.cpp b/test/platform_page_websocket_late_events_test.cpp similarity index 78% rename from test/browser_websocket_late_events_test.cpp rename to test/platform_page_websocket_late_events_test.cpp index dca164b..d9536b7 100644 --- a/test/browser_websocket_late_events_test.cpp +++ b/test/platform_page_websocket_late_events_test.cpp @@ -4,19 +4,22 @@ // 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. +// 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 @@ -43,25 +46,30 @@ 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(). +// 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({}); + if (this.onopen) this.onopen({type: "open"}); }, 0); } send(text) { this.bufferedAmount += new TextEncoder().encode(text).length; setTimeout(() => { - if (this.onmessage) this.onmessage({data: "late"}); + if (this.onmessage) this.onmessage({type: "message", data: "late"}); }, 0); } close() { @@ -69,7 +77,7 @@ EM_JS(void, install_late_websocket, (), { ++globalThis.lateCloses; setTimeout(() => { this.readyState = 3; - if (this.onclose) this.onclose({code: 1006}); + if (this.onclose) this.onclose({type: "close", code: 1006, reason: ""}); }, 0); } }; @@ -81,7 +89,7 @@ namespace { struct state { asio::io_context io; asio::executor_work_guard guard{io.get_executor()}; - trystero::browser::backend backend{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; std::shared_ptr stalled; std::shared_ptr big; int stalled_closes = 0; diff --git a/test/native_peer_connection_test.cpp b/test/platform_peer_connection_test.cpp similarity index 97% rename from test/native_peer_connection_test.cpp rename to test/platform_peer_connection_test.cpp index 5f7e86e..7c0454b 100644 --- a/test/native_peer_connection_test.cpp +++ b/test/platform_peer_connection_test.cpp @@ -4,14 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Tests the native backend's peer connection, webcpp::webrtc's over libdatachannel, between two +// 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 @@ -74,7 +75,7 @@ std::shared_ptr program_runtime(webcpp::webrtc::runtime struct pair { webcpp::webrtc::runtime runtime; asio::io_context io; - trystero::native::backend factory{io.get_executor(), runtime, {.bind_address = loopback}}; + 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; @@ -571,7 +572,7 @@ void pending_frames_and_delivery_use_the_channels_resource() { void a_malformed_candidate_fails_without_throwing() { asio::io_context io; - trystero::native::backend factory(io.get_executor(), {.bind_address = loopback}); + 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; @@ -594,7 +595,7 @@ void a_malformed_candidate_fails_without_throwing() { void the_backend_makes_at_most_its_budget_in_a_minute() { asio::io_context io; - trystero::native::backend factory( + trystero::platform::backend factory( io.get_executor(), {.bind_address = std::pmr::string(loopback), .max_peer_connections_per_minute = 3}); std::vector> made; @@ -613,7 +614,7 @@ void the_backend_makes_at_most_its_budget_in_a_minute() { void the_runtime_holds_at_most_its_cap_at_once() { asio::io_context io; - trystero::native::backend factory( + 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()); @@ -630,7 +631,7 @@ void the_runtime_holds_at_most_its_cap_at_once() { void a_url_libdatachannel_cannot_parse_is_left_out() { asio::io_context io; - trystero::native::backend factory(io.get_executor(), {.bind_address = loopback}); + 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({ @@ -655,14 +656,14 @@ std::string json_of(const webcpp::webrtc::ice_candidate& c) { } /** - * The native backend's connection, offering, and a peer connection of webcpp::webrtc's own, + * 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::native::backend factory{io.get_executor(), runtime, {.bind_address = loopback}}; + 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; diff --git a/test/native_room_test.cpp b/test/platform_room_test.cpp similarity index 91% rename from test/native_room_test.cpp rename to test/platform_room_test.cpp index c767afe..d9cf631 100644 --- a/test/native_room_test.cpp +++ b/test/platform_room_test.cpp @@ -4,12 +4,13 @@ // 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 @@ -38,11 +39,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( diff --git a/test/platform_sealer_test.cpp b/test/platform_sealer_test.cpp new file mode 100644 index 0000000..f5f60d9 --- /dev/null +++ b/test/platform_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 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. 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 + +namespace asio = webcpp::asio; +namespace json = boost::json; +namespace tp = webcpp::trystero::protocol; +namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; + +namespace { + +json::value load(const char* path) { + const std::ifstream file(path); + std::stringstream text; + text << file.rdbuf(); + return json::parse(text.str()); +} + +/** 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(json::object fixture) : sealed_by_js(std::move(fixture)) {} + + json::object sealed_by_js; + 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; +}; + +/** 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, + std::string_view(s.sealed_by_js.at("plaintext").as_string())); + } + 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); +#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 the wrong key and the garbage are refused: on emscripten, a page without crypto.subtle. */ +void refused(state& s) { + if (!s.wrong_key || !s.garbage) { + return; + } +#ifdef WEBCPP_TARGET_EMSCRIPTEN + seal_without_subtle(s); +#else + verdict(s); +#endif +} + +/** + * 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.at("text").as_string(), 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.at("text").as_string(), 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()); + } + state s(load(argv[1]).at("sealed").as_object()); + 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/native_websocket_test.cpp b/test/platform_websocket_test.cpp similarity index 84% rename from test/native_websocket_test.cpp rename to test/platform_websocket_test.cpp index 693a198..283554a 100644 --- a/test/native_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -4,12 +4,12 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Tests the native WebSocket client, webcpp::beast's, natively 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. +// 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 @@ -332,7 +332,7 @@ bool run_until(asio::io_context& io, const std::function& done, } void urls_name_a_scheme_host_port_and_path() { - const auto secure = trystero::native::detail::parse_url("wss://relay.example.org"); + const auto secure = trystero::platform::detail::parse_url("wss://relay.example.org"); if (!BOOST_TEST(secure.has_value())) { return; } @@ -342,7 +342,7 @@ void urls_name_a_scheme_host_port_and_path() { BOOST_TEST_EQ(secure->port, "443"); BOOST_TEST_EQ(secure->handshake_host, "relay.example.org"); BOOST_TEST_EQ(secure->target, "/"); - const auto plain = trystero::native::detail::parse_url("ws://127.0.0.1:7447/nostr?x=1"); + const auto plain = trystero::platform::detail::parse_url("ws://127.0.0.1:7447/nostr?x=1"); if (!BOOST_TEST(plain.has_value())) { return; } @@ -352,14 +352,14 @@ void urls_name_a_scheme_host_port_and_path() { 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::native::detail::parse_url("https://example.org").has_value()); - BOOST_TEST(!trystero::native::detail::parse_url("wss://").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("https://example.org").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("wss://").has_value()); } // 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::native::detail::parse_url("ws://[::1]:7447/nostr"); + const auto ipv6 = trystero::platform::detail::parse_url("ws://[::1]:7447/nostr"); if (!BOOST_TEST(ipv6.has_value())) { return; } @@ -368,14 +368,14 @@ void urls_name_ipv6_hosts_and_refuse_what_a_page_refuses() { 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::native::detail::parse_url("wss://[2001:db8::1]"); + 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::native::detail::parse_url("WSS://Relay.Example.ORG/Path"); + const auto capitals = trystero::platform::detail::parse_url("WSS://Relay.Example.ORG/Path"); if (!BOOST_TEST(capitals.has_value())) { return; } @@ -384,34 +384,36 @@ void urls_name_ipv6_hosts_and_refuse_what_a_page_refuses() { 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::native::detail::parse_url("ws://relay.example.org:080"); + 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::native::detail::parse_url("wss://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::native::detail::parse_url("ws://relay.example.org?x=1"); + 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::native::detail::parse_url("ws://rel%61y.example.org/"); + 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::native::detail::parse_url("wss://user:pw@relay.example.org").has_value()); - BOOST_TEST(!trystero::native::detail::parse_url("wss://relay.example.org/#top").has_value()); - BOOST_TEST(!trystero::native::detail::parse_url("wss://relay.example.org:99999").has_value()); - BOOST_TEST(!trystero::native::detail::parse_url("ws:relay.example.org").has_value()); - BOOST_TEST(!trystero::native::detail::parse_url("ws://[v1.x]/").has_value()); + 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::native::detail::parse_url("ws://relay%00.example.org/").has_value()); + BOOST_TEST(!trystero::platform::detail::parse_url("ws://relay%00.example.org/").has_value()); } // A relay at an IPv6 literal, here 127.0.0.1 written as an IPv4-mapped IPv6 address so that the @@ -423,7 +425,7 @@ void a_relay_at_an_ipv6_address_opens() { bool opened = false; int closes = 0; std::vector received; - const auto socket = trystero::native::connect_websocket( + 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", @@ -462,7 +464,7 @@ struct reports { // 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::native::make_tls_context(); + auto tls = trystero::platform::make_tls_context(); if (!BOOST_TEST(tls.has_value())) { return; } @@ -481,8 +483,8 @@ void a_relay_over_tls_opens_and_is_sent_its_name() { } reports seen; const auto socket = - trystero::native::connect_websocket(io.get_executor(), &*tls, server.url("localhost"), - seen.record(), std::pmr::get_default_resource()); + 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; @@ -507,8 +509,8 @@ void a_relay_whose_certificate_names_another_host_closes_without_opening() { } reports seen; const auto socket = - trystero::native::connect_websocket(io.get_executor(), &*tls, server.url("127.0.0.1"), - seen.record(), std::pmr::get_default_resource()); + 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{""}; @@ -521,14 +523,14 @@ void a_relay_whose_certificate_names_another_host_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::native::make_tls_context(); + auto tls = trystero::platform::make_tls_context(); if (!BOOST_TEST(tls.has_value())) { return; } reports seen; const auto socket = - trystero::native::connect_websocket(io.get_executor(), &*tls, server.url("localhost"), - seen.record(), std::pmr::get_default_resource()); + 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); } @@ -540,8 +542,8 @@ void a_backend_reaches_relays_with_the_tls_context_it_is_given() { const echo_server plain(io); const tls_echo_server secure(io); { - trystero::native::backend backend(io.get_executor(), - webcpp::asio::make_tls_client_context(test_authority)); + 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(), @@ -549,7 +551,8 @@ void a_backend_reaches_relays_with_the_tls_context_it_is_given() { BOOST_TEST(run_until(io, [&] { return seen.opened || seen.closes != 0; })); BOOST_TEST(seen.opened); } - trystero::native::backend backend(io.get_executor(), webcpp::asio::make_tls_client_context("")); + 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; @@ -572,7 +575,7 @@ void a_backend_reaches_relays_with_the_tls_context_it_is_given() { // 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::native::backend backend(io.get_executor()); + trystero::platform::backend backend(io.get_executor()); BOOST_TEST(backend.tls_context().has_value()); } @@ -583,7 +586,7 @@ void a_backend_may_trust_webcpps_embedded_roots() { asio::io_context io; const tls_echo_server server(io); // tag::embedded-roots[] - trystero::native::backend backend(io.get_executor(), webcpp::asio::make_tls_client_context()); + 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; @@ -600,7 +603,7 @@ void opens_sends_in_order_receives_and_closes_once() { bool opened = false; int closes = 0; std::vector received; - const auto socket = trystero::native::connect_websocket( + const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, @@ -635,7 +638,7 @@ void a_message_longer_than_a_relay_sends_closes_the_socket() { bool opened = false; int closes = 0; std::vector received; - const auto socket = trystero::native::connect_websocket( + const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, @@ -664,7 +667,7 @@ void an_unreachable_relay_closes_without_opening() { asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; int closes = 0; - const auto socket = trystero::native::connect_websocket( + const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, "ws://127.0.0.1:" + std::to_string(port), { .open = [&] { opened = true; }, @@ -682,14 +685,14 @@ void a_dropped_socket_reports_nothing() { 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()); + 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, 0); @@ -701,13 +704,13 @@ void closing_right_after_a_send_lets_the_write_finish_first() { 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()); + 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; } @@ -734,19 +737,19 @@ void a_connection_that_ends_during_a_write_closes_once(misbehaviour what) { 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()); + socket = trystero::platform::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; } @@ -766,13 +769,13 @@ void a_relay_that_stops_reading_is_dropped_at_the_queue_bound() { 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()); + 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; } @@ -794,7 +797,7 @@ void a_relay_that_stops_answering_times_out() { asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; int closes = 0; - const auto socket = trystero::native::connect_websocket( + const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, @@ -803,7 +806,7 @@ void a_relay_that_stops_answering_times_out() { }, std::pmr::get_default_resource(), { - .max_queued_bytes = trystero::native::websocket_limits{}.max_queued_bytes, + .max_queued_bytes = trystero::platform::websocket_limits{}.max_queued_bytes, .idle_timeout = 1s, }); if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { @@ -821,7 +824,7 @@ void a_quiet_relay_that_answers_pings_stays_connected() { bool opened = false; int closes = 0; std::vector received; - const auto socket = trystero::native::connect_websocket( + const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, @@ -830,7 +833,7 @@ void a_quiet_relay_that_answers_pings_stays_connected() { }, std::pmr::get_default_resource(), { - .max_queued_bytes = trystero::native::websocket_limits{}.max_queued_bytes, + .max_queued_bytes = trystero::platform::websocket_limits{}.max_queued_bytes, .idle_timeout = 1s, }); if (!BOOST_TEST(run_until(io, [&] { return opened; }))) { diff --git a/test/browser_websocket_test.cpp b/test/platform_websocket_unreachable_test.cpp similarity index 66% rename from test/browser_websocket_test.cpp rename to test/platform_websocket_unreachable_test.cpp index 8f26e20..7804251 100644 --- a/test/browser_websocket_test.cpp +++ b/test/platform_websocket_unreachable_test.cpp @@ -4,26 +4,26 @@ // 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. +// 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 where nothing listens, fails to +// connect, natively over Boost.Beast and on emscripten over node's WebSocket, and reports a close +// too. Each reports exactly one, after the call that made it, never inside it, and nothing is +// thrown; a send and a close before the connection opened change nothing. Before the fix, a page's +// `new WebSocket` threw a SyntaxError through the room's constructor. // // 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 #include -#include #include #include #include @@ -31,7 +31,6 @@ #include #include #include -#include #include #include #include @@ -43,19 +42,19 @@ using namespace std::chrono_literals; 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. + * 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{ - "ftp://relay.invalid", "wss://relay.invalid/#fragment", "not a url", "/relative", - "http://127.0.0.1:9", "https://127.0.0.1:9", +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", "ws://127.0.0.1:9", "ws://[::1]:9", }; struct state { asio::io_context io; asio::executor_work_guard guard{io.get_executor()}; - trystero::browser::backend backend{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; asio::steady_timer settle{io}; std::array, urls.size()> sockets; std::array closes{}; @@ -63,20 +62,6 @@ struct state { bool judged = false; }; -/** Whether node's WebSocket makes a socket of `url`, as the page's own code would see it. */ -bool node_accepts(std::string_view url) { - // clang-format off - return EM_ASM_INT(({ - try { - new WebSocket(UTF8ToString($0, $1)).close(); - return 1; - } catch (_) { - return 0; - } - }), url.data(), url.size()) != 0; - // clang-format on -} - /** 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) { @@ -98,7 +83,6 @@ void closed(state& s, std::size_t i) { /** Makes a WebSocket of each URL, then sends on it and closes it. */ void connect_all(state& s) { for (std::size_t i = 0; i < urls.size(); ++i) { - std::cout << urls.at(i) << (node_accepts(urls.at(i)) ? ": a socket\n" : ": refused\n"); s.sockets.at(i) = s.backend.connect(urls.at(i), { .open = [] { BOOST_ERROR("a URL opened"); }, diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index af95e65..76a2a0a 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -81,7 +81,7 @@ struct virtual_clock_state { double now_ms = 0; }; -/** 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 { From dbf78dfd8b20b21984fabc5be8d586ed46377631 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:42:35 -0300 Subject: [PATCH 018/116] trystero: the first phase's texts applied, its changelog in ten lines The hand-over texts of the browser on webcpp::asio's run model, the native relays on webcpp::beast with Boost.URL and the core on Boost reach the files no package owned: AGENTS.md (the page's names on the wire, the browser's bridge, page_call and work guard, the relay session and its TLS, the Boost containers, the keyed event-id set, what stays outside the resources), design.adoc, allocation.adoc, overview.adoc, building.adoc, testing.adoc, README.md and build.jam's comment. The changelog's Unreleased holds the three packages' lines and the WebRTC move's in ten, breaking changes first. test/Jamfile compiles native/websocket.hpp alone on emscripten too, against webcpp::beast's browser implementation and Boost.URL, so that the lanes prove the relay session compiles there. The reference no longer defines BOOST_ASIO_DISABLE_THREADS: the native backend's Asio and Beast are webcpp::asio and webcpp::beast, and the page builds without it. The provider lane no longer asks for exceptions, which the backend no longer needs, and two tests cite Trystero's dist/ files rather than C/. --- AGENTS.md | 151 +++++++++++++++++++++++++-------------- README.md | 19 +++-- build.jam | 2 +- doc/Jamfile | 9 ++- doc/allocation.adoc | 47 ++++++------ doc/building.adoc | 5 +- doc/changelog.adoc | 34 +++++---- doc/design.adoc | 12 ++-- doc/overview.adoc | 15 ++-- doc/testing.adoc | 29 ++++---- test/Jamfile | 20 +++++- test/app_impl_test.cpp | 4 +- test/connection_test.cpp | 2 +- test/provider/Jamfile | 3 +- 14 files changed, 223 insertions(+), 129 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3312a7f..33c3c09 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,14 +14,16 @@ 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 files of + `@trystero-p2p/core` 0.26.0 as published. - **The core and the backends.** ``, the headers directly under `include/webcpp/trystero/`, `protocol/` and `detail/` are the core: the rooms over the backend interface of `backend.hpp`, which @@ -34,13 +36,18 @@ holds only what is specific to trystero. `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. `browser/` is the browser backend, over the - page's WebSocket, timers and Web Crypto 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 Boost.Beast and OpenSSL, which builds only natively. - `test/Jamfile` compiles each header alone on the targets that build it, in - three calls; `webrtc/` natively, and on emscripten through - `browser/backend.hpp`. + page's WebSocket and Web Crypto through webcpp::asio's bridge and + `browser::async_await`, with the core's `detail::timer` over webcpp::asio's + steady timer, which builds only on emscripten; a program includes no + source file of trystero's: `/webcpp/asio//asio` links the browser runtime. + `native/` is the native backend, over webcpp::beast (natively Boost.Beast) + and OpenSSL, which builds only natively; its relay session, + `native/websocket.hpp`, names only webcpp::asio and webcpp::beast and + compiles for Emscripten too, where nothing uses it yet. `test/Jamfile` + compiles each header alone on the targets that build it, in four calls; + `webrtc/` natively, and on emscripten through `browser/backend.hpp`, and + `native/websocket.hpp` on emscripten too, with `/webcpp/beast//browser` + and `/webcpp//boost_url`. - **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 @@ -56,28 +63,33 @@ holds only what is specific to trystero. program or test asks for `on`. `native_peer_connection` and `native_room` also run with `exception-handling=off`, as the evidence. trystero raises nothing of its own; a raise would go through - `boost::throw_exception`, as the native backend's TLS context does when - OpenSSL cannot make it. + `boost::throw_exception`; the native 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 browser 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 native backend - names it too (its executor, timer and sealer), but for its relays' - WebSockets, which are Boost.Beast's over Boost.Asio: `native::backend`'s - private `relay_executor` hands them the backend's executor, natively the - same type. The guide's reference reads every header for Emscripten's - target, where webcpp::asio is its own and the native backend is never - built: there `relay_executor` names no executor, and the native headers - still parse. `/webcpp/trystero//trystero` + names it everywhere, 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 the native headers parse there as they + are. `/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 (`quick_start-60-d-jspi.js`), and the suites run in both. - `browser::event_loop` polls the `io_context` as before and never runs it, - but a test whose `main` runs it, as the tests over the memory relays do, - suspends there under Asyncify, which loses what a `main` that suspended - returns: those end with `webcpp::test::exit_status`. + A browser 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 + `browser::page_call`, 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. + 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; `browser_page` proves the program's + shape. `native::timer` is still the same code as `detail::timer`. - **The dependencies.** libsecp256k1 (every room) remains an external installation, found through `webcpp.external` and `webcpp.external-found` at `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=`, then @@ -91,7 +103,10 @@ holds only what is specific to trystero. 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 + Asio and Beast, so a combined application has one provider. For the + relays `/webcpp/trystero//native` also names `/webcpp/beast//tls`, + `/webcpp//boost_url` and `/webcpp/asio//tls`, whose embedded authorities a + program may trust in place of the system's. No `LIBDATACHANNEL_ROOT`, `OPENSSL_ROOT` or installed binary is consulted. Initialize their sources with `git submodule update --init --recursive third_party/libs/libdatachannel third_party/libs/openssl`. Native builds @@ -113,6 +128,21 @@ holds only what is specific to trystero. queued handler holds after the backend is gone never outlives it. `browser::backend` owns one capped at `max_peer_connections` (256); webcpp::webrtc's census of the page counts every runtime's connections. +- **The native relays.** A relay's URL is read with Boost.URL as a page's + `WebSocket` reads it: an IPv6 address in brackets reaches the resolver + without them, the scheme in any case, and userinfo, a fragment, a port + beyond 65535 and an IPvFuture host are refused, which reports a close. + Over TLS the connection sends the host (SNI), through + `webcpp::beast::set_server_name`, only when it is a name, and checks the + certificate against the URL's host, a name or an address, with Asio's + `host_name_verification`. A backend trusts the system's authorities by + default (`native::make_tls_context()`), 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/native_websocket_test.cpp` (EC P-256, valid from 2026-01-01 to + 2126-01-01), which nothing else trusts. - **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 @@ -141,20 +171,19 @@ holds only what is specific to trystero. - **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 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. - webcpp::webrtc's JavaScript catches the page's WebRTC exceptions the same - way, and its events come through webcpp::asio's bridge, which posts to the - loop's executor. A message that is not a frame is dropped on the executor, +- **No JavaScript exception enters WebAssembly.** The browser backend's + calls that can throw (a `WebSocket` constructor or `send`, a Web Crypto + method) are `EM_ASM` blocks in inline functions of `browser/backend.hpp` + that catch in JavaScript and return what failed as a value, which the C++ + turns into the error its interface has; a Web Crypto call is made inside + an `async` function, so that what it throws rejects its promise. 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 browser tests run under node with exceptions and without them (`*_no_exceptions`), and the @@ -213,6 +242,14 @@ 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 `colliding_event_ids_stay_fast` feeds it 2048 + ids found to share one bucket of `std::unordered_set` and reads + Boost.Unordered's statistics (`BOOST_UNORDERED_ENABLE_STATS`, defined by + that test only). - 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 @@ -429,14 +466,19 @@ holds only what is specific to trystero. 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 + - **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`, `boost::json::value` 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 @@ -533,17 +575,20 @@ holds only what is specific to trystero. 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; 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), and under Asyncify the unwind data of a call that suspends, which - webcpp::asio's run family does (the test counts it apart, 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. + touched only on the room's executor; natively, Boost.Beast's state + inside the relay WebSocket (its stream's) and the resolver's results, + while the WebSocket's operations, read buffer and queued texts are in + the room's resource; the payload types `std::string`, `bytes` 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 the + browser, each pending Web Crypto promise's entry in the bridge's map, in + the io_context's allocator (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 diff --git a/README.md b/README.md index f777137..7f33fe2 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ A room runs on two targets, through a backend of each: | Backend | Header | Target | Built on | | --- | --- | --- | --- | | the browser's | `` | emscripten | the page's `WebSocket` and `crypto.subtle`, through webcpp::asio's bridge, webcpp::asio's timers, and webcpp::webrtc over its `RTCPeerConnection` | -| the native one | `` | native | webcpp::webrtc over libdatachannel for WebRTC, Boost.Beast for the relays' WebSockets, OpenSSL for TLS and AES-GCM | +| the native one | `` | native | webcpp::webrtc over libdatachannel for WebRTC, webcpp::beast for the relays' WebSockets, natively Boost.Beast's, their URLs read with Boost.URL, OpenSSL for TLS and AES-GCM | `` is the rooms themselves, which build on both targets and include neither backend. Both backends' WebRTC is @@ -68,15 +68,18 @@ 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. It builds on webcpp::asio and webcpp::webrtc, two -libraries of the superproject; its TLS and WebRTC dependencies are built from -pinned sources; only libsecp256k1 needs an external installation: +developed inside Boost. It builds on webcpp::asio, webcpp::webrtc and, for +the native relays, webcpp::beast, three libraries of the superproject; its +TLS and WebRTC dependencies are built from pinned sources; only libsecp256k1 +needs an external installation: | Library | Needed by | Found where | | --- | --- | --- | | libsecp256k1 0.8.0, with its `schnorrsig` and `extrakeys` modules | every room: it signs the Nostr events peers meet through | `-sSECP256K1_ROOT=` natively, `-sSECP256K1_EMSCRIPTEN_ROOT=` for its emscripten build, else `.local/secp256k1-native` and `.local/secp256k1-emscripten` | | webcpp::asio | every room | `/webcpp/asio//asio` | | webcpp::webrtc | both backends' WebRTC | `/webcpp/webrtc//webrtc` | +| webcpp::beast | the native backend's relays: their WebSockets and TLS | `/webcpp/beast//tls`: natively Boost.Beast over the source-built OpenSSL | +| Boost.URL | the native backend's relays: their URLs | `/webcpp//boost_url`, built from Boost's sources once per variant | | libdatachannel 0.24.6 | the native backend, through webcpp::webrtc | `/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 | @@ -102,9 +105,11 @@ project uses the rooms and the browser backend through webcpp::asio, libsecp256k1 and Boost.JSON's definitions, compiled once per variant, and on emscripten webcpp::webrtc and embind; a program there is built in webcpp::asio's suspension variant, `webcpp-suspend=jspi` by default -or `asyncify`. A native program uses `/webcpp/trystero//native`, which adds -webcpp::webrtc, with libdatachannel and OpenSSL, and declares -`multi` itself, as `example/Jamfile` does. +or `asyncify`. A native program uses `/webcpp/trystero//native` and +declares `multi` itself, as `example/Jamfile` does; the target +adds webcpp::webrtc, with libdatachannel and OpenSSL, webcpp::beast's TLS and +Boost.URL for the relays, and webcpp::asio's `//tls`, whose embedded +authorities a program may trust in place of the system's. ## The examples diff --git a/build.jam b/build.jam index 01ad84f..1ec71a6 100644 --- a/build.jam +++ b/build.jam @@ -53,7 +53,7 @@ rule native-dependencies ( properties * ) } # Asio is webcpp::asio: natively Boost.Asio itself, on emscripten the shipped -# backend, without threads (the event loop drives it), whose browser runtime +# backend, without threads (main runs it), whose browser runtime # webcpp::webrtc's browser objects deliver through. On emscripten the browser # backend's WebRTC is webcpp::webrtc's, and the backend reaches the page # through embind: -lembind, what b2's on links, which as a usage diff --git a/doc/Jamfile b/doc/Jamfile index 7ef2708..598c00f 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -12,7 +12,10 @@ webcpp.doc trystero : trystero.adoc ; # 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 webcpp::webrtc, libdatachannel and OpenSSL, and Boost.Asio without -# threads, as wasm32 has none, for the native backend's Beast and timers. +# brings webcpp::webrtc, webcpp::beast, Boost.URL, libdatachannel and +# OpenSSL. The native 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//native multi - /webcpp//emscripten-reference BOOST_ASIO_DISABLE_THREADS ; + /webcpp//emscripten-reference ; diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 31e5ccb..3f74020 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -62,9 +62,9 @@ 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. +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, @@ -110,11 +110,14 @@ 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 @@ -160,7 +163,8 @@ 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. +executor the wrapper stays Asio's. On both targets the room's executor is the +executor of an `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, @@ -206,22 +210,25 @@ nothing. 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`; -* Boost.Beast's and Asio's state inside the native WebSocket: its stream, - its resolver's results, its coroutines' frames; +* natively, Boost.Beast's state inside a relay's WebSocket, its stream's, + and the resolver's results; the WebSocket's operations, its read buffer + and its queued texts are in the room's resource, since each of its + handlers carries the room's allocator; * the payload types `std::string`, `bytes` 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; -* on Emscripten under Asyncify, the unwind data Asyncify allocates when a - call of webcpp::asio's run family suspends, which a program whose - `io_context` the browser's `event_loop` polls never does. - -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. +* on Emscripten under Asyncify, the unwind data Asyncify allocates whenever + the browser program's `run` suspends; +* in the browser, the entry of each pending Web Crypto promise in the map of + webcpp::asio's bridge, in the allocator of the `io_context`: 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 diff --git a/doc/building.adoc b/doc/building.adoc index 797f6b4..91e6555 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -8,8 +8,9 @@ == Building trystero is header-only, and is developed inside the webcpp superproject, as -a Boost library is developed inside Boost. It builds on two libraries of -webcpp's: webcpp::asio, and webcpp::webrtc, the WebRTC of both its backends. +a Boost library is developed inside Boost. It builds on three libraries of +webcpp's: webcpp::asio; webcpp::webrtc, the WebRTC of both its backends; and +webcpp::beast, the native backend's relays. Its native TLS and WebRTC dependencies are built from pinned sources. Only libsecp256k1 needs an external installation: diff --git a/doc/changelog.adoc b/doc/changelog.adoc index e593d77..e10adb3 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,20 +16,26 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Changed both backends' WebRTC to webcpp::webrtc, one implementation for -native and the browser. -* Changed the native backend to work without exceptions, as the rest does. -* *Breaking change:* Removed the backends' own peer connection and data -channel classes, and their `native_handle()`; use `native::backend` or -`browser::backend`. -* *Breaking change:* Changed trystero's Asio to webcpp::asio; a browser -program uses `webcpp::asio::io_context`. -* Added `native::backend_config::runtime`: at most 256 native connections -alive at once. -* Added a `native::backend` constructor that takes the program's -webcpp::webrtc runtime. -* Changed browser data channels to keep frames that arrive before a -handler, 64 for 10 s. +* *Breaking change:* Changed trystero's Asio to webcpp::asio; a page's `main` +runs its `webcpp::asio::io_context` under a work guard. +* *Breaking change:* Removed `browser::event_loop` and `browser/src.hpp`; +`browser::backend` takes an executor, pages call `browser::page_call`. +* *Breaking change:* Removed the backends' own connection and channel classes +for webcpp::webrtc's; use `native::backend` or `browser::backend`. +* *Breaking change:* Changed the native backend to work without exceptions and +throw nothing; `tls_context()` returns a `boost::system::result`. +* *Breaking change:* Changed `protocol::make_id` to `protocol::random_id`, and +`protocol::proposal::size` to `std::uint64_t`. +* Fixed native relays at an IPv6 address being unreachable; relays now use +webcpp::beast and Boost.URL. +* Added `native::backend_config::runtime`, at most 256 connections at once, and +constructors taking a runtime or TLS context. +* Fixed 32-bit receivers, pages among them, misreading transfer offers of 4 GiB +or more. +* Changed browser data channels to keep frames that arrive before a handler, +64 for 10 s. +* Fixed rooms slowed by relays' event ids chosen to collide, and pages ignoring +a failed `getentropy`. // end::unreleased[] [#trystero-changelog-0-1-0] diff --git a/doc/design.adoc b/doc/design.adoc index c072b4e..72d3c16 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -38,11 +38,12 @@ | Browser backend | `browser/*.hpp` -| `emscripten::val` over the browser's APIs, and the event loop +| the page's WebSocket and Web Crypto through webcpp::asio's bridge and + `async_await`, webcpp::asio's timers, and `page_call` | Native backend | `native/*.hpp` -| Boost.Beast, OpenSSL and Asio's timers +| webcpp::beast (natively Boost.Beast), Boost.URL, OpenSSL and Asio's timers |=== Everything above the backend interface is the core, which builds on both @@ -213,8 +214,11 @@ trystero builds on webcpp::asio, and its backends on webcpp::webrtc. `/webcpp/trystero//trystero` brings `/webcpp/asio//asio`, and on emscripten `/webcpp/webrtc//webrtc`, the browser's WebRTC; `/webcpp/trystero//native` brings `/webcpp/webrtc//webrtc` natively, with its libdatachannel, under the -MPL 2.0, and OpenSSL, under the Apache License 2.0. Neither is in a browser -program, as OpenSSL is optional for Asio. +MPL 2.0, and OpenSSL, under the Apache License 2.0, and for the relays +`/webcpp/beast//tls`, `/webcpp//boost_url` and `/webcpp/asio//tls`, whose +embedded authorities a program may trust in place of the system's. Neither +libdatachannel nor OpenSSL is in a browser program, as OpenSSL is optional +for Asio. [#trystero-design-licensing] === Licensing diff --git a/doc/overview.adoc b/doc/overview.adoc index 0c68f1f..0dd09fa 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -60,9 +60,9 @@ Each backend is a header of its own: | `` | native -| webcpp::webrtc over libdatachannel for WebRTC, Boost.Beast for the relays' - WebSockets, OpenSSL for TLS and AES-GCM, and Asio's timers - (<>) +| webcpp::webrtc over libdatachannel for WebRTC, webcpp::beast for the + relays' WebSockets, natively Boost.Beast's, their URLs read with Boost.URL, + OpenSSL for TLS and AES-GCM, and Asio's timers (<>) |=== Both run the same room, and both meet Trystero JS peers. Every name is in the @@ -72,10 +72,11 @@ namespace `webcpp::trystero`. === 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. -* webcpp::asio, and webcpp::webrtc for both backends' WebRTC - (<>). +* Boost 1.92: Asio, Circular Buffer, Container (its `pmr` base class), Core, + Endian, Hash2, JSON, System and Unordered; and Beast and URL for the native + backend. +* webcpp::asio, webcpp::webrtc for both backends' WebRTC, and webcpp::beast + for the native backend's 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. diff --git a/doc/testing.adoc b/doc/testing.adoc index ea17f51..c18ba75 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -124,10 +124,13 @@ include::{library-root}/test/Jamfile[tag=allocation] | `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. + same process, opens, sends in order, closes once, reaches a relay at an + IPv6 address, reads URLs as a page does, 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, keeps a TLS context's error + in the backend, 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`, and each `_no_exceptions` | Two connections of the backend's WebRTC, over webcpp::webrtc's @@ -168,8 +171,8 @@ include::{library-root}/test/Jamfile[tag=browser] 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, +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: @@ -292,12 +295,14 @@ runtime and static link configuration. These builds need no network access. 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. +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 diff --git a/test/Jamfile b/test/Jamfile index 9ce2ec7..9080382 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -12,6 +12,7 @@ project : requirements /webcpp/trystero//trystero msvc:_CRT_SECURE_NO_WARNINGS msvc:/bigobj ; +import feature ; import webcpp ; webcpp.targets native emscripten ; @@ -24,10 +25,27 @@ webcpp.targets native emscripten ; webcpp.headers-alone trystero : ../include : trystero.hpp trystero/*.hpp trystero/protocol/*.hpp trystero/detail/*.hpp ; webcpp.headers-alone trystero : ../include - : trystero/native/*.hpp trystero/webrtc/*.hpp + : trystero/native/backend.hpp trystero/native/sealer.hpp trystero/native/timer.hpp + trystero/webrtc/*.hpp : /webcpp/trystero//native multi : native ; webcpp.headers-alone trystero : ../include : trystero/browser/*.hpp : : emscripten ; +# The relay session names webcpp::asio and webcpp::beast only, and compiles on +# both targets, though only the native backend uses it: natively against the +# native backend's dependencies, on emscripten against webcpp::beast's browser +# implementation and Boost.URL, so that the lanes, not only the reference's +# parse, prove it compiles there. +rule relay-session-dependencies ( properties * ) +{ + if [ feature.get-values : $(properties) ] = emscripten + { + return /webcpp/beast//browser /webcpp//boost_url ; + } + return /webcpp/trystero//native multi ; +} +webcpp.headers-alone trystero : ../include : trystero/native/websocket.hpp + : @relay-session-dependencies : native 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 # them. diff --git a/test/app_impl_test.cpp b/test/app_impl_test.cpp index a154081..6ab8a36 100644 --- a/test/app_impl_test.cpp +++ b/test/app_impl_test.cpp @@ -456,7 +456,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; @@ -483,7 +483,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); diff --git a/test/connection_test.cpp b/test/connection_test.cpp index b175685..2404e95 100644 --- a/test/connection_test.cpp +++ b/test/connection_test.cpp @@ -731,7 +731,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); diff --git a/test/provider/Jamfile b/test/provider/Jamfile index a438ce5..0a234a4 100644 --- a/test/provider/Jamfile +++ b/test/provider/Jamfile @@ -11,7 +11,6 @@ webcpp.original python3 ; # Keep ownership with Trystero so CI provisions its external secp256k1. # The common executable names all three public dependency aliases. webcpp.drive combined : ../../../../tools/openssl/test//combined_provider - : release multi on - 60 + : release multi 60 : driver.py : : native ; webcpp.lane provider-integration : combined : native ; From 438abfbd54763cc4ebf8ec9a1256f3ee3c83e9b9 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:57:22 -0300 Subject: [PATCH 019/116] trystero: the core's time as std::chrono, Nostr's kinds and times typed Every time the core keeps is a std::chrono::steady_clock::time_point (detail::time_point) and every delay a std::chrono::milliseconds: the Nostr strategy's cadence, backoff and reconnection bound, the signaling's last message, replays, counter-announcements and failed-open reports, the action wire's waiting frames, a ping's start and the construction window. The numbers are Trystero's, as before, and the wire does not change. The backend's clocks reach the core only through detail/clock.hpp: steady_now and unix_now convert the seam's now_ms and unix_seconds, so that the seam's own types change in one place. construction_window keeps a take(double) for a backend's own window until then. A Nostr kind is a std::uint32_t, and an event's created_at and a subscription's since a std::chrono::sys_seconds, in protocol::nostr::topic_kind, event_id, event_message and subscribe_message. The signaling's offer retries count in std::uint32_t, the announce attempt in std::size_t, and the failed-open report's "never" is an empty optional rather than minus infinity. --- .../webcpp/trystero/detail/action_wire.hpp | 9 +- include/webcpp/trystero/detail/clock.hpp | 49 ++++++++ .../trystero/detail/construction_window.hpp | 22 ++-- .../webcpp/trystero/detail/nostr_strategy.hpp | 114 +++++++++++------- include/webcpp/trystero/detail/signaling.hpp | 83 +++++++------ include/webcpp/trystero/protocol/nostr.hpp | 43 ++++--- include/webcpp/trystero/room.hpp | 8 +- test/protocol_test.cpp | 10 +- test/support/rooms.hpp | 13 +- 9 files changed, 224 insertions(+), 127 deletions(-) create mode 100644 include/webcpp/trystero/detail/clock.hpp diff --git a/include/webcpp/trystero/detail/action_wire.hpp b/include/webcpp/trystero/detail/action_wire.hpp index bcb026f..c2aa8e8 100644 --- a/include/webcpp/trystero/detail/action_wire.hpp +++ b/include/webcpp/trystero/detail/action_wire.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -362,7 +363,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 { @@ -573,7 +574,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) { @@ -697,14 +698,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)); } } diff --git a/include/webcpp/trystero/detail/clock.hpp b/include/webcpp/trystero/detail/clock.hpp new file mode 100644 index 0000000..e155f5f --- /dev/null +++ b/include/webcpp/trystero/detail/clock.hpp @@ -0,0 +1,49 @@ +// 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 + +/** + * A time of the backend's monotonic clock given in its milliseconds, as `backend::factory::now_ms` + * gives it, to the nearest tick of a @ref time_point. + */ +inline time_point from_backend_ms(double ms) { + return time_point( + std::chrono::round(std::chrono::duration(ms))); +} + +/** The time of the backend's monotonic clock, its `now_ms`, as a @ref time_point. */ +inline time_point steady_now(backend::factory& factory) { + return from_backend_ms(factory.now_ms()); +} + +/** The time of the backend's wall clock, its `unix_seconds`, 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 std::chrono::sys_seconds(std::chrono::seconds(factory.unix_seconds())); +} + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/construction_window.hpp b/include/webcpp/trystero/detail/construction_window.hpp index e222e87..52d6e30 100644 --- a/include/webcpp/trystero/detail/construction_window.hpp +++ b/include/webcpp/trystero/detail/construction_window.hpp @@ -9,6 +9,8 @@ #include +#include + #include #include @@ -30,21 +32,25 @@ 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, memory), window_ms_(static_cast(window.count())) {} + : times_(limit, memory), window_(window) {} - /** 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_.capacity() == 0 || (times_.full() && now_ms - times_.front() < window_ms_)) { + /** 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_.push_back(now_ms); // in the oldest's place once full + times_.push_back(now); // in the oldest's place once full return true; } + /** Takes a construction at `now_ms`, milliseconds of the backend's clock as a backend reads + * its own `now_ms`, as take(time_point) does. */ + bool take(double now_ms) { return take(from_backend_ms(now_ms)); } + private: - boost::circular_buffer> times_; - 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 c79f99d..1ac3fb4 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -182,7 +183,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)); @@ -219,12 +220,27 @@ 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 { @@ -237,11 +253,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; }; @@ -269,12 +288,13 @@ class nostr_strategy : public std::enable_shared_from_this { 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) { @@ -323,12 +343,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 = 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; @@ -344,16 +364,18 @@ 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 double share = ((std::uint32_t{random[0]} << 8U) | random[1]) / 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] { @@ -368,36 +390,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) { @@ -445,8 +466,8 @@ class nostr_strategy : public std::enable_shared_from_this { 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); @@ -475,8 +496,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] { @@ -488,7 +510,7 @@ 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_)); } }}); } diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index ba91a95..604f946 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -29,10 +30,10 @@ #include #include #include -#include #include #include #include +#include #include #include #include @@ -179,7 +180,7 @@ class signaling : public std::enable_shared_from_this { 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()) { @@ -230,8 +231,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); @@ -265,12 +269,12 @@ 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) {} 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{}; // 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 @@ -286,7 +290,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; @@ -297,10 +301,10 @@ 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; }; pmr_allocator allocator() const { return {memory_}; } @@ -337,7 +341,7 @@ class signaling : public std::enable_shared_from_this { } ++unconnected; if (!n.offer.pc && !n.answer.pc && - (idle == peers_.end() || n.last_ms < idle->second.last_ms)) { + (idle == peers_.end() || n.last_message < idle->second.last_message)) { idle = it; } } @@ -372,7 +376,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(), @@ -403,20 +407,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_)); @@ -612,7 +615,7 @@ class signaling : public std::enable_shared_from_this { n.answered_offer_id = offer_id; n.answered_offer = offer; n.answer_relays.insert(relay); - n.answer_replayed_ms[relay] = factory_.now_ms(); + n.answer_replayed[relay] = steady_now(factory_); const auto pc = n.answer.pc; const auto weak = weak_from_this(); pc->set_handlers({ @@ -663,13 +666,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) { @@ -838,10 +841,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; } @@ -849,8 +853,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(); @@ -864,11 +871,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); } @@ -1121,7 +1130,7 @@ 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(); } @@ -1139,13 +1148,13 @@ class signaling : public std::enable_shared_from_this { std::pmr::map> peers_; 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/protocol/nostr.hpp b/include/webcpp/trystero/protocol/nostr.hpp index 4d4f4a1..8851429 100644 --- a/include/webcpp/trystero/protocol/nostr.hpp +++ b/include/webcpp/trystero/protocol/nostr.hpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -44,10 +45,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 +58,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())); @@ -100,7 +103,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 +111,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,7 +231,7 @@ inline bool verify(std::span sig, 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 +254,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,14 +273,16 @@ 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. */ 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)); } @@ -286,14 +291,14 @@ inline std::pmr::string subscribe_message( out += R"(["REQ",)"; json::append_string(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) { diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index cfd46d6..44eae8e 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -774,7 +774,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); } @@ -903,7 +903,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; }; @@ -1310,8 +1310,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") { diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index 3afa45e..12ee74e 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -119,8 +120,10 @@ 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()), + const auto created_at = + std::chrono::sys_seconds(std::chrono::seconds(e.at("created_at").as_int64())); + const auto id = tp::nostr::event_id(str(e.at("pubkey")), created_at, + 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"))); } @@ -131,7 +134,8 @@ 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); + tp::nostr::event_message(*key, std::chrono::sys_seconds(std::chrono::seconds(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()); diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp index 07645f4..5f3704a 100644 --- a/test/support/rooms.hpp +++ b/test/support/rooms.hpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -190,13 +191,13 @@ 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) { const std::array aux{}; - 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, protocol::write_signal(m), aux)); } @@ -210,12 +211,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)); } } @@ -227,7 +228,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)); } } From 9840b00452cdc0f144c5076333b0d370698146ad Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:57:28 -0300 Subject: [PATCH 020/116] trystero: fixed-width integers in the protocol and the room tests The protocol's hexadecimal and base64 digits are std::uint32_t with a sentinel for a character that is none, rather than an int of -1; a sealed signal's IV byte is read as a std::uint8_t, whose from_chars refuses a number above 255 as before; the action wire's format nibble is shifted as a std::uint32_t. The doubles that stay are JavaScript's Numbers, which str_to_num, the UTF-16 sum and the relay shuffle now say. The room tests count in std::size_t and std::int64_t, and the memory backend's time scale is a std::uint32_t and its refusal knobs std::size_t. --- .../webcpp/trystero/protocol/action_wire.hpp | 2 +- include/webcpp/trystero/protocol/relays.hpp | 3 +- include/webcpp/trystero/protocol/signal.hpp | 7 +- include/webcpp/trystero/protocol/text.hpp | 46 ++++----- include/webcpp/trystero/protocol/topics.hpp | 3 + test/app_impl_test.cpp | 2 +- test/connection_test.cpp | 8 +- test/memory_backend_test.cpp | 11 ++- test/room_test.cpp | 93 ++++++++++--------- test/shared_test.cpp | 90 +++++++++--------- test/support/memory_backend.hpp | 10 +- 11 files changed, 143 insertions(+), 132 deletions(-) diff --git a/include/webcpp/trystero/protocol/action_wire.hpp b/include/webcpp/trystero/protocol/action_wire.hpp index b1f35f7..0085905 100644 --- a/include/webcpp/trystero/protocol/action_wire.hpp +++ b/include/webcpp/trystero/protocol/action_wire.hpp @@ -168,7 +168,7 @@ 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()); set_u16(out, at + 34, static_cast(metadata.size())); } diff --git a/include/webcpp/trystero/protocol/relays.hpp b/include/webcpp/trystero/protocol/relays.hpp index 01ac535..d6b97b3 100644 --- a/include/webcpp/trystero/protocol/relays.hpp +++ b/include/webcpp/trystero/protocol/relays.hpp @@ -80,7 +80,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..9626efa 100644 --- a/include/webcpp/trystero/protocol/signal.hpp +++ b/include/webcpp/trystero/protocol/signal.hpp @@ -134,12 +134,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); 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 affc011..2f1da06 100644 --- a/include/webcpp/trystero/protocol/topics.hpp +++ b/include/webcpp/trystero/protocol/topics.hpp @@ -183,6 +183,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/test/app_impl_test.cpp b/test/app_impl_test.cpp index a154081..a533075 100644 --- a/test/app_impl_test.cpp +++ b/test/app_impl_test.cpp @@ -577,7 +577,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)))); } diff --git a/test/connection_test.cpp b/test/connection_test.cpp index b175685..6d11bbe 100644 --- a/test/connection_test.cpp +++ b/test/connection_test.cpp @@ -279,7 +279,7 @@ void a_65th_advertised_token_ends_the_connection() { 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; }))); @@ -310,7 +310,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; })); @@ -347,7 +347,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( @@ -381,7 +381,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; diff --git a/test/memory_backend_test.cpp b/test/memory_backend_test.cpp index 580146c..598ade0 100644 --- a/test/memory_backend_test.cpp +++ b/test/memory_backend_test.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -252,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); @@ -358,7 +359,7 @@ void the_virtual_clock_moves_only_when_advanced() { 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); @@ -370,10 +371,10 @@ void the_virtual_clock_moves_only_when_advanced() { BOOST_TEST(fired.empty()); BOOST_TEST_EQ(net.now_ms(), 0.0); net.advance(7s); - BOOST_TEST(fired == std::vector{5}); + BOOST_TEST(fired == std::vector{5}); BOOST_TEST_EQ(net.now_ms(), 7000.0); net.advance(3s); - BOOST_TEST((fired == std::vector{5, 10})); + BOOST_TEST((fired == std::vector{5, 10})); BOOST_TEST_EQ(net.now_ms(), 10000.0); // 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); @@ -381,7 +382,7 @@ void the_virtual_clock_moves_only_when_advanced() { 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 diff --git a/test/room_test.cpp b/test/room_test.cpp index ec82575..0bb64c5 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -173,7 +173,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) { @@ -484,7 +484,7 @@ 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); @@ -508,7 +508,7 @@ 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); } @@ -521,7 +521,7 @@ void forged_offers_make_no_connection() { 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) { + for (std::size_t i = 0; i < 200; ++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"}); @@ -536,7 +536,7 @@ void forged_offers_make_no_connection() { // and their number, so that the application is not handed one report per id. The clock runs 10 // times faster. void signals_that_do_not_open_are_reported_once_per_interval() { - constexpr int flood = 2000; + constexpr std::size_t flood = 2000; fixture f; f.net.time_scale = 10; const std::string a_id = "zzzzzzzzzzzzzzzzzzzz"; @@ -561,7 +561,7 @@ void signals_that_do_not_open_are_reported_once_per_interval() { // 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) { + for (std::size_t i = 0; i < flood; ++i) { attacker.publish(a_topic, { .peer_id = "0garbage" + std::to_string(i), .offer_id = "o", @@ -596,9 +596,10 @@ 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"); @@ -809,7 +810,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) { @@ -830,7 +831,7 @@ void a_replayed_answer_is_refused() { 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_GE(replays, 1U); BOOST_TEST(std::ranges::none_of(errors, [](boost::system::error_code ec) { return ec == trystero::error::wrong_password; })); @@ -864,7 +865,7 @@ 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; + std::size_t replays = 0; const auto end = std::chrono::steady_clock::now() + 10s; while (joined.size() < 2 && std::chrono::steady_clock::now() < end) { watcher.publish(a_topic, { @@ -875,7 +876,7 @@ void a_replayed_offer_is_refused() { run_until(f.io, [] { return false; }, 50ms); } 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 @@ -891,7 +892,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()) { @@ -904,7 +905,7 @@ 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 @@ -918,7 +919,7 @@ void a_reflected_offer_is_refused_as_an_offer() { 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; }; @@ -931,7 +932,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) { @@ -955,8 +956,8 @@ void a_reflected_offer_is_refused_as_an_offer() { 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_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 @@ -981,7 +982,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) { @@ -1005,7 +1006,7 @@ 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); } @@ -1020,8 +1021,8 @@ void a_relay_that_closes_at_once_is_tried_less_and_less_often() { 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) { @@ -1032,7 +1033,7 @@ 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}; + 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()); @@ -1040,7 +1041,7 @@ void a_relay_that_closes_at_once_is_tried_less_and_less_often() { // A connection that lasts: the 60 s announcement after it opened is on the relay, then the // relay goes away. relay.close_after_subscribe = false; - const int before = reconnections; + const std::size_t before = reconnections; BOOST_TEST(run_until(f.io, [&] { return reconnections > before; })); const auto seen = relay.events_seen; // the warm-up's five announcements, then the first of the steady ones, 60 s later @@ -1081,8 +1082,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; @@ -1097,7 +1098,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); } @@ -1140,7 +1141,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*/) { @@ -1162,7 +1163,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) { @@ -1220,13 +1221,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"); @@ -1236,8 +1237,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; }))); @@ -1252,7 +1253,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)); } @@ -1277,17 +1278,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)); } @@ -1310,7 +1311,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); @@ -1325,14 +1326,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 @@ -1347,8 +1348,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( @@ -1363,7 +1364,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(); @@ -1375,7 +1376,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; @@ -1440,7 +1441,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; @@ -1449,7 +1450,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. diff --git a/test/shared_test.cpp b/test/shared_test.cpp index d92b262..979ee77 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -96,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"); @@ -213,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; }))); @@ -227,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); } @@ -241,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(); @@ -263,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; }))); @@ -271,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(); @@ -468,11 +468,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; }); } @@ -482,7 +482,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)); } @@ -585,12 +585,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; @@ -610,7 +610,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"); @@ -683,7 +683,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( @@ -710,7 +710,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) { @@ -720,7 +720,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; }); } @@ -728,7 +728,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: @@ -802,20 +802,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())); @@ -824,7 +824,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})); @@ -832,9 +832,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 @@ -847,14 +847,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); } { @@ -1430,7 +1430,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; @@ -1438,11 +1438,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) { @@ -1466,7 +1466,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; @@ -1495,7 +1495,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)); @@ -1610,7 +1610,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; @@ -1618,7 +1618,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()); } @@ -1627,7 +1627,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) { @@ -1647,7 +1647,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()); } @@ -1661,8 +1661,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"); @@ -1692,8 +1692,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); } @@ -1730,7 +1730,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; }))); @@ -1768,16 +1768,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"); diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index af95e65..4d17038 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -88,7 +88,7 @@ class memory_timer : public backend::timer { public: /** A timer on the virtual clock `clock`, or on Asio's when `clock` is empty. */ memory_timer(webcpp::asio::io_context& io, std::pmr::memory_resource* memory, - int time_scale = 1, std::weak_ptr clock = {}) + std::uint32_t time_scale = 1, std::weak_ptr clock = {}) : io_(io), timer_(io), memory_(memory), @@ -160,7 +160,7 @@ class memory_timer : public backend::timer { webcpp::asio::io_context& io_; webcpp::asio::steady_timer timer_; std::pmr::memory_resource* memory_; - int time_scale_; + std::uint32_t time_scale_; bool on_clock_; std::weak_ptr clock_; std::optional key_; @@ -200,7 +200,7 @@ class memory_relay { std::size_t events_seen = 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; @@ -762,9 +762,9 @@ class memory_network : public backend::factory { /** 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; + std::uint32_t time_scale = 1; /** 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. */ From d5cbc9c43e1b790ed0da1e374810084c275de008 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:58:10 -0300 Subject: [PATCH 021/116] trystero: the guide, AGENTS.md and the changelog name the platform backend doc/platform.adoc's page is the one backend's; every page, the README and AGENTS.md name platform::backend, /webcpp/trystero//platform and the platform_* tests, say that no type is meant for a shared segment and that backend_config::memory holds the backend's own state, and the changelog's ten lines lead with the breaking rename. --- AGENTS.md | 338 ++++++++++++++++++++++---------------- README.md | 78 +++++---- doc/acknowledgements.adoc | 4 +- doc/allocation.adoc | 51 +++++- doc/building.adoc | 88 +++++----- doc/changelog.adoc | 30 ++-- doc/design.adoc | 104 +++++++----- doc/guarantees.adoc | 16 +- doc/overview.adoc | 58 ++++--- doc/protocol.adoc | 8 +- doc/quick-start.adoc | 10 +- doc/testing.adoc | 147 ++++++++++------- doc/usage.adoc | 2 +- 13 files changed, 547 insertions(+), 387 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 33c3c09..6a72123 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,72 +24,91 @@ holds only what is specific to trystero. 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 backends.** ``, the headers +- **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 backends, of the - backend's WebRTC and webcpp::webrtc, of libdatachannel, OpenSSL and - Emscripten, and the lint fails an include that crosses it. `webrtc/` is the - backend's WebRTC, over webcpp::webrtc, on both targets: one peer - connection and one data channel that both backends make, which hold + `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. `browser/` is the browser backend, over the - page's WebSocket and Web Crypto through webcpp::asio's bridge and - `browser::async_await`, with the core's `detail::timer` over webcpp::asio's - steady timer, which builds only on emscripten; a program includes no - source file of trystero's: `/webcpp/asio//asio` links the browser runtime. - `native/` is the native backend, over webcpp::beast (natively Boost.Beast) - and OpenSSL, which builds only natively; its relay session, - `native/websocket.hpp`, names only webcpp::asio and webcpp::beast and - compiles for Emscripten too, where nothing uses it yet. `test/Jamfile` - compiles each header alone on the targets that build it, in four calls; - `webrtc/` natively, and on emscripten through `browser/backend.hpp`, and - `native/websocket.hpp` on emscripten too, with `/webcpp/beast//browser` - and `/webcpp//boost_url`. + 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` (`unix_seconds`) and + `std::chrono::steady_clock` (`now_ms`), 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 (the library never + tests `__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 `getentropy`, which + Emscripten draws from `crypto.getRandomValues`. 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 native backend's (`delayed_channel`, + 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. - **Exceptions.** trystero's WebRTC is webcpp::webrtc's, which natively calls libdatachannel's C API, where no exception crosses: every part of trystero, - both backends included, works with exceptions and without them, and no - program or test asks for `on`. `native_peer_connection` - and `native_room` also run with `exception-handling=off`, as the evidence. + 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`; the native backend keeps a TLS context OpenSSL - cannot make as an error value (`tls_context()`), and its `wss://` relays - report a close. + `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 browser backend, the tests over the memory + 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 native backend - names it everywhere, 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 the native headers parse there as they - are. `/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 (`quick_start-60-d-jspi.js`), and the suites run in both. - A browser program runs its io_context from `main` under a work guard, as + 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 + (`quick_start-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 - `browser::page_call`, 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. + `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. 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; `browser_page` proves the program's - shape. `native::timer` is still the same code as `detail::timer`. + suspended loses what it returns; `platform_page` proves the program's + shape. 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) remains an external installation, found through `webcpp.external` and `webcpp.external-found` at `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=`, then @@ -97,16 +116,23 @@ holds only what is specific to trystero. fallback outside Windows is allowed only for this dependency. A missing installation leaves trystero out unless `webcpp-require-external=on`. MSVC links its static `libsecp256k1.lib` with `SECP256K1_STATIC`. - Both backends' WebRTC is webcpp::webrtc's, `/webcpp/webrtc//webrtc`, which - `/webcpp/trystero//native` names, and `/webcpp/trystero//trystero` on - emscripten; 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//native` also names `/webcpp/beast//tls`, - `/webcpp//boost_url` and `/webcpp/asio//tls`, whose embedded authorities a - program may trust in place of the system's. No + `/webcpp/trystero//trystero` (`build.jam`'s `tag::trystero[]`) is the + rooms alone, the core: its headers, Boost, Boost.JSON, config, + webcpp::asio and libsecp256k1; 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, alternatives by `emscripten`, which a + native program and a page's program both name. Its 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`. Native builds @@ -115,34 +141,46 @@ 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 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. `native::backend` makes one of its own - (`backend_config::runtime`, 256 connections) or takes the program's - (`backend(ex, runtime, config)`), 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. - `browser::backend` owns one capped at `max_peer_connections` (256); + 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 native relays.** A relay's URL is read with Boost.URL as a page's - `WebSocket` reads it: an IPv6 address in brackets reaches the resolver - without them, the scheme in any case, and userinfo, a fragment, a port - beyond 65535 and an IPvFuture host are refused, which reports a close. - Over TLS the connection sends the host (SNI), through - `webcpp::beast::set_server_name`, only when it is a name, and checks the - certificate against the URL's host, a name or an address, with Asio's - `host_name_verification`. A backend trusts the system's authorities by - default (`native::make_tls_context()`), 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/native_websocket_test.cpp` (EC P-256, valid from 2026-01-01 to - 2126-01-01), which nothing else trusts. +- **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 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, as a page's `WebSocket` reads it: + an IPv6 address in brackets reaches the resolver without them, the scheme + in any case, and userinfo, a fragment, a port beyond 65535 and an + IPvFuture host are refused, which reports a close; so are `http://` and + `https://`, in a page too, where a `WebSocket` alone would take them as + `ws://` and `wss://`. Natively, over TLS the connection sends the host + (SNI), through `webcpp::beast::set_server_name`, only when it is a name, + 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 both. 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 @@ -152,8 +190,12 @@ holds only what is specific to trystero. 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, as before; in the browser a refused server refuses the connection. - The per-minute window stays `native::backend`'s. + 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 @@ -163,30 +205,34 @@ holds only what is specific to trystero. 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. `native_peer_connection` tests real queued events + 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. - **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's - calls that can throw (a `WebSocket` constructor or `send`, a Web Crypto - method) are `EM_ASM` blocks in inline functions of `browser/backend.hpp` - that catch in JavaScript and return what failed as a value, which the C++ - turns into the error its interface has; a Web Crypto call is made inside - an `async` function, so that what it throws rejects its promise. 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, + `/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. 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 browser tests run - under node with exceptions and without them (`*_no_exceptions`), and the + one at most 256 KiB, past which the channel closes. The platform's tests + on emscripten (`platform_backend`, `platform_sealer`, + `platform_websocket_unreachable` 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 @@ -226,15 +272,15 @@ holds only what is specific to trystero. gives its place to a new peer, and a new peer beyond the bound is refused and logged once. - 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), the cap of its - 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 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), and holds at - most its runtime's `max_peer_connections` (256) alive at once. + 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 @@ -251,17 +297,22 @@ holds only what is specific to trystero. Boost.Unordered's statistics (`BOOST_UNORDERED_ENABLE_STATS`, defined by that test only). - 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`). 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 @@ -332,7 +383,7 @@ holds only what is specific to trystero. 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 + `protocol` and `platform_sealer` tests read; `update-expected` is its only writer. `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` @@ -365,12 +416,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 @@ -394,7 +445,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, @@ -457,10 +508,10 @@ 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 @@ -484,7 +535,11 @@ holds only what is specific to trystero. 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 @@ -512,7 +567,13 @@ holds only what is specific to trystero. 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. + 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), @@ -578,17 +639,18 @@ holds only what is specific to trystero. touched only on the room's executor; natively, Boost.Beast's state inside the relay WebSocket (its stream's) and the resolver's results, while the WebSocket's operations, read buffer and queued texts are in - the room's resource; the payload types `std::string`, `bytes` 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 the - browser, each pending Web Crypto promise's entry in the bridge's map, in - the io_context's allocator (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 room's resource (in a page the stream's own state is there too, + made with `std::allocator_arg` and the room's allocator); the payload + types `std::string`, `bytes` 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, each pending Web Crypto promise's entry in + the bridge's map, in the io_context's allocator (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 diff --git a/README.md b/README.md index 7f33fe2..c38f574 100644 --- a/README.md +++ b/README.md @@ -7,15 +7,16 @@ 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` and `crypto.subtle`, through webcpp::asio's bridge, webcpp::asio's timers, and webcpp::webrtc over its `RTCPeerConnection` | -| the native one | `` | native | webcpp::webrtc over libdatachannel for WebRTC, webcpp::beast for the relays' WebSockets, natively Boost.Beast's, their URLs read with Boost.URL, 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. Both backends' WebRTC is +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 @@ -26,9 +27,9 @@ 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. Every part of it, both backends included, compiles and -works without exceptions: webcpp::webrtc calls libdatachannel's C API, where -none crosses. +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 @@ -69,7 +70,7 @@ send a wrong room proof, reported by the lower id only. trystero is developed inside the webcpp superproject, as a Boost library is developed inside Boost. It builds on webcpp::asio, webcpp::webrtc and, for -the native relays, webcpp::beast, three libraries of the superproject; its +the relays, webcpp::beast, three libraries of the superproject; its TLS and WebRTC dependencies are built from pinned sources; only libsecp256k1 needs an external installation: @@ -77,11 +78,11 @@ needs an external installation: | --- | --- | --- | | libsecp256k1 0.8.0, with its `schnorrsig` and `extrakeys` modules | every room: it signs the Nostr events peers meet through | `-sSECP256K1_ROOT=` natively, `-sSECP256K1_EMSCRIPTEN_ROOT=` for its emscripten build, else `.local/secp256k1-native` and `.local/secp256k1-emscripten` | | webcpp::asio | every room | `/webcpp/asio//asio` | -| webcpp::webrtc | both backends' WebRTC | `/webcpp/webrtc//webrtc` | -| webcpp::beast | the native backend's relays: their WebSockets and TLS | `/webcpp/beast//tls`: natively Boost.Beast over the source-built OpenSSL | -| Boost.URL | the native backend's relays: their URLs | `/webcpp//boost_url`, built from Boost's sources once per variant | -| libdatachannel 0.24.6 | the native backend, through webcpp::webrtc | `/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::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 libsecp256k1 `-s` option, on b2's command line, names a directory with the library's `include/` and `lib/`; the environment is never read. Without it, the library @@ -100,16 +101,20 @@ instead. With them found, 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, -webcpp::asio, libsecp256k1 and Boost.JSON's definitions, compiled once per -variant, and on emscripten webcpp::webrtc and embind; a program there is -built in webcpp::asio's suspension variant, `webcpp-suspend=jspi` by default -or `asyncify`. A native program uses `/webcpp/trystero//native` and -declares `multi` itself, as `example/Jamfile` does; the target -adds webcpp::webrtc, with libdatachannel and OpenSSL, webcpp::beast's TLS and -Boost.URL for the relays, and webcpp::asio's `//tls`, whose embedded -authorities a program may trust in place of the system's. +program uses the rooms and the platform backend through +`/webcpp/trystero//platform`, on both targets, as `example/Jamfile` does. +The target adds `/webcpp/trystero//trystero`, the rooms alone: trystero's +headers, Boost's, webcpp::asio, which links embind on emscripten, +libsecp256k1 and Boost.JSON'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 @@ -127,7 +132,7 @@ The native quick start, whole: ```cpp #include -#include +#include #include #include @@ -140,7 +145,7 @@ namespace trystero = webcpp::trystero; int main() { boost::asio::io_context io; - trystero::native::backend backend(io.get_executor()); + trystero::platform::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) { @@ -179,7 +184,7 @@ struct lobby { /** What the page keeps alive: its io_context, the backend, the app, and the room it joined. */ struct application { asio::io_context io; - trystero::browser::backend backend{io.get_executor()}; + trystero::platform::backend backend{io.get_executor()}; trystero::app app{io.get_executor(), backend, {.app_id = "webcpp-trystero-quick-start"}}; std::optional joined; @@ -202,13 +207,14 @@ struct application { ``` webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//native multi : native ; + : /webcpp/trystero//platform multi : native ; ``` ``` webcpp.link quick_start : quick_start.cpp - : -sENVIRONMENT=web -sALLOW_MEMORY_GROWTH : emscripten ; + : /webcpp/trystero//platform -sENVIRONMENT=web + -sALLOW_MEMORY_GROWTH : emscripten ; ``` `b2 toolset=emscripten libs/trystero/example/chat//site` copies the chat page @@ -285,9 +291,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. @@ -369,9 +375,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 and the backend's WebRTC natively, against webcpp::webrtc's -libdatachannel and OpenSSL, 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/doc/acknowledgements.adoc b/doc/acknowledgements.adoc index a61eaab..bca9d6f 100644 --- a/doc/acknowledgements.adoc +++ b/doc/acknowledgements.adoc @@ -20,7 +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 -webcpp::webrtc's, over +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 3f74020..6369fa2 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, @@ -27,6 +28,12 @@ an optional resource for each room. 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`. +* `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. @@ -58,10 +65,13 @@ 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. +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. +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. @@ -136,6 +146,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 @@ -174,7 +193,20 @@ 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. +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. *Boost.JSON* allocates through `json_resource`, a `boost::container::pmr::memory_resource` that forwards to a @@ -212,8 +244,9 @@ nothing. which it posts through `webcpp::asio::any_io_executor`; * natively, Boost.Beast's state inside a relay's WebSocket, its stream's, and the resolver's results; the WebSocket's operations, its read buffer - and its queued texts are in the room's resource, since each of its - handlers carries the room's allocator; + and its queued texts are in the room's resource on both targets, since + each of its handlers carries the room's allocator, and in a page the + stream's own state is there too; * the payload types `std::string`, `bytes` and `payload`, with `std::allocator`, the user's choice; * on Emscripten, the C library's `select()`, which Asio's reactor calls on diff --git a/doc/building.adoc b/doc/building.adoc index 91e6555..7ae7751 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -9,8 +9,8 @@ trystero is header-only, and is developed inside the webcpp superproject, as a Boost library is developed inside Boost. It builds on three libraries of -webcpp's: webcpp::asio; webcpp::webrtc, the WebRTC of both its backends; and -webcpp::beast, the native backend's relays. +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 are built from pinned sources. Only libsecp256k1 needs an external installation: @@ -29,23 +29,25 @@ libsecp256k1 needs an external installation: | `/webcpp/asio//asio`: natively Boost.Asio, on emscripten the backend it ships | webcpp::webrtc -| both backends' WebRTC +| the platform backend's WebRTC, on both targets | `/webcpp/webrtc//webrtc`, the superproject's `libs/webrtc` | webcpp::beast -| the native backend's relays: their WebSockets and TLS -| `/webcpp/beast//tls`: natively Boost.Beast over the source-built OpenSSL +| 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 native backend's relays: their URLs +| 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, through webcpp::webrtc +| 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 |=== @@ -73,59 +75,69 @@ include::{library-root}/build.jam[tag=dependencies] [#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, -webcpp::asio, libsecp256k1 and Boost.JSON's definitions, compiled once per -variant, and, on emscripten, webcpp::webrtc and embind: +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 Boost.JSON'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. On emscripten webcpp::asio builds without threads, since the page has none, -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 `quick_start-60-d-jspi.js`. - -A native program uses `/webcpp/trystero//native`, which 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; 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 -(<>): +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 `quick_start-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, with an +alternative for each target. 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 works with exceptions and without them -(<>), so a program builds as it asks, 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 native one with `multi`: [listing] ---- include::{examples}/Jamfile[tag=native] ---- -and as trystero's own tests of the native backend's connections do, once -without exceptions too: +and as trystero's own tests of the platform backend do, on each target that +builds them, once without exceptions too: [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: [listing] ---- @@ -209,7 +221,7 @@ three libraries. 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 +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 diff --git a/doc/changelog.adoc b/doc/changelog.adoc index e10adb3..f03c939 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,26 +16,28 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* *Breaking change:* Changed `native::backend` and `browser::backend` to one +`platform::backend`; include `` and +link `/webcpp/trystero//platform` on both targets. * *Breaking change:* Changed trystero's Asio to webcpp::asio; a page's `main` -runs its `webcpp::asio::io_context` under a work guard. -* *Breaking change:* Removed `browser::event_loop` and `browser/src.hpp`; -`browser::backend` takes an executor, pages call `browser::page_call`. +runs its `io_context` under a work guard, and calls in through +`platform::page_call` of `platform/page.hpp`. * *Breaking change:* Removed the backends' own connection and channel classes -for webcpp::webrtc's; use `native::backend` or `browser::backend`. -* *Breaking change:* Changed the native backend to work without exceptions and -throw nothing; `tls_context()` returns a `boost::system::result`. +for webcpp::webrtc's, and `browser::event_loop`. +* *Breaking change:* Changed the backend to throw nothing; `tls_context()` +returns a `boost::system::result`. * *Breaking change:* Changed `protocol::make_id` to `protocol::random_id`, and `protocol::proposal::size` to `std::uint64_t`. -* Fixed native relays at an IPv6 address being unreachable; relays now use -webcpp::beast and Boost.URL. -* Added `native::backend_config::runtime`, at most 256 connections at once, and -constructors taking a runtime or TLS context. +* Changed a page's relays to the native ones' webcpp::beast session, which +refuses `http://` relay URLs and bounds what the page holds unsent. +* Added `backend_config::memory` for the backend's own state, and +`backend_config::runtime`, at most 256 connections at once, on both targets. +* Fixed relays at an IPv6 address being unreachable, and pages ignoring a +failed `getentropy`. * Fixed 32-bit receivers, pages among them, misreading transfer offers of 4 GiB or more. -* Changed browser data channels to keep frames that arrive before a handler, -64 for 10 s. -* Fixed rooms slowed by relays' event ids chosen to collide, and pages ignoring -a failed `getentropy`. +* Fixed rooms slowed by relays' event ids chosen to collide; channels keep +frames that arrive before a handler, 64 for 10 s. // end::unreleased[] [#trystero-changelog-0-1-0] diff --git a/doc/design.adoc b/doc/design.adoc index 72d3c16..eff603b 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -36,23 +36,21 @@ | webcpp::webrtc's peer connections and data channels, and trystero's policies over them, on both targets -| Browser backend -| `browser/*.hpp` -| the page's WebSocket and Web Crypto through webcpp::asio's bridge and - `async_await`, webcpp::asio's timers, and `page_call` - -| Native backend -| `native/*.hpp` -| webcpp::beast (natively Boost.Beast), Boost.URL, 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 `getentropy` 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 WebRTC and libdatachannel's, both through webcpp::webrtc, and over the memory relays of the tests -(<>). The core never includes a 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 +(<>). 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. @@ -115,34 +113,45 @@ deliver their events to. 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 webcpp::webrtc -Both backends' 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 +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 -fixtures wrap the native backend's connections. +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 -Both backends make their peer connections and data channels the same way, 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 +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 @@ -180,12 +189,15 @@ in them, over webcpp::webrtc: 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 native backend makes at most +* The caps. The backend makes at most `backend_config::max_peer_connections_per_minute` connections in any - minute, its own policy against floods (<>); and the - `runtime` of webcpp::webrtc caps the connections alive at once, natively - the backend's own (<>), in the browser over the - page's census (<>). + 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 @@ -210,15 +222,17 @@ The asynchronous operations are the exception, for the reason [#trystero-design-dependencies] === Dependencies -trystero builds on webcpp::asio, and its backends on webcpp::webrtc. -`/webcpp/trystero//trystero` brings `/webcpp/asio//asio`, and on emscripten -`/webcpp/webrtc//webrtc`, the browser's WebRTC; `/webcpp/trystero//native` -brings `/webcpp/webrtc//webrtc` natively, with its libdatachannel, under the -MPL 2.0, and OpenSSL, under the Apache License 2.0, and for the relays -`/webcpp/beast//tls`, `/webcpp//boost_url` and `/webcpp/asio//tls`, whose -embedded authorities a program may trust in place of the system's. Neither -libdatachannel nor OpenSSL is in a browser program, 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/guarantees.adoc b/doc/guarantees.adoc index 97f396e..5424959 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, @@ -66,11 +66,13 @@ 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 by +`platform_page_websocket_bound`, where the page's `WebSocket` holds what is +unsent, and `platform_page_websocket_late_events`, where the session's queue +does, with exceptions and without them, which also check that the socket +never holds more than 4 MiB; 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/overview.adoc b/doc/overview.adoc index 0dd09fa..c667f90 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -37,57 +37,61 @@ The library provides: 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, whose WebRTC - is webcpp::webrtc's on both. +* 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` and `crypto.subtle`, through webcpp::asio's bridge, - webcpp::asio's timers, and webcpp::webrtc over the page's - `RTCPeerConnection` and `RTCDataChannel` (<>) +| `` +| 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 `getentropy` (<>) -| `` -| native -| webcpp::webrtc over libdatachannel for WebRTC, webcpp::beast for the - relays' WebSockets, natively Boost.Beast's, their URLs read with Boost.URL, - 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, Circular Buffer, Container (its `pmr` base class), Core, - Endian, Hash2, JSON, System and Unordered; and Beast and URL for the native - backend. -* webcpp::asio, webcpp::webrtc for both backends' WebRTC, and webcpp::beast - for the native backend's relays (<>). +* Boost 1.92: Asio, Assert, Circular Buffer, Container (its `pmr` base + class), Endian, Hash2, JSON, System and Unordered for the rooms; URL for the + platform backend's relays, and Beast for them natively. +* 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. * 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, and a program whose `main` runs its `io_context` - (<>). + (<>). * Natively: 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. Every part of it, both backends included, -compiles and works without exceptions (<>). +completes with an error code. Every part of it, the platform backend +included, compiles and works without exceptions +(<>). diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 51862ef..3f9bd18 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -193,16 +193,16 @@ what each costs a room. place to a new peer, and a new peer beyond the bound is refused and logged once. * 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 94cf516..0512b65 100644 --- a/doc/quick-start.adoc +++ b/doc/quick-start.adoc @@ -18,8 +18,8 @@ both. <> builds and runs them. === In the browser A browser program keeps four things alive for as long as its page: an -`io_context`, the `browser::backend` that implements the platform over the -browser's APIs on the executor of that `io_context`, the app that owns its +`io_context`, the `platform::backend` that implements the platform over the +page's own objects on the executor of that `io_context`, 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: @@ -53,14 +53,14 @@ program does, under a work guard, since a page that waits for its peers may have no work of its own. Nothing blocks the browser: whenever nothing is ready, `run` suspends into the browser's event loop, and every JavaScript event that reaches the library is posted to the `io_context`, whose handlers -run when `run` resumes (<>). +run when `run` resumes (<>). [#trystero-quick-start-native] === Natively 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` as the browser's does, and webcpp::webrtc posts what +and prints what it receives on `chat`, over the same `platform::backend`. A native program runs +its `io_context` as the browser's does, and webcpp::webrtc posts what libdatachannel's threads report to it: [source] diff --git a/doc/testing.adoc b/doc/testing.adoc index c18ba75..6028c99 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -37,11 +37,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 @@ -50,8 +51,8 @@ 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, each in both of webcpp::asio's -suspension variants, JSPI and Asyncify. The protocol, the rooms and the -allocation test run on both: +suspension variants, JSPI and Asyncify. The protocol, the rooms, the timer +and the allocation test run on both: [listing] ---- @@ -64,10 +65,11 @@ include::{library-root}/test/Jamfile[tag=allocation] | Test | What it checks | the public headers -| Each compiled alone, on each target that builds it: the core on both, the - native backend and the backend's WebRTC natively, against webcpp::webrtc's - libdatachannel and OpenSSL, and the browser backend, with the backend's - WebRTC it includes, 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` @@ -116,58 +118,81 @@ include::{library-root}/test/Jamfile[tag=allocation] (<>). | `timer` -| The timer over webcpp::asio's `steady_timer`, which the browser backend - makes: a wait fires once, in the timer's resource, and one cancelled, - restarted or destroyed never fires, even when its expiry was already - queued. - -| `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, reaches a relay at an - IPv6 address, reads URLs as a page does, 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, keeps a TLS context's error - in the backend, 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`, and each `_no_exceptions` -| Two connections of the backend's WebRTC, over webcpp::webrtc's +| 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`, + 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, 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, and completes after the call that started it, never + inside it; 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, or of a port on 127.0.0.1 or + `::1` where nothing listens, reports exactly one close, after the call + that made it. + +| `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, reads URLs as a page + does, 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, keeps a TLS context's error in the backend, 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_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 native rooms over 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 connection's resource; a peer of + 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 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; 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. -| `browser_websocket`, `browser_websocket_bound`, `browser_websocket_late_events`, `browser_sealer`, `browser_data_channel`, `browser_peer_connection`, `browser_page` -| The browser backend, on emscripten under node, which has the page's - WebSocket and Web Crypto but no WebRTC, each test's `main` running its - `io_context` as a page's program does: the WebSocket's URLs, its bound on - what a relay holds unsent and its silence once dropped, the sealer's - completions, and, 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, and - webcpp::webrtc's census of them; and the shape of a page's program, whose - work guard keeps a page with no room yet running, and whose - `browser::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. +| `platform_page_websocket_bound`, `platform_page_websocket_late_events`, + `platform_page_data_channel`, `platform_page_peer_connection`, + `platform_page`, 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; 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. |=== -The native backend's tests run once more without exceptions -(<>), 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: [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] ---- @@ -202,7 +227,7 @@ 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 +`protocol` and `platform_sealer` tests reproduce; `update-expected` is its only writer. [listing] @@ -294,15 +319,15 @@ 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, 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. +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 diff --git a/doc/usage.adoc b/doc/usage.adoc index ffe0753..f68d283 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -205,7 +205,7 @@ messages travel and how they are received: 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 From 431b25336abf7c52a9dd0cc16a002f38a65c215a Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:09:11 -0300 Subject: [PATCH 022/116] trystero: no move of a pmr circular buffer's holder; random_id's bias said construction_window, recent_challenges and replay_cache hold a boost::circular_buffer over a std::pmr allocator, which moves by swapping its allocator, which std::pmr's cannot: they reported themselves move-constructible and failed to compile when moved. Their moves are deleted. random_id's tip said an id is as unpredictable as its bytes. A character carries about 5.95 bits, and byte % 62 favours the first eight characters, where Trystero draws each alike. --- include/webcpp/trystero/detail/construction_window.hpp | 6 ++++++ include/webcpp/trystero/detail/rebinding.hpp | 6 ++++++ include/webcpp/trystero/detail/replay_cache.hpp | 6 ++++++ include/webcpp/trystero/protocol/topics.hpp | 3 ++- 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/include/webcpp/trystero/detail/construction_window.hpp b/include/webcpp/trystero/detail/construction_window.hpp index 52d6e30..9617172 100644 --- a/include/webcpp/trystero/detail/construction_window.hpp +++ b/include/webcpp/trystero/detail/construction_window.hpp @@ -34,6 +34,12 @@ class construction_window { std::pmr::memory_resource* memory) : 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) { diff --git a/include/webcpp/trystero/detail/rebinding.hpp b/include/webcpp/trystero/detail/rebinding.hpp index b776c33..48d265f 100644 --- a/include/webcpp/trystero/detail/rebinding.hpp +++ b/include/webcpp/trystero/detail/rebinding.hpp @@ -53,6 +53,12 @@ class recent_challenges { /** Keeps the bounded challenge history in the room resource. */ explicit recent_challenges(std::pmr::polymorphic_allocator<> a) : values_(capacity, a) {} + /** 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)); } diff --git a/include/webcpp/trystero/detail/replay_cache.hpp b/include/webcpp/trystero/detail/replay_cache.hpp index dddf471..3053d69 100644 --- a/include/webcpp/trystero/detail/replay_cache.hpp +++ b/include/webcpp/trystero/detail/replay_cache.hpp @@ -39,6 +39,12 @@ class replay_cache { replay_cache(std::size_t capacity, std::pmr::memory_resource* memory) : 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 { return std::ranges::find(digests_, protocol::sha256(opened)) != digests_.end(); diff --git a/include/webcpp/trystero/protocol/topics.hpp b/include/webcpp/trystero/protocol/topics.hpp index 2f1da06..c2ad80d 100644 --- a/include/webcpp/trystero/protocol/topics.hpp +++ b/include/webcpp/trystero/protocol/topics.hpp @@ -44,7 +44,8 @@ inline constexpr std::size_t nonce_size = 8; * `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: the id is as unpredictable as its bytes, not uniform. + * 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. From 81dc4a9e57864de6d14ccbd0d653adb2559bc152 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:09:11 -0300 Subject: [PATCH 023/116] trystero: remember only NIP-01 event ids, and test the dedup's key A relay could send 4096 events with distinct ids of nearly 1 MiB each, about 4 GiB kept in the room's resource. recent_event_ids now remembers only an id of 64 lowercase hexadecimal digits, NIP-01's; an event with any other id is acted on every time, as Trystero 0.26.0, which has no dedup, acts on every event, and its id is never stored. The id is read in protocol/nostr.hpp's relay-message parsing, which is left as it is. The collision search, about 8.4 million hashes, passed even with a hash that ignored its key. It is replaced by two cases: the keyed hash gives an id another value under another key, and a strategy draws its 16-byte key from the backend's randomness, which the memory backend now counts. A third case checks that the holders of a pmr circular buffer do not move. Each failed first: the first against the dedup as it was, the second and third against a hash and a strategy made to ignore the key, the last against the moves before they were deleted. The reconnection share reads its two random bytes with Boost.Endian. The appendix "Differences" records the dedup and random_id's bias. --- doc/differences.adoc | 4 + .../webcpp/trystero/detail/nostr_strategy.hpp | 26 ++- test/room_test.cpp | 150 +++++++++++------- test/support/memory_backend.hpp | 3 + 4 files changed, 116 insertions(+), 67 deletions(-) diff --git a/doc/differences.adoc b/doc/differences.adoc index e6e8ac0..e81a4f6 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -106,6 +106,10 @@ These features of Trystero are not ported, each for its reason: | 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 NIP-01's, 64 lowercase hexadecimal digits; 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 of another form would let a relay fill the room's resource with the ids kept + +| 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) + |=== *`on_peer_join` does not replay the joined peers.* Trystero calls a newly diff --git a/include/webcpp/trystero/detail/nostr_strategy.hpp b/include/webcpp/trystero/detail/nostr_strategy.hpp index 1ac3fb4..83f3843 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -45,6 +46,10 @@ 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. * + * Only an id NIP-01 defines, 64 lowercase hexadecimal digits, is remembered: an event with any + * other id is acted on every time, as Trystero, which remembers none, acts on every event, 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. @@ -54,6 +59,9 @@ class recent_event_ids { /** 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: @@ -87,9 +95,9 @@ class recent_event_ids { capacity_(capacity) {} /** Whether `id` is new; a new one is remembered in place of the oldest beyond `capacity`, and - * an empty one is always new and never remembered. */ + * one that is not NIP-01's is always new and never remembered. */ bool remember(std::string_view id) { - if (id.empty()) { + if (!is_nip01_id(id)) { return true; } if (index_.contains(id)) { @@ -108,11 +116,14 @@ class recent_event_ids { /** How many ids are remembered. */ [[nodiscard]] std::size_t size() const { return order_.size(); } - /** The index, for its statistics, which Boost.Unordered keeps with - * `BOOST_UNORDERED_ENABLE_STATS`. */ - [[nodiscard]] const index_type& index() const noexcept { return index_; } - private: + /** Whether `id` is an event id as NIP-01 writes it: 64 lowercase hexadecimal digits. */ + static bool is_nip01_id(std::string_view id) { + return id.size() == id_size && std::ranges::all_of(id, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }); + } + index_type index_; std::pmr::deque order_; std::size_t capacity_; @@ -373,7 +384,8 @@ class nostr_strategy : public std::enable_shared_from_this { factory_.random(random); // A share of the bound in [0, 1), in steps of 1/65536, and the delay in whole // milliseconds below it. - const double share = ((std::uint32_t{random[0]} << 8U) | random[1]) / 65536.0; + 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_); diff --git a/test/room_test.cpp b/test/room_test.cpp index 0bb64c5..8ba209f 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -8,10 +8,6 @@ // support/memory_backend.hpp. WEBCPP_TEST_TRYSTERO_VERBOSE in the environment prints each room's // log on the standard error. -// Boost.Unordered counts the probes and the comparisons of its open-addressing containers, which -// the case of colliding event ids reads; before any of its headers. -#define BOOST_UNORDERED_ENABLE_STATS - #include #include @@ -39,7 +35,7 @@ #include #include #include -#include +#include #include #include @@ -694,6 +690,12 @@ 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() { @@ -701,68 +703,93 @@ void recent_event_ids_drop_a_repeat_and_forget_the_oldest() { { const std::array key{}; trystero::detail::recent_event_ids ids(3, key, &memory); - 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")); + 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")); - // An event without an id is never taken for a repeat. - BOOST_TEST(ids.remember("")); - BOOST_TEST(ids.remember("")); + 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); } -// Ids a relay chooses so that the standard library's unseeded hash puts them all in one bucket of a -// std::unordered_set sized for the ids remembered, the strategy's index before, where each lookup -// walks every one of them, cost the index a probe and a comparison each: it hashes them with -// SipHash under a key of its own. The ids are found by search, as an attacker finds them. -void colliding_event_ids_stay_fast() { - constexpr std::size_t count = 2048; - constexpr std::size_t capacity = trystero::detail::nostr_strategy::remembered_events; - std::unordered_set reference; - reference.reserve(capacity); - std::vector colliding; - colliding.reserve(count); - std::string candidate(64, '0'); // the length of a Nostr event id, in hexadecimal - const auto target = reference.bucket(candidate); - for (std::uint64_t n = 0; colliding.size() < count; ++n) { - for (std::size_t i = 0; i < 16; ++i) { - candidate[candidate.size() - 1 - i] = "0123456789abcdef"[(n >> (4 * i)) & 15U]; - } - if (reference.bucket(candidate) == target) { - colliding.push_back(candidate); - } +// 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. +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); + 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)); } - reference.insert(colliding.begin(), colliding.end()); - BOOST_TEST_GE(reference.bucket_count(), capacity); - BOOST_TEST_EQ(reference.bucket_size(target), count); - - std::array key{}; - key.fill(0x5a); - trystero::detail::recent_event_ids ids(capacity, key, std::pmr::get_default_resource()); - const auto fresh = - std::ranges::count_if(colliding, [&](const auto& id) { return ids.remember(id); }); - const auto repeated = - std::ranges::count_if(colliding, [&](const auto& id) { return !ids.remember(id); }); - BOOST_TEST_EQ(static_cast(fresh), count); - BOOST_TEST_EQ(static_cast(repeated), count); - const auto stats = ids.index().get_stats(); - // Measured: 1.08, 1.04, 0.03, 1 and 1.01; a chain of `count` ids would cost about half of them, - // a thousand comparisons, at each lookup. - BOOST_TEST_LE(stats.insertion.probe_length.average, 1.5); - BOOST_TEST_LE(stats.unsuccessful_lookup.probe_length.average, 1.5); - BOOST_TEST_LE(stats.unsuccessful_lookup.num_comparisons.average, 0.5); - BOOST_TEST_LE(stats.successful_lookup.probe_length.average, 1.5); - BOOST_TEST_LE(stats.successful_lookup.num_comparisons.average, 1.5); + BOOST_TEST_EQ(ids.size(), 0U); + BOOST_TEST_EQ(memory.in_use, 0U); +} + +// 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, beside its +// signer's secret: a relay cannot know it. +void a_strategy_draws_the_key_of_its_event_ids() { + fixture f; + const auto before = f.net.random_bytes; + const auto strategy = std::make_shared( + f.net, std::span(), std::pmr::vector(), "topic", + trystero::handler(), + trystero::detail::nostr_strategy::message_handler(), trystero::detail::logger(), + std::pmr::get_default_resource(), boost::json::storage_ptr()); + BOOST_TEST_EQ(f.net.random_bytes - before, + 32U + trystero::detail::recent_event_ids::key_size); // the secret, the key +} + +// 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 @@ -1487,7 +1514,10 @@ int main() { announcements_with_forged_answers_are_bounded(); the_replay_cache_remembers_the_last_ones(); recent_event_ids_drop_a_repeat_and_forget_the_oldest(); - colliding_event_ids_stay_fast(); + event_ids_other_than_nip01_ones_are_never_remembered(); + the_event_id_hash_is_keyed(); + a_strategy_draws_the_key_of_its_event_ids(); + classes_over_a_pmr_circular_buffer_do_not_move(); a_replayed_answer_is_refused(); a_replayed_offer_is_refused(); a_reflected_offer_is_refused_as_an_answer(); diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index 4d17038..f1fc799 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -729,6 +729,7 @@ 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_()); } @@ -761,6 +762,8 @@ 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 many random bytes were drawn. */ + std::size_t random_bytes = 0; /** How much faster than real time the timers and the clock run, for tests of long timeouts. */ std::uint32_t time_scale = 1; /** How many of the next peer connections to refuse, as a browser at its limit does. */ From b416047bd896ffb795b3b2d51bbc7543ef5dc58f Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:09:38 -0300 Subject: [PATCH 024/116] trystero: a relay is verified whatever the verify mode of the program's context Asio makes a client's context with verify_none, and the session's host name verification callback does not change the mode, so a program's context that names its authorities with load_verify_file or add_certificate_authority but sets no verify mode accepted any certificate for any name. Natively the session now sets verify_peer on each stream before the TLS handshake, with the error_code overload, and reports a close if it fails, as a page's WebSocket always verifies. The program's context is left as it is. --- doc/platform.adoc | 11 ++++-- .../webcpp/trystero/platform/websocket.hpp | 19 ++++++++-- test/platform_websocket_test.cpp | 38 +++++++++++++++++++ 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/doc/platform.adoc b/doc/platform.adoc index fc51268..59bf65d 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -137,9 +137,14 @@ reports a close, as an unreachable one does, and the room retries it later as it would any other. Over TLS, natively, the connection names the relay's host to the server -(SNI) when it is a name, never when it is an address, and checks the relay's -certificate against the URL's host, a name or an address; in a page the -browser does both, against its own authorities. By default the backend makes +(SNI) when it is a name, never when it is an address, verifies the relay's +certificate whatever the verify mode of the context, 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. 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 against the authorities it +trusts, as a page's `WebSocket` always verifies; the context itself is left +as it is. 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 diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index a5e6008..335be0e 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -415,6 +415,15 @@ class websocket_session : public std::enable_shared_from_this Date: Sat, 14 Nov 2026 20:12:54 -0300 Subject: [PATCH 025/116] trystero: a TLS context's error is the one OpenSSL queued last detail::openssl_error() read the queue with ERR_get_error, the earliest error, which may be one an earlier call left behind, and left the rest queued. It now reads ERR_peek_last_error and empties the queue, and make_tls_context empties it before its first call. --- include/webcpp/trystero/platform/websocket.hpp | 9 +++++++-- test/platform_websocket_test.cpp | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 335be0e..354ce99 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -81,11 +81,14 @@ struct websocket_limits { namespace detail { -/** The error OpenSSL queued last, or `not_enough_memory` when it queued none. */ +/** 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 (const auto code = ERR_get_error(); code != 0) { + if (code != 0) { return {static_cast(code), webcpp::asio::error::get_ssl_category()}; } #endif @@ -112,6 +115,8 @@ inline boost::system::error_code openssl_error() { */ 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) { diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp index 91a2b14..2977466 100644 --- a/test/platform_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -14,6 +14,7 @@ #include +#include #include #include #include @@ -472,6 +473,19 @@ void the_tls_context_verifies_peers_from_tls_1_2() { 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() { @@ -889,6 +903,7 @@ int main() { urls_name_ipv6_hosts_and_refuse_what_a_page_refuses(); 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_of_an_authority_not_trusted_closes_without_opening(); From 439ea28c192edbf9881a88d51ce092bbcacc5a08 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:14:04 -0300 Subject: [PATCH 026/116] trystero: oracle cases for JSON quoting and keys written twice The oracle now has Trystero JS 0.26.0 compute three more parts of the wire, so that moving the protocol's JSON onto webcpp::document keeps it byte for byte. Event messages come from Trystero's own createEvent, its Nostr key drawn from fixed bytes when the module loads and its clock and auxiliary bytes fixed too, with topics and contents that hold the controls U+0000 to U+001F, the quote, the backslash, U+2028, U+2029, DEL and astral characters. Signal texts are JSON.stringify's of the same strings, in the member orders Trystero writes. Keys written twice are read by Trystero's own code: signals by its signal handler, run in a room of the oracle's that records what it looks up and opens, and relay events by its Nostr strategy, joined through a WebSocket of the oracle's, whose room reports the sender of an answer it fails to open exactly when it acted on the event. --- test/fixtures/cases/protocol.json | 72 +++++++++- test/fixtures/expected/expected.json | 188 +++++++++++++++++++++++++++ test/oracle/oracle.mjs | 179 ++++++++++++++++++++++++- 3 files changed, 435 insertions(+), 4 deletions(-) diff --git a/test/fixtures/cases/protocol.json b/test/fixtures/cases/protocol.json index b1b6421..53d495b 100644 --- a/test/fixtures/cases/protocol.json +++ b/test/fixtures/cases/protocol.json @@ -36,5 +36,75 @@ "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"} + ], + "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\"}" + ], + "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] + ] + ] + } + } } diff --git a/test/fixtures/expected/expected.json b/test/fixtures/expected/expected.json index 7de4191..014ed80 100644 --- a/test/fixtures/expected/expected.json +++ b/test/fixtures/expected/expected.json @@ -372,5 +372,193 @@ "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\"}" + } + ], + "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 + } + } + ], + "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 + } + ] } } diff --git a/test/oracle/oracle.mjs b/test/oracle/oracle.mjs index 751d1e4..c88f46d 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 ') @@ -27,6 +27,19 @@ const {sha1, hashWith, deriveRoomNamespace, encrypt, genKey} = await import(join const {strToNum, getRelays, toHex, toJson, topicPath, shuffle} = 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')) + +// 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 +84,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 +187,167 @@ 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), and an answer to an offer +// without an id {peerId, answer} (handleOffer); 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 +} + mkdirSync(outputDirectory, {recursive: true}) const target = join(outputDirectory, 'expected.json') writeFileSync(target, JSON.stringify(out, null, 4) + '\n') From 74a965b344210a94381375dcdec4878ba46ea849 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:15:05 -0300 Subject: [PATCH 027/116] trystero: a relay's host is an address or a name once decoded parse_url took Boost.URL's host type, decided before percent-decoding, so wss://%31%32%37.0.0.1/ was a name and the session sent 127.0.0.1 to the server as its name (SNI). A decoded host that parses as an IPv4 address is now an address, as a page reads it: no SNI, named false. A decoded name holds no ':', which is refused, so it is never an IPv6 address. --- .../webcpp/trystero/platform/websocket.hpp | 7 +++- test/platform_websocket_test.cpp | 40 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 354ce99..9317c57 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -208,7 +209,7 @@ inline std::optional parse_url( } url_parts out{ .secure = secure, - .named = view.host_type() == boost::urls::host_type::name, + .named = false, .host = std::pmr::string(memory), .port = std::pmr::string(memory), .handshake_host = std::pmr::string(memory), @@ -226,6 +227,10 @@ inline std::optional parse_url( 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(); out.handshake_host = out.host; break; } diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp index 2977466..05c926e 100644 --- a/test/platform_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -357,6 +357,24 @@ void urls_name_a_scheme_host_port_and_path() { 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() { @@ -532,6 +550,26 @@ void a_relay_whose_certificate_names_another_host_closes_without_opening() { 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() { @@ -900,12 +938,14 @@ void a_quiet_relay_that_answers_pings_stays_connected() { 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(); 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(); From 952b3e9dd8c4c954f74e74f27bdc7dd154b5432b Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:20:36 -0300 Subject: [PATCH 028/116] trystero: the IPv6 relay case does not apply where no IPv6 socket opens a_relay_at_an_ipv6_address_opens connects through a socket of IPv6's family to an IPv4-mapped address, which a kernel without IPv6 cannot open (EAFNOSUPPORT), so the case failed there. It now opens such a socket first and, when it cannot, prints that the case is not applicable and returns. A kernel with IPv6 disabled by sysctl, as a container has it, opens the socket and reaches the mapped address (measured in a Linux container, where binding ::1 fails), so the probe binds nothing and the case still runs there. --- test/platform_websocket_test.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp index 05c926e..c6fadbc 100644 --- a/test/platform_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -437,8 +438,17 @@ void urls_name_ipv6_hosts_and_refuse_what_a_page_refuses() { // 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; From 44b5f1038f611b7cc195ccdef34cab3cb3819bb1 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:24:33 -0300 Subject: [PATCH 029/116] trystero: the relay session's reads and writes complete through an erased handler On Emscripten the lint analyses native/websocket.hpp, which test/Jamfile now compiles there, against webcpp::asio's and webcpp::beast's own headers, and misc-no-recursion reported in them the cycle of the read loop and of the writes through Asio's post, where no NOLINT of trystero reaches. Each read's and write's handler is now given to Beast as an any_completion_handler, whose call goes through a pointer, allocated with the room's allocator, so the analysis sees no cycle on either target and the exemptions go. The handshake's timeouts, changed natively only, say so to misc-const-correctness. --- include/webcpp/trystero/native/websocket.hpp | 57 ++++++++++++-------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/include/webcpp/trystero/native/websocket.hpp b/include/webcpp/trystero/native/websocket.hpp index 4eb1aed..98af618 100644 --- a/include/webcpp/trystero/native/websocket.hpp +++ b/include/webcpp/trystero/native/websocket.hpp @@ -14,15 +14,16 @@ #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 +#include // lint-world: erases a handler's type only +#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 @@ -441,6 +442,7 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()]( // NOLINT(misc-no-recursion) - const boost::system::error_code& ec, std::size_t size) { + /** + * A read's or a write's completion, its type erased. + * + * 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. Its type is erased, the call made 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. It is allocated with the handler's allocator, in the room's resource. + */ + using transfer_handler = + webcpp::asio::any_completion_handler; + + void read() { + auto handler = [self = this->shared_from_this()](const boost::system::error_code& ec, + std::size_t size) { self->on_read(ec, size); }; - ws_.async_read(buffer_, bound(std::move(handler))); + ws_.async_read(buffer_, transfer_handler(bound(std::move(handler)))); } - // NOLINTNEXTLINE(misc-no-recursion) void on_read(const boost::system::error_code& ec, std::size_t size) { if (ec) { end(); @@ -508,9 +518,9 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()]( // NOLINT(misc-no-recursion) - const boost::system::error_code& ec, std::size_t) { + auto handler = [self = this->shared_from_this()](const boost::system::error_code& ec, + std::size_t) { if (ec) { self->writing_ = false; return; } self->write_next(); }; - ws_.async_write(webcpp::asio::buffer(writing_text_), bound(std::move(handler))); + ws_.async_write(webcpp::asio::buffer(writing_text_), + transfer_handler(bound(std::move(handler)))); } void end() { From c60223302e1c01e91e4470b6194f4dbc2de3e69f Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:26:59 -0300 Subject: [PATCH 030/116] trystero: say exactly what a native relay connection allocates outside the room The session's Doc Comment and the guide said that what Asio and Beast allocate for a relay connection is in the room's resource, but natively Beast, Asio and OpenSSL allocate of their own, with no allocator, for each connection: the streams' state, the WebSocket's write buffer and Asio's TLS buffers, the resolver's state and results, the handshake's request and response, the verify callback Asio's set_verify_callback makes with new and its copy of the host, Beast's timer waits and each keep-alive ping's frame. A relay that answers the handshake with a status other than 101 can have Beast read a body of up to 8 MiB, its default limit for a response (measured: about 18 MiB at its peak). Boost.Beast 1.92 gives no public way to lower that limit: the parser is a member of websocket::stream's handshake operation, made with the default limits, the response_type& overload only receives the response after it is read, the decorator option decorates the request alone, and the stream takes no other option that reaches the parser. None of these allocations takes an allocator, so none can move into the room's resource. The Doc Comments of the session and of connect_websocket, the relays' section and the list of what stays outside the resource now say so, from a measurement that recorded a stack for each operator new of a connection: none for a message. --- doc/allocation.adoc | 28 +++++++++++++++---- doc/platform.adoc | 16 ++++++++++- .../webcpp/trystero/platform/websocket.hpp | 28 +++++++++++++++---- 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 6369fa2..31328ea 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -242,11 +242,29 @@ nothing. 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, Boost.Beast's state inside a relay's WebSocket, its stream's, - and the resolver's results; 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 in a page the - stream's own state is there too; +* 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, the header fields of both and, for a + response that is not 101, its body, which Beast's own parser reads up to + Beast's default limit for a response, 8 MiB, that no option of its stream + lowers (measured: an 8 MiB body held about 18 MiB at its peak, as its + string grew); 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; 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 a message allocates nothing + outside it (measured with a stack for each `operator new` on the room's + thread: a hundred texts sent and received made none but the write + buffer's, at the first); in a page the stream's own state is there too, + and the page's `WebSocket` makes the handshake; * the payload types `std::string`, `bytes` and `payload`, with `std::allocator`, the user's choice; * on Emscripten, the C library's `select()`, which Asio's reactor calls on diff --git a/doc/platform.adoc b/doc/platform.adoc index 59bf65d..182077c 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -120,7 +120,12 @@ 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 -(<>); in a page the stream's own state is there too. A +(<>), and a message allocates nothing outside it; in a +page the stream's own state is there too. Natively what Beast, Asio and +OpenSSL allocate of their own, which takes no allocator, stays outside it, +for each connection: 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 (<>). A write that fails ends the connection, which reports its close at once. The WebSockets are Beast's rather than libdatachannel's own, so the relays run on the room's executor like everything else. @@ -180,6 +185,15 @@ hold: * 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 + can have Boost.Beast read a body of up to 8 MiB, its default limit for a + response, outside the room's resource, before the connection reports its + close (measured: an 8 MiB body held about 18 MiB at its peak, as the + string that holds it grew); it is freed then, and the room retries with + its backoff. Beast's WebSocket stream reads the response with a parser of + its own, inside its handshake, and none of its options, nor its handshake + that returns the response, reaches that parser's limit, so the backend + cannot lower it. 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 diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 9317c57..dc39027 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -271,9 +271,18 @@ inline std::optional parse_url( * * 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; natively Boost.Beast's stream state, the resolver's results and - * OpenSSL's state are theirs. On Emscripten the page's stream keeps its state in the room's - * resource too. + * handlers and its queued texts, with nothing in the default allocator for a message. On + * Emscripten the page's stream keeps its state in the room's resource too, and its `WebSocket` + * makes the handshake. 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, + * the header fields of both and, for a response that is not 101, its body, which Beast's own + * parser reads up to Beast's default limit for a response, 8 MiB, that no option of its stream + * lowers; 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); and each keep-alive ping's frame. */ template class websocket_session : public std::enable_shared_from_this> { @@ -648,18 +657,25 @@ class websocket_handle : public backend::websocket { * `tls`, and checks it against the URL's host, a name or an address; in a page the browser does * all three. It needs no exceptions. * + * The connection, its handlers, its queued texts, its read buffer and its operations are in + * `memory`, and a message allocates nothing in the default allocator. Natively what Boost.Beast, + * Asio and OpenSSL allocate of their own stays outside it, for each connection: 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. Among it, a relay that answers the handshake with a + * status other than 101 can have Beast read a body of up to 8 MiB, Beast's default limit for a + * response, which no option of its stream lowers, before the connection reports its close. + * * @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; natively the connection verifies the relay against its authorities even when * its verify mode is `verify_none`, as Asio makes a client's context. * @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, its queued texts, its read - * buffer and its operations are allocated in; natively Boost.Beast's stream state and OpenSSL's - * are theirs. + * @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, From 2935cfc3e48aa2c354ea1c81f71ac0c4589ba62f Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:38:00 -0300 Subject: [PATCH 031/116] trystero: a relay URL a page reads otherwise is refused, and the guide says what is read The guide said a relay's URL is read as a page's WebSocket reads it, but parse_url took what a page reads otherwise as a name: ws://127.1/, which a page reads as 127.0.0.1, reached that address through the system's resolver under the name 127.1, and an escaped international name went to the resolver as its UTF-8 bytes. It now fails closed on both: a decoded host with a byte beyond ASCII is refused, and so is a name whose last label is a number (a page's ends-in-a-number check) unless it is a dotted quad, which covers IPv4 shorthands, octal and hexadecimal parts, a final dot and a single number. Tabs, newlines and backslashes were already refused. The relays' section now says exactly what is accepted and refused, and what fails closed. It also says that on Windows OpenSSL's default verify paths are in its build-time directory under the common program files, which nothing fills, and that OpenSSL reads no Windows store by default, so the system's authorities are none there unless SSL_CERT_FILE or SSL_CERT_DIR names some, and a Windows program gives its own context; make_tls_context's Doc Comment says it too. --- doc/platform.adoc | 74 +++++++++++++------ .../webcpp/trystero/platform/websocket.hpp | 63 ++++++++++++---- test/platform_websocket_test.cpp | 59 +++++++++++++++ 3 files changed, 158 insertions(+), 38 deletions(-) diff --git a/doc/platform.adoc b/doc/platform.adoc index 182077c..20056d4 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -118,28 +118,44 @@ 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 +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 (<>), and a message allocates nothing outside it; in a page the stream's own state is there too. Natively what Beast, Asio and OpenSSL allocate of their own, which takes no allocator, stays outside it, for each connection: 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 (<>). A -write that fails ends the connection, which reports its close at once. 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, as a page's -`WebSocket` reads it: the scheme in any case, a host name in lower case and -with its escapes decoded, an IPv6 address in brackets +keep-alive ping's frame (<>). A write that +fails ends the connection, which reports its close at once. 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 the scheme's port when the URL names none. A URL of +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://`, without a host, with a -user name or a fragment, or with a port beyond 65535, is refused; the relay -reports a close, as an unreachable one does, and the room retries it later -as it would any other. +`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; and a tab, +a newline or a backslash anywhere in the URL, which a page drops or reads as +a slash. 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, 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 @@ -149,16 +165,26 @@ 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`, still has every relay verified against the authorities it trusts, as a page's `WebSocket` always verifies; the context itself is left -as it is. 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. +as it is. 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)`: +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] ---- diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index dc39027..a45a8dc 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -31,6 +31,8 @@ #include #include #include +#include +#include #include #include #include @@ -104,11 +106,14 @@ inline boost::system::error_code openssl_error() { * 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. 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. + * 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. @@ -171,19 +176,41 @@ struct url_parts { // NOLINT(bugprone-exception-escape) std::pmr::string target; }; -/** Whether a decoded host name holds a byte that a page's URL parser refuses in a host. */ +/** + * 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; + 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, or with a port beyond 65535. + * 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()) { @@ -231,6 +258,12 @@ inline std::optional parse_url( // 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; } @@ -650,12 +683,14 @@ class websocket_handle : public backend::websocket { * page's before it is copied into WebAssembly. 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: an IPv6 address in brackets, a scheme in any - * case. A URL it cannot parse, one with userinfo or a fragment, and a `wss://` URL without `tls`, - * report a close, as an unreachable relay does. Natively a `wss://` connection names the host to - * the server (SNI) when it is a name, verifies the relay's certificate whatever the verify mode of - * `tls`, and checks it against the URL's host, a name or an address; in a page the browser does - * all three. It needs no exceptions. + * 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. Natively a `wss://` connection names + * the host to the server (SNI) when it is a name, verifies the relay's certificate whatever the + * verify mode of `tls`, and checks it against the URL's host, a name or an address; in a page the + * browser does all three. It needs no exceptions. * * The connection, its handlers, its queued texts, its read buffer and its operations are in * `memory`, and a message allocates nothing in the default allocator. Natively what Boost.Beast, diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp index c6fadbc..e8f0285 100644 --- a/test/platform_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -436,6 +436,47 @@ void urls_name_ipv6_hosts_and_refuse_what_a_page_refuses() { 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; and +// a tab, a newline or a backslash, which a page drops or reads as a slash. +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)", + }) { + 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); + } +} + // 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 @@ -778,6 +819,22 @@ void an_unreachable_relay_closes_without_opening() { 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, 1); +} + void a_dropped_socket_reports_nothing() { asio::io_context io; const echo_server server(io); @@ -950,6 +1007,7 @@ 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(); 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(); @@ -964,6 +1022,7 @@ int main() { 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_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); From 1965443ecdef5af13d0d374c69e0e6f7153b1921 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:44:14 -0300 Subject: [PATCH 032/116] trystero: the allocation test's arenas left uninitialized Under Asyncify the test ran past its bound of 120 s twice under load, and took 105 to 118 s at a load average of 90 to 150. Node's profiler put 96 s of a 118 s run in constructing and destroying the 64 MiB std::vector of its sixteen counting resources: one call per byte in a debug build, and under Asyncify, built with Emscripten's exceptions in JavaScript, each call inside a try crosses into JavaScript and back. The rooms' own work took the rest. Each arena is now std::make_unique_for_overwrite, which sets nothing; what the test counts and checks is unchanged. Measured back to back at a load average of 91 to 126, the same build before and after: Asyncify 104.6 s, then 0.8 s; JSPI 6.3 s, then 0.6 s; native 7.0 s, then 0.4 s. --- test/allocation_test.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 544b554..e6aaa11 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -380,8 +380,14 @@ 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). + std::unique_ptr storage_ = std::make_unique_for_overwrite(capacity); + std::pmr::monotonic_buffer_resource buffer_{storage_.get(), capacity, std::pmr::null_memory_resource()}; void* do_allocate(std::size_t bytes, std::size_t alignment) override { @@ -393,7 +399,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_.get() || at >= storage_.get() + capacity) { ++foreign; return; } From 47412f494e593e421dd9f60f51f43c24f1618a66 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:50:17 -0300 Subject: [PATCH 033/116] trystero: the allocation test's arenas are std::arrays the heap holds modernize-avoid-c-arrays refused std::unique_ptr. Each arena is now a std::array of 64 MiB made by std::make_unique_for_overwrite, which sets none of its bytes either: under Asyncify the test takes 0.7 s, JSPI 0.5 s and natively 0.4 s (load average 58). --- test/allocation_test.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index e6aaa11..0dd857e 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -386,8 +386,9 @@ class counting_resource final : public std::pmr::memory_resource { // 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). - std::unique_ptr storage_ = std::make_unique_for_overwrite(capacity); - std::pmr::monotonic_buffer_resource buffer_{storage_.get(), capacity, + 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 { @@ -399,7 +400,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_.get() || at >= storage_.get() + capacity) { + if (at < storage_->data() || at >= storage_->data() + storage_->size()) { ++foreign; return; } From f2ae0c400edf4acea1bf11a331dbb6cce0b7b064 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:52:05 -0300 Subject: [PATCH 034/116] trystero: a page's sealer awaits Web Crypto through the io_context's own executor Through the type-erased executor Asio posted each settlement in a function object and an operation of std::allocator, two C library allocations a seal or an open. platform_page_sealer_allocation counts operator new and the C library from the start of a seal or an open to its completion, and requires none; allocation.adoc and AGENTS.md say exactly what a page's sealer still allocates outside the room's resource, and no longer claim that the room's executor is an io_context's on both targets. --- AGENTS.md | 18 +- doc/allocation.adoc | 38 +- include/webcpp/trystero/platform/sealer.hpp | 104 +++-- test/Jamfile | 8 + test/platform_page_sealer_allocation_test.cpp | 399 ++++++++++++++++++ 5 files changed, 504 insertions(+), 63 deletions(-) create mode 100644 test/platform_page_sealer_allocation_test.cpp diff --git a/AGENTS.md b/AGENTS.md index 6a72123..c3a3c45 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -583,11 +583,14 @@ holds only what is specific to trystero. (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 @@ -646,8 +649,9 @@ holds only what is specific to trystero. 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, each pending Web Crypto promise's entry in - the bridge's map, in the io_context's allocator (the WebSocket and + 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. diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 31328ea..3fadf63 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -179,11 +179,15 @@ A move assignment carries the source's allocator with its target. `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 the wrapper stays Asio's. On both targets the room's executor is the -executor of an `io_context`. +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, @@ -234,10 +238,12 @@ nothing. * 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`; + 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, @@ -272,11 +278,17 @@ nothing. 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 entry of each pending Web Crypto promise in the map of - webcpp::asio's bridge, in the allocator of the `io_context`: 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. +* 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 an `io_context`'s: 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. diff --git a/include/webcpp/trystero/platform/sealer.hpp b/include/webcpp/trystero/platform/sealer.hpp index 4fc8d9b..82cd358 100644 --- a/include/webcpp/trystero/platform/sealer.hpp +++ b/include/webcpp/trystero/platform/sealer.hpp @@ -21,6 +21,7 @@ #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 @@ -182,10 +183,12 @@ inline std::optional aes_gcm(bool encrypt, const std::array + 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; } - webcpp::asio::browser::async_await( - ex_, - 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 { - if (ec) { - done(make_error_code(error::backend_failure), {}); - return; - } - const auto sealed = - protocol::format_sealed(iv, detail::from_js(cipher, memory), memory); - done({}, sealed); - })); + 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 { + if (ec) { + done(make_error_code(error::backend_failure), {}); + return; + } + const auto sealed = + protocol::format_sealed(iv, detail::from_js(cipher, memory), memory); + done({}, sealed); + })); } void decrypt(std::string_view sealed, done_handler done) { @@ -296,21 +317,19 @@ class sealer : public backend::sealer, public std::enable_shared_from_thisiv.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); - done({}, std::string_view(reinterpret_cast(b.data()), b.size())); - })); + 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); + done({}, std::string_view(reinterpret_cast(b.data()), b.size())); + })); } /** @@ -332,14 +351,13 @@ class sealer : public backend::sealer, public std::enable_shared_from_thiskey_imported(!ec, key); - } - })); + 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) { diff --git a/test/Jamfile b/test/Jamfile index 3b46517..a82167b 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -140,6 +140,11 @@ webcpp.run platform_page_peer_connection : platform_page_peer_connection_test.cp # 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) : emscripten ; # end::page[] # The same, built without exceptions, as a page's program may be: no @@ -156,6 +161,9 @@ webcpp.run platform_page_peer_connection_no_exceptions : platform_page_peer_conn : $(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) off : emscripten ; # end::no-exceptions[] # The combined Asio/Beast/Trystero provider has its own recurring native lane. diff --git a/test/platform_page_sealer_allocation_test.cpp b/test/platform_page_sealer_allocation_test.cpp new file mode 100644 index 0000000..965c123 --- /dev/null +++ b/test/platform_page_sealer_allocation_test.cpp @@ -0,0 +1,399 @@ +// 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 + +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) +unsigned char 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 allocation_test's does, so that the count sees the +// sealer's allocations. +extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, + timeval* timeout) { + if (nfds < 0 || nfds > FD_SETSIZE) { + errno = EINVAL; + return -1; + } + std::array fds{}; + int 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; + if (events != 0) { + fds[n++] = pollfd{fd, events, 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; + } + if (readfds != nullptr) { + FD_ZERO(readfds); + } + if (writefds != nullptr) { + FD_ZERO(writefds); + } + if (exceptfds != nullptr) { + FD_ZERO(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; + } + } + 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(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(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()); +} From 83666dd0f3e89599c28b8109f17e21a423474195 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:57:31 -0300 Subject: [PATCH 035/116] trystero: the tests read and write JSON with webcpp::document --- test/native_peer_connection_test.cpp | 26 +++++-- test/native_room_test.cpp | 22 ++++-- test/native_sealer_test.cpp | 35 ++++++--- test/oracle/interop/native_peer.cpp | 94 ++++++++++++++++++++---- test/oracle/interop/peer.cpp | 105 +++++++++++++++++++++------ test/room_test.cpp | 75 +++++++++---------- test/support/memory_backend.hpp | 87 ++++++++++++---------- test/support/rooms.hpp | 37 +++++++--- 8 files changed, 330 insertions(+), 151 deletions(-) diff --git a/test/native_peer_connection_test.cpp b/test/native_peer_connection_test.cpp index 5f7e86e..55b8c78 100644 --- a/test/native_peer_connection_test.cpp +++ b/test/native_peer_connection_test.cpp @@ -19,10 +19,14 @@ #include #include +#include +#include +#include +#include + #include #include #include -#include #include #include @@ -647,11 +651,15 @@ void a_url_libdatachannel_cannot_parse_is_left_out() { /** The JSON of a candidate of webcpp::webrtc, as a peer sends it. */ std::string json_of(const webcpp::webrtc::ice_candidate& c) { - return boost::json::serialize(boost::json::object{ - {"candidate", c.candidate}, - {"sdpMid", c.sdp_mid}, + 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(); } /** @@ -694,10 +702,12 @@ struct mixed_pair { } void add_to_remote(std::string_view json) { - const auto v = boost::json::parse(json).as_object(); - const std::string_view text = v.at("candidate").as_string(); - const std::string_view mid = v.at("sdpMid").as_string(); - remote->async_add_ice_candidate({.candidate = text, .sdp_mid = mid}, + 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) {}); } diff --git a/test/native_room_test.cpp b/test/native_room_test.cpp index c767afe..76c98a9 100644 --- a/test/native_room_test.cpp +++ b/test/native_room_test.cpp @@ -12,6 +12,9 @@ #include #include +#include +#include + #include #include @@ -104,13 +107,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 +130,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/native_sealer_test.cpp b/test/native_sealer_test.cpp index 0334070..6eb397a 100644 --- a/test/native_sealer_test.cpp +++ b/test/native_sealer_test.cpp @@ -11,9 +11,12 @@ #include #include +#include +#include +#include + #include #include -#include #include #include @@ -24,7 +27,6 @@ #include "require.hpp" -namespace json = boost::json; namespace tp = webcpp::trystero::protocol; namespace trystero = webcpp::trystero; @@ -32,11 +34,19 @@ using webcpp::test::require; namespace { -json::value load(const char* path) { +/** The fixture at `path`, which must parse: a failure ends the test. */ +webcpp::document::document load(const char* path) { const std::ifstream file(path); std::stringstream text; text << file.rdbuf(); - return json::parse(text.str()); + auto parsed = webcpp::document::parse(text.str()); + require(BOOST_TEST(parsed.has_value())); + return std::move(*parsed); +} + +/** The text a fixture's string holds; empty for any other value. */ +std::string_view text_of(const webcpp::document::const_value& v) { + return v.value_or(std::string_view()); } struct outcome { @@ -57,14 +67,13 @@ outcome run(boost::asio::io_context& io, Operation operation) { return *result; } -void opens_what_trystero_js_sealed(const json::object& sealed) { +void opens_what_trystero_js_sealed(const webcpp::document::const_value& 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); }); + const auto opened = run(io, [&](auto done) { sealer.open(text_of(sealed["text"]), done); }); BOOST_TEST(!opened.ec); - BOOST_TEST_EQ(opened.text, std::string_view(sealed.at("plaintext").as_string())); + BOOST_TEST_EQ(opened.text, text_of(sealed["plaintext"])); } void seals_in_trystero_form_and_opens_it_back() { @@ -87,14 +96,13 @@ void seals_in_trystero_form_and_opens_it_back() { BOOST_TEST_EQ(opened.text, plaintext); } -void another_key_is_a_wrong_password(const json::object& sealed) { +void another_key_is_a_wrong_password(const webcpp::document::const_value& 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); }); + const auto opened = run(io, [&](auto done) { intruder.open(text_of(sealed["text"]), 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); @@ -109,7 +117,10 @@ int main(int argc, char* argv[]) { return boost::report_errors(); } const auto loaded = load(argv[1]); - const auto& sealed = loaded.at("sealed").as_object(); + const webcpp::document::const_value sealed = loaded["sealed"]; + if (!BOOST_TEST(sealed.is_object())) { + return boost::report_errors(); + } opens_what_trystero_js_sealed(sealed); seals_in_trystero_form_and_opens_it_back(); another_key_is_a_wrong_password(sealed); diff --git a/test/oracle/interop/native_peer.cpp b/test/oracle/interop/native_peer.cpp index 8b05d2d..63ab9a5 100644 --- a/test/oracle/interop/native_peer.cpp +++ b/test/oracle/interop/native_peer.cpp @@ -30,25 +30,33 @@ #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. */ @@ -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 c0573d5..a3d21a1 100644 --- a/test/oracle/interop/peer.cpp +++ b/test/oracle/interop/peer.cpp @@ -29,16 +29,24 @@ #include #include +#include +#include +#include +#include + #include -#include -#include +#include #include #include +#include #include +#include #include #include +#include #include +#include #include using emscripten::val; @@ -62,7 +70,7 @@ struct page { 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 = {}}; @@ -86,11 +94,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. */ @@ -274,16 +336,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 +356,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 +393,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}, diff --git a/test/room_test.cpp b/test/room_test.cpp index ec82575..6a14413 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -13,6 +13,7 @@ #define BOOST_UNORDERED_ENABLE_STATS #include +#include #include #include @@ -21,9 +22,10 @@ #include #include +#include +#include + #include -#include -#include #include #include @@ -57,6 +59,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; @@ -108,16 +111,16 @@ 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); }); 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); }); 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; })); @@ -130,14 +133,14 @@ 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"}}, + a.make_action("drink").async_send( + document_of(R"({"drink":"negroni"})"), [&](boost::system::error_code ec) { sent.push_back(ec); }); 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); @@ -145,9 +148,12 @@ 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; + } + BOOST_TEST_EQ((*drink)["drink"].value_or(std::string_view()), "negroni"); } void large_payloads_travel_in_chunks_both_ways() { @@ -486,18 +492,8 @@ void a_forged_answer_changes_nothing() { const auto a_topic = trystero::protocol::peer_topic(app_id, "forged", a_id); int 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"}); @@ -640,20 +636,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, @@ -1106,11 +1094,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"); + trystero::protocol::json::append_string(text, id); + text += '}'; + auto parsed = trystero::protocol::json::parse( + text, + trystero::protocol::json::protocol_limits(trystero::protocol::max_parsed_signal_bytes), + 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)); @@ -1170,13 +1170,14 @@ 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()); diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index af95e65..fc4480e 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -10,9 +10,9 @@ #include #include #include -#include #include #include +#include #include #include @@ -21,9 +21,6 @@ #include #include -#include -#include - #include #include #include @@ -199,6 +196,10 @@ 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; /** Closes each connection right after its subscription, as a relay does after a text longer @@ -217,13 +218,10 @@ class memory_websocket : public backend::websocket, public: 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_) { @@ -251,10 +249,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); } }); @@ -284,7 +286,6 @@ class memory_websocket : public backend::websocket, memory_relay* relay_; handlers h_; std::pmr::memory_resource* memory_; - json_resource json_; bool open_ = false; bool closed_ = false; }; @@ -303,45 +304,51 @@ inline void memory_relay::close_all() { 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 = protocol::json::parse( + text, protocol::json::protocol_limits(protocol::max_relay_message_bytes), from->memory()); + if (!parsed.has_value()) { + return; + } + const protocol::json::const_value message = parsed->root(); + if (!message.at(0).is_string()) { return; } - const std::string_view type = message->at(0).get_string(); - if (type == "REQ" && message->size() >= 3) { + const std::string_view type = protocol::json::text_of(message.at(0)); + 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()); + const protocol::json::const_value filter = message.at(2); + for (const protocol::json::const_value k : filter["kinds"]) { + if (const auto kind = k.get(); kind.has_value()) { + s.kinds.insert(*kind); + } } - for (const auto& t : filter.at("#x").as_array()) { - s.topics.emplace(std::string_view(t.as_string())); + for (const protocol::json::const_value t : filter["#x"]) { + s.topics.emplace(protocol::json::text_of(t)); } subscriptions_.insert_or_assign( - key{from.get(), - std::pmr::string(std::string_view(message->at(1).as_string()), memory_)}, + key{from.get(), std::pmr::string(protocol::json::text_of(message.at(1)), memory_)}, std::move(s)); 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"])"; @@ -351,22 +358,24 @@ 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); forwarded += ','; - protocol::json::append_value(forwarded, message->at(1)); + protocol::json::append_value(forwarded, event); forwarded += ']'; socket->deliver(std::move(forwarded)); } diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp index 07645f4..0205a5c 100644 --- a/test/support/rooms.hpp +++ b/test/support/rooms.hpp @@ -13,15 +13,18 @@ #include #include +#include #include +#include #include #include #include +#include +#include + #include -#include -#include #include #include @@ -40,9 +43,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; @@ -67,6 +70,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 = {}) { @@ -251,17 +262,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 auto parsed = protocol::json::parse(text, limits, std::pmr::get_default_resource()); + 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 = + protocol::json::parse(event->content, limits, std::pmr::get_default_resource()); + const auto signal = content.has_value() ? protocol::read_signal(content->root()) : std::nullopt; if (!signal) { return std::nullopt; } From 19eceb5380bce05a4ff7ec68fa7ea599e9b97332 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 20:57:56 -0300 Subject: [PATCH 036/116] trystero: a page_call's handler lets no JavaScript error out The chat and platform_page converted the page's value with as() unchecked: a number made embind throw a BindingError, which left the run from inside the handler and ended the program, in either suspension variant. Their handlers now check the value's type, and read a form's fields only of what is neither null nor undefined. platform_page has the page pass a number and undefined before its texts, which still reach the other room. page_call's Doc Comment and the guide state webcpp::asio's rule. --- doc/platform.adoc | 20 ++++++++++--- example/chat/chat.cpp | 32 ++++++++++++++------- include/webcpp/trystero/platform/page.hpp | 13 +++++++-- test/platform_page_test.cpp | 34 ++++++++++++++++++----- 4 files changed, 76 insertions(+), 23 deletions(-) diff --git a/doc/platform.adoc b/doc/platform.adoc index 20056d4..6b7cb0a 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -345,6 +345,16 @@ in either suspension variant). 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). +* A `page_call`'s handler is a handler of the run, and lets no JavaScript + error out, webcpp::asio's rule for every handler (webcpp::asio's guide, "a + JavaScript error out of a handler"): 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`. 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` @@ -452,16 +462,18 @@ include::{examples}/chat/chat.cpp[tag=state] ---- The program joins the app and the room its user typed, and sets its -handlers; a received message goes from its frame straight into a JavaScript -string: +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` shows the message at once, and reports a failure in the -page's log: +`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] ---- diff --git a/example/chat/chat.cpp b/example/chat/chat.cpp index 000b1e7..b2416fd 100644 --- a/example/chat/chat.cpp +++ b/example/chat/chat.cpp @@ -53,13 +53,22 @@ void ui(const char* name, const Args&... args) { } // tag::join[] -void join_room(chat& c, const std::string& app_id, const std::string& room_id) { - 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); }; @@ -88,8 +97,12 @@ void join_room(chat& c, const std::string& app_id, const std::string& room_id) { // end::join[] // tag::send[] -void send_message(chat& c, std::string text) { - 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); @@ -109,11 +122,10 @@ 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["app"].as(), form["room"].as()); - }); - const trystero::platform::page_call send( - c.io.get_executor(), [&c](const val& text) { send_message(c, text.as()); }); + 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); diff --git a/include/webcpp/trystero/platform/page.hpp b/include/webcpp/trystero/platform/page.hpp index a57353f..538293e 100644 --- a/include/webcpp/trystero/platform/page.hpp +++ b/include/webcpp/trystero/platform/page.hpp @@ -80,8 +80,17 @@ inline emscripten::val js_string(std::string_view utf8) { * page_call is destroyed, or once its work is posted and the page_call destroyed before it runs, * reaches nothing. * + * `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`. + * * @tparam F A callable of one `const emscripten::val&`, the value the page passed. - * @see "The program runs its io_context", in the guide. + * @see "The program runs its io_context", in the guide, and webcpp::asio's guide, "A JavaScript + * error out of a handler". */ template // The bridge indexes the call by its registration, a private base: its one owner is the call. @@ -92,7 +101,7 @@ class page_call final : private webcpp::asio::browser::intrusive_registration { * * @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. + * @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. */ page_call(webcpp::asio::any_io_executor ex, F f, diff --git a/test/platform_page_test.cpp b/test/platform_page_test.cpp index cc3275f..e9008af 100644 --- a/test/platform_page_test.cpp +++ b/test/platform_page_test.cpp @@ -13,11 +13,17 @@ // 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 twice 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. +// 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 @@ -68,6 +74,7 @@ struct page { bool joined = false; int met = 0; std::vector received; + int ignored = 0; int late = 0; }; @@ -78,7 +85,10 @@ void handling(page& p) { } } -/** Calls the page's second function twice from a JavaScript timer, once both rooms met. */ +/** + * 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; @@ -87,6 +97,8 @@ void met(page& p) { EM_ASM({ setTimeout( function() { + globalThis.pageSend(42); + globalThis.pageSend(undefined); globalThis.pageReturned = globalThis.pageSend("from the page"); globalThis.pageSend("again"); }, @@ -114,9 +126,16 @@ void join(page& p) { }); } -/** Sends the page's text on the first room's action. */ +/** + * 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); }); } @@ -152,6 +171,7 @@ int main() { 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, 2); BOOST_TEST(!p.ran_inside_a_call); BOOST_TEST_EQ(p.late, 0); return webcpp::test::exit_status(boost::report_errors()); From 34ebfbaa0257b3962028ddde9fc615fbcc80fdcc Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:00:08 -0300 Subject: [PATCH 037/116] trystero: a page's relay and sealer handlers run outside its events platform_page_handlers checks, over a stand-in WebSocket, that a relay socket's open, message and close handlers, and a sealer's completions of a seal and an open, find webcpp::asio's bridge delivering nothing, beside a probe that sees a delivery inside a call of the bridge's function. --- test/Jamfile | 5 + test/platform_page_handlers_test.cpp | 209 +++++++++++++++++++++++++++ 2 files changed, 214 insertions(+) create mode 100644 test/platform_page_handlers_test.cpp diff --git a/test/Jamfile b/test/Jamfile index a82167b..07b254e 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -145,6 +145,9 @@ webcpp.run platform_page : platform_page_test.cpp : $(platform) : emscripten ; # the C library's allocation functions, replaced, count none. webcpp.run platform_page_sealer_allocation : platform_page_sealer_allocation_test.cpp : $(platform) : 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 page's program may be: no @@ -164,6 +167,8 @@ webcpp.run platform_page_no_exceptions : platform_page_test.cpp webcpp.run platform_page_sealer_allocation_no_exceptions : platform_page_sealer_allocation_test.cpp : $(platform) 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/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()); +} From 67746a6ace8f7280be1dddd77128b36cc3090d96 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:00:12 -0300 Subject: [PATCH 038/116] trystero: page_call says what its memory holds and when it reads the page's value A page_call's resource holds each call until the io_context runs it or is destroyed, so it outlives the io_context; its handler is given the page's value as it is when it runs. platform_page_call proves both, and that a function the page kept reaches nothing once its page_call is destroyed and breaks nothing, and that a page_call destroyed after its io_context is harmless, its function() then undefined. --- AGENTS.md | 7 +- doc/platform.adoc | 9 +- include/webcpp/trystero/platform/page.hpp | 9 +- test/Jamfile | 6 + test/platform_page_call_test.cpp | 173 ++++++++++++++++++++++ 5 files changed, 199 insertions(+), 5 deletions(-) create mode 100644 test/platform_page_call_test.cpp diff --git a/AGENTS.md b/AGENTS.md index c3a3c45..12f7131 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,7 +103,12 @@ holds only what is specific to trystero. `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. + 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 diff --git a/doc/platform.adoc b/doc/platform.adoc index 6b7cb0a..b5c2346 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -354,7 +354,14 @@ in either suspension variant). 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`. + `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` diff --git a/include/webcpp/trystero/platform/page.hpp b/include/webcpp/trystero/platform/page.hpp index 538293e..96f2316 100644 --- a/include/webcpp/trystero/platform/page.hpp +++ b/include/webcpp/trystero/platform/page.hpp @@ -78,7 +78,7 @@ inline emscripten::val js_string(std::string_view utf8) { * 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. + * 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 @@ -86,7 +86,8 @@ inline emscripten::val js_string(std::string_view utf8) { * 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`. + * undefined 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 @@ -102,7 +103,9 @@ class page_call final : private webcpp::asio::browser::intrusive_registration { * @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. + * @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()) diff --git a/test/Jamfile b/test/Jamfile index 07b254e..5fd8e34 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -145,6 +145,10 @@ webcpp.run platform_page : platform_page_test.cpp : $(platform) : emscripten ; # the C library's allocation functions, replaced, count none. webcpp.run platform_page_sealer_allocation : platform_page_sealer_allocation_test.cpp : $(platform) : 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) : 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 ; @@ -167,6 +171,8 @@ webcpp.run platform_page_no_exceptions : platform_page_test.cpp webcpp.run platform_page_sealer_allocation_no_exceptions : platform_page_sealer_allocation_test.cpp : $(platform) off : emscripten ; +webcpp.run platform_page_call_no_exceptions : platform_page_call_test.cpp + : $(platform) off : emscripten ; webcpp.run platform_page_handlers_no_exceptions : platform_page_handlers_test.cpp : $(platform) off : emscripten ; # end::no-exceptions[] diff --git a/test/platform_page_call_test.cpp b/test/platform_page_call_test.cpp new file mode 100644 index 0000000..f630b16 --- /dev/null +++ b/test/platform_page_call_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 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 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 + +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; + int stage = 0; + int seen_n = 0; + int doomed_calls = 0; + int 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, [](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, 0); +} + +/** + * 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()) { + const val n = argument["n"]; + p.seen_n = n.isNumber() ? n.as() : -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, 0); + outlive_the_io_context(p); + p.judged = true; + p.guard.reset(); +} + +} // namespace + +int main() { + program p; + p.doomed.emplace(p.io.get_executor(), + step{&p, [](program& q, const val& /*argument*/) { ++q.doomed_calls; }}); + p.next.emplace(p.io.get_executor(), step{&p, 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()); +} From 2fd362c0eb0f1e81029da01d338a958e131dde2f Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:04:50 -0300 Subject: [PATCH 039/116] trystero: the new page tests pass clang-tidy platform_page_sealer_allocation takes webcpp::asio's allocation test's select(), which clang-tidy accepts, and platform_page_call names the members it initializes. --- test/platform_page_call_test.cpp | 14 ++-- test/platform_page_sealer_allocation_test.cpp | 73 ++++++++++--------- 2 files changed, 48 insertions(+), 39 deletions(-) diff --git a/test/platform_page_call_test.cpp b/test/platform_page_call_test.cpp index f630b16..83d76c4 100644 --- a/test/platform_page_call_test.cpp +++ b/test/platform_page_call_test.cpp @@ -98,9 +98,10 @@ void outlive_the_io_context(program& p) { counting_resource memory; std::optional orphan; std::optional other(std::in_place); - orphan.emplace(other->get_executor(), - step{&p, [](program& q, const val& /*argument*/) { ++q.orphan_calls; }}, - &memory); + 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. @@ -150,9 +151,10 @@ void advance(program& p, const val& argument) { int main() { program p; - p.doomed.emplace(p.io.get_executor(), - step{&p, [](program& q, const val& /*argument*/) { ++q.doomed_calls; }}); - p.next.emplace(p.io.get_executor(), step{&p, advance}); + 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); diff --git a/test/platform_page_sealer_allocation_test.cpp b/test/platform_page_sealer_allocation_test.cpp index 965c123..45900d1 100644 --- a/test/platform_page_sealer_allocation_test.cpp +++ b/test/platform_page_sealer_allocation_test.cpp @@ -120,10 +120,34 @@ int posix_memalign(void** out, std::size_t alignment, std::size_t size) { // 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 allocation_test's does, so that the count sees the -// sealer's allocations. +// 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 { + +unsigned requested_event(int fd, const fd_set* set, unsigned event) { + return set != nullptr && FD_ISSET(fd, set) ? event : 0U; +} + +void clear_set(fd_set* set) { + if (set != nullptr) { + FD_ZERO(set); + } +} + +int ready_event(const pollfd& descriptor, fd_set* set, unsigned 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; @@ -131,45 +155,28 @@ extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* excep std::array fds{}; int 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 unsigned 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; - } + 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; } @@ -288,7 +295,7 @@ done_handler completion(state& s, F f) { } /** Starts counting what `into` will report, from zero. */ -void start_counting(state& s, counts& into) { +void start_counting(const state& s, counts& into) { global_allocations = 0; c_allocations = 0; into.room = s.room.allocations; @@ -296,7 +303,7 @@ void start_counting(state& s, counts& into) { } /** Stops counting, and records what was counted since start_counting into `into`. */ -void stop_counting(state& s, counts& into, boost::system::error_code ec) { +void stop_counting(const state& s, counts& into, boost::system::error_code ec) { counting = false; into.completed = true; into.ec = ec; From 1a23d42e5aa39a3ea3a9a7af9a28883658ed8a82 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:07:44 -0300 Subject: [PATCH 040/116] trystero: the backend takes its window by the core's time point, and names no entropy call in prose platform::backend reads its window's time with detail::steady_now, as the signaling does, so construction_window's take(double) goes. Comments that named an entropy call without reaching it now describe it, as the lint's world rule asks; the tls parameter says a relay is always verified. --- include/webcpp/trystero/detail/construction_window.hpp | 4 ---- include/webcpp/trystero/platform/backend.hpp | 9 +++++---- include/webcpp/trystero/platform/entropy.hpp | 8 ++++---- include/webcpp/trystero/platform/sealer.hpp | 2 +- 4 files changed, 10 insertions(+), 13 deletions(-) diff --git a/include/webcpp/trystero/detail/construction_window.hpp b/include/webcpp/trystero/detail/construction_window.hpp index 9617172..5e20eb8 100644 --- a/include/webcpp/trystero/detail/construction_window.hpp +++ b/include/webcpp/trystero/detail/construction_window.hpp @@ -50,10 +50,6 @@ class construction_window { return true; } - /** Takes a construction at `now_ms`, milliseconds of the backend's clock as a backend reads - * its own `now_ms`, as take(time_point) does. */ - bool take(double now_ms) { return take(from_backend_ms(now_ms)); } - private: boost::circular_buffer> times_; std::chrono::milliseconds window_; diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index b1e18b9..499ed23 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -148,9 +149,9 @@ class backend : public trystero::backend::factory { * `webcpp::asio::make_tls_client_context()` trusts natively, or a private one. * * @param ex The executor everything the backend reports runs on. - * @param tls The TLS context of every `wss://` connection, which should verify peers; or the - * error that kept the program from making it, which `tls_context()` then holds, every `wss://` - * relay reporting a close. + * @param tls The TLS context of every `wss://` connection, whose authorities each relay is + * verified against, whatever its verify mode; 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, @@ -253,7 +254,7 @@ class backend : public trystero::backend::factory { std::shared_ptr make_peer_connection( std::span servers, std::pmr::memory_resource* memory) override { - if (!constructions_.take(now_ms())) { + if (!constructions_.take(trystero::detail::steady_now(*this))) { return nullptr; } auto made = webrtc::peer_connection::make(runtime_, ex_, servers, config_.bind_address, diff --git a/include/webcpp/trystero/platform/entropy.hpp b/include/webcpp/trystero/platform/entropy.hpp index 3f2cac7..c99207f 100644 --- a/include/webcpp/trystero/platform/entropy.hpp +++ b/include/webcpp/trystero/platform/entropy.hpp @@ -24,18 +24,18 @@ namespace webcpp::trystero::platform::detail { /** * Fills `out` from the platform's one secure source of randomness, its result checked: natively - * OpenSSL's generator, `RAND_bytes`; on emscripten `getentropy`, which Emscripten draws from the - * page's `crypto.getRandomValues`. + * OpenSSL's generator; on emscripten the C library's entropy call, which Emscripten draws from + * the page's `crypto.getRandomValues`. * * @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 - // getentropy fills at most 256 bytes a call. + // The C library's entropy call fills at most 256 bytes at a time. constexpr std::size_t most = 256; #else - // RAND_bytes takes its count as an int. + // 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) { diff --git a/include/webcpp/trystero/platform/sealer.hpp b/include/webcpp/trystero/platform/sealer.hpp index 82cd358..a412731 100644 --- a/include/webcpp/trystero/platform/sealer.hpp +++ b/include/webcpp/trystero/platform/sealer.hpp @@ -188,7 +188,7 @@ inline std::optional aes_gcm(bool encrypt, const std::array Date: Sat, 14 Nov 2026 21:07:44 -0300 Subject: [PATCH 041/116] trystero: AGENTS.md, the testing page and the guarantees name the review's fixes and tests --- AGENTS.md | 42 ++++++++++++++++++++++++++++-------------- doc/guarantees.adoc | 3 ++- doc/testing.adoc | 11 +++++++++-- test/Jamfile | 7 ++++--- 4 files changed, 43 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 12f7131..fa38a27 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -168,15 +168,22 @@ holds only what is specific to trystero. 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, as a page's `WebSocket` reads it: - an IPv6 address in brackets reaches the resolver without them, the scheme - in any case, and userinfo, a fragment, a port beyond 65535 and an - IPvFuture host are refused, which reports a close; so are `http://` and - `https://`, in a page too, where a `WebSocket` alone would take them as - `ws://` and `wss://`. Natively, over TLS the connection sends the host - (SNI), through `webcpp::beast::set_server_name`, only when it is a name, - 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 both. A + 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. Each refusal reports a close. Natively, over TLS the + connection sets `verify_peer` on its stream whatever the program's context + says, 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. 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 @@ -644,11 +651,18 @@ holds only what is specific to trystero. 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, Boost.Beast's state - inside the relay WebSocket (its stream's) and the resolver's results, - while the WebSocket's operations, read buffer and queued texts are in - the room's resource (in a page the stream's own state is there too, - made with `std::allocator_arg` and the room's allocator); the payload + 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, and a non-101 + response's body up to Beast's default 8 MiB, which no option of its + stream lowers, the verify callback and its copy of the host, the timers' + waits 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 outside it (in a page the stream's own state + is there too, made with `std::allocator_arg` and the room's allocator); + the payload types `std::string`, `bytes` 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 diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index 5424959..bcdcbfa 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -46,7 +46,8 @@ file transfers of the `interop` lane. 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. +by_ `allocation`, natively and on emscripten, and, for a page's sealer, +`platform_page_sealer_allocation`. . [[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 diff --git a/doc/testing.adoc b/doc/testing.adoc index 6028c99..43e5d3e 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -168,7 +168,8 @@ include::{library-root}/test/Jamfile[tag=allocation] | `platform_page_websocket_bound`, `platform_page_websocket_late_events`, `platform_page_data_channel`, `platform_page_peer_connection`, - `platform_page`, and each `_no_exceptions` + `platform_page`, `platform_page_call`, `platform_page_handlers`, + `platform_page_sealer_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 @@ -181,7 +182,13 @@ include::{library-root}/test/Jamfile[tag=allocation] 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. + 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; the relay socket's + and the sealer's handlers run outside the page's events; 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 platform backend's tests run on each target that builds them, and once diff --git a/test/Jamfile b/test/Jamfile index 5fd8e34..c8dacf0 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -88,9 +88,10 @@ webcpp.run timer : timer_test.cpp ; # 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; -# the backend's WebRTC; and whole rooms over it. Each as the build asks and -# without exceptions: webcpp::webrtc calls libdatachannel's C API, which -# catches what libdatachannel throws, so the backend needs 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 From 7f76a5a3d57ce880cafd4ceae30cefaa7b3b5259 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:22:05 -0300 Subject: [PATCH 042/116] trystero: the bound test's posted send loop is exempt from misc-no-recursion, with its reason --- test/platform_page_websocket_bound_test.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/test/platform_page_websocket_bound_test.cpp b/test/platform_page_websocket_bound_test.cpp index 47ed0cb..62df506 100644 --- a/test/platform_page_websocket_bound_test.cpp +++ b/test/platform_page_websocket_bound_test.cpp @@ -106,8 +106,14 @@ void verdict(state& s) { s.guard.reset(); } -/** Sends the next text, and posts the one after it, so that one text is sent a turn. */ -void send_next(state& s) { +/** + * 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); @@ -117,7 +123,7 @@ void send_next(state& s) { s.in_send = true; s.socket->send(s.text); s.in_send = false; - asio::post(s.io, [&s] { send_next(s); }); + asio::post(s.io, [&s] { send_next(s); }); // NOLINT(misc-no-recursion) } } // namespace From a3e0c5f0f34e5da4b2700b436e21bd99301267c9 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:22:05 -0300 Subject: [PATCH 043/116] trystero: twins and difference programs over a local relay, the first two --- example/Jamfile | 25 + example/diff_already_joined.cpp | 47 ++ example/diff_already_joined.expected | 2 + example/diff_peer_join.cpp | 79 +++ example/diff_peer_join.expected | 3 + example/run_difference.mjs | 57 ++ test/oracle/Jamfile | 10 +- test/oracle/package-lock.json | 573 ++++++++++++++++++ test/oracle/package.json | 1 + test/oracle/page.mjs | 56 ++ test/oracle/run_twin.mjs | 35 ++ .../oracle/twins/diff_already_joined.expected | 2 + test/oracle/twins/diff_already_joined.mjs | 14 + test/oracle/twins/diff_peer_join.expected | 3 + test/oracle/twins/diff_peer_join.mjs | 37 ++ test/oracle/twins/without-twin.txt | 14 + 16 files changed, 956 insertions(+), 2 deletions(-) create mode 100644 example/diff_already_joined.cpp create mode 100644 example/diff_already_joined.expected create mode 100644 example/diff_peer_join.cpp create mode 100644 example/diff_peer_join.expected create mode 100644 example/run_difference.mjs create mode 100644 test/oracle/page.mjs create mode 100644 test/oracle/run_twin.mjs create mode 100644 test/oracle/twins/diff_already_joined.expected create mode 100644 test/oracle/twins/diff_already_joined.mjs create mode 100644 test/oracle/twins/diff_peer_join.expected create mode 100644 test/oracle/twins/diff_peer_join.mjs create mode 100644 test/oracle/twins/without-twin.txt diff --git a/example/Jamfile b/example/Jamfile index fed3412..402113b 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -25,3 +25,28 @@ webcpp.link quick_start : quick_start.cpp # The chat page, on emscripten: its program and the site it is served from. build-project chat ; + +# The programs of the appendix "Differences" (doc: #trystero-differences), each +# with its twin under test/oracle/twins/, run natively over a Nostr relay of +# their own on 127.0.0.1: run_difference.mjs starts it, gives the program its +# URL in TRYSTERO_RELAY_URL, and passes when the program prints its .expected. +# Node runs the relay with the packages test/oracle pins. +# tag::differences[] +webcpp.original node --conditions=development : ../test/oracle ; +local differences = + diff_already_joined + diff_passwords + diff_peer_join + diff_peers + diff_relay_config + diff_rooms_per_app + diff_self_id + diff_send_to_absent_peer + ; +for local difference in $(differences) +{ + webcpp.drive $(difference) : $(difference).cpp + : /webcpp/trystero//native multi : run_difference.mjs : : native ; +} +webcpp.lane differences : $(differences) : native ; +# end::differences[] diff --git a/example/diff_already_joined.cpp b/example/diff_already_joined.cpp new file mode 100644 index 0000000..871c267 --- /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::native::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"); + 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_peer_join.cpp b/example/diff_peer_join.cpp new file mode 100644 index 0000000..6ce442b --- /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::native::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/run_difference.mjs b/example/run_difference.mjs new file mode 100644 index 0000000..1fb6eb2 --- /dev/null +++ b/example/run_difference.mjs @@ -0,0 +1,57 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Runs one program of the appendix "Differences" 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 each diff_ that +// the Jamfile declares with webcpp.drive, which gives it the native program last: +// +// node --conditions=development example/run_difference.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/test/oracle/Jamfile b/test/oracle/Jamfile index d4eac81..eacfea1 100644 --- a/test/oracle/Jamfile +++ b/test/oracle/Jamfile @@ -12,10 +12,16 @@ 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 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..7a4cd12 100644 --- a/test/oracle/package.json +++ b/test/oracle/package.json @@ -8,6 +8,7 @@ "@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..b6a1354 --- /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_difference.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_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/without-twin.txt b/test/oracle/twins/without-twin.txt new file mode 100644 index 0000000..f54e10f --- /dev/null +++ b/test/oracle/twins/without-twin.txt @@ -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) + +# 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 these three from one. Each is linked and never run, so it has no +# output to compare, and a twin could not agree with it. +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 +native_quick_start: it prints only the messages peers send it, each after its sender's random id, and runs until it is stopped, so no run of it prints an output of its own to compare +quick_start: a browser program, which node refuses to run; it prints only the messages peers send it, each after its sender's random id, and runs as long as its page, so no run of it prints an output of its own to compare From 71fc751441bd8d4fa9a0510195a01b0cebdbff9c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:24:23 -0300 Subject: [PATCH 044/116] trystero: the guide builds: a test names the platform's relays anchor, a brief is one sentence, and no code span is followed by an apostrophe --- doc/allocation.adoc | 2 +- doc/platform.adoc | 24 ++++++++++---------- include/webcpp/trystero/platform/backend.hpp | 5 ++-- test/platform_websocket_test.cpp | 2 +- 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 3fadf63..84b13a3 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -283,7 +283,7 @@ nothing. 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 an `io_context`'s: 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 diff --git a/doc/platform.adoc b/doc/platform.adoc index b5c2346..15164d9 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -345,18 +345,18 @@ in either suspension variant). 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). -* A `page_call`'s handler is a handler of the run, and lets no JavaScript - error out, webcpp::asio's rule for every handler (webcpp::asio's guide, "a - JavaScript error out of a handler"): 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. +* 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 diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index 499ed23..a53375a 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -94,8 +94,9 @@ struct backend_config { /** * 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. + * 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. */ diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp index e8f0285..56e915a 100644 --- a/test/platform_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -720,7 +720,7 @@ void a_backend_makes_its_own_tls_context() { } // A backend that trusts webcpp's embedded Mozilla roots in place of the system's, as the guide -// shows it made (doc: #trystero-native-relays): the test's authority is not among them, so its +// 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; From ad198e13580153ed03dcf76ad922e3ed22583c16 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:24:29 -0300 Subject: [PATCH 045/116] trystero: the protocol's JSON on webcpp::document Relay texts, signals, handshake messages and remote candidates are read by webcpp::document's parser into a buffer of the room's or the app's resource, each caller's text bounded by parse_options::max_bytes (68,608, 66,560, 1,024 and 16 KiB bytes) and its image by twice that and 64 KiB. The protocol's texts are still written field by field, their strings quoted by webcpp::document::quote, JSON.stringify's own quoting. A JSON payload is a webcpp::document::document, or a pmr_document in the room's resource; json_resource and the rooms' JSON storage are gone. A self id that is not UTF-8 is set aside for a random one, and a local candidate that is not UTF-8 is not reported. --- build.jam | 6 +- include/webcpp/trystero.hpp | 1 - .../webcpp/trystero/detail/action_wire.hpp | 17 +- include/webcpp/trystero/detail/app_impl.hpp | 7 + .../webcpp/trystero/detail/nostr_strategy.hpp | 18 +- include/webcpp/trystero/detail/signaling.hpp | 19 +- include/webcpp/trystero/json_resource.hpp | 98 ----- include/webcpp/trystero/protocol/json.hpp | 385 +++++++++++++++--- include/webcpp/trystero/protocol/nostr.hpp | 75 ++-- include/webcpp/trystero/protocol/signal.hpp | 54 ++- include/webcpp/trystero/room.hpp | 133 +++--- .../trystero/webrtc/peer_connection.hpp | 59 +-- test/room_test.cpp | 2 +- 13 files changed, 551 insertions(+), 323 deletions(-) delete mode 100644 include/webcpp/trystero/json_resource.hpp diff --git a/build.jam b/build.jam index 1ec71a6..2efc5a6 100644 --- a/build.jam +++ b/build.jam @@ -59,10 +59,12 @@ rule native-dependencies ( properties * ) # 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. +# from usage requirements. Every JSON text the rooms read or write is +# webcpp::document's, which brings Boost.JSON's parser and Boost.Charconv's +# definitions. # tag::trystero[] alias trystero : : @trystero-dependencies - : : include /boost//headers /webcpp//boost_json + : : include /boost//headers /webcpp/document//document /webcpp/config//config /webcpp/asio//asio secp256k1 emscripten:/webcpp/webrtc//webrtc emscripten:-lembind ; diff --git a/include/webcpp/trystero.hpp b/include/webcpp/trystero.hpp index 8ea9f2f..68f35f5 100644 --- a/include/webcpp/trystero.hpp +++ b/include/webcpp/trystero.hpp @@ -21,7 +21,6 @@ #include #include #include -#include #include #include diff --git a/include/webcpp/trystero/detail/action_wire.hpp b/include/webcpp/trystero/detail/action_wire.hpp index c2aa8e8..1de04b7 100644 --- a/include/webcpp/trystero/detail/action_wire.hpp +++ b/include/webcpp/trystero/detail/action_wire.hpp @@ -16,8 +16,6 @@ #include #include -#include - #include #include #include @@ -38,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) @@ -63,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); } @@ -181,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)), @@ -564,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)); @@ -678,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)); @@ -732,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 2022244..771568b 100644 --- a/include/webcpp/trystero/detail/app_impl.hpp +++ b/include/webcpp/trystero/detail/app_impl.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -105,6 +106,12 @@ 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_ = detail::random_id(factory_, protocol::peer_id_size, memory_); } diff --git a/include/webcpp/trystero/detail/nostr_strategy.hpp b/include/webcpp/trystero/detail/nostr_strategy.hpp index 83f3843..c5277aa 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -21,7 +21,6 @@ #include #include #include -#include #include #include @@ -157,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)), @@ -458,12 +455,14 @@ class nostr_strategy : public std::enable_shared_from_this { } 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 = protocol::json::parse( + text, protocol::json::protocol_limits(protocol::nostr::max_parsed_relay_text_bytes), + 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; } @@ -529,7 +528,6 @@ class nostr_strategy : public std::enable_shared_from_this { backend::factory& factory_; std::pmr::memory_resource* memory_; - boost::json::storage_ptr json_; std::pmr::vector topics_; std::pmr::string announce_topic_; handler announcement_; diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index 604f946..690a74a 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -22,8 +22,6 @@ #include #include -#include - #include #include #include @@ -133,18 +131,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), @@ -159,9 +155,11 @@ 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 = protocol::json::parse( + content, protocol::json::protocol_limits(protocol::max_parsed_signal_bytes), memory_); + const auto message = + document.has_value() ? protocol::read_signal(document->root()) : std::nullopt; if (!message || message->peer_id == self_id_) { return; } @@ -1137,7 +1135,6 @@ class signaling : public std::enable_shared_from_this { 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_; 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/protocol/json.hpp b/include/webcpp/trystero/protocol/json.hpp index 7c54cb2..3003ae9 100644 --- a/include/webcpp/trystero/protocol/json.hpp +++ b/include/webcpp/trystero/protocol/json.hpp @@ -9,72 +9,365 @@ #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 /** - * 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. + * Reading and writing the protocol's JSON texts on webcpp::document, with every value in the + * resource the caller gives. A text is read into a document whose image is a buffer of that + * resource; 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. * - * 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. + * Tip: document's parser and writer keep their working state (Boost.JSON's parser stack, the path + * and the pending text, the tree's record of each change, the writer's stack) in the standard + * allocator, each freed before the call that made it returns: the guide's "Allocation" lists it + * outside the resource, measured. */ 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; + +/** The read-only handle of a value of a @ref document. */ +using const_value = webcpp::document::basic_const_value; + +/** The handle of a value of a @ref document, which reads and writes. */ +using value = webcpp::document::basic_value; + +class document; + +webcpp::document::result parse(std::string_view text, + const webcpp::document::parse_options& options, + std::pmr::memory_resource* memory); + +/** + * A JSON document whose image is a buffer of a memory resource: every value in it, strings + * included, lives in that buffer, which the document owns and gives back when it goes. + * + * The buffer never grows: a change that needs more room returns `errc::capacity`, as document's + * external storage does. @ref parse sizes it for the text it reads. It is move-only; moving keeps + * the buffer where it is, so the handles of its values stay valid. + * + * @see "Allocation", in the guide. + */ +class document { +public: + /** The document over the buffer: document's external storage. */ + using document_type = webcpp::document::basic_document; + + /** A document that holds no image, as one moved from does. */ + document() noexcept = default; + + /** + * Takes the image and the buffer of `other`, which holds nothing after it. + * + * @param other The document. + */ + document(document&& other) noexcept + : memory_(std::exchange(other.memory_, nullptr)), + buffer_(std::exchange(other.buffer_, nullptr)), + size_(std::exchange(other.size_, 0)), + document_(std::move(other.document_)) { + other.document_.reset(); + } + + /** + * Gives this document's buffer back, then takes the image and the buffer of `other`. + * + * @param other The document. + * @return This document. + */ + document& operator=(document&& other) noexcept { + if (this != &other) { + release(); + memory_ = std::exchange(other.memory_, nullptr); + buffer_ = std::exchange(other.buffer_, nullptr); + size_ = std::exchange(other.size_, 0); + document_ = std::move(other.document_); + other.document_.reset(); + } + return *this; + } + + /** A document is not copied: `get().clone()` copies its content into an owned document. */ + document(const document&) = delete; + + /** A document is not copied: `get().clone()` copies its content into an owned document. */ + document& operator=(const document&) = delete; + + /** Gives the buffer back to its resource. */ + ~document() { release(); } + + /** + * Makes a new document holding `null`, in a buffer of `bytes` from `memory`. + * + * @param bytes The size of the buffer, which every change of the document must fit; rounded up + * to 16. + * @param memory The resource the buffer comes from; it must outlive the document. + * @return The document; `errc::capacity` when `bytes` cannot hold an empty document. + */ + static webcpp::document::result create(std::size_t bytes, + std::pmr::memory_resource* memory) { + document made(memory, bytes); + auto formatted = webcpp::document::format(made.buffer()); + if (!formatted.has_value()) { + return formatted.error(); + } + made.document_.emplace(std::move(formatted).unsafe_value()); + return made; + } + + /** + * Whether it holds an image: false for one default-constructed or moved from. + * + * @return Whether there is a value to read. + */ + [[nodiscard]] bool has_value() const noexcept { return document_.has_value(); } + + /** + * The handle of the document's value. + * + * @return The handle; one that names nothing, which reads `undefined`, when it holds no image. + */ + [[nodiscard]] const_value root() const noexcept { + return document_.has_value() ? std::as_const(*document_).root() : const_value(); + } + + /** + * The handle of the document's value, which writes in the buffer. + * + * @return The handle; one that names nothing when it holds no image. + */ + [[nodiscard]] value root() noexcept { + return document_.has_value() ? document_->root() : value(); + } + + /** + * document's own document over the buffer, for what the handles do not do, such as `clone` + * and `image`. + * + * @return The document; it must hold an image. + */ + [[nodiscard]] const document_type& get() const noexcept { + BOOST_ASSERT(document_.has_value()); + return *document_; // NOLINT(bugprone-unchecked-optional-access): asserted + } + + /** + * document's own document over the buffer, which writes. + * + * @return The document; it must hold an image. + */ + [[nodiscard]] document_type& get() noexcept { + BOOST_ASSERT(document_.has_value()); + return *document_; // NOLINT(bugprone-unchecked-optional-access): asserted + } + + /** + * The resource the buffer comes from. + * + * @return The resource; null when it holds no image. + */ + [[nodiscard]] std::pmr::memory_resource* resource() const noexcept { return memory_; } + + /** + * The size of the buffer, the most the image can take. + * + * @return The bytes; 0 when it holds no image. + */ + [[nodiscard]] std::size_t capacity() const noexcept { return size_; } + +private: + friend webcpp::document::result parse(std::string_view text, + const webcpp::document::parse_options& options, + std::pmr::memory_resource* memory); + + /** The alignment of document's images. */ + static constexpr std::size_t alignment = 16; + + /** `bytes` rounded up to the alignment. */ + static constexpr std::size_t aligned(std::size_t bytes) noexcept { + return (bytes + alignment - 1) / alignment * alignment; + } -/** 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()); + /** A document with a buffer of `bytes`, rounded up to 16, from `memory`, and no image yet. */ + document(std::pmr::memory_resource* memory, std::size_t bytes) + : memory_(memory), + buffer_(static_cast(memory->allocate(aligned(bytes), alignment))), + size_(aligned(bytes)) {} + + /** The buffer. */ + [[nodiscard]] std::span buffer() const noexcept { return {buffer_, size_}; } + + /** Ends the document, then gives its buffer back. */ + void release() noexcept { + document_.reset(); + if (buffer_ != nullptr) { + memory_->deallocate(buffer_, size_, alignment); + } + memory_ = nullptr; + buffer_ = nullptr; + size_ = 0; + } + + std::pmr::memory_resource* memory_ = nullptr; + std::byte* buffer_ = nullptr; + std::size_t size_ = 0; + std::optional document_; +}; + +/** + * The limits of a protocol text's parse: at most `max_bytes` of text, into an image 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 parse has + * filled the bound, so that no text costs a room more than a multiple of its bound to read. + * + * @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_document_bytes = (2 * max_bytes) + (std::uint64_t{64} << 10U); + return o; +} + +/** + * `JSON.parse(text)` into a @ref document in a buffer of `memory`, as webcpp::document reads it: a + * key written twice keeps the last value in the first one's place, and a lone surrogate is + * refused. + * + * The buffer is first sized for a text of a few values, twice the text and 4 KiB; a parse that + * fills it is made again in a buffer twice the size, up to `options.max_document_bytes`. + * + * @param text The text. + * @param options The limits: `max_bytes` of text, checked before anything is read, + * `max_document_bytes` of buffer, and `max_depth`. + * @param memory The resource the buffer comes from; it must outlive the document. + * @return The document; `errc::capacity` for a text longer than `max_bytes`, nested deeper than + * `max_depth`, or whose image needs more than `max_document_bytes`, `errc::syntax` for malformed + * text, `errc::range` for a number document refuses. + */ +inline webcpp::document::result parse(std::string_view text, + const webcpp::document::parse_options& options, + std::pmr::memory_resource* memory) { + if (text.size() > options.max_bytes) { + return webcpp::document::errc::capacity; + } + constexpr std::size_t first_spare = std::size_t{4} << 10U; + const auto most = static_cast(std::min( + options.max_document_bytes, std::numeric_limits::max() / 4)); + std::size_t bytes = std::min((2 * text.size()) + first_spare, most); + for (;;) { + document made(memory, bytes); + webcpp::document::basic_parser parser(made.buffer(), + options); + const webcpp::document::result written = parser.write(text); + auto finished = written.has_value() + ? parser.finish() + : webcpp::document::result(written.error()); + if (finished.has_value()) { + made.document_.emplace(std::move(finished).unsafe_value()); + return made; + } + // A full buffer is errc::capacity without a cause of Boost.JSON's, which a text nested past + // max_depth has. + const bool full = finished.error() == webcpp::document::errc::capacity && !parser.cause(); + if (!full || bytes >= most) { + return finished.error(); + } + bytes = std::min(2 * bytes, most); } } +/** + * 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 text The string, in UTF-8 (@ref quotable): every string the protocol writes is, the self + * id checked when the app is made, a candidate's fields when it is written, and every other one is + * ASCII or was read from JSON. */ 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); + [[maybe_unused]] const webcpp::document::result quoted = + webcpp::document::quote(text, out); + BOOST_ASSERT(quoted.has_value()); } /** - * Appends `value` serialized, as `boost::json::serialize` writes it. + * 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. +// NOLINTNEXTLINE(performance-unnecessary-value-param) +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( + v, [&out](std::string_view text) { out.append(text); }, 0, piece)); } /** @@ -103,28 +396,6 @@ inline void append_key(std::pmr::string& out, std::string_view 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 8851429..135a27e 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,7 +19,6 @@ #include #include #include -#include #include #include @@ -37,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"; @@ -377,34 +391,23 @@ 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); - } - if (const auto* c = o.if_contains("content")) { - e.content = text_of(*c); - } - 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; - } + e.subscription = json::text_of(array[1]); + e.id = json::text_of(o["id"]); + e.content = json::text_of(o["content"]); + // An array is its own range of elements, which the handle, outliving the loop, keeps. + const json::const_value tags = o["tags"]; + for (const json::const_value tag : tags) { + if (tag.is_array() && tag.size() >= 2 && json::text_of(tag[0]) == topic_tag && + tag[1].is_string()) { + e.topic = json::text_of(tag[1]); + break; } } return e; @@ -413,28 +416,28 @@ inline std::optional read_event(const boost::json::array& array) } // 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. * - * @param document The parsed text, which the caller keeps alive while it reads the views. + * A key written twice is read as JavaScript reads it, the last value, which the parse keeps. + * + * @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/signal.hpp b/include/webcpp/trystero/protocol/signal.hpp index 9626efa..517c9dd 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 * "::". @@ -188,32 +209,33 @@ 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. + * 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, 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) { + if (!document.is_object()) { 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) || @@ -222,9 +244,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 || diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 44eae8e..7b6b4a2 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -38,9 +37,10 @@ #include // lint-world: posts handlers only #include // lint-world: posts handlers only +#include +#include + #include -#include -#include #include #include @@ -89,13 +89,25 @@ using bytes = std::vector; */ using pmr_bytes = std::pmr::vector; +/** + * A JSON document in a memory resource, an action's JSON payload in the room's resource. + * + * A message received as `pmr_document` is parsed into a buffer of the room's effective + * `room_options::memory`, which must outlive the value, with every value of the document in that + * buffer. One sent is written once, as `JSON.stringify` writes it, into the room's resource. + * + * @see "Allocation", in the guide. + */ +using pmr_document = protocol::json::document; + /** * 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. */ -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 @@ -158,14 +170,15 @@ inline std::string_view as_text(std::span data) { * 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. + * are built in the receiving room's resource, `pmr_document` in a buffer of it; the standard + * types allocate with `std::allocator`, as the user chose, and so does an owned document. * * | 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 | + * | webcpp::document::document | JSON | parsed, in an image of its own | + * | trystero::pmr_document | JSON | parsed, in a buffer of 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 | @@ -249,34 +262,68 @@ struct payload_traits { } }; -/** How an action of `boost::json::value`, Trystero's JSON payload, travels. */ +/** How an action of `webcpp::document::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` does, 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.root()); + return own(protocol::payload_format::json, keep(memory, std::move(text))); + } + + /** + * The message's payload as this type: the parsed text, an owned document, whose image comes + * from the global `operator new` as document's own does; nothing for another format or a text + * that does not parse. + */ + static std::optional decode(incoming& m, + std::pmr::memory_resource* /*memory*/) { + if (m.format != protocol::payload_format::json) { + return std::nullopt; + } + auto v = webcpp::document::parse(as_text(m.payload())); + if (!v.has_value()) { + return std::nullopt; + } + return std::move(v).unsafe_value(); + } +}; + +/** How an action of `trystero::pmr_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` does, into a shared string of the room's + * resource. */ + static encoded_payload encode(const pmr_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, in a buffer of the room's resource, as + * large as document's limits let a parse grow (`parse_options::max_document_bytes`); nothing + * for another format or a text that does not parse. */ - static std::optional decode(incoming& m, - std::pmr::memory_resource* /*memory*/) { + static std::optional decode(incoming& m, std::pmr::memory_resource* memory) { 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) { + auto v = + protocol::json::parse(as_text(m.payload()), webcpp::document::parse_options{}, memory); + if (!v.has_value()) { return std::nullopt; } - return v; + return std::move(v).unsafe_value(); } }; @@ -388,7 +435,7 @@ struct payload_traits { } return std::nullopt; case protocol::payload_format::json: - if (auto v = payload_traits::decode(m, memory)) { + if (auto v = payload_traits::decode(m, memory)) { return payload(std::move(*v)); } return std::nullopt; @@ -449,17 +496,10 @@ class room_impl final : public std::enable_shared_from_this, public r /** 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()), @@ -545,7 +585,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(), @@ -579,7 +619,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_); @@ -599,7 +639,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(); } @@ -1208,14 +1248,13 @@ 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 = protocol::json::parse( + data, protocol::json::protocol_limits(protocol::max_handshake_bytes), 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); @@ -1235,9 +1274,7 @@ 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; } @@ -1482,7 +1519,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_; @@ -1675,7 +1711,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 + * `webcpp::document::document`, @ref 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`. @@ -1791,7 +1828,7 @@ class action { } // 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`. * @@ -1806,7 +1843,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. diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp index f1ffa7c..9b9a338 100644 --- a/include/webcpp/trystero/webrtc/peer_connection.hpp +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -12,8 +12,8 @@ #include #include #include -#include #include +#include #include #include @@ -25,8 +25,6 @@ #include // lint-world: binds an allocator only #include // lint-world: posts handlers only -#include -#include #include #include @@ -185,11 +183,7 @@ class peer_connection : public backend::peer_connection, 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), - json_(memory), - pc_(std::move(pc)) {} + : 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; @@ -272,36 +266,38 @@ class peer_connection : public backend::peer_connection, /** * 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 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 { - 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* text = object != nullptr ? object->if_contains("candidate") : nullptr; - if (text == nullptr || !text->is_string()) { + // The document lives in the app's resource for the call: the platform copies the views. + const auto document = protocol::json::parse( + candidate_json, protocol::json::protocol_limits(protocol::max_sealed_candidate_bytes), + 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 = text->get_string()}; - if (const auto* mid = object->if_contains("sdpMid"); mid != nullptr && mid->is_string()) { - candidate.sdp_mid = std::string_view(mid->get_string()); + ::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->if_contains("sdpMLineIndex"); index != nullptr) { - if (const auto value = index->to_number(parse_error); - !parse_error && value >= 0 && value <= 65535) { - candidate.sdp_m_line_index = static_cast(value); - } + if (const auto index = object["sdpMLineIndex"].get(); + index.has_value() && *index >= 0 && *index <= 65535) { + candidate.sdp_m_line_index = static_cast(*index); } - if (const auto* fragment = object->if_contains("usernameFragment"); - fragment != nullptr && fragment->is_string()) { - candidate.username_fragment = fragment->get_string(); + 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 { @@ -411,12 +407,20 @@ class peer_connection : public backend::peer_connection, // 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. */ + /** + * 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; } + if (!protocol::json::quotable(candidate.candidate) || + !protocol::json::quotable(candidate.sdp_mid) || + !protocol::json::quotable(candidate.username_fragment)) { + return; + } std::pmr::string json(R"({"candidate":)", memory_); protocol::json::append_string(json, candidate.candidate); json += R"(,"sdpMid":)"; @@ -478,7 +482,6 @@ class peer_connection : public backend::peer_connection, std::shared_ptr<::webcpp::webrtc::runtime> runtime_; backend::factory& factory_; std::pmr::memory_resource* memory_; - json_resource json_; std::shared_ptr h_; state state_ = state::new_; ice_state ice_state_ = ice_state::new_; diff --git a/test/room_test.cpp b/test/room_test.cpp index 93be6b6..15697dc 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -763,7 +763,7 @@ void a_strategy_draws_the_key_of_its_event_ids() { f.net, std::span(), std::pmr::vector(), "topic", trystero::handler(), trystero::detail::nostr_strategy::message_handler(), trystero::detail::logger(), - std::pmr::get_default_resource(), boost::json::storage_ptr()); + std::pmr::get_default_resource()); BOOST_TEST_EQ(f.net.random_bytes - before, 32U + trystero::detail::recent_event_ids::key_size); // the secret, the key } From 3dc86fb12f3250f7dc9e678b4f73e29ec436630c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:24:30 -0300 Subject: [PATCH 046/116] trystero: the protocol test reads with webcpp::document and checks the bounds of a parse The fixture is read with webcpp::document; the oracle's quoting, signal text and duplicate-key sections are compared byte for byte; each caller's bound holds to the byte, a text that fills its image bound is refused, a text nested past max_depth is refused without a second buffer, and the image is the resource's. --- test/protocol_test.cpp | 632 ++++++++++++++++++++++++++++++++++------- 1 file changed, 535 insertions(+), 97 deletions(-) diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index 12ee74e..ccb6e03 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -6,17 +6,23 @@ // 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 protocol::json::parse and its bounds. #include #include +#include #include #include #include #include +#include +#include +#include +#include + #include -#include #include #include @@ -24,108 +30,160 @@ #include #include #include +#include #include +#include #include #include #include #include +#include #include #include -namespace json = boost::json; +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 fixture_value& v) { + return v.value_or(std::string_view()); +} + +// 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}); } -std::string_view str(const json::value& v) { - return v.as_string(); +tp::bytes hex(const fixture_value& v) { + return tp::from_hex(str(v)).value(); } -tp::bytes hex(const json::value& v) { - return *tp::from_hex(v.as_string()); +/** A protocol text read as a room reads it: at most `max_bytes`, into a buffer 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 tp::json::parse(text, tp::json::protocol_limits(max_bytes), memory); } -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"))); - } - 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()); +/** A resource that counts what it gives: its buffers, their bytes, 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; + /** The bytes of all its allocations. */ + std::size_t allocated = 0; + /** The bytes of its largest allocation. */ + std::size_t largest = 0; + /** Its last allocation. */ + void* last = nullptr; + /** The bytes of its last allocation. */ + std::size_t last_bytes = 0; + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations; + ++outstanding; + allocated += bytes; + largest = std::max(largest, bytes); + last_bytes = bytes; + last = std::pmr::new_delete_resource()->allocate(bytes, alignment); + return last; + } + + 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; + } +}; + +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()); +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(e.at("created_at").as_int64())); - const auto id = tp::nostr::event_id(str(e.at("pubkey")), created_at, - 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"))); + 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{}; @@ -136,29 +194,38 @@ void nostr_events(const json::object& fixture) { const auto message = tp::nostr::event_message(*key, std::chrono::sys_seconds(std::chrono::seconds(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()); + 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); + // The relay's echo holds the event's text whole: `["EVENT",]` less its first 9 and last + // byte, in `["EVENT","sub",]`. + const std::string_view written = message; + BOOST_TEST(written.starts_with(R"(["EVENT",{)") && written.ends_with("}]")); + std::string echo = R"(["EVENT","sub",)"; + echo += written.substr(9, written.size() - 10); + echo += ']'; + const auto echoed_document = parse_text(echo, 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(); +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( @@ -166,33 +233,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"); @@ -205,12 +272,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); @@ -222,7 +288,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()); @@ -232,7 +298,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()); @@ -242,30 +308,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()); @@ -273,10 +339,14 @@ 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); + tp::json::document 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; + } + document = std::move(parsed).value(); + return tp::read_signal(std::as_const(document).root()); }; const auto announce = read(R"({"peerId":"abc","nonce":"x1"})"); if (!BOOST_TEST(announce.has_value())) { @@ -406,10 +476,14 @@ void wide_fields_are_big_endian() { // 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; + tp::json::document 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; + } + document = std::move(parsed).value(); + return tp::read_signal(std::as_const(document).root()).has_value(); }; std::array iv{}; iv.fill(255); @@ -432,6 +506,360 @@ 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(), 5U); + for (const auto entry : fixture["signal_texts"]) { + const auto s = entry["signal"]; + 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), + }; + 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); + } +} + +/** + * 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(), 11U); + 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); + +// 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 fills the bound; and what the +// parse took from the resource, its doubling buffers, sums to less than three times the bound. +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); + + 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 = tp::json::parse(event_with(keys), limits, &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.allocated, 3 * bound); + BOOST_TEST_EQ(keyed.outstanding, 0U); + + 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(tp::json::parse(values(100), limits, &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 = tp::json::parse(text, limits, &many); + BOOST_TEST(!refused.has_value() && refused.error() == wd::errc::capacity); + BOOST_TEST_EQ(many.largest, bound); + BOOST_TEST_LT(many.allocated, 3 * bound); + BOOST_TEST_EQ(many.outstanding, 0U); + } +} + +// A text nested past max_depth is refused at once: Boost.JSON's parser stops at the 257th level, +// which the parse does not take for a full buffer, so it makes no larger one to try again. The +// texts are padded so that their first buffer holds the 256 levels a room reads; unpadded, the +// same nesting fills the first buffers, which do grow. +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, 256U); + const auto nested = [](std::size_t levels, std::size_t size) { + std::string text(size - (2 * levels), ' '); + text.append(levels, '['); + text.append(levels, ']'); + return text; + }; + const std::size_t size = tp::nostr::max_parsed_relay_text_bytes; + counting_resource deepest; + BOOST_TEST(tp::json::parse(nested(depth, size), limits, &deepest).has_value()); + BOOST_TEST_EQ(deepest.allocations, 1U); + counting_resource deeper; + const auto refused = tp::json::parse(nested(depth + 1, size), limits, &deeper); + BOOST_TEST(!refused.has_value() && refused.error() == wd::errc::capacity); + BOOST_TEST_EQ(deeper.allocations, 1U); + BOOST_TEST_EQ(deeper.outstanding, 0U); + counting_resource growing; + BOOST_TEST(tp::json::parse(nested(depth, 2 * depth), limits, &growing).has_value()); + BOOST_TEST_GT(growing.allocations, 1U); +} + +// A parse's image is one buffer of the resource it is given, the only thing it holds there once +// the parse succeeds: the strings read from it point into it, a move keeps it where it is, and the +// resource has nothing out once the document goes. +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; + } + tp::json::document document = std::move(parsed).value(); + BOOST_TEST(document.resource() == &memory); + BOOST_TEST_EQ(memory.outstanding, 1U); + BOOST_TEST_EQ(memory.last_bytes, document.capacity()); + const auto image = document.get().image(); + BOOST_TEST(static_cast(image.data()) == memory.last); + BOOST_TEST_EQ(image.size(), 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 tp::json::document moved = std::move(document); + // A document moved from holds no image. + BOOST_TEST(!document.has_value()); // NOLINT(bugprone-use-after-move) + BOOST_TEST(static_cast(moved.get().image().data()) == memory.last); + BOOST_TEST_EQ(tp::json::text_of(moved.root()[2]["content"]), R"({"peerId":"p"})"); + BOOST_TEST_EQ(memory.allocations, 1U); + BOOST_TEST_EQ(memory.outstanding, 1U); + } + BOOST_TEST_EQ(memory.outstanding, 0U); +} + void text() { BOOST_TEST_EQ(tp::base64_encode(tp::bytes{}), ""); BOOST_TEST_EQ(tp::base64_encode(tp::bytes{'f'}), "Zg=="); @@ -452,7 +880,10 @@ 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); @@ -465,6 +896,13 @@ int main(int argc, char* argv[]) { signals(); random_ids(); signal_bounds(); + event_messages(fixture); + signal_texts(fixture); + duplicate_keys(fixture); + parse_bounds(); + parse_cost(); + parse_depth(); + parse_resource(); text(); return boost::report_errors(); } From c07b8ba37a2593a267dab5f9cbce46befd2caa9e Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:24:30 -0300 Subject: [PATCH 047/116] trystero: the allocation test measures webcpp::document's working state Every global allocation is tracked until freed. Exchanging a std::pmr::string or a pmr_bytes sees none; exchanging a pmr_document sees exactly what writing and reading its text cost webcpp::document, counted outside the window; reading each protocol text costs at most 8 allocations a value and 16 more, none left; the long cases leave nothing on the global heap. --- test/allocation_test.cpp | 290 +++++++++++++++++++++++++++++++++------ 1 file changed, 247 insertions(+), 43 deletions(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 0dd857e..68f1c74 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -6,9 +6,10 @@ // While two rooms over the memory relays exchange a message, every allocation // they make goes through the resources of their configurations: the counting -// resources see them, and the global operator new, replaced here, sees none, -// nor do the C library's allocation functions where the platform lets a -// program count them (doc: #trystero-allocation). +// resources see them, and the global operator new, replaced here, sees only +// webcpp::document's working state while it reads or writes a JSON text, each +// freed before the call returns, nor do the C library's allocation functions +// where the platform lets a program count them (doc: #trystero-allocation). #include @@ -19,10 +20,11 @@ #include #include #include +#include +#include +#include #include -#include -#include #include #include @@ -55,6 +57,7 @@ #endif namespace trystero = webcpp::trystero; +namespace tp = webcpp::trystero::protocol; namespace { @@ -71,6 +74,17 @@ 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) @@ -294,6 +308,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.at(i) != nullptr) { + i = (i + 1) & (live_slots - 1); + } + live.at(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.at(i) != pointer) { + if (live.at(i) == nullptr) { + return; + } + i = (i + 1) & (live_slots - 1); + } + live.at(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.at(j) != nullptr; + j = (j + 1) & (live_slots - 1)) { + const std::size_t k = home_of(live.at(j)); + const bool stays = i < j ? (i < k && k <= j) : (i < k || k <= j); + if (!stays) { + live.at(i) = live.at(j); + live.at(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 @@ -309,6 +371,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) @@ -342,6 +407,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; } @@ -485,9 +553,30 @@ 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. */ -template -void exchange_allocates_through_the_rooms_resources(Make make) { +/** + * What webcpp::document's working state costs the global operator new for a JSON payload: writing + * it as a sending room does and reading the text back as a receiving room does, into `memory`. + * Freed before each call returns, and counted here outside any window. + */ +std::size_t document_cost(const trystero::pmr_document& payload, + std::pmr::memory_resource* memory) { + std::pmr::string text(memory); + global_allocations = 0; + counting = true; + tp::json::append_value(text, payload.root()); + const bool read = tp::json::parse(text, webcpp::document::parse_options{}, memory).has_value(); + counting = false; + BOOST_TEST(read); + BOOST_TEST_EQ(live_count, 0U); + return std::exchange(global_allocations, 0); +} + +/** + * Two rooms exchange two payloads that make builds; the second is counted, and the global + * operator new sees exactly what `cost` says webcpp::document's working state takes for it. + */ +template +void exchange_allocates_through_the_rooms_resources(Make make, Cost cost) { // The resources outlive the io_context, whose pending operations they hold. counting_resource a_memory; counting_resource z_memory; @@ -496,9 +585,7 @@ void exchange_allocates_through_the_rooms_resources(Make make) { // 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::test::memory_relay& relay_state = network.relay(relay); trystero::app a_app(io.get_executor(), network, { .app_id = "allocation", @@ -519,8 +606,8 @@ void exchange_allocates_through_the_rooms_resources(Make make) { auto from_a = a.make_action("chat"); z.make_action("chat").on_message( [&](const Payload& /*payload*/, const trystero::message_info& /*info*/) { ++received; }); - const auto send = [&] { - from_a.async_send(make(&a_memory, json_storage), + const auto send = [&](Payload value) { + from_a.async_send(std::move(value), webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_memory), [](boost::system::error_code /*ec*/) {})); }; @@ -530,25 +617,128 @@ void exchange_allocates_through_the_rooms_resources(Make make) { run_until(io, [&] { return a.peers().size() == 1 && z.peers().size() == 1; }))) { return; } - send(); + send(make(&a_memory)); if (!BOOST_TEST(run_until(io, [&] { return received == 1; }))) { return; } - const std::size_t before = a_memory.allocations + z_memory.allocations; - 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); - BOOST_TEST_GT(a_memory.allocations + z_memory.allocations, before); + // A window in which the relay carries a text, an announcement the rooms read, sees that + // parse too; such a window is opened again, five times at most. + bool quiet = false; + for (int window = 0; window < 5 && !quiet; ++window) { + Payload value = make(&a_memory); + const std::size_t expected = cost(value, &z_memory); + const std::size_t texts = relay_state.texts; + const std::size_t before = a_memory.allocations + z_memory.allocations; + const std::size_t wanted = received + 1; + global_allocations = 0; + c_allocations = 0; + counting = true; + send(std::move(value)); + const bool arrived = run_until(io, [&] { return received == wanted; }); + counting = false; + BOOST_TEST(arrived); + quiet = relay_state.texts == texts; + if (!quiet) { + continue; + } + explain_global_allocations(expected); + BOOST_TEST_EQ(global_allocations, expected); + BOOST_TEST_EQ(live_count, 0U); + BOOST_TEST_EQ(c_allocations, 0U); + BOOST_TEST_GT(a_memory.allocations + z_memory.allocations, before); + } + BOOST_TEST(quiet); BOOST_TEST_EQ(a_memory.foreign + z_memory.foreign, 0U); global_allocations = 0; c_allocations = 0; } +/** How many values a document holds, its own included. */ +std::size_t values_in(const tp::json::const_value& v) { + std::size_t n = 1; + if (v.is_array()) { + for (const tp::json::const_value element : v) { + n += values_in(element); + } + } else if (v.is_object()) { + for (const tp::json::const_value member : v.values()) { + n += values_in(member); + } + } + return n; +} + +/** + * webcpp::document's working state for each text a room reads, counted: Boost.JSON's parser + * stack, the path and the pending text, and the tree's record of each value it places, from the + * global operator new, all freed before the parse returns, and at most 8 allocations a value and + * 16 more; the document itself is in the resource it is given (doc: #trystero-allocation). + */ +void reading_a_text_costs_the_heap_a_bounded_working_state() { + 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; + }; + + const std::array texts{{ + {"relay event", relayed, tp::nostr::max_parsed_relay_text_bytes}, + {"relay OK", ok, tp::nostr::max_parsed_relay_text_bytes}, + {"signal", signal, tp::max_parsed_signal_bytes}, + {"handshake", handshake, tp::max_handshake_bytes}, + {"candidate", candidate, tp::max_sealed_candidate_bytes}, + }}; + for (const text& t : texts) { + const std::size_t outstanding = memory.outstanding; + global_allocations = 0; + counting = true; + auto document = tp::json::parse(t.json, tp::json::protocol_limits(t.bound), &memory); + counting = false; + const std::size_t cost = std::exchange(global_allocations, 0); + if (!BOOST_TEST(document.has_value())) { + continue; + } + const std::size_t values = values_in(document->root()); + BOOST_TEST_LE(cost, 16 + (8 * values)); + BOOST_TEST_EQ(live_count, 0U); + // The image is the resource's, and goes back with the document. + BOOST_TEST_GT(memory.outstanding, outstanding); + document = webcpp::document::result(tp::json::document()); + BOOST_TEST_EQ(memory.outstanding, outstanding); + } + BOOST_TEST_EQ(c_allocations, 0U); + BOOST_TEST_EQ(memory.foreign, 0U); + c_allocations = 0; +} + /** Runs io for about `milliseconds`, whatever happens. */ void run_for(webcpp::asio::io_context& io, int milliseconds) { for (int slice = 0; slice < milliseconds / 10; ++slice) { @@ -608,8 +798,9 @@ trystero::room_options options_in(counting_resource& memory) { * 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). + * webcpp::document's working state alone, while the rooms and the relay read and + * write JSON texts, and nothing of it is left at the drain; the C library sees + * nothing (doc: #trystero-allocation). */ void a_room_allocates_through_its_resource_from_join_to_destruction() { counting_resource network_memory; @@ -697,8 +888,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); + // The global operator new saw webcpp::document's working state alone, each piece freed before + // the parse or the write that made it returned. + 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; @@ -708,10 +901,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). + * webcpp::document's working state, none of it left at the drain, 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). */ void rooms_of_one_app_allocate_through_their_resources() { counting_resource network_memory; @@ -784,8 +977,9 @@ void rooms_of_one_app_allocate_through_their_resources() { } counting = false; } - explain_global_allocations(4U); - BOOST_TEST_EQ(global_allocations, 4U); // the four rooms' JSON storage counters + // webcpp::document's working state alone, freed as the long case's. + 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); @@ -871,19 +1065,29 @@ int main() { #endif the_replaced_operators_serve_every_alignment(); the_counts_see_an_allocation(); + const auto nothing = [](const auto& /*payload*/, std::pmr::memory_resource* /*memory*/) { + return std::size_t{0}; + }; exchange_allocates_through_the_rooms_resources( - [](std::pmr::memory_resource* memory, const boost::json::storage_ptr& /*storage*/) { + [](std::pmr::memory_resource* memory) { return std::pmr::string("a text that no small string holds", memory); - }); + }, + nothing); exchange_allocates_through_the_rooms_resources>( - [](std::pmr::memory_resource* memory, const boost::json::storage_ptr& /*storage*/) { + [](std::pmr::memory_resource* memory) { 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); - }); + }, + nothing); + exchange_allocates_through_the_rooms_resources( + [](std::pmr::memory_resource* memory) { + auto made = tp::json::parse( + R"({"drink":"a text that no small string holds","ice":[1,2.5,true,null]})", + webcpp::document::parse_options{}, memory); + webcpp::test::require(BOOST_TEST(made.has_value())); + return std::move(made).unsafe_value(); + }, + &document_cost); + reading_a_text_costs_the_heap_a_bounded_working_state(); a_room_allocates_through_its_resource_from_join_to_destruction(); rooms_of_one_app_allocate_through_their_resources(); return webcpp::test::exit_status(boost::report_errors()); From 23440f2055ae75c727ab3978ebe273156470a282 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:29:50 -0300 Subject: [PATCH 048/116] trystero: the guide on webcpp::document's JSON The protocol page gains its JSON texts and their bounds, the allocation page webcpp::document's buffers and its working state measured outside them, usage the JSON payload types, and differences the bounds and the self id that is not UTF-8. --- README.md | 7 ++-- doc/allocation.adoc | 87 ++++++++++++++++++++++++++++++-------------- doc/browser.adoc | 6 +-- doc/building.adoc | 4 +- doc/design.adoc | 19 +++++++--- doc/differences.adoc | 6 +++ doc/guarantees.adoc | 5 ++- doc/overview.adoc | 8 ++-- doc/protocol.adoc | 35 ++++++++++++++++++ doc/usage.adoc | 27 ++++++++++++-- 10 files changed, 152 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 7f33fe2..c3ef96d 100644 --- a/README.md +++ b/README.md @@ -102,8 +102,8 @@ 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, -webcpp::asio, libsecp256k1 and Boost.JSON's definitions, compiled once per -variant, and on emscripten webcpp::webrtc and embind; a program there is +webcpp::asio, libsecp256k1 and webcpp::document with Boost.JSON's and +Boost.Charconv's definitions, compiled once per variant, and on emscripten webcpp::webrtc and embind; a program there is built in webcpp::asio's suspension variant, `webcpp-suspend=jspi` by default or `asyncify`. A native program uses `/webcpp/trystero//native` and declares `multi` itself, as `example/Jamfile` does; the target @@ -311,7 +311,8 @@ b2 --user-config=../user-config.jam libs/trystero/example//native_quick_start-pr 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 +The first build also compiles 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`, diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 3f74020..3caecf8 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -25,7 +25,7 @@ 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 + frames, transfers, the documents of the JSON texts it reads, and handlers. The signing context is made there with `secp256k1_context_preallocated_create`. * Adoption replaces negotiation handlers with the app's; ending a negotiation clears the room's handlers. Detachment fails and frees a @@ -36,7 +36,9 @@ 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 buffer of the room's resource, a remote + candidate into one of the app's, and a `pmr_document` payload into one of + the room's resource, every value of the document in that buffer. 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,7 +59,7 @@ 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 `pmr_document` values, and its pending operations. 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 @@ -121,9 +123,11 @@ 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 an image +of its own, from the global `operator new`, as document's owned documents +are. A struct that holds `std::pmr` containers takes the room's `std::pmr::polymorphic_allocator<>` in its constructor, and a container of @@ -152,7 +156,7 @@ 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,* webcpp::asio's, which natively is Boost.Asio itself. Every `post`, `dispatch`, timer wait and `any_completion_handler` the room makes carries @@ -176,15 +180,28 @@ 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. -*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. +*webcpp::document* keeps a document's image in one buffer, and its external +storage leaves that buffer to its user: every value, strings included, is +allocated inside it by Boost.Interprocess's `rbtree_best_fit` heap, with +offsets for pointers. trystero gives each text it reads such a buffer of the +room's resource (`protocol::json::document`), sized for a text of a few +values, twice the text and 4 KiB, and made again twice as large when the +parse fills it, up to the caller's bound. 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. + +What document's parser and writer use while they work stays in the standard +allocator: Boost.JSON's parser stack, the path and the pending key and text +of the value being read, the tree's record of each change, which places a +value, and the writer's stack. Each is freed before the parse or the write +that made it returns, so none is left at any moment the room's executor is +between handlers. Measured natively with libc++, each text a room reads +costs `operator new` about seven allocations a value: a relay's event +carrying an offer, 1,581 bytes and 14 values, 93; a relay's `OK`, 5 values, +32; a signal, 4 values, 26; a handshake message, 3 values, 20; a candidate, +5 values, 32. Writing and reading back a JSON payload of 7 values costs 48. *The protocol* (`protocol/`) takes a `std::pmr::memory_resource*` as the last parameter of every function that returns what it allocates, with the @@ -200,8 +217,9 @@ nothing. 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; +* webcpp::document's working state while it reads or writes a JSON text, + freed before the call returns (above): its parser's stack, path and + pending text, its tree's record of each change, its writer's stack; * 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 the @@ -214,8 +232,9 @@ nothing. and the resolver's results; the WebSocket's operations, its read buffer and its queued texts are in the room's resource, since each of its handlers carries the room's allocator; -* the payload types `std::string`, `bytes` and `payload`, with - `std::allocator`, the user's choice; +* the payload types `std::string`, `bytes`, `webcpp::document::document` and + `payload`, with `std::allocator` or document's own `operator new`, 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; @@ -239,18 +258,29 @@ 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 `pmr_document` in turn. For the + first two `operator new` sees nothing; for the document, exactly what + writing it and reading its text back cost webcpp::document's working + state, counted apart beforehand on the same value, and nothing left; the C + library sees nothing, and the counting resources of the two + configurations see the rooms'. A window in which the relay carried a text, + an announcement the rooms read, is opened again. +* 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 in a + counting resource: its image is the resource's, and goes back with the + document, and document's working state costs `operator new` at most 8 + allocations a value and 16 more, none left after the parse. * 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 + `operator new` sees webcpp::document's working state alone, as the rooms + and the relay read and write their JSON texts (2,320 allocations, measured + natively), none of it left at the drain, 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. @@ -258,12 +288,13 @@ the thread `main` runs on is counted. 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. + webcpp::document's working state, none of it left, 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 +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 diff --git a/doc/browser.adoc b/doc/browser.adoc index a73c8b5..06a7b55 100644 --- a/doc/browser.adoc +++ b/doc/browser.adoc @@ -135,9 +135,9 @@ connection. * 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. -* 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. +* webcpp::document, with Boost.JSON's and Boost.Charconv's definitions, + which `/webcpp/trystero//trystero` brings through `/webcpp/document//document` + and which build on emscripten as on every target. [#trystero-browser-chat] === A page and its program diff --git a/doc/building.adoc b/doc/building.adoc index 91e6555..af24814 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -75,8 +75,8 @@ include::{library-root}/build.jam[tag=dependencies] A b2 project uses the rooms and the browser backend through `/webcpp/trystero//trystero`, which adds trystero's headers, Boost's, -webcpp::asio, libsecp256k1 and Boost.JSON's definitions, compiled once per -variant, and, on emscripten, webcpp::webrtc and embind: +webcpp::asio, libsecp256k1 and webcpp::document with Boost.JSON's and +Boost.Charconv's definitions, compiled once per variant, and, on emscripten, webcpp::webrtc and embind: [listing] ---- diff --git a/doc/design.adoc b/doc/design.adoc index 72d3c16..4ba968f 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -154,9 +154,10 @@ in them, over webcpp::webrtc: 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. Natively it carries `sdpMid` and an - `sdpMLineIndex` of 0, and no user name fragment, as libdatachannel gives - none. + 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 @@ -196,9 +197,15 @@ 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 into a document whose image is a buffer + of the room's or the app's resource, and read as views into it; each + caller bounds its text (<>). The JSON the room + writes goes field by field into one reserved buffer, its strings quoted by + `webcpp::document::quote`, `JSON.stringify`'s own quoting, 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. * 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. diff --git a/doc/differences.adoc b/doc/differences.adoc index e81a4f6..5ffe89b 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -108,6 +108,12 @@ These features of Trystero are not ported, each for its reason: | 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 NIP-01's, 64 lowercase hexadecimal digits; 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 of another form would let a relay 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 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 + | 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) |=== diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index 97f396e..704239e 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -45,8 +45,9 @@ 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. +sees only webcpp::document's working state while it reads or writes a JSON +text, each piece freed before that call returns, and the C library nothing. +_Held by_ `allocation`, natively and on emscripten. . [[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 diff --git a/doc/overview.adoc b/doc/overview.adoc index 0dd09fa..74327bb 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -25,7 +25,7 @@ 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; @@ -73,9 +73,9 @@ namespace `webcpp::trystero`. * A {cpp}20 compiler. * Boost 1.92: Asio, Circular Buffer, Container (its `pmr` base class), Core, - Endian, Hash2, JSON, System and Unordered; and Beast and URL for the native - backend. -* webcpp::asio, webcpp::webrtc for both backends' WebRTC, and webcpp::beast + Endian, Hash2, JSON (the parser webcpp::document uses), System and + Unordered; and Beast and URL for the native backend. +* webcpp::document for every JSON text, webcpp::asio, webcpp::webrtc for both backends' WebRTC, and webcpp::beast for the native backend's relays (<>). * https://github.com/bitcoin-core/secp256k1[libsecp256k1] 0.8.0, with its `schnorrsig` and `extrakeys` modules, for the BIP-340 signatures of Nostr diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 51862ef..bd1c99a 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -79,6 +79,41 @@ 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 `protocol::json::parse` into a `protocol::json::document`, whose image is a +buffer of the room's resource, or of the app's for a candidate, 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, 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 is at most twice the text and 64 KiB: 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 the parse has filled that bound. 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 has no bound of +its own but the room's `max_receive_bytes` and document's 64 MiB of image. + +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: 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`. + [#trystero-protocol-channel] === The data channel diff --git a/doc/usage.adoc b/doc/usage.adoc index ffe0753..6c0d972 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -195,13 +195,32 @@ 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 +| `trystero::pmr_document` | JSON | parsed into a buffer of the room's resource | `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, or a `pmr_document`, whose image is a buffer of a +memory resource, the room's when it is received. A text that does not parse +is not delivered. A C++ peer sends what `JSON.stringify` writes of the +document, the bytes Trystero JS sends of the same value: + +[source] +---- +namespace wd = webcpp::document; +auto drink = room.make_action("drink"); +drink.on_message([](const wd::document& d, const trystero::message_info&) { + std::cout << d["drink"].value_or(std::string_view()) << '\n'; +}); +if (auto d = wd::parse(R"({"drink":"negroni"})")) { + drink.async_send(std::move(*d), webcpp::asio::detached); +} +---- + 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 @@ -239,8 +258,8 @@ 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` +resource when it is a view, and written at once, as `JSON.stringify` +writes it, 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`. From d93bb51e6c81e59d734337025a618dbb618a31f1 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:29:50 -0300 Subject: [PATCH 049/116] trystero: an answerer's signal in Trystero's member order, and a signal naming peer ignored Trystero's answerer writes offerId after its answer or candidate, and its signal handler ignores a text with a member peer; both are oracle cases now. The expected results are written by the oracle's update-expected next. --- include/webcpp/trystero/detail/signaling.hpp | 2 ++ include/webcpp/trystero/protocol/signal.hpp | 20 +++++++++++++++++--- test/fixtures/cases/protocol.json | 8 ++++++-- test/oracle/oracle.mjs | 6 ++++-- test/protocol_test.cpp | 12 +++++++++++- 5 files changed, 40 insertions(+), 8 deletions(-) diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index 690a74a..a620353 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -738,6 +738,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; @@ -1013,6 +1014,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_)); } diff --git a/include/webcpp/trystero/protocol/signal.hpp b/include/webcpp/trystero/protocol/signal.hpp index 517c9dd..8d6cb0b 100644 --- a/include/webcpp/trystero/protocol/signal.hpp +++ b/include/webcpp/trystero/protocol/signal.hpp @@ -197,6 +197,12 @@ struct signal_message { * announces only once it has seen a peer that is not passive. */ bool passive = false; + /** + * Whether the sender answers the offer: 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. @@ -215,14 +221,17 @@ struct signal_message { * * @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, no peer id, or an + * @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 json::const_value& document) { - if (!document.is_object()) { + // 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; @@ -278,10 +287,15 @@ inline std::pmr::string write_signal( json::append_string(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/test/fixtures/cases/protocol.json b/test/fixtures/cases/protocol.json index 53d495b..a7b9125 100644 --- a/test/fixtures/cases/protocol.json +++ b/test/fixtures/cases/protocol.json @@ -54,7 +54,9 @@ {"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": "q\"\\\n", "answer": "
\u0000"}, + {"peerId": "a", "answer": "sealed \u007f", "offerId": "o"}, + {"peerId": "a", "candidate": "\u2028\u2029", "offerId": "o", "passive": true} ], "duplicate_keys": { "signals": [ @@ -68,7 +70,9 @@ "{\"peerId\":\"p\",\"passive\":true,\"passive\":false}", "{\"peerId\":\"p\",\"passive\":false,\"passive\":true}", "{\"peerId\":\"p\",\"peerId\":\"\"}", - "{\"peerId\":\"\",\"answer\":\"sealed\",\"peerId\":\"p\"}" + "{\"peerId\":\"\",\"answer\":\"sealed\",\"peerId\":\"p\"}", + "{\"peerId\":\"p\",\"peer\":\"x\",\"offer\":\"sealed\"}", + "{\"peerId\":\"p\",\"peer\":null,\"nonce\":\"n\"}" ], "events": { "app_id": "my-app", diff --git a/test/oracle/oracle.mjs b/test/oracle/oracle.mjs index c88f46d..6211ddf 100644 --- a/test/oracle/oracle.mjs +++ b/test/oracle/oracle.mjs @@ -217,8 +217,10 @@ out.actions = await captureActions() // 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), and an answer to an offer -// without an id {peerId, answer} (handleOffer); their strings hold the event messages' characters. +// 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 diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index ccb6e03..337a10c 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -540,9 +540,17 @@ void event_messages(const fixture_value& fixture) { // 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(), 5U); + 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"]), @@ -550,6 +558,8 @@ void signal_texts(const fixture_value& fixture) { .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); From 8366f9d54064bd3af1ab8caf4f1034b8217123d4 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:34:11 -0300 Subject: [PATCH 050/116] trystero: the oracle's results for the answerer's order and a signal naming peer Written by update-expected; the protocol test counts the two new signals read with keys written twice. --- test/fixtures/expected/expected.json | 25 +++++++++++++++++++++++++ test/protocol_test.cpp | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/test/fixtures/expected/expected.json b/test/fixtures/expected/expected.json index 014ed80..5262a99 100644 --- a/test/fixtures/expected/expected.json +++ b/test/fixtures/expected/expected.json @@ -455,6 +455,23 @@ "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": { @@ -531,6 +548,14 @@ "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", diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index 337a10c..ebf4cde 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -607,7 +607,7 @@ std::string answer_sender(std::string_view text, std::string_view root_topic) { // 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(), 11U); + 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()); From 54086391c0192e8b917cdf8efe2e32387472058c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:38:46 -0300 Subject: [PATCH 051/116] trystero: the backend's clocks are std::chrono's, steady_now and unix_now The seam between the room and a platform gave its clocks as a double of milliseconds (now_ms) and a std::int64_t of seconds (unix_seconds), which the core converted in detail/clock.hpp. backend::factory now returns them in the types the core keeps: steady_now() a std::chrono::steady_clock::time_point, from an origin of the backend's, and unix_now() a std::chrono::sys_seconds. Their names lose the unit their types now carry. detail::steady_now and detail::unix_now return the seam's values as they are, and from_backend_ms is gone. The platform backend returns the standard library's clocks unconverted, its window reading steady_now(). The memory backend's virtual clock, its keys, step and due_by are std::chrono too, and the tests compare the clock's durations exactly, as before. What a peer sees does not change: created_at and since are the same whole seconds. --- AGENTS.md | 29 +++++--- include/webcpp/trystero/backend.hpp | 15 +++-- include/webcpp/trystero/detail/clock.hpp | 19 ++---- include/webcpp/trystero/platform/backend.hpp | 20 +++--- test/memory_backend_test.cpp | 16 +++-- test/platform_backend_test.cpp | 22 +++--- test/room_test.cpp | 6 +- test/shared_test.cpp | 71 ++++++++++---------- test/support/memory_backend.hpp | 53 ++++++++------- test/support/rooms.hpp | 2 +- 10 files changed, 128 insertions(+), 125 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fa38a27..d0b697e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,13 +42,14 @@ holds only what is specific to trystero. 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` (`unix_seconds`) and - `std::chrono::steady_clock` (`now_ms`), 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 (the library never - tests `__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, + 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 (the library never tests `__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 `getentropy`, which Emscripten draws from `crypto.getRandomValues`. Without randomness @@ -70,7 +71,12 @@ holds only what is specific to trystero. 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. + 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 @@ -382,8 +388,11 @@ 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.** diff --git a/include/webcpp/trystero/backend.hpp b/include/webcpp/trystero/backend.hpp index c7e6090..719e7d8 100644 --- a/include/webcpp/trystero/backend.hpp +++ b/include/webcpp/trystero/backend.hpp @@ -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/detail/clock.hpp b/include/webcpp/trystero/detail/clock.hpp index e155f5f..6c2e70b 100644 --- a/include/webcpp/trystero/detail/clock.hpp +++ b/include/webcpp/trystero/detail/clock.hpp @@ -24,24 +24,15 @@ namespace webcpp::trystero::detail { */ using time_point = std::chrono::steady_clock::time_point; // lint-world: names a type only -/** - * A time of the backend's monotonic clock given in its milliseconds, as `backend::factory::now_ms` - * gives it, to the nearest tick of a @ref time_point. - */ -inline time_point from_backend_ms(double ms) { - return time_point( - std::chrono::round(std::chrono::duration(ms))); -} - -/** The time of the backend's monotonic clock, its `now_ms`, as a @ref time_point. */ +/** The time of the backend's monotonic clock, its `steady_now`. */ inline time_point steady_now(backend::factory& factory) { - return from_backend_ms(factory.now_ms()); + return factory.steady_now(); } -/** The time of the backend's wall clock, its `unix_seconds`, in whole seconds since the Unix - * epoch: what a Nostr event's `created_at` and a subscription's `since` say. */ +/** 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 std::chrono::sys_seconds(std::chrono::seconds(factory.unix_seconds())); + return factory.unix_now(); } } // namespace webcpp::trystero::detail diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index a53375a..6dc5052 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -10,7 +10,6 @@ #include #include -#include #include #include #include @@ -255,7 +254,7 @@ class backend : public trystero::backend::factory { std::shared_ptr make_peer_connection( std::span servers, std::pmr::memory_resource* memory) override { - if (!constructions_.take(trystero::detail::steady_now(*this))) { + if (!constructions_.take(steady_now())) { return nullptr; } auto made = webrtc::peer_connection::make(runtime_, ex_, servers, config_.bind_address, @@ -308,23 +307,22 @@ class backend : public trystero::backend::factory { } /** - * Seconds since the Unix epoch, from the system's wall clock, in a page `Date.now()`'s. + * The standard library's wall clock, in a page `Date.now()`'s, to the whole second below. * - * @return The current time, in whole seconds. + * @return The current time, in whole seconds since the Unix epoch. */ - std::int64_t unix_seconds() override { + 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.time_since_epoch()).count(); + return std::chrono::floor(now); } /** - * Milliseconds from the standard library's steady clock, in a page `performance.now()`'s. + * The standard library's steady clock, in a page `performance.now()`'s. * - * @return The current time, in milliseconds since the clock's epoch. + * @return The current time, from the steady 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(); + std::chrono::steady_clock::time_point steady_now() override { + return std::chrono::steady_clock::now(); // lint-world: Trystero's timing } private: diff --git a/test/memory_backend_test.cpp b/test/memory_backend_test.cpp index 598ade0..c2ba605 100644 --- a/test/memory_backend_test.cpp +++ b/test/memory_backend_test.cpp @@ -353,7 +353,7 @@ 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}; @@ -369,13 +369,15 @@ 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(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(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); @@ -392,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; }); @@ -400,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. */ @@ -480,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() { diff --git a/test/platform_backend_test.cpp b/test/platform_backend_test.cpp index 3dc415b..3610b14 100644 --- a/test/platform_backend_test.cpp +++ b/test/platform_backend_test.cpp @@ -11,7 +11,7 @@ // 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 a steady clock in milliseconds that a 20 ms wait moves forward. +// and the steady clock, which a 20 ms wait moves forward. // - Its randomness fills what it is given, differently each time. // - Its executor is the one it was given, and its relays' TLS context was made. // @@ -101,20 +101,18 @@ void its_own_state_is_in_its_memory() { void its_clocks_are_the_standard_librarys() { asio::io_context io; trystero::platform::backend backend(io.get_executor()); - const auto seconds = std::chrono::floor( - std::chrono::system_clock::now().time_since_epoch()) - .count(); - const std::int64_t read = backend.unix_seconds(); - BOOST_TEST_LE(seconds, read); - BOOST_TEST_LE(read, seconds + 1); - - const double start = backend.now_ms(); + 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.now_ms() - start; }); + 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_GE(*waited, 19.0); // a whole millisecond of the steady clock's rounding + BOOST_TEST(*waited >= 19ms); // a whole millisecond of the steady clock's rounding } } diff --git a/test/room_test.cpp b/test/room_test.cpp index 8ba209f..6472f1b 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -552,7 +552,7 @@ 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 @@ -577,8 +577,8 @@ 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)); + 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"); } diff --git a/test/shared_test.cpp b/test/shared_test.cpp index 979ee77..05ff61b 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -760,13 +760,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); } @@ -991,12 +991,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()); } }; }; @@ -1007,19 +1007,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, @@ -1042,13 +1041,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)); @@ -1062,12 +1061,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")); @@ -1077,8 +1076,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()); @@ -1086,13 +1085,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( @@ -1100,7 +1099,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); @@ -1155,7 +1154,7 @@ 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(); + 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); @@ -1166,7 +1165,7 @@ void binding_needs_the_peers_own_presence() { 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); + BOOST_TEST(t.f.net.steady_now() - joined == 21s); BOOST_TEST(!offer_or_answer); } @@ -1196,14 +1195,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 @@ -1264,18 +1263,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 = {}; @@ -1285,7 +1284,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); } @@ -1375,7 +1374,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, [&] { @@ -1383,7 +1382,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; })); } @@ -1521,12 +1520,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); } diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index a4b50d8..97cad51 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -75,10 +75,10 @@ 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 platform backend's: a wait cancelled, replaced or destroyed never fires, @@ -109,8 +109,7 @@ 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; @@ -735,17 +734,21 @@ class memory_network : public backend::factory { } } - 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, `time_scale` times + * faster; 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_) * + time_scale); } std::shared_ptr find(std::size_t id) { @@ -810,8 +813,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; @@ -823,9 +826,9 @@ 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; @@ -844,8 +847,8 @@ class memory_network : public backend::factory { /** 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; webcpp::asio::io_context& io_; std::mt19937_64 random_; @@ -1095,8 +1098,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() { @@ -1113,7 +1116,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(); @@ -1121,14 +1124,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(); @@ -1136,7 +1139,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()) { diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp index 5f3704a..66dac4b 100644 --- a/test/support/rooms.hpp +++ b/test/support/rooms.hpp @@ -110,7 +110,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"); From a0cfac5ed745213448f00b47d34511f36e02b950 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:44:33 -0300 Subject: [PATCH 052/116] trystero: the guide shows a JSON payload from the room test, and builds The usage page includes the room test's send, receive and read of a document by tag; a brief is one sentence; no C++ or libc++ in prose, and no code span followed by an apostrophe. --- doc/allocation.adoc | 2 +- doc/design.adoc | 4 +-- doc/usage.adoc | 28 +++++++++++++-------- include/webcpp/trystero/protocol/signal.hpp | 8 +++--- test/room_test.cpp | 13 +++++++--- 5 files changed, 36 insertions(+), 19 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 7910cc7..c6118c3 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -233,7 +233,7 @@ allocator: Boost.JSON's parser stack, the path and the pending key and text of the value being read, the tree's record of each change, which places a value, and the writer's stack. Each is freed before the parse or the write that made it returns, so none is left at any moment the room's executor is -between handlers. Measured natively with libc++, each text a room reads +between handlers. Measured natively with the LLVM standard library, each text a room reads costs `operator new` about seven allocations a value: a relay's event carrying an offer, 1,581 bytes and 14 values, 93; a relay's `OK`, 5 values, 32; a signal, 4 values, 26; a handshake message, 3 values, 20; a candidate, diff --git a/doc/design.adoc b/doc/design.adoc index c72b338..4765a8d 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -214,8 +214,8 @@ key, a member, a capture of a handler that runs later. of the room's or the app's resource, and read as views into it; each caller bounds its text (<>). The JSON the room writes goes field by field into one reserved buffer, its strings quoted by - `webcpp::document::quote`, `JSON.stringify`'s own quoting, and a Nostr - event's id is hashed over those same bytes. Building each text as a + `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. * A frame is written once, inside its room envelope, and shared by every diff --git a/doc/usage.adoc b/doc/usage.adoc index 3d75d80..1ab566a 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -206,19 +206,27 @@ messages travel and how they are received: A JSON payload is webcpp::document's: a `webcpp::document::document` the program builds or parses, or a `pmr_document`, whose image is a buffer of a memory resource, the room's when it is received. A text that does not parse -is not delivered. A C++ peer sends what `JSON.stringify` writes of the -document, the bytes Trystero JS sends of the same value: +is not delivered. A {cpp} peer sends what `JSON.stringify` writes of the +document, the bytes Trystero JS sends of the same value. The room test sends +one: [source] ---- -namespace wd = webcpp::document; -auto drink = room.make_action("drink"); -drink.on_message([](const wd::document& d, const trystero::message_info&) { - std::cout << d["drink"].value_or(std::string_view()) << '\n'; -}); -if (auto d = wd::parse(R"({"drink":"negroni"})")) { - drink.async_send(std::move(*d), webcpp::asio::detached); -} +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. diff --git a/include/webcpp/trystero/protocol/signal.hpp b/include/webcpp/trystero/protocol/signal.hpp index 8d6cb0b..439aba0 100644 --- a/include/webcpp/trystero/protocol/signal.hpp +++ b/include/webcpp/trystero/protocol/signal.hpp @@ -198,9 +198,11 @@ struct signal_message { */ bool passive = false; /** - * Whether the sender answers the offer: 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. + * 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; diff --git a/test/room_test.cpp b/test/room_test.cpp index 15697dc..255cd76 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -115,8 +115,10 @@ void two_peers_join_and_exchange_every_payload_format() { 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( [&](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; })); @@ -129,9 +131,12 @@ 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( - document_of(R"({"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); }); @@ -149,7 +154,9 @@ void two_peers_join_and_exchange_every_payload_format() { 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() { From 33bc65ee4bfcdce98bddfd8e883ae05a8c3ad099 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:47:07 -0300 Subject: [PATCH 053/116] trystero: the backend tests count in std::size_t and read the page in fixed-width types Chapter 4 keeps plain int for an interface that asks for it. The timer test and the platform tests counted firings, closes, messages and calls, and looped, in plain int: they count in std::size_t now, a frame's first byte is a std::uint8_t, the page's number a std::int32_t and its counters a std::uint32_t read through embind, and the page's census a std::size_t. What stays int is POSIX's and OpenSSL's: an error_code's value and the SNI callback's signature. --- test/platform_page_call_test.cpp | 15 +++--- test/platform_page_data_channel_test.cpp | 4 +- test/platform_page_peer_connection_test.cpp | 6 +-- test/platform_page_test.cpp | 11 ++-- test/platform_page_websocket_bound_test.cpp | 11 ++-- ...atform_page_websocket_late_events_test.cpp | 17 +++--- test/platform_peer_connection_test.cpp | 20 +++---- test/platform_websocket_test.cpp | 54 ++++++++++--------- test/platform_websocket_unreachable_test.cpp | 6 +-- test/timer_test.cpp | 22 ++++---- 10 files changed, 87 insertions(+), 79 deletions(-) diff --git a/test/platform_page_call_test.cpp b/test/platform_page_call_test.cpp index 83d76c4..7880d38 100644 --- a/test/platform_page_call_test.cpp +++ b/test/platform_page_call_test.cpp @@ -33,6 +33,7 @@ #include #include +#include #include #include @@ -82,10 +83,10 @@ struct program { asio::executor_work_guard guard{io.get_executor()}; std::optional doomed; std::optional next; - int stage = 0; - int seen_n = 0; - int doomed_calls = 0; - int orphan_calls = 0; + 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; }; @@ -113,7 +114,7 @@ void outlive_the_io_context(program& p) { BOOST_TEST(kept(2).isUndefined()); orphan.reset(); BOOST_TEST_EQ(memory.outstanding, 0U); - BOOST_TEST_EQ(p.orphan_calls, 0); + BOOST_TEST_EQ(p.orphan_calls, 0U); } /** @@ -125,7 +126,7 @@ void advance(program& p, const val& argument) { // The page's value is checked before it is read, as a page_call's handler does. if (!argument.isNull() && !argument.isUndefined()) { const val n = argument["n"]; - p.seen_n = n.isNumber() ? n.as() : -1; + p.seen_n = n.isNumber() ? n.as() : -1; } p.doomed.reset(); // The page calls the function it kept, then the next. @@ -141,7 +142,7 @@ void advance(program& p, const val& argument) { } BOOST_TEST_EQ(p.seen_n, 2); BOOST_TEST(val::global("keptReturned").isUndefined()); - BOOST_TEST_EQ(p.doomed_calls, 0); + BOOST_TEST_EQ(p.doomed_calls, 0U); outlive_the_io_context(p); p.judged = true; p.guard.reset(); diff --git a/test/platform_page_data_channel_test.cpp b/test/platform_page_data_channel_test.cpp index 33bb32c..b413cce 100644 --- a/test/platform_page_data_channel_test.cpp +++ b/test/platform_page_data_channel_test.cpp @@ -67,7 +67,7 @@ struct state { trystero::platform::backend backend{io.get_executor()}; std::shared_ptr connection; std::shared_ptr wrapper; - int messages = 0; + std::size_t messages = 0; std::size_t last_size = 0; }; @@ -132,7 +132,7 @@ int main() { 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, 1); + 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_peer_connection_test.cpp b/test/platform_page_peer_connection_test.cpp index 0132cb0..488c22d 100644 --- a/test/platform_page_peer_connection_test.cpp +++ b/test/platform_page_peer_connection_test.cpp @@ -63,10 +63,10 @@ struct state { }; /** The connections webcpp::webrtc's census of the page counts. */ -double held() { +std::size_t held() { const val census = val::global( "globalThis")[val::global("Symbol").call("for", val("webcpp.webrtc.census"))]; - return census.isUndefined() ? 0 : census["held"].as(); + return census.isUndefined() ? 0 : static_cast(census["held"].as()); } /** Runs node's garbage collector, exposed for this test. */ @@ -165,7 +165,7 @@ int main() { pc->close(); } } - BOOST_TEST_EQ(held(), static_cast(budget)); + 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 diff --git a/test/platform_page_test.cpp b/test/platform_page_test.cpp index e9008af..c68710c 100644 --- a/test/platform_page_test.cpp +++ b/test/platform_page_test.cpp @@ -46,6 +46,7 @@ #include #include +#include #include #include #include @@ -72,10 +73,10 @@ struct page { std::optional> chat_z; bool ran_inside_a_call = false; bool joined = false; - int met = 0; + std::size_t met = 0; std::vector received; - int ignored = 0; - int late = 0; + 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. */ @@ -171,8 +172,8 @@ int main() { 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, 2); + BOOST_TEST_EQ(p.ignored, 2U); BOOST_TEST(!p.ran_inside_a_call); - BOOST_TEST_EQ(p.late, 0); + 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 index 62df506..17370a3 100644 --- a/test/platform_page_websocket_bound_test.cpp +++ b/test/platform_page_websocket_bound_test.cpp @@ -30,6 +30,7 @@ #include #include +#include #include #include #include @@ -75,7 +76,7 @@ EM_JS(void, install_stalled_websocket, (), { namespace { -constexpr int texts = 100; +constexpr std::size_t texts = 100; struct state { asio::io_context io; @@ -83,8 +84,8 @@ struct state { trystero::platform::backend backend{io.get_executor()}; std::shared_ptr socket; const std::string text = std::string(std::size_t{64} * 1024, 't'); - int sending = 0; - int closes = 0; + std::size_t sending = 0; + std::size_t closes = 0; bool in_send = false; bool sent = false; bool judged = false; @@ -98,9 +99,9 @@ void verdict(state& s) { if (!s.sent || s.closes == 0) { return; } - BOOST_TEST_EQ(s.closes, 1); + BOOST_TEST_EQ(s.closes, 1U); BOOST_TEST_LE(held(), trystero::protocol::max_queued_relay_bytes); - BOOST_TEST_GE(val::global("stalledCloses").as(), 1); + BOOST_TEST_GE(val::global("stalledCloses").as(), 1U); s.socket.reset(); s.judged = true; s.guard.reset(); diff --git a/test/platform_page_websocket_late_events_test.cpp b/test/platform_page_websocket_late_events_test.cpp index d9536b7..e2ae36d 100644 --- a/test/platform_page_websocket_late_events_test.cpp +++ b/test/platform_page_websocket_late_events_test.cpp @@ -35,6 +35,7 @@ #include #include +#include #include #include #include @@ -92,17 +93,17 @@ struct state { trystero::platform::backend backend{io.get_executor()}; std::shared_ptr stalled; std::shared_ptr big; - int stalled_closes = 0; - int messages_after_close = 0; - int big_closes = 0; + 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, 1); - BOOST_TEST_EQ(s.messages_after_close, 0); - BOOST_TEST_EQ(s.big_closes, 1); - BOOST_TEST_EQ(val::global("lateCloses").as(), 2); + 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; @@ -132,7 +133,7 @@ int main() { .open = [&s] { const std::string text(std::size_t{64} * 1024, 't'); - for (int i = 0; i < 100; ++i) { + for (std::size_t i = 0; i < 100; ++i) { s.stalled->send(text); } }, diff --git a/test/platform_peer_connection_test.cpp b/test/platform_peer_connection_test.cpp index 7c0454b..88a1303 100644 --- a/test/platform_peer_connection_test.cpp +++ b/test/platform_peer_connection_test.cpp @@ -27,6 +27,8 @@ #include #include +#include +#include #include #include #include @@ -84,7 +86,7 @@ struct pair { std::vector at_offerer, at_answerer; bool offer_open = false, answer_open = false, off_thread = false; std::vector answerer_states; - int answer_closes = 0; + std::size_t answer_closes = 0; /** What makes the offerer's executor of the io_context's. */ using executor_wrapper = std::function; @@ -174,7 +176,7 @@ struct pair { } void watch(const std::shared_ptr& channel, bool& open, - std::vector& received, int* closes) { + std::vector& received, std::size_t* closes) { channel->set_handlers({ .open = [this, &open] { @@ -394,7 +396,7 @@ void a_full_pending_queue_drains_in_order_and_uses_replacement_handlers() { p.answer_end->send(backend::bytes{i}); } p.receive(64); - std::vector received; + 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}); @@ -424,7 +426,7 @@ void a_full_pending_queue_drains_in_order_and_uses_replacement_handlers() { 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)); + 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({}); @@ -437,7 +439,7 @@ void a_full_pending_queue_drains_in_order_and_uses_replacement_handlers() { .buffered_amount_low = {}, }); require(BOOST_TEST(p.until([&] { return received.size() == 66; }))); - BOOST_TEST_EQ(received.back(), 65); + BOOST_TEST_EQ(received.back(), 65U); } void a_pending_queue_overflow_closes_the_channel() { @@ -483,7 +485,7 @@ void a_receiver_can_close_and_destroy_its_channel_during_pending_delivery() { p.answer_end->send(backend::bytes{1}); p.answer_end->send(backend::bytes{2}); p.receive(2); - int received = 0; + std::size_t received = 0; p.offer_end->set_handlers({ .open = {}, .message = @@ -496,7 +498,7 @@ void a_receiver_can_close_and_destroy_its_channel_during_pending_delivery() { .buffered_amount_low = {}, }); require(BOOST_TEST(p.until([&] { return p.answer_closes == 1; }))); - BOOST_TEST_EQ(received, 1); + BOOST_TEST_EQ(received, 1U); } class pending_memory : public std::pmr::memory_resource { @@ -543,7 +545,7 @@ void pending_frames_and_delivery_use_the_channels_resource() { p.open(); 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) { + for (std::size_t i = 0; i < 64; ++i) { p.answer_end->send(backend::bytes(1024, static_cast(i))); } p.receive(64); @@ -599,7 +601,7 @@ void the_backend_makes_at_most_its_budget_in_a_minute() { 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) { + 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); } diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp index 56e915a..36279d6 100644 --- a/test/platform_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -30,6 +30,7 @@ #include #include +#include #include #include #include @@ -211,7 +212,7 @@ struct tls_echo_server { 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 int failed_handshakes = 0; + mutable std::size_t failed_handshakes = 0; }; /** What a hostile relay does once it reads a client's first message. */ @@ -493,7 +494,7 @@ void a_relay_at_an_ipv6_address_opens() { const echo_server server(io); asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + std::size_t closes = 0; std::vector received; const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, @@ -513,13 +514,13 @@ void a_relay_at_an_ipv6_address_opens() { } socket->send("over IPv6"); BOOST_TEST(run_until(io, [&] { return received.size() == 1; })); - BOOST_TEST_EQ(closes, 0); + BOOST_TEST_EQ(closes, 0U); } // What a socket reported, recorded by the handlers record() makes. struct reports { bool opened = false; - int closes = 0; + std::size_t closes = 0; std::vector received; trystero::backend::websocket::handlers record() { @@ -574,8 +575,8 @@ void a_relay_over_tls_opens_and_is_sent_its_name() { } socket->send("over TLS"); BOOST_TEST(run_until(io, [&] { return seen.received.size() == 1; })); - BOOST_TEST_EQ(seen.closes, 0); - BOOST_TEST_EQ(server.failed_handshakes, 0); + 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()); @@ -741,7 +742,7 @@ void opens_sends_in_order_receives_and_closes_once() { const echo_server server(io); asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + std::size_t closes = 0; std::vector received; const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), @@ -766,7 +767,7 @@ void opens_sends_in_order_receives_and_closes_once() { BOOST_TEST(run_until(io, [&] { return closes == 1; })); socket->close(); run_until(io, [] { return false; }, 100ms); - BOOST_TEST_EQ(closes, 1); + BOOST_TEST_EQ(closes, 1U); } // A message longer than any relay's (protocol::max_relay_message_bytes) is never handed over: the @@ -776,7 +777,7 @@ void a_message_longer_than_a_relay_sends_closes_the_socket() { const echo_server server(io); asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + std::size_t closes = 0; std::vector received; const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), @@ -806,7 +807,7 @@ void an_unreachable_relay_closes_without_opening() { taken.close(); // nothing listens there now asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + 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), { @@ -832,14 +833,14 @@ void a_relay_at_an_ipv4_shorthand_closes_without_opening() { 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, 1); + 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); - int events = 0; + std::size_t events = 0; { const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), @@ -851,7 +852,7 @@ void a_dropped_socket_reports_nothing() { std::pmr::get_default_resource()); } run_until(io, [] { return false; }, 200ms); - BOOST_TEST_EQ(events, 0); + BOOST_TEST_EQ(events, 0U); } void closing_right_after_a_send_lets_the_write_finish_first() { @@ -859,7 +860,7 @@ void closing_right_after_a_send_lets_the_write_finish_first() { const echo_server server(io); asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + std::size_t closes = 0; const auto socket = trystero::platform::connect_websocket(io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, @@ -883,22 +884,23 @@ void closing_right_after_a_send_lets_the_write_finish_first() { // 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; + 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 (int i = 0; i < connections; ++i) { + for (std::size_t i = 0; i < connections; ++i) { bool opened = false; - int closes = 0; + std::size_t closes = 0; std::shared_ptr socket; socket = trystero::platform::connect_websocket(io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; - for (int t = 0; t < texts; ++t) { + for (std::size_t t = 0; + t < texts; ++t) { socket->send(text); } }, @@ -912,7 +914,7 @@ void a_connection_that_ends_during_a_write_closes_once(misbehaviour what) { 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); + BOOST_TEST_EQ(closes, 1U); } } @@ -924,7 +926,7 @@ void a_relay_that_stops_reading_is_dropped_at_the_queue_bound() { const stalled_server server(io); asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + std::size_t closes = 0; const auto socket = trystero::platform::connect_websocket(io.get_executor(), &tls, server.url(), { .open = [&] { opened = true; }, @@ -936,13 +938,13 @@ void a_relay_that_stops_reading_is_dropped_at_the_queue_bound() { return; } const std::string text(std::size_t{64} * 1024, 't'); - for (int i = 0; i < 2000 && closes == 0; ++i) { + 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, 1); + BOOST_TEST_EQ(closes, 1U); } // A relay that stops answering while the room has nothing to send: a keep-alive ping goes @@ -952,7 +954,7 @@ void a_relay_that_stops_answering_times_out() { const stalled_server server(io); asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + std::size_t closes = 0; const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), { @@ -978,7 +980,7 @@ void a_quiet_relay_that_answers_pings_stays_connected() { const echo_server server(io); asio::ssl::context tls(asio::ssl::context::tls_client); bool opened = false; - int closes = 0; + std::size_t closes = 0; std::vector received; const auto socket = trystero::platform::connect_websocket( io.get_executor(), &tls, server.url(), @@ -996,7 +998,7 @@ void a_quiet_relay_that_answers_pings_stays_connected() { return; } run_until(io, [&] { return closes != 0; }, 3s); // three idle timeouts - BOOST_TEST_EQ(closes, 0); + BOOST_TEST_EQ(closes, 0U); socket->send("still there"); BOOST_TEST(run_until(io, [&] { return received.size() == 1; })); } diff --git a/test/platform_websocket_unreachable_test.cpp b/test/platform_websocket_unreachable_test.cpp index 7804251..f6d1844 100644 --- a/test/platform_websocket_unreachable_test.cpp +++ b/test/platform_websocket_unreachable_test.cpp @@ -57,7 +57,7 @@ struct state { trystero::platform::backend backend{io.get_executor()}; asio::steady_timer settle{io}; std::array, urls.size()> sockets; - std::array closes{}; + std::array closes{}; std::size_t total = 0; bool judged = false; }; @@ -72,7 +72,7 @@ void closed(state& s, std::size_t i) { 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), 1); + BOOST_TEST_EQ(s.closes.at(j), 1U); } s.sockets = {}; // destroyed after the close: nothing more is reported s.judged = true; @@ -92,7 +92,7 @@ void connect_all(state& s) { 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 + BOOST_TEST_EQ(s.closes.at(i), 0U); // not inside the call } } diff --git a/test/timer_test.cpp b/test/timer_test.cpp index 66e6dde..98c007a 100644 --- a/test/timer_test.cpp +++ b/test/timer_test.cpp @@ -66,7 +66,7 @@ std::shared_ptr make_timer(asio::io_context& io, */ template void both_expired(asio::io_context& io, trystero::detail::timer& first, - trystero::detail::timer& second, int& second_fired, Then then) { + 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 @@ -78,10 +78,10 @@ void an_uncancelled_wait_fires_once() { counting_resource memory; const auto timer = make_timer(io, &memory); const std::size_t made = memory.allocations; - int fired = 0; + std::size_t fired = 0; timer->start(1ms, [&] { ++fired; }); io.run_for(100ms); // lint-run: the wait expires - BOOST_TEST_EQ(fired, 1); + 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 @@ -92,9 +92,9 @@ void a_cancelled_wait_never_fires() { 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); - int fired = 0; + std::size_t fired = 0; both_expired(io, *first, *second, fired, [&] { second->cancel(); }); - BOOST_TEST_EQ(fired, 0); + BOOST_TEST_EQ(fired, 0U); } void a_destroyed_timer_never_fires() { @@ -102,9 +102,9 @@ void a_destroyed_timer_never_fires() { std::pmr::memory_resource* const memory = std::pmr::get_default_resource(); const auto first = make_timer(io, memory); auto second = make_timer(io, memory); - int fired = 0; + std::size_t fired = 0; both_expired(io, *first, *second, fired, [&] { second.reset(); }); - BOOST_TEST_EQ(fired, 0); + BOOST_TEST_EQ(fired, 0U); } void a_restarted_timer_fires_only_its_new_wait() { @@ -112,12 +112,12 @@ void a_restarted_timer_fires_only_its_new_wait() { 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); - int fired = 0; - int restarted = 0; + 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, 0); - BOOST_TEST_EQ(restarted, 1); + BOOST_TEST_EQ(fired, 0U); + BOOST_TEST_EQ(restarted, 1U); } } // namespace From 1dad17602390266882e585c4e80bdb4a5b1e0fb0 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:47:20 -0300 Subject: [PATCH 054/116] trystero: six more difference programs and their twins --- example/diff_passwords.cpp | 99 ++++++++++ example/diff_passwords.expected | 3 + example/diff_peers.cpp | 72 +++++++ example/diff_peers.expected | 2 + example/diff_relay_config.cpp | 184 ++++++++++++++++++ example/diff_relay_config.expected | 4 + example/diff_rooms_per_app.cpp | 69 +++++++ example/diff_rooms_per_app.expected | 4 + example/diff_self_id.cpp | 104 ++++++++++ example/diff_self_id.expected | 2 + example/diff_send_to_absent_peer.cpp | 53 +++++ example/diff_send_to_absent_peer.expected | 1 + test/oracle/twins/diff_passwords.expected | 3 + test/oracle/twins/diff_passwords.mjs | 37 ++++ test/oracle/twins/diff_peers.expected | 2 + test/oracle/twins/diff_peers.mjs | 33 ++++ test/oracle/twins/diff_relay_config.expected | 4 + test/oracle/twins/diff_relay_config.mjs | 58 ++++++ test/oracle/twins/diff_rooms_per_app.expected | 4 + test/oracle/twins/diff_rooms_per_app.mjs | 29 +++ test/oracle/twins/diff_self_id.expected | 2 + test/oracle/twins/diff_self_id.mjs | 39 ++++ .../twins/diff_send_to_absent_peer.expected | 1 + .../oracle/twins/diff_send_to_absent_peer.mjs | 19 ++ 24 files changed, 828 insertions(+) create mode 100644 example/diff_passwords.cpp create mode 100644 example/diff_passwords.expected create mode 100644 example/diff_peers.cpp create mode 100644 example/diff_peers.expected create mode 100644 example/diff_relay_config.cpp create mode 100644 example/diff_relay_config.expected create mode 100644 example/diff_rooms_per_app.cpp create mode 100644 example/diff_rooms_per_app.expected create mode 100644 example/diff_self_id.cpp create mode 100644 example/diff_self_id.expected create mode 100644 example/diff_send_to_absent_peer.cpp create mode 100644 example/diff_send_to_absent_peer.expected create mode 100644 test/oracle/twins/diff_passwords.expected create mode 100644 test/oracle/twins/diff_passwords.mjs create mode 100644 test/oracle/twins/diff_peers.expected create mode 100644 test/oracle/twins/diff_peers.mjs create mode 100644 test/oracle/twins/diff_relay_config.expected create mode 100644 test/oracle/twins/diff_relay_config.mjs create mode 100644 test/oracle/twins/diff_rooms_per_app.expected create mode 100644 test/oracle/twins/diff_rooms_per_app.mjs create mode 100644 test/oracle/twins/diff_self_id.expected create mode 100644 test/oracle/twins/diff_self_id.mjs create mode 100644 test/oracle/twins/diff_send_to_absent_peer.expected create mode 100644 test/oracle/twins/diff_send_to_absent_peer.mjs diff --git a/example/diff_passwords.cpp b/example/diff_passwords.cpp new file mode 100644 index 0000000..8a50415 --- /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::native::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_peers.cpp b/example/diff_peers.cpp new file mode 100644 index 0000000..9b6a457 --- /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::native::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..d0f0b13 --- /dev/null +++ b/example/diff_relay_config.cpp @@ -0,0 +1,184 @@ +// 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 native 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::int64_t unix_seconds() override { return backend_.unix_seconds(); } + + double now_ms() override { return backend_.now_ms(); } + +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::native::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 native 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_rooms_per_app.cpp b/example/diff_rooms_per_app.cpp new file mode 100644 index 0000000..8fb6de3 --- /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::native::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..bb3add7 --- /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::native::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_send_to_absent_peer.cpp b/example/diff_send_to_absent_peer.cpp new file mode 100644 index 0000000..b4ea436 --- /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::native::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/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_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_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() From fd748dfb39e60d9a2fb43260ad30f8fe394e784d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:47:50 -0300 Subject: [PATCH 055/116] trystero: the allocation test chooses its target by config's macro, and its select() to clang-tidy test/allocation_test.cpp tested __EMSCRIPTEN__, the compiler's macro, where the library chooses its code by WEBCPP_TARGET_EMSCRIPTEN, config's: it tests config's now, and neither the library nor its tests name the compiler's. The lint analyses the test natively only, so its Emscripten-only select() was never analysed: with Emscripten's flags, exceptions on and off, the pinned clang-tidy reported eleven findings there (cognitive complexity 45, bugprone-signed-bitwise six times, misc-const-correctness, a pollfd without designated initializers, and two missing parentheses). It is now platform_page_sealer_allocation's and webcpp::asio's, a set's requested and ready events in helpers, and clean. Both replacements keep their event masks in std::uint32_t, their index in std::size_t and the flag JavaScript writes in std::uint8_t; the allocation test runs its io_context for a std::chrono::milliseconds, in slices of 10 ms. --- AGENTS.md | 8 +- test/allocation_test.cpp | 113 ++++++++++-------- test/platform_page_sealer_allocation_test.cpp | 21 ++-- 3 files changed, 79 insertions(+), 63 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d0b697e..ed938d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,10 +46,10 @@ holds only what is specific to trystero. (`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 (the library never tests `__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, + 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 `getentropy`, which Emscripten draws from `crypto.getRandomValues`. Without randomness diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 0dd857e..fc9464a 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -45,7 +45,7 @@ #else #include #endif -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN #include #include #include @@ -55,6 +55,7 @@ #endif namespace trystero = webcpp::trystero; +using namespace std::chrono_literals; namespace { @@ -75,13 +76,13 @@ bool counting = false; // counts nothing: that allocation is operator new's, counted once. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool inside_operator_new = false; -#ifdef __EMSCRIPTEN__ +#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) -unsigned char inside_runtime = 0; +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; @@ -131,7 +132,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" { @@ -158,7 +159,7 @@ namespace { void* counted(void* pointer) { if (on_counted_thread() && counting && !inside_operator_new) { -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN ++(inside_runtime != 0 ? runtime_allocations : c_allocations); #else ++c_allocations; @@ -205,60 +206,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; } @@ -412,12 +422,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(webcpp::asio::io_context& io, Predicate done) { - for (int slice = 0; slice < 500 && !done(); ++slice) { + 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(); } @@ -549,11 +562,11 @@ void exchange_allocates_through_the_rooms_resources(Make make) { c_allocations = 0; } -/** Runs io for about `milliseconds`, whatever happens. */ -void run_for(webcpp::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 } } @@ -564,7 +577,7 @@ void run_for(webcpp::asio::io_context& io, int milliseconds) { */ void warm(webcpp::asio::io_context& io) { std::vector> timers; - for (int i = 0; i < 256; ++i) { + 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*/) {}); } @@ -572,7 +585,7 @@ void warm(webcpp::asio::io_context& io) { timer->cancel(); } webcpp::asio::post(io, [] {}); - run_for(io, 20); + run_for(io, 20ms); } // tag::config[] @@ -644,7 +657,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)); @@ -686,7 +699,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); @@ -780,7 +793,7 @@ void rooms_of_one_app_allocate_through_their_resources() { 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; } @@ -838,7 +851,7 @@ namespace { * apart, since a suspension of webcpp::asio's run family makes one, which is no room's. */ void mark_the_runtime_allocations() { -#ifdef __EMSCRIPTEN__ +#ifdef WEBCPP_TARGET_EMSCRIPTEN // clang-format off EM_ASM({ if (typeof Asyncify !== 'object' || typeof Asyncify.allocateData !== 'function') { @@ -866,7 +879,7 @@ 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(); diff --git a/test/platform_page_sealer_allocation_test.cpp b/test/platform_page_sealer_allocation_test.cpp index 45900d1..a71f75f 100644 --- a/test/platform_page_sealer_allocation_test.cpp +++ b/test/platform_page_sealer_allocation_test.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -67,7 +68,7 @@ bool counting = false; // 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) -unsigned char inside_runtime = 0; +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; @@ -124,7 +125,8 @@ int posix_memalign(void** out, std::size_t alignment, std::size_t size) { // sees the sealer's allocations. namespace { -unsigned requested_event(int fd, const fd_set* set, unsigned event) { +/** 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; } @@ -134,8 +136,9 @@ void clear_set(fd_set* set) { } } -int ready_event(const pollfd& descriptor, fd_set* set, unsigned events) { - if (set != nullptr && (static_cast(descriptor.revents) & events) != 0) { +/** 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; } @@ -153,11 +156,11 @@ extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* excep return -1; } std::array fds{}; - int n = 0; + std::size_t n = 0; for (int fd = 0; fd < nfds; ++fd) { - const unsigned events = requested_event(fd, readfds, POLLIN) | - requested_event(fd, writefds, POLLOUT) | - requested_event(fd, exceptfds, POLLPRI); + 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}; } @@ -173,7 +176,7 @@ extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* excep clear_set(writefds); clear_set(exceptfds); int count = 0; - for (int i = 0; i < n && ready > 0; ++i) { + 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); From c82e45614ddcff365464ceac2c336c8d76d73d24 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:47:50 -0300 Subject: [PATCH 056/116] trystero: the platform's clocks say where a page reads them Their Doc Comments name Date.now() and performance.now() as what a page reads, without a code span followed by an apostrophe. --- include/webcpp/trystero/platform/backend.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index 6dc5052..c4cea9b 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -307,7 +307,7 @@ class backend : public trystero::backend::factory { } /** - * The standard library's wall clock, in a page `Date.now()`'s, to the whole second below. + * 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. */ @@ -317,7 +317,7 @@ class backend : public trystero::backend::factory { } /** - * The standard library's steady clock, in a page `performance.now()`'s. + * The standard library's steady clock, which a page reads from `performance.now()`. * * @return The current time, from the steady clock's epoch. */ From 02c3adfae00a142cf4494b027d87b1b6f66d815f Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:49:49 -0300 Subject: [PATCH 057/116] trystero: the allocation test counts its windows in std::size_t WP7's window loop counted in plain int, which chapter 4 keeps for an interface that asks for it; a count is a std::size_t. --- test/allocation_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 06f94c2..990080b 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -637,7 +637,7 @@ void exchange_allocates_through_the_rooms_resources(Make make, Cost cost) { // A window in which the relay carries a text, an announcement the rooms read, sees that // parse too; such a window is opened again, five times at most. bool quiet = false; - for (int window = 0; window < 5 && !quiet; ++window) { + for (std::size_t window = 0; window < 5 && !quiet; ++window) { Payload value = make(&a_memory); const std::size_t expected = cost(value, &z_memory); const std::size_t texts = relay_state.texts; From 58a41c78e2ec79621cc4ed1ad11bdde775dc6e81 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:50:53 -0300 Subject: [PATCH 058/116] trystero: the difference programs on the platform backend, in the lane relayed with the quick start --- example/Jamfile | 38 +++++++++---------- example/diff_already_joined.cpp | 4 +- example/diff_passwords.cpp | 4 +- example/diff_peer_join.cpp | 4 +- example/diff_peers.cpp | 4 +- example/diff_relay_config.cpp | 13 ++++--- example/diff_rooms_per_app.cpp | 4 +- example/diff_self_id.cpp | 4 +- example/diff_send_to_absent_peer.cpp | 4 +- ...{run_difference.mjs => run_over_relay.mjs} | 9 +++-- test/oracle/run_twin.mjs | 2 +- 11 files changed, 44 insertions(+), 46 deletions(-) rename example/{run_difference.mjs => run_over_relay.mjs} (86%) diff --git a/example/Jamfile b/example/Jamfile index f46e592..0ea68b5 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,27 +13,23 @@ import webcpp ; webcpp.targets native emscripten ; -# Each needs the public relays or a browser, so it is linked and never run. -# tag::native[] -webcpp.link native_quick_start : native_quick_start.cpp - : /webcpp/trystero//platform multi : native ; -# end::native[] -# tag::browser[] -webcpp.link quick_start : quick_start.cpp - : /webcpp/trystero//platform -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 of the appendix "Differences" (doc: #trystero-differences), each -# with its twin under test/oracle/twins/, run natively over a Nostr relay of -# their own on 127.0.0.1: run_difference.mjs starts it, gives the program its -# URL in TRYSTERO_RELAY_URL, and passes when the program prints its .expected. -# Node runs the relay with the packages test/oracle pins. -# tag::differences[] +# 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_passwords @@ -47,7 +43,7 @@ local differences = for local difference in $(differences) { webcpp.drive $(difference) : $(difference).cpp - : /webcpp/trystero//native multi : run_difference.mjs : : native ; + : /webcpp/trystero//platform multi : run_over_relay.mjs : : native ; } -webcpp.lane differences : $(differences) : native ; +webcpp.lane relayed : quick_start $(differences) : native ; # end::differences[] diff --git a/example/diff_already_joined.cpp b/example/diff_already_joined.cpp index 871c267..9a75c14 100644 --- a/example/diff_already_joined.cpp +++ b/example/diff_already_joined.cpp @@ -11,7 +11,7 @@ // environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. #include -#include +#include #include #include @@ -29,7 +29,7 @@ int main() { return 1; } boost::asio::io_context io; - trystero::native::backend backend(io.get_executor()); + trystero::platform::backend backend(io.get_executor()); // tag::example[] trystero::app app(io.get_executor(), backend, {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); diff --git a/example/diff_passwords.cpp b/example/diff_passwords.cpp index 8a50415..7c2fa3d 100644 --- a/example/diff_passwords.cpp +++ b/example/diff_passwords.cpp @@ -16,7 +16,7 @@ // start on 127.0.0.1. #include -#include +#include #include #include @@ -41,7 +41,7 @@ int main() { 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::native::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + 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"; diff --git a/example/diff_peer_join.cpp b/example/diff_peer_join.cpp index 6ce442b..57d5183 100644 --- a/example/diff_peer_join.cpp +++ b/example/diff_peer_join.cpp @@ -12,7 +12,7 @@ // TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. #include -#include +#include #include #include @@ -36,7 +36,7 @@ int main() { 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::native::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + 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"; diff --git a/example/diff_peers.cpp b/example/diff_peers.cpp index 9b6a457..71d9a77 100644 --- a/example/diff_peers.cpp +++ b/example/diff_peers.cpp @@ -12,7 +12,7 @@ // on 127.0.0.1. #include -#include +#include #include #include @@ -35,7 +35,7 @@ int main() { 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::native::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + 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"; diff --git a/example/diff_relay_config.cpp b/example/diff_relay_config.cpp index d0f0b13..53ce770 100644 --- a/example/diff_relay_config.cpp +++ b/example/diff_relay_config.cpp @@ -12,13 +12,13 @@ // 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 native 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. +// 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 @@ -107,7 +107,7 @@ int main() { 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::native::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + 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"}; @@ -130,7 +130,8 @@ int main() { 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 native one. + // 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. diff --git a/example/diff_rooms_per_app.cpp b/example/diff_rooms_per_app.cpp index 8fb6de3..7100524 100644 --- a/example/diff_rooms_per_app.cpp +++ b/example/diff_rooms_per_app.cpp @@ -12,7 +12,7 @@ // relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. #include -#include +#include #include #include @@ -35,7 +35,7 @@ int main() { return 1; } boost::asio::io_context io; - trystero::native::backend backend(io.get_executor()); + 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; diff --git a/example/diff_self_id.cpp b/example/diff_self_id.cpp index bb3add7..e7895d1 100644 --- a/example/diff_self_id.cpp +++ b/example/diff_self_id.cpp @@ -13,7 +13,7 @@ // whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. #include -#include +#include #include #include @@ -38,7 +38,7 @@ int main() { 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::native::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); + 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; diff --git a/example/diff_send_to_absent_peer.cpp b/example/diff_send_to_absent_peer.cpp index b4ea436..11f67b8 100644 --- a/example/diff_send_to_absent_peer.cpp +++ b/example/diff_send_to_absent_peer.cpp @@ -11,7 +11,7 @@ // environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. #include -#include +#include #include #include @@ -31,7 +31,7 @@ int main() { return 1; } boost::asio::io_context io; - trystero::native::backend backend(io.get_executor()); + 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"); diff --git a/example/run_difference.mjs b/example/run_over_relay.mjs similarity index 86% rename from example/run_difference.mjs rename to example/run_over_relay.mjs index 1fb6eb2..e0669a1 100644 --- a/example/run_difference.mjs +++ b/example/run_over_relay.mjs @@ -4,11 +4,12 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Runs one program of the appendix "Differences" 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 each diff_ that -// the Jamfile declares with webcpp.drive, which gives it the native program last: +// 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_difference.mjs +// 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 diff --git a/test/oracle/run_twin.mjs b/test/oracle/run_twin.mjs index b6a1354..79002e2 100644 --- a/test/oracle/run_twin.mjs +++ b/test/oracle/run_twin.mjs @@ -10,7 +10,7 @@ // 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_difference.mjs starts the program's relay). The run ends once the +// 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, From f583207dc1978089e827f4c7f24efa7dabaac41f Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 21:54:56 -0300 Subject: [PATCH 059/116] trystero: AGENTS.md says the rooms' JSON is webcpp::document's The core names /webcpp/document//document in place of Boost.JSON. The Allocation rules take the page's webcpp::document paragraph in place of json_resource and the rooms' JSON storage: a room's documents, the payload variant, pmr_document and webcpp::document::document among the payloads, document's working state outside the resource, and the proof's three exchanges, its case of each text a room reads and nothing live at a drain. The warm-up's sentence says what the page measures now. --- AGENTS.md | 121 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 75 insertions(+), 46 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fa38a27..6cf0f8c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,9 +122,10 @@ holds only what is specific to trystero. installation leaves trystero out unless `webcpp-require-external=on`. MSVC links its static `libsecp256k1.lib` with `SECP256K1_STATIC`. `/webcpp/trystero//trystero` (`build.jam`'s `tag::trystero[]`) is the - rooms alone, the core: its headers, Boost, Boost.JSON, config, - webcpp::asio and libsecp256k1; on no target does it bring webcpp::webrtc, - and the tests over the memory relays use it alone. + rooms alone, the core: its headers, Boost, webcpp::document + (`/webcpp/document//document`, with Boost.JSON's and Boost.Charconv's + definitions), config, webcpp::asio and libsecp256k1; 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, alternatives by `emscripten`, which a native program and a page's program both name. Its WebRTC is @@ -505,7 +506,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 @@ -532,8 +534,9 @@ holds only what is specific to trystero. - **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`, `boost::json::value` and - `bytes`), the user's choice of `std::allocator`: + `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` and `std::pmr::set`, and three Boost containers over @@ -611,31 +614,44 @@ 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** keeps a document's image in one buffer, and its + external storage leaves that buffer to its user: every value, strings + included, is allocated inside it by Boost.Interprocess's + `rbtree_best_fit` heap, with offsets for pointers. trystero gives each + text it reads such a buffer of the room's resource + (`protocol::json::document`, of the app's for a remote candidate), + sized for a text of a few values, twice the text and 4 KiB, and made + again twice as large when the parse fills it, up to the caller's bound + (`protocol::json::protocol_limits`: twice its text bound and 64 KiB). 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. What document's parser + and writer use while they work stays in the standard allocator: + Boost.JSON's parser stack, the path and the pending key and text of the + value being read, the tree's record of each change, which places a + value, and the writer's stack. Each is freed before the parse or the + write that made it returns, so none is left at any moment the room's + executor is between handlers (measured natively with the LLVM standard + library: about seven allocations a value for each text a room reads, + and 48 to write and read back a JSON payload of 7 values). - **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 `std::pmr` types are built in it, and `pmr_document` in a buffer of + it. `std::string`, `bytes`, `webcpp::document::document` and `payload` + stay as they are, with `std::allocator` or document's own + `operator new`: 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; a received `webcpp::document::document` is an image of its + own, from the global `operator new`, as document's owned documents are. + 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 @@ -644,8 +660,10 @@ holds only what is specific to trystero. - **Outside the resource**, stated on the page: libdatachannel's and 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; the JSON storage's counter, which Boost.JSON allocates with - `operator new` once per room; Asio's own once-per-context allocations + heap; webcpp::document's working state while it reads or writes a JSON + text (its parser's stack, path and pending text, its tree's record of + each change, its writer's stack), each piece freed before the call + returns; 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, which webcpp::webrtc's completions get, through `any_io_executor`; @@ -662,9 +680,9 @@ holds only what is specific to trystero. operations, read buffer and queued texts are in the room's resource and a message allocates nothing outside it (in a page the stream's own state is there too, made with `std::allocator_arg` and the room's allocator); - the payload - types `std::string`, `bytes` and `payload`, with `std::allocator`; on - Emscripten, the C library's `select()`, which Asio's reactor calls on + the payload types `std::string`, `bytes`, `webcpp::document::document` + and `payload`, with `std::allocator` or document's own `operator new`; + 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 @@ -681,26 +699,37 @@ 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 `pmr_document` in turn: for the first two + `operator new` sees nothing, for the document exactly what writing it + and reading its text back cost webcpp::document's working state, counted + apart beforehand on the same value, and nothing left; the C library + sees nothing, and the counting resources of the two configurations see + the rooms'. 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 in a + counting resource, which holds its image until the document goes, and + document's working state costs `operator new` at most 8 allocations a + value and 16 more, none left after the parse. 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 webcpp::document's working state alone, none + of it live at the drain, 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 webcpp::document's working + state, nothing live at the drain, 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 From 648331bcc5e38e980ddc0e9c8af0088c39d74463 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:07:32 -0300 Subject: [PATCH 060/116] trystero: WP7's JSON code to the pinned clang-tidy Once merged, the pinned clang-tidy (wasi-sdk's 23.1) reported, natively and with Emscripten's flags, exceptions on and off, what WP7's change brought: - protocol::json::append_value copied its handle once; it moves it on now, in place of a NOLINT that no longer covered the line clang-tidy names. - readability-trailing-comma takes parse_options{}, as an argument, for a list ending in a comma (room.hpp and the allocation test): it is value-initialized as parse_options() there. - memory_relay::receive reached a cognitive complexity of 27: the subscription a REQ's filter names is read by subscription_of. - In the allocation test, track and untrack, noexcept, called std::array::at, which may throw: their index is masked into the table, so they index it; values_in recurses as deep as a parsed document nests, said beside its NOLINT; a relay's state is read through a const reference; and the texts measured are designated, in a list ending in a comma. --- include/webcpp/trystero/protocol/json.hpp | 5 ++- include/webcpp/trystero/room.hpp | 2 +- test/allocation_test.cpp | 41 ++++++++++++----------- test/support/memory_backend.hpp | 36 +++++++++++--------- 4 files changed, 46 insertions(+), 38 deletions(-) diff --git a/include/webcpp/trystero/protocol/json.hpp b/include/webcpp/trystero/protocol/json.hpp index 3003ae9..aad2ac0 100644 --- a/include/webcpp/trystero/protocol/json.hpp +++ b/include/webcpp/trystero/protocol/json.hpp @@ -361,13 +361,12 @@ inline void append_string(std::pmr::string& out, std::string_view text) { * @param v The value; `undefined` writes nothing. */ template -// A handle is taken by value, as document passes every handle. -// NOLINTNEXTLINE(performance-unnecessary-value-param) +// 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( - v, [&out](std::string_view text) { out.append(text); }, 0, piece)); + std::move(v), [&out](std::string_view text) { out.append(text); }, 0, piece)); } /** diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 7b6b4a2..8b9774c 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -319,7 +319,7 @@ struct payload_traits { return std::nullopt; } auto v = - protocol::json::parse(as_text(m.payload()), webcpp::document::parse_options{}, memory); + protocol::json::parse(as_text(m.payload()), webcpp::document::parse_options(), memory); if (!v.has_value()) { return std::nullopt; } diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 990080b..d93d8a0 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -332,10 +332,10 @@ void track(void* pointer) noexcept { return; } std::size_t i = home_of(pointer); - while (live.at(i) != nullptr) { + while (live[i] != nullptr) { i = (i + 1) & (live_slots - 1); } - live.at(i) = pointer; + live[i] = pointer; ++live_count; } @@ -345,22 +345,22 @@ void untrack(const void* pointer) noexcept { return; } std::size_t i = home_of(pointer); - while (live.at(i) != pointer) { - if (live.at(i) == nullptr) { + while (live[i] != pointer) { + if (live[i] == nullptr) { return; } i = (i + 1) & (live_slots - 1); } - live.at(i) = nullptr; + 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.at(j) != nullptr; + 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.at(j)); + 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.at(i) = live.at(j); - live.at(j) = nullptr; + live[i] = live[j]; + live[j] = nullptr; i = j; } } @@ -577,7 +577,7 @@ std::size_t document_cost(const trystero::pmr_document& payload, global_allocations = 0; counting = true; tp::json::append_value(text, payload.root()); - const bool read = tp::json::parse(text, webcpp::document::parse_options{}, memory).has_value(); + const bool read = tp::json::parse(text, webcpp::document::parse_options(), memory).has_value(); counting = false; BOOST_TEST(read); BOOST_TEST_EQ(live_count, 0U); @@ -598,7 +598,7 @@ void exchange_allocates_through_the_rooms_resources(Make make, Cost cost) { // 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"; - trystero::test::memory_relay& relay_state = network.relay(relay); + const trystero::test::memory_relay& relay_state = network.relay(relay); trystero::app a_app(io.get_executor(), network, { .app_id = "allocation", @@ -667,6 +667,8 @@ void exchange_allocates_through_the_rooms_resources(Make make, Cost cost) { } /** How many values a document holds, its own included. */ +// Recursive as deep as the document nests, which its parse bounded. +// NOLINTNEXTLINE(misc-no-recursion) std::size_t values_in(const tp::json::const_value& v) { std::size_t n = 1; if (v.is_array()) { @@ -722,13 +724,14 @@ void reading_a_text_costs_the_heap_a_bounded_working_state() { std::size_t bound; }; - const std::array texts{{ - {"relay event", relayed, tp::nostr::max_parsed_relay_text_bytes}, - {"relay OK", ok, tp::nostr::max_parsed_relay_text_bytes}, - {"signal", signal, tp::max_parsed_signal_bytes}, - {"handshake", handshake, tp::max_handshake_bytes}, - {"candidate", candidate, tp::max_sealed_candidate_bytes}, - }}; + 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; @@ -1095,7 +1098,7 @@ int main() { [](std::pmr::memory_resource* memory) { auto made = tp::json::parse( R"({"drink":"a text that no small string holds","ice":[1,2.5,true,null]})", - webcpp::document::parse_options{}, memory); + webcpp::document::parse_options(), memory); webcpp::test::require(BOOST_TEST(made.has_value())); return std::move(made).unsafe_value(); }, diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index 772ca19..809948e 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -301,6 +301,26 @@ 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) { ++texts; @@ -317,23 +337,9 @@ inline void memory_relay::receive(const std::shared_ptr& from, } const std::string_view type = protocol::json::text_of(message.at(0)); if (type == "REQ" && message.size() >= 3) { - subscription s{ - .socket = from, - .kinds = std::pmr::set(memory_), - .topics = std::pmr::set>(memory_), - }; - const protocol::json::const_value filter = message.at(2); - 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)); - } subscriptions_.insert_or_assign( key{from.get(), std::pmr::string(protocol::json::text_of(message.at(1)), memory_)}, - std::move(s)); + subscription_of(from, message.at(2), memory_)); std::pmr::string eose(R"(["EOSE",)", from->memory()); protocol::json::append_value(eose, message.at(1)); eose += ']'; From 06806de216b526a99649875969efe0189d8965e5 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:08:21 -0300 Subject: [PATCH 061/116] trystero: steady_now's signature names its clock with lint-world The lint's world rule finds steady_clock wherever a library header names it: the platform backend's steady_now names it as its return type, which reaches no clock, and says so. --- include/webcpp/trystero/platform/backend.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index c4cea9b..86c5fc6 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -321,8 +321,8 @@ class backend : public trystero::backend::factory { * * @return The current time, from the steady clock's epoch. */ - std::chrono::steady_clock::time_point steady_now() override { - return std::chrono::steady_clock::now(); // lint-world: Trystero's timing + 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: From 41fe3936ab97963c4a8bd255c63783f37bf7c279 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:14:23 -0300 Subject: [PATCH 062/116] trystero: one quick start, two peers over a relay, with its agreeing twin --- AGENTS.md | 23 ++- README.md | 249 ++++++++++++++++++----------- doc/building.adoc | 66 ++++---- doc/quick-start.adoc | 94 ++++++----- doc/trystero.adoc | 9 +- example/chat/Jamfile | 4 + example/native_quick_start.cpp | 49 ------ example/quick_start.cpp | 155 ++++++++++-------- example/quick_start.expected | 2 + test/oracle/twins/quick_start.mjs | 42 +++++ test/oracle/twins/without-twin.txt | 4 +- 11 files changed, 408 insertions(+), 289 deletions(-) delete mode 100644 example/native_quick_start.cpp create mode 100644 example/quick_start.expected create mode 100644 test/oracle/twins/quick_start.mjs diff --git a/AGENTS.md b/AGENTS.md index fa38a27..a7b395f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,7 +96,7 @@ holds only what is specific to trystero. (`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 - (`quick_start-60-d-jspi.js`), and the suites run in both. + (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 @@ -718,8 +718,23 @@ holds only what is specific to trystero. 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. -- **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 +- **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 5bbe8ab..245a5bc 100644 --- a/README.md +++ b/README.md @@ -99,10 +99,12 @@ instead. With them found, 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 -program uses the rooms and the platform backend through -`/webcpp/trystero//platform`, on both targets, as `example/Jamfile` does. +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 @@ -119,103 +121,147 @@ over a backend of its own, as the tests' memory relays do, uses ## 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 +namespace asio = boost::asio; namespace trystero = webcpp::trystero; -int main() { - boost::asio::io_context io; - trystero::platform::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 its `main` keeps alive as long as the -tab, running the `io_context` as a native program does: - -```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: its io_context, the backend, the 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::platform::backend backend{io.get_executor()}; - trystero::app app{io.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//platform multi : 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 - : /webcpp/trystero//platform -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 @@ -223,12 +269,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 @@ -310,17 +356,21 @@ using emscripten : : $PWD/emsdk/upstream/emscripten/em++ EOF ``` -### 8. Build the native quick start and the chat page +### 8. 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 and Boost.Charconv's definitions, -which webcpp::document uses, 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 its WebAssembly, @@ -330,31 +380,36 @@ builds one that every browser runs. ### 9. 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 diff --git a/doc/building.adoc b/doc/building.adoc index 38ee4de..98ba8fb 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -93,10 +93,10 @@ include::{library-root}/build.jam[tag=trystero] 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 `quick_start-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. +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, with an alternative for each target. Natively it adds webcpp::webrtc, with @@ -123,11 +123,12 @@ that says to add `multi`. A page has no threads, and needs none. The platform backend works with exceptions and without them (<>), so a program builds as it asks, as the -examples do, the native one with `multi`: +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 platform backend do, on each target that @@ -138,11 +139,12 @@ builds them, once without exceptions too: include::{library-root}/test/Jamfile[tag=platform] ---- -A page's 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] @@ -219,27 +221,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: -The native quick start is built as a program of its own, and runs until it -is stopped: +[source,bash] +---- +b2 libs/trystero/example//relayed +b2 libs/trystero/example//quick_start +---- + +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] ---- @@ -247,8 +257,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/quick-start.adoc b/doc/quick-start.adoc index 0512b65..a7a8c57 100644 --- a/doc/quick-start.adoc +++ b/doc/quick-start.adoc @@ -7,66 +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 four things alive for as long as its page: an -`io_context`, the `platform::backend` that implements the platform over the -page's own objects on the executor of that `io_context`, 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] ---- -Handlers are set once the application exists. This program greets every peer -that completes the handshake, prints every `chat` message, starts a -coroutine that answers the `echo` action, and runs the `io_context`: +`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`. `webcpp::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` runs the `io_context` for as long as the page lives, as a native -program does, under a work guard, since a page that waits for its peers may -have no work of its own. Nothing blocks the browser: whenever nothing is -ready, `run` suspends into the browser's event loop, and every JavaScript -event that reaches the library is posted to the `io_context`, whose handlers -run when `run` resumes (<>). +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`, over the same `platform::backend`. A native program runs -its `io_context` as the browser's does, and webcpp::webrtc 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/trystero.adoc b/doc/trystero.adoc index fcd4f06..5594fed 100644 --- a/doc/trystero.adoc +++ b/doc/trystero.adoc @@ -23,10 +23,11 @@ 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 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[] diff --git a/example/chat/Jamfile b/example/chat/Jamfile index 25ab69f..7011a5f 100644 --- a/example/chat/Jamfile +++ b/example/chat/Jamfile @@ -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 diff --git a/example/native_quick_start.cpp b/example/native_quick_start.cpp deleted file mode 100644 index 0b87822..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, over the same platform backend, 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::platform::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 d45630e..6b6d2d1 100644 --- a/example/quick_start.cpp +++ b/example/quick_start.cpp @@ -5,103 +5,122 @@ // 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 -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include -#include +#include +#include #include -#include #include +#include -namespace asio = webcpp::asio; +namespace asio = boost::asio; namespace trystero = webcpp::trystero; // end::includes[] 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: its io_context, the backend, the app, and the room it joined. */ -struct application { - asio::io_context io; - trystero::platform::backend backend{io.get_executor()}; - trystero::app app{io.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() { - application app; // lives in main, whose run lasts 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.io, echo_back(lobby->echo), asio::detached); + asio::co_spawn(io, answer(*bob_lobby, bob_chat), asio::detached); - // The page waits for its peers with no work of its own at times: the guard keeps the run going. - const auto guard = asio::make_work_guard(app.io); - app.io.run(); // lint-run: the page's program, suspended into the browser's event loop + 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/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 index f54e10f..c8f95ed 100644 --- a/test/oracle/twins/without-twin.txt +++ b/test/oracle/twins/without-twin.txt @@ -7,8 +7,6 @@ # 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 these three from one. Each is linked and never run, so it has no +# what keeps those below from one. Each is linked and never run, so it has no # output to compare, and a twin could not agree with it. 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 -native_quick_start: it prints only the messages peers send it, each after its sender's random id, and runs until it is stopped, so no run of it prints an output of its own to compare -quick_start: a browser program, which node refuses to run; it prints only the messages peers send it, each after its sender's random id, and runs as long as its page, so no run of it prints an output of its own to compare From 7e24a4ac608975b432a1cbc9475b661128c682ad Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:15:22 -0300 Subject: [PATCH 063/116] trystero: the relay configuration's program reads the seam's std::chrono clocks --- example/diff_relay_config.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/example/diff_relay_config.cpp b/example/diff_relay_config.cpp index 53ce770..ecae417 100644 --- a/example/diff_relay_config.cpp +++ b/example/diff_relay_config.cpp @@ -86,9 +86,9 @@ class observing_backend final : public trystero::backend::factory { void random(std::span out) override { backend_.random(out); } - std::int64_t unix_seconds() override { return backend_.unix_seconds(); } + std::chrono::sys_seconds unix_now() override { return backend_.unix_now(); } - double now_ms() override { return backend_.now_ms(); } + std::chrono::steady_clock::time_point steady_now() override { return backend_.steady_now(); } private: trystero::backend::factory& backend_; From 059fa9372de0cb3a4114f68df5d1ad4c8c78723e Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:20:30 -0300 Subject: [PATCH 064/116] trystero: the relay sockets' difference, and the self id that is not UTF-8 without twin --- example/Jamfile | 4 + example/diff_relay_sockets.cpp | 111 ++++++++++++++++++ example/diff_relay_sockets.expected | 1 + example/diff_self_id_not_utf8.cpp | 46 ++++++++ example/diff_self_id_not_utf8.expected | 3 + test/oracle/twins/diff_relay_sockets.expected | 1 + test/oracle/twins/diff_relay_sockets.mjs | 16 +++ test/oracle/twins/without-twin.txt | 4 +- 8 files changed, 184 insertions(+), 2 deletions(-) create mode 100644 example/diff_relay_sockets.cpp create mode 100644 example/diff_relay_sockets.expected create mode 100644 example/diff_self_id_not_utf8.cpp create mode 100644 example/diff_self_id_not_utf8.expected create mode 100644 test/oracle/twins/diff_relay_sockets.expected create mode 100644 test/oracle/twins/diff_relay_sockets.mjs diff --git a/example/Jamfile b/example/Jamfile index 0ea68b5..8e859e8 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -36,6 +36,7 @@ local differences = diff_peer_join diff_peers diff_relay_config + diff_relay_sockets diff_rooms_per_app diff_self_id diff_send_to_absent_peer @@ -46,4 +47,7 @@ for local difference in $(differences) : /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/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_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/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/without-twin.txt b/test/oracle/twins/without-twin.txt index c8f95ed..b34e059 100644 --- a/test/oracle/twins/without-twin.txt +++ b/test/oracle/twins/without-twin.txt @@ -7,6 +7,6 @@ # 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. Each is linked and never run, so it has no -# output to compare, and a twin could not agree with it. +# 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 From 1b1d0189478debd6636cd38f00ddb312bf31ef3d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:24:05 -0300 Subject: [PATCH 065/116] trystero: the appendix shows each difference beside its twin, and the testing chapter the twins --- AGENTS.md | 11 +- doc/differences.adoc | 441 ++++++++++++++++++++++++++++++++-- doc/testing.adoc | 64 ++++- test/oracle/Jamfile | 4 +- test/oracle/interop/relay.mjs | 8 +- test/oracle/package.json | 2 +- 6 files changed, 493 insertions(+), 37 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9e44da0..192fba8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -399,14 +399,17 @@ holds only what is specific to trystero. - **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 `platform_sealer` tests read; `update-expected` is its only - writer. `interop`, on native and emscripten (`native.trystero.interop` and + `protocol` 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. `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 diff --git a/doc/differences.adoc b/doc/differences.adoc index 5ffe89b..40ecf26 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 @@ -118,22 +121,422 @@ These features of Trystero are not ported, each for its reason: |=== -*`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. - -*`peers()` lists ids.* Trystero's `getPeers` maps each id to its -`RTCPeerConnection`. A connection is the backend's, webcpp::webrtc's over a -page's object in the browser and over libdatachannel's natively, and the -room does not hand it out. - -*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. - -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 -(<>). +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 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: each program and +its twin 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-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. + +| 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. + +| 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. + +| 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 (<>). + +| `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. + +| 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, which neither API reports: a program sees one join either way. The `room` test feeds the dedup. + +| A relay's text, a signal or a handshake message past its bound; a protocol text of thousands of values +| 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` test holds 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/testing.adoc b/doc/testing.adoc index 43e5d3e..438de21 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -215,16 +215,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] ---- @@ -234,8 +237,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 `platform_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] ---- @@ -309,6 +313,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 @@ -340,8 +387,9 @@ that dependent archives precede OpenSSL in the link order. === 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`, 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/test/oracle/Jamfile b/test/oracle/Jamfile index 5eee24e..b15dad4 100644 --- a/test/oracle/Jamfile +++ b/test/oracle/Jamfile @@ -6,7 +6,9 @@ # 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 ; 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/package.json b/test/oracle/package.json index 7a4cd12..f50e3a7 100644 --- a/test/oracle/package.json +++ b/test/oracle/package.json @@ -2,7 +2,7 @@ "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", From 4128cc1080f56dcab82d944be0375a76b9fa1ce2 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:28:03 -0300 Subject: [PATCH 066/116] trystero: remember an event id only once it is the event's own, and the dedup's tests A relay chooses the id it sends, and the dedup trusted it: a relay on a peer's list could send a forged event under a genuine event's id first, which a counter-announcement, holding no nonce, makes easy to predict, and the room then dropped the genuine event an honest relay carried. Trystero 0.26.0, which has no dedup, acts on both. read_relay_message now reads an event's pubkey, created_at, kind and whether its one tag is its topic's, and protocol::nostr::has_own_id checks, with event_id, that the id is the SHA-256 of the event's NIP-01 serialization. The strategy remembers only such an id; any other event is acted on every time, as Trystero acts on it. room's a_forged_event_under_a_genuine_id_hides_nothing failed first: it heard forged and later, not forged, genuine, forged and later. event_ids_other_than_nip01_ones_are_never_remembered compares the resource with what the index held once made. libstdc++'s deque allocates its map and a node when it is made (544 bytes, measured with g++ 15), as MSVC's debug containers do, so its check of zero failed there; no other test checks zero with such a container alive. a_strategy_draws_the_key_of_its_event_ids reads the index's hash (recent_event_ids::hash_function, through nostr_strategy::seen) and compares it, for two seeds, with the hash under the 16 bytes a twin of the backend's stream gives after the secret. It failed against a draw_key that drew the bytes and returned a zero key. The protocol test parses an event message and a subscription and checks their created_at, kind, tags, content, since and kinds, at a time past 2^32 seconds too, and computes the id again from the message's own fields. It failed against a created_at and a since written in 32 bits, which the oracle's messages, all at 1759700000, let through. It also checks has_own_id on Trystero's own createEvent messages and on altered ones. The guide's "Discovery over Nostr", the appendix's row for the dedup and AGENTS.md say so; AGENTS.md no longer names colliding_event_ids_stay_fast, removed in 81dc4a9. The lint's fluent-chains rule refused a chain of three calls in parse_resource, which now binds the moved image first. --- AGENTS.md | 12 +- doc/differences.adoc | 2 +- doc/protocol.adoc | 13 +- .../webcpp/trystero/detail/nostr_strategy.hpp | 31 +-- include/webcpp/trystero/protocol/nostr.hpp | 71 ++++++- test/protocol_test.cpp | 194 +++++++++++++++++- test/room_test.cpp | 114 ++++++++-- 7 files changed, 394 insertions(+), 43 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 034f1fd..b4b081a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -311,10 +311,14 @@ holds only what is specific to trystero. (`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 `colliding_event_ids_stay_fast` feeds it 2048 - ids found to share one bucket of `std::unordered_set` and reads - Boost.Unordered's statistics (`BOOST_UNORDERED_ENABLE_STATS`, defined by - that test only). + 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 targets, in a page before it is copied into WebAssembly (webcpp::beast's `read_message_max`). A relay that stops diff --git a/doc/differences.adoc b/doc/differences.adoc index 5ffe89b..cc46969 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -106,7 +106,7 @@ These features of Trystero are not ported, each for its reason: | 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 NIP-01's, 64 lowercase hexadecimal digits; 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 of another form would let a relay fill the room's resource with the ids kept +| 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 diff --git a/doc/protocol.adoc b/doc/protocol.adoc index a381475..5926b37 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -57,10 +57,15 @@ 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 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. +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 diff --git a/include/webcpp/trystero/detail/nostr_strategy.hpp b/include/webcpp/trystero/detail/nostr_strategy.hpp index c5277aa..597d88e 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -45,9 +45,11 @@ 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. * - * Only an id NIP-01 defines, 64 lowercase hexadecimal digits, is remembered: an event with any - * other id is acted on every time, as Trystero, which remembers none, acts on every event, so that - * what a relay makes the room hold is `capacity` ids of 64 bytes. + * 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 @@ -96,7 +98,7 @@ class recent_event_ids { /** 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 (!is_nip01_id(id)) { + if (!protocol::nostr::detail::is_nip01_hex(id)) { return true; } if (index_.contains(id)) { @@ -115,14 +117,10 @@ class recent_event_ids { /** How many ids are remembered. */ [[nodiscard]] std::size_t size() const { return order_.size(); } -private: - /** Whether `id` is an event id as NIP-01 writes it: 64 lowercase hexadecimal digits. */ - static bool is_nip01_id(std::string_view id) { - return id.size() == id_size && std::ranges::all_of(id, [](char c) { - return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); - }); - } + /** 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_; @@ -210,6 +208,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; @@ -468,10 +469,14 @@ class nostr_strategy : public std::enable_shared_from_this { } 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() || !seen_.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); diff --git a/include/webcpp/trystero/protocol/nostr.hpp b/include/webcpp/trystero/protocol/nostr.hpp index 135a27e..da46d9b 100644 --- a/include/webcpp/trystero/protocol/nostr.hpp +++ b/include/webcpp/trystero/protocol/nostr.hpp @@ -110,6 +110,28 @@ inline std::pmr::string quoted(std::string_view text, std::pmr::memory_resource* 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 /** @@ -350,8 +372,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. */ @@ -401,15 +455,28 @@ inline std::optional read_event(const json::const_value& array) { 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 kind = o["kind"].get(); kind.has_value()) { + e.kind = *kind; + } // 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 (tag.is_array() && tag.size() >= 2 && json::text_of(tag[0]) == topic_tag && - tag[1].is_string()) { + 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; } diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index ebf4cde..086177a 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -175,6 +175,20 @@ void handshake_and_sealing(const fixture_value& fixture) { BOOST_TEST(!tp::parse_sealed("no dollar").has_value()); } +/** 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"])); @@ -202,14 +216,10 @@ void nostr_events(const fixture_value& fixture) { BOOST_TEST(tp::nostr::verify(std::span(sig.data(), 64), std::span(id.data(), 32), std::span(pub.data(), 32))); - // The relay's echo holds the event's text whole: `["EVENT",]` less its first 9 and last - // byte, in `["EVENT","sub",]`. const std::string_view written = message; BOOST_TEST(written.starts_with(R"(["EVENT",{)") && written.ends_with("}]")); - std::string echo = R"(["EVENT","sub",)"; - echo += written.substr(9, written.size() - 10); - echo += ']'; - const auto echoed_document = parse_text(echo, tp::nostr::max_parsed_relay_text_bytes).value(); + 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); @@ -224,6 +234,173 @@ void nostr_events(const fixture_value& fixture) { BOOST_TEST(!std::get(*rejected).accepted); } +// 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, @@ -862,7 +1039,8 @@ void parse_resource() { const tp::json::document moved = std::move(document); // A document moved from holds no image. BOOST_TEST(!document.has_value()); // NOLINT(bugprone-use-after-move) - BOOST_TEST(static_cast(moved.get().image().data()) == memory.last); + const auto moved_image = moved.get().image(); + BOOST_TEST(static_cast(moved_image.data()) == memory.last); BOOST_TEST_EQ(tp::json::text_of(moved.root()[2]["content"]), R"({"peerId":"p"})"); BOOST_TEST_EQ(memory.allocations, 1U); BOOST_TEST_EQ(memory.outstanding, 1U); @@ -898,6 +1076,8 @@ int main(int argc, char* argv[]) { 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); diff --git a/test/room_test.cpp b/test/room_test.cpp index 0af7abf..e95f2d1 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -722,11 +722,13 @@ void recent_event_ids_drop_a_repeat_and_forget_the_oldest() { // 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. +// 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'); @@ -743,7 +745,7 @@ void event_ids_other_than_nip01_ones_are_never_remembered() { BOOST_TEST(ids.remember(id)); } BOOST_TEST_EQ(ids.size(), 0U); - BOOST_TEST_EQ(memory.in_use, 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 @@ -761,18 +763,105 @@ void the_event_id_hash_is_keyed() { 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, beside its -// signer's secret: a relay cannot know it. +// 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() { - fixture f; - const auto before = f.net.random_bytes; + 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, 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(f.net.random_bytes - before, - 32U + trystero::detail::recent_event_ids::key_size); // the secret, the key + 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 @@ -1525,6 +1614,7 @@ int main() { event_ids_other_than_nip01_ones_are_never_remembered(); the_event_id_hash_is_keyed(); a_strategy_draws_the_key_of_its_event_ids(); + a_forged_event_under_a_genuine_id_hides_nothing(); classes_over_a_pmr_circular_buffer_do_not_move(); a_replayed_answer_is_refused(); a_replayed_offer_is_refused(); From e9e146ffcfd44502663ddaabf3f1b46f823b654c Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:29:11 -0300 Subject: [PATCH 067/116] trystero: the already-joined program's second result is const --- example/diff_already_joined.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/diff_already_joined.cpp b/example/diff_already_joined.cpp index 9a75c14..dfeb52b 100644 --- a/example/diff_already_joined.cpp +++ b/example/diff_already_joined.cpp @@ -34,7 +34,7 @@ int main() { trystero::app app(io.get_executor(), backend, {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); auto first = app.join("lobby"); - auto second = 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: " From 6f20d6c676c2a8b2fa62f824a71b052b78aa4245 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:29:20 -0300 Subject: [PATCH 068/116] trystero: the reason no program shows a repeated event, after its checked id --- doc/differences.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/differences.adoc b/doc/differences.adoc index 6c8ef2f..bbab4e5 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -532,7 +532,7 @@ its reason. | 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, which neither API reports: a program sees one join either way. The `room` test feeds the dedup. +| 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 | 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` test holds the bounds. From 62cb27a583bc71d1e41dfa137bfbeb97b9f73e1b Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:32:11 -0300 Subject: [PATCH 069/116] trystero: the appendix says the last difference has no twin --- doc/differences.adoc | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/doc/differences.adoc b/doc/differences.adoc index bbab4e5..1ca8d8a 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -129,17 +129,17 @@ reason of each other row. [#trystero-differences-shown] === The differences, shown -Each difference below is shown by a {cpp} program and 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: each program and -its twin 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 +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 From 830b3cde00cd570996c5d9ee7a859c2156f52aa5 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:33:42 -0300 Subject: [PATCH 070/116] trystero: an answerer's signals and JSON payloads against Trystero's own The oracle drives Trystero's signal handler as an answerer: a room of its own opens an offer sealed under the room's key, its answering peer gives an answer and a candidate, and Trystero seals and publishes them, its self id drawn from the fixture's pattern while its core loads. The new signaling test drives detail::signaling with the same offers, over a sealer that gives Trystero's sealed texts, and compares every byte it publishes: each answerer's .answering = true is now needed. It also reads a signal and a relay's text at their bounds and drops one byte past them, through the signaling and a Nostr strategy over the test's relay connection. The oracle also writes JSON.stringify's text of JSON payloads, whose numbers and keys the protocol test compares with webcpp::document's, and of numbers a double cannot hold, which the payload writes exact. --- AGENTS.md | 7 +- doc/testing.adoc | 10 +- test/Jamfile | 4 + test/fixtures/cases/protocol.json | 31 +- test/fixtures/expected/expected.json | 79 ++++- test/oracle/oracle.mjs | 102 ++++++- test/protocol_test.cpp | 39 +++ test/signaling_test.cpp | 435 +++++++++++++++++++++++++++ 8 files changed, 699 insertions(+), 8 deletions(-) create mode 100644 test/signaling_test.cpp diff --git a/AGENTS.md b/AGENTS.md index b4b081a..575b107 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -409,8 +409,11 @@ holds only what is specific to trystero. 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 `platform_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; `update-expected` + is its only writer. 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 diff --git a/doc/testing.adoc b/doc/testing.adoc index 43e5d3e..9e3baf4 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -81,8 +81,14 @@ 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, and a signal or a relay's text read at its bound and + dropped one byte past it. | `room` | Whole rooms in one process, over the memory relays: every payload format, diff --git a/test/Jamfile b/test/Jamfile index c8dacf0..18d79ce 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -58,6 +58,10 @@ webcpp.compile config_all_off : config_test.cpp # 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 diff --git a/test/fixtures/cases/protocol.json b/test/fixtures/cases/protocol.json index a7b9125..4c3ccf9 100644 --- a/test/fixtures/cases/protocol.json +++ b/test/fixtures/cases/protocol.json @@ -110,5 +110,34 @@ ] ] } - } + }, + "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 5262a99..9525ab0 100644 --- a/test/fixtures/expected/expected.json +++ b/test/fixtures/expected/expected.json @@ -585,5 +585,82 @@ "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/oracle/oracle.mjs b/test/oracle/oracle.mjs index 6211ddf..44f3d53 100644 --- a/test/oracle/oracle.mjs +++ b/test/oracle/oracle.mjs @@ -22,12 +22,23 @@ 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 @@ -350,6 +361,93 @@ const until = async (done, what) => { 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/protocol_test.cpp b/test/protocol_test.cpp index 086177a..2917326 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -754,6 +754,44 @@ void signal_texts(const fixture_value& fixture) { } } +/** `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 buffer of a resource, + * as a 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 = + tp::json::parse(text, wd::parse_options(), 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. @@ -1088,6 +1126,7 @@ int main(int argc, char* argv[]) { signal_bounds(); event_messages(fixture); signal_texts(fixture); + payload_texts(fixture); duplicate_keys(fixture); parse_bounds(); parse_cost(); diff --git a/test/signaling_test.cpp b/test/signaling_test.cpp new file mode 100644 index 0000000..b99ee40 --- /dev/null +++ b/test/signaling_test.cpp @@ -0,0 +1,435 @@ +// 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, std::string(topic), 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; + 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(); +} + +} // 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(); + return webcpp::test::exit_status(boost::report_errors()); +} From 8253119addb2da5691e9aa2bad2b1099bec3e7fc Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:38:40 -0300 Subject: [PATCH 071/116] trystero: a handshake message and a remote candidate at their bounds, and one byte past Through the real path: a challenge of 1,024 bytes injected on a shared connection is answered with a proof, and one of 1,025 fails the handshake as wrong_password; a remote candidate's JSON of 16 KiB is added to the platform backend's connection once an offer is its remote description, and one byte longer fails add_ice_candidate with backend_failure. With the signaling test's signal and relay text, each of the four bounds now has a test that fails when its call site parses with parse_options() instead. --- doc/testing.adoc | 7 ++-- test/platform_peer_connection_test.cpp | 54 ++++++++++++++++++++++++++ test/shared_test.cpp | 51 ++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 3 deletions(-) diff --git a/doc/testing.adoc b/doc/testing.adoc index 5f21944..9ac42f8 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -115,8 +115,8 @@ 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` @@ -167,7 +167,8 @@ include::{library-root}/test/Jamfile[tag=allocation] handler replacement and destruction, the 64-frame and 10-second bounds, 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; the backend + malformed candidates and descriptions fail without throwing, and so does a + candidate one byte past its bound, which at the bound is added; 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. diff --git a/test/platform_peer_connection_test.cpp b/test/platform_peer_connection_test.cpp index 1bb5b3b..960765f 100644 --- a/test/platform_peer_connection_test.cpp +++ b/test/platform_peer_connection_test.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -599,6 +600,58 @@ void a_malformed_candidate_fails_without_throwing() { } } +/** `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); +} + void the_backend_makes_at_most_its_budget_in_a_minute() { asio::io_context io; trystero::platform::backend factory( @@ -832,6 +885,7 @@ int main() { 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(); 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(); diff --git a/test/shared_test.cpp b/test/shared_test.cpp index 05ff61b..280c946 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -1855,6 +1855,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")") != text.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) { @@ -1926,6 +1976,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, From cd97f85e550f7c1a7bd949f1c32dd5c97d9628bb Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:46:26 -0300 Subject: [PATCH 072/116] trystero: the JSON writer returns its error, and the UTF-8 guards are tested protocol::json::append_string returns webcpp::document::quote's result, the error errc::type for a text that is not UTF-8, in place of a BOOST_ASSERT that a release build compiles out. A local candidate is written by webrtc::detail::candidate_json, which returns that error, and is not sent then; the protocol's own writers state their UTF-8 precondition, which ids, topics, nonces and sealed texts in ASCII, texts read from JSON and the checked self id meet. app_impl's test sets aside a self id that is not UTF-8 and keeps one past ASCII, and the platform's test refuses a candidate, mid or user name fragment that is not UTF-8. --- doc/testing.adoc | 6 +- include/webcpp/trystero/protocol/json.hpp | 32 ++++++--- include/webcpp/trystero/protocol/nostr.hpp | 12 ++-- include/webcpp/trystero/protocol/signal.hpp | 5 +- include/webcpp/trystero/room.hpp | 4 +- .../trystero/webrtc/peer_connection.hpp | 69 ++++++++++++------- test/app_impl_test.cpp | 28 ++++++++ test/platform_peer_connection_test.cpp | 31 +++++++++ test/room_test.cpp | 2 +- test/support/memory_backend.hpp | 3 +- 10 files changed, 149 insertions(+), 43 deletions(-) diff --git a/doc/testing.adoc b/doc/testing.adoc index 9ac42f8..515b764 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -99,7 +99,8 @@ include::{library-root}/test/Jamfile[tag=allocation] coroutines and view handlers. | `app_impl` -| Configuration copying and validation, resource ownership, weak room +| 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. @@ -168,7 +169,8 @@ include::{library-root}/test/Jamfile[tag=allocation] 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; the backend + 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. diff --git a/include/webcpp/trystero/protocol/json.hpp b/include/webcpp/trystero/protocol/json.hpp index aad2ac0..4130db1 100644 --- a/include/webcpp/trystero/protocol/json.hpp +++ b/include/webcpp/trystero/protocol/json.hpp @@ -341,17 +341,30 @@ inline bool quotable(std::string_view text) { * 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 (@ref quotable): every string the protocol writes is, the self - * id checked when the app is made, a candidate's fields when it is written, and every other one is - * ASCII or was read from JSON. + * @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) { - [[maybe_unused]] const webcpp::document::result quoted = - webcpp::document::quote(text, out); - BOOST_ASSERT(quoted.has_value()); +[[nodiscard]] inline webcpp::document::result append_string(std::pmr::string& out, + std::string_view text) { + return webcpp::document::quote(text, out); } +namespace detail { + +/** + * 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. * @@ -386,12 +399,13 @@ 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 += ':'; } diff --git a/include/webcpp/trystero/protocol/nostr.hpp b/include/webcpp/trystero/protocol/nostr.hpp index da46d9b..9c91349 100644 --- a/include/webcpp/trystero/protocol/nostr.hpp +++ b/include/webcpp/trystero/protocol/nostr.hpp @@ -106,7 +106,7 @@ inline std::array event_id(std::string_view pubkey, 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; } @@ -273,6 +273,8 @@ inline bool verify(std::span sig, std::span topics, @@ -325,7 +328,7 @@ inline std::pmr::string subscribe_message( 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 std::uint32_t k : kinds) { if (out.back() != '[') { @@ -340,7 +343,7 @@ inline std::pmr::string subscribe_message( if (i != 0) { out += ','; } - json::append_string(out, topics[i]); + json::detail::append_utf8(out, topics[i]); } out += "]}]"; return out; @@ -352,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; } diff --git a/include/webcpp/trystero/protocol/signal.hpp b/include/webcpp/trystero/protocol/signal.hpp index 439aba0..c8eb77f 100644 --- a/include/webcpp/trystero/protocol/signal.hpp +++ b/include/webcpp/trystero/protocol/signal.hpp @@ -273,6 +273,9 @@ inline std::optional read_signal(const json::const_value& docume * @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 = {}, @@ -286,7 +289,7 @@ 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); if (!m.answering) { diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 8b9774c..5eaf03a 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -1236,7 +1236,7 @@ class room_impl final : public std::enable_shared_from_this, public r 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; @@ -1279,7 +1279,7 @@ class room_impl final : public std::enable_shared_from_this, public r 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 += '}'; diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp index 9b9a338..7f0b662 100644 --- a/include/webcpp/trystero/webrtc/peer_connection.hpp +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -34,12 +34,53 @@ #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 (auto quoted = protocol::json::append_string(json, candidate); !quoted) { + return quoted.error(); + } + json += R"(,"sdpMid":)"; + if (sdp_mid.empty()) { + json += "null"; + } else if (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 (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 @@ -416,31 +457,13 @@ class peer_connection : public backend::peer_connection, if (!h || !h->ice_candidate) { return; } - if (!protocol::json::quotable(candidate.candidate) || - !protocol::json::quotable(candidate.sdp_mid) || - !protocol::json::quotable(candidate.username_fragment)) { + 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; } - std::pmr::string json(R"({"candidate":)", memory_); - protocol::json::append_string(json, candidate.candidate); - json += R"(,"sdpMid":)"; - if (candidate.sdp_mid.empty()) { - json += "null"; - } else { - protocol::json::append_string(json, candidate.sdp_mid); - } - json += R"(,"sdpMLineIndex":)"; - if (candidate.sdp_m_line_index) { - protocol::json::append_integer(json, *candidate.sdp_m_line_index); - } else { - json += "null"; - } - if (!candidate.username_fragment.empty()) { - json += R"(,"usernameFragment":)"; - protocol::json::append_string(json, candidate.username_fragment); - } - json += '}'; - h->ice_candidate(json); + h->ice_candidate(*json); } void on_channel(data_channel::channel_type channel) { diff --git a/test/app_impl_test.cpp b/test/app_impl_test.cpp index c64ac5a..c1ea125 100644 --- a/test/app_impl_test.cpp +++ b/test/app_impl_test.cpp @@ -278,6 +278,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. @@ -682,6 +709,7 @@ int main() { the_configuration_is_copied_and_completed(); what_the_configuration_names_is_kept(); what_no_peer_could_use_is_set_aside(); + a_self_id_that_is_not_utf8_is_set_aside(); every_allocation_goes_through_the_apps_resource(); the_registry_holds_rooms_by_a_weak_reference(); adopt_starts_one_connection_per_peer(); diff --git a/test/platform_peer_connection_test.cpp b/test/platform_peer_connection_test.cpp index 960765f..5801443 100644 --- a/test/platform_peer_connection_test.cpp +++ b/test/platform_peer_connection_test.cpp @@ -652,6 +652,36 @@ void a_candidate_past_its_bound_fails() { 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( @@ -886,6 +916,7 @@ int main() { 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(); diff --git a/test/room_test.cpp b/test/room_test.cpp index e95f2d1..1028ab3 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -1222,7 +1222,7 @@ void long_peer_ids_are_bounded() { const auto signal = [](std::string_view id) { std::pmr::string text("{"); trystero::protocol::json::append_key(text, "peerId"); - trystero::protocol::json::append_string(text, id); + webcpp::test::require(BOOST_TEST(trystero::protocol::json::append_string(text, id))); text += '}'; auto parsed = trystero::protocol::json::parse( text, diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index 809948e..0ab31bf 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -378,7 +378,8 @@ inline void memory_relay::receive(const std::shared_ptr& from, // 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, event); forwarded += ']'; From 1ffc7a605610839f7364fcd1b28e22bd0547059d Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:47:49 -0300 Subject: [PATCH 073/116] trystero: the relays' session as the WP4 review asks The session sets its message bound (1 MiB) and text mode before the handshake: a page's stream checks each message as its event arrives, and a relay's first ones can come in the same task as the open, which were checked against webcpp::beast's default of 16 MiB and reached the room whole (platform_page_websocket_ingress). Over TLS the stream asks for verify_peer on both targets: a page's stream refused a program's context made as Asio makes a client's, whose mode is verify_none, so every wss:// relay reported a close (platform_page_websocket_tls, which also pins what a page refuses). A binary message from a relay is dropped on both targets, as the page's own backend dropped it; it reached the room as a text, natively too. The reads' and writes' completions are a handler of the session's own, with the room's allocator and no executor: Asio's any_completion_handler had Asio make an any_completion_executor with new for each operation and dispatch each completion through it, six operator new natively for a text sent and its echo received (platform_websocket_allocation, none now). platform_page_relay_allocation pins what a page's relay allocates outside the room's resource: per connection the resolver's results (three, five for a long host) and embind's string of the open's and the close's type, per message two of embind's strings. The URL rules run on both targets (platform_websocket_url), with path characters outside RFC 3986, and platform_websocket_unreachable attempts the URLs it takes again, so that a page makes its WebSocket and natively a TCP connect fails. --- include/webcpp/trystero/platform/backend.hpp | 30 +- .../webcpp/trystero/platform/websocket.hpp | 180 ++++--- test/Jamfile | 38 +- test/platform_page_relay_allocation_test.cpp | 498 ++++++++++++++++++ test/platform_page_websocket_ingress_test.cpp | 180 +++++++ test/platform_page_websocket_tls_test.cpp | 230 ++++++++ test/platform_websocket_allocation_test.cpp | 237 +++++++++ test/platform_websocket_test.cpp | 189 ++----- test/platform_websocket_unreachable_test.cpp | 73 ++- test/platform_websocket_url_test.cpp | 183 +++++++ 10 files changed, 1594 insertions(+), 244 deletions(-) create mode 100644 test/platform_page_relay_allocation_test.cpp create mode 100644 test/platform_page_websocket_ingress_test.cpp create mode 100644 test/platform_page_websocket_tls_test.cpp create mode 100644 test/platform_websocket_allocation_test.cpp create mode 100644 test/platform_websocket_url_test.cpp diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index 86c5fc6..cc56996 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -130,11 +130,12 @@ struct backend_config { class backend : public trystero::backend::factory { public: /** - * A backend with a runtime of its own, made with `backend_config::runtime`, whose TLS verifies - * relays against the system's certificate authorities, as @ref make_tls_context makes it. + * A backend with a runtime of its own, made with `backend_config::runtime`, whose TLS context + * is @ref make_tls_context's: natively it verifies relays against the system's certificate + * authorities, and in a page the browser verifies them against its own. * - * It throws nothing: when OpenSSL cannot make the TLS context, `tls_context()` holds the error, - * and every `wss://` relay reports a close, as an unreachable relay does. + * 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. @@ -148,10 +149,15 @@ class backend : public trystero::backend::factory { * 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, whose authorities each relay is - * verified against, whatever its verify mode; or the error that kept the program from making - * it, which `tls_context()` then holds, every `wss://` relay reporting a close. + * @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, @@ -159,8 +165,8 @@ class backend : public trystero::backend::factory { : backend(std::move(ex), std::move(tls), nullptr, config) {} /** - * A backend whose peer connections the program's runtime counts, and whose TLS verifies relays - * against the system's certificate authorities, as the first constructor's does. + * 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, @@ -203,6 +209,12 @@ class backend : public trystero::backend::factory { * 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. */ diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 6c5e72b..eb82285 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -14,16 +14,15 @@ #include #include -#include // lint-world: erases a handler's type only -#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 +#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 @@ -305,18 +304,25 @@ inline std::optional parse_url( * * 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, with nothing in the default allocator for a message. On - * Emscripten the page's stream keeps its state in the room's resource too, and its `WebSocket` - * makes the handshake. 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, - * the header fields of both and, for a response that is not 101, its body, which Beast's own - * parser reads up to Beast's default limit for a response, 8 MiB, that no option of its stream - * lowers; 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); and each keep-alive ping's frame. + * 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, the header fields of both and, for a response that is not + * 101, its body, which Beast's own parser reads up to Beast's default limit for a response, 8 MiB, + * that no option of its stream lowers; 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> { @@ -466,17 +472,19 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()](const boost::system::error_code& error) { self->on_tls(error); @@ -524,6 +532,12 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()](const boost::system::error_code& ec) { @@ -537,9 +551,6 @@ class websocket_session : public std::enable_shared_from_thisopen) { h->open(); } @@ -547,24 +558,43 @@ class websocket_session : public std::enable_shared_from_this; + 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() { - auto handler = [self = this->shared_from_this()](const boost::system::error_code& ec, - std::size_t size) { - self->on_read(ec, size); - }; - ws_.async_read(buffer_, transfer_handler(bound(std::move(handler)))); + 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) { @@ -572,7 +602,9 @@ class websocket_session : public std::enable_shared_from_thismessage) { + // 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)); } @@ -590,8 +622,8 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()](const boost::system::error_code& ec, - std::size_t) { - if (ec) { - self->fail(); - return; - } - self->write_next(); - }; ws_.async_write(webcpp::asio::buffer(writing_text_), - transfer_handler(bound(std::move(handler)))); + 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(); } /** @@ -689,32 +722,41 @@ class websocket_handle : public backend::websocket { * 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 message is handed over as a view of the - * read buffer, and one longer than `protocol::max_relay_message_bytes` closes the connection, a - * page's before it is copied into WebAssembly. A relay that stops reading is dropped once the + * 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. Natively a `wss://` connection names - * the host to the server (SNI) when it is a name, verifies the relay's certificate whatever the - * verify mode of `tls`, and checks it against the URL's host, a name or an address; in a page the - * browser does all three. It needs no exceptions. + * 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`, and a message allocates nothing in the default allocator. Natively what Boost.Beast, - * Asio and OpenSSL allocate of their own stays outside it, for each connection: 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. Among it, a relay that answers the handshake with a - * status other than 101 can have Beast read a body of up to 8 MiB, Beast's default limit for a - * response, which no option of its stream lowers, before the connection reports its close. + * `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; among it, a relay that answers the handshake with a status other + * than 101 can have Beast read a body of up to 8 MiB, Beast's default limit for a response, which + * no option of its stream lowers, 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; natively the connection verifies the relay against its authorities even when - * its verify mode is `verify_none`, as Asio makes a client's context. + * 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. diff --git a/test/Jamfile b/test/Jamfile index c8dacf0..3b9e43e 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -83,12 +83,14 @@ webcpp.run timer : timer_test.cpp ; # 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; and relays it -# cannot reach. 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; -# the backend's WebRTC; and whole rooms over it. Each as the build asks and, +# 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. @@ -98,10 +100,13 @@ 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) ; webcpp.run platform_websocket : platform_websocket_test.cpp : $(platform) _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS : 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 ; @@ -111,6 +116,10 @@ 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) 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 @@ -134,6 +143,13 @@ webcpp.run platform_page_websocket_bound : platform_page_websocket_bound_test.cp : $(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 @@ -146,6 +162,10 @@ webcpp.run platform_page : platform_page_test.cpp : $(platform) : emscripten ; # the C library's allocation functions, replaced, count none. webcpp.run platform_page_sealer_allocation : platform_page_sealer_allocation_test.cpp : $(platform) : 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_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. @@ -163,6 +183,10 @@ webcpp.run platform_page_websocket_bound_no_exceptions : platform_page_websocket 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 @@ -172,6 +196,8 @@ webcpp.run platform_page_no_exceptions : platform_page_test.cpp webcpp.run platform_page_sealer_allocation_no_exceptions : platform_page_sealer_allocation_test.cpp : $(platform) 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) off : emscripten ; webcpp.run platform_page_handlers_no_exceptions : platform_page_handlers_test.cpp 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_websocket_ingress_test.cpp b/test/platform_page_websocket_ingress_test.cpp new file mode 100644 index 0000000..56a7452 --- /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)(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(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(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_tls_test.cpp b/test/platform_page_websocket_tls_test.cpp new file mode 100644 index 0000000..10dffd2 --- /dev/null +++ b/test/platform_page_websocket_tls_test.cpp @@ -0,0 +1,230 @@ +// 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, refused::certificate, refused::option, refused::method, refused::callback, +}; + +/** 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_websocket_allocation_test.cpp b/test/platform_websocket_allocation_test.cpp new file mode 100644 index 0000000..2963185 --- /dev/null +++ b/test/platform_websocket_allocation_test.cpp @@ -0,0 +1,237 @@ +// 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. +// +// main runs the io_context once; each echo sends the next text, and the last closes the socket. + +#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; + +/** 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; + } + // 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; + } + // 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_); + acceptor_.accept(socket, ec); + if (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_; +}; + +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); +} + +} // namespace + +int main() { + 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::report_errors(); + } + 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(); + return boost::report_errors(); +} diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp index 36279d6..8fb964a 100644 --- a/test/platform_websocket_test.cpp +++ b/test/platform_websocket_test.cpp @@ -221,6 +221,8 @@ enum class misbehaviour { 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, }; /** @@ -274,6 +276,24 @@ struct hostile_server { 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 { @@ -334,150 +354,6 @@ bool run_until(asio::io_context& io, const std::function& done, return done(); } -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; and -// a tab, a newline or a backslash, which a page drops or reads as a slash. -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)", - }) { - 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); - } -} - // 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 @@ -800,6 +676,26 @@ void a_message_longer_than_a_relay_sends_closes_the_socket() { 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}); @@ -1006,10 +902,6 @@ void a_quiet_relay_that_answers_pings_stays_connected() { } // 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(); 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(); @@ -1023,6 +915,7 @@ int main() { 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(); diff --git a/test/platform_websocket_unreachable_test.cpp b/test/platform_websocket_unreachable_test.cpp index f6d1844..b364bf6 100644 --- a/test/platform_websocket_unreachable_test.cpp +++ b/test/platform_websocket_unreachable_test.cpp @@ -7,11 +7,15 @@ // 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 where nothing listens, fails to -// connect, natively over Boost.Beast and on emscripten over node's WebSocket, and reports a close -// too. Each reports exactly one, after the call that made it, never inside it, and nothing is -// thrown; a send and a close before the connection opened change nothing. Before the fix, a page's -// `new WebSocket` threw a SyntaxError through the room's constructor. +// 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 @@ -24,6 +28,10 @@ #include #include +#ifdef WEBCPP_TARGET_EMSCRIPTEN +#include +#include +#endif #include #include #include @@ -31,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -39,17 +48,46 @@ 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{ - "ftp://relay.invalid", "wss://relay.invalid/#fragment", "not a url", "/relative", - "http://127.0.0.1:9", "https://127.0.0.1:9", "ws://127.0.0.1:9", "ws://[::1]:9", -}; +constexpr std::array urls{{ + {.url = "ftp://relay.invalid", .attempted = false}, + {.url = "wss://relay.invalid/#fragment", .attempted = false}, + {.url = "not a url", .attempted = false}, + {.url = "/relative", .attempted = false}, + {.url = "http://127.0.0.1:9", .attempted = false}, + {.url = "https://127.0.0.1:9", .attempted = false}, + {.url = "ws://127.0.0.1:9", .attempted = true}, + {.url = "ws://[::1]:9", .attempted = true}, +}}; struct state { asio::io_context io; @@ -74,16 +112,22 @@ void closed(state& s, std::size_t i) { 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, then sends on it and closes it. */ +/** + * 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), + s.sockets.at(i) = s.backend.connect(urls.at(i).url, { .open = [] { BOOST_ERROR("a URL opened"); }, .message = {}, @@ -91,7 +135,9 @@ void connect_all(state& s) { }, std::pmr::get_default_resource()); s.sockets.at(i)->send("ignored"); - s.sockets.at(i)->close(); + if (!urls.at(i).attempted) { + s.sockets.at(i)->close(); + } BOOST_TEST_EQ(s.closes.at(i), 0U); // not inside the call } } @@ -99,6 +145,9 @@ void connect_all(state& s) { } // 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 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(); +} From c07ae1b1eacbb834640a0bfa4dfce7fd73bca1ee Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:48:01 -0300 Subject: [PATCH 074/116] trystero: a page's randomness and sealer let no JavaScript exception in In a page the platform's source of randomness calls crypto.getRandomValues itself, in JavaScript that catches what it throws and reports a failure: Emscripten's entropy call let a missing or throwing getRandomValues through into WebAssembly, where the program ended, and a seal never reached its error::backend_failure. It fills up to Web Crypto's 65536 bytes a call. The page's sealer reads a Web Crypto settlement only when it is an ArrayBuffer, and fails the seal or the open with error::backend_failure otherwise: a settlement of -1 threw a RangeError into WebAssembly, and one of undefined opened as an empty text (platform_page_sealer). platform_backend fills more than one piece of the source on both targets, and platform_sealer gives a fresh sealer two seals and two opens in one call, which in a page wait while it imports its key. --- include/webcpp/trystero/platform/entropy.hpp | 45 +++- include/webcpp/trystero/platform/sealer.hpp | 24 +- test/Jamfile | 5 + test/platform_backend_test.cpp | 31 ++- test/platform_page_sealer_test.cpp | 231 +++++++++++++++++++ test/platform_sealer_test.cpp | 61 ++++- 6 files changed, 376 insertions(+), 21 deletions(-) create mode 100644 test/platform_page_sealer_test.cpp diff --git a/include/webcpp/trystero/platform/entropy.hpp b/include/webcpp/trystero/platform/entropy.hpp index c99207f..7962403 100644 --- a/include/webcpp/trystero/platform/entropy.hpp +++ b/include/webcpp/trystero/platform/entropy.hpp @@ -10,7 +10,7 @@ #include #ifdef WEBCPP_TARGET_EMSCRIPTEN -#include // lint-world: getentropy, the page's crypto.getRandomValues +#include #else #include #endif @@ -22,18 +22,51 @@ 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 C library's entropy call, which Emscripten draws from - * the page's `crypto.getRandomValues`. + * 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 - // The C library's entropy call fills at most 256 bytes at a time. - constexpr std::size_t most = 256; + // 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; @@ -41,7 +74,7 @@ inline bool fill_random(std::span out) noexcept { 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 (getentropy(out.data() + at, piece) != 0) { // lint-world: Trystero's randomness + if (js_fill_random(out.data() + at, piece) != 0) { // lint-world: Trystero's randomness return false; } #else diff --git a/include/webcpp/trystero/platform/sealer.hpp b/include/webcpp/trystero/platform/sealer.hpp index a412731..7bd9852 100644 --- a/include/webcpp/trystero/platform/sealer.hpp +++ b/include/webcpp/trystero/platform/sealer.hpp @@ -108,8 +108,16 @@ inline emscripten::val take(emscripten::EM_VAL handle) { return emscripten::val::take_ownership(handle); } -/** A copy of an `ArrayBuffer`'s bytes, in `memory`. */ -inline backend::bytes from_js(const emscripten::val& buffer, std::pmr::memory_resource* memory) { +/** + * 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()); @@ -301,12 +309,12 @@ class sealer : public backend::sealer, public std::enable_shared_from_this(b.data()), b.size())); + if (!b) { + done(make_error_code(error::backend_failure), {}); + return; + } + done({}, std::string_view(reinterpret_cast(b->data()), b->size())); })); } diff --git a/test/Jamfile b/test/Jamfile index 3b9e43e..870ca7e 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -166,6 +166,9 @@ webcpp.run platform_page_sealer_allocation : platform_page_sealer_allocation_tes # 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) : 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. @@ -196,6 +199,8 @@ webcpp.run platform_page_no_exceptions : platform_page_test.cpp webcpp.run platform_page_sealer_allocation_no_exceptions : platform_page_sealer_allocation_test.cpp : $(platform) off : emscripten ; +webcpp.run platform_page_sealer_no_exceptions : platform_page_sealer_test.cpp + : $(platform) 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 diff --git a/test/platform_backend_test.cpp b/test/platform_backend_test.cpp index 3610b14..347871b 100644 --- a/test/platform_backend_test.cpp +++ b/test/platform_backend_test.cpp @@ -12,7 +12,8 @@ // 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. +// - 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. @@ -33,6 +34,8 @@ #include #include #include +#include +#include namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; @@ -127,6 +130,31 @@ void its_randomness_fills_and_differs() { 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()); @@ -140,6 +168,7 @@ int main() { its_own_state_is_in_its_memory(); its_clocks_are_the_standard_librarys(); its_randomness_fills_and_differs(); + its_randomness_fills_more_than_a_piece(); its_executor_and_tls_context_are_there(); 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_sealer_test.cpp b/test/platform_sealer_test.cpp index 9873dfe..ec54a27 100644 --- a/test/platform_sealer_test.cpp +++ b/test/platform_sealer_test.cpp @@ -9,10 +9,12 @@ // 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. 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. +// 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, @@ -34,6 +36,7 @@ #include #include +#include #include #include #include @@ -101,6 +104,9 @@ struct state { 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. */ @@ -152,6 +158,21 @@ void verdict(state& s) { } 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); @@ -180,10 +201,12 @@ void seal_without_subtle(state& s) { } #endif -/** Once the wrong key and the garbage are refused: on emscripten, a page without crypto.subtle. */ -void refused(state& s) { - if (!s.wrong_key || !s.garbage) { - return; +/** 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); @@ -192,6 +215,28 @@ void refused(state& 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. From ca895f0f758af93b7bc46ab821b088dccbcb9cde Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:48:09 -0300 Subject: [PATCH 075/116] trystero: a page_call's handler checks a number's range before reading it embind's as() of a number beyond the type's range, as 1e10, throws a TypeError in a build with assertions, which leaves run for good: page.hpp says to read a number as a double and check its range first, and platform_page_call reads its numbers so, with cases that would throw. --- include/webcpp/trystero/platform/page.hpp | 9 +++-- test/platform_page_call_test.cpp | 41 +++++++++++++++++++++-- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/include/webcpp/trystero/platform/page.hpp b/include/webcpp/trystero/platform/page.hpp index 96f2316..2a57a20 100644 --- a/include/webcpp/trystero/platform/page.hpp +++ b/include/webcpp/trystero/platform/page.hpp @@ -86,12 +86,15 @@ inline emscripten::val js_string(std::string_view utf8) { * 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`. `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. + * 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 out of a handler". + * error that a handler lets escape". */ template // The bridge indexes the call by its registration, a private base: its one owner is the call. diff --git a/test/platform_page_call_test.cpp b/test/platform_page_call_test.cpp index 7880d38..24a0852 100644 --- a/test/platform_page_call_test.cpp +++ b/test/platform_page_call_test.cpp @@ -9,6 +9,10 @@ // // - 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 @@ -32,8 +36,10 @@ #include #include +#include #include #include +#include #include #include @@ -117,6 +123,37 @@ void outlive_the_io_context(program& p) { 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 double 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. @@ -125,8 +162,7 @@ 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()) { - const val n = argument["n"]; - p.seen_n = n.isNumber() ? n.as() : -1; + p.seen_n = read_int32(argument["n"]).value_or(-1); } p.doomed.reset(); // The page calls the function it kept, then the next. @@ -151,6 +187,7 @@ void advance(program& p, const val& argument) { } // namespace int main() { + numbers_are_read_within_their_range(); program p; p.doomed.emplace( p.io.get_executor(), From ba7cc2e698de788d38ba33a2a2b4fc9b9843fa5b Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:48:09 -0300 Subject: [PATCH 076/116] trystero: stale words of the two backends, and a broken comment max_relay_message_bytes names the platform backend on both targets, the guide's opening the platform backend and its targets, and platform_peer_connection's opening comment is one paragraph again. --- doc/trystero.adoc | 2 +- include/webcpp/trystero/protocol/relays.hpp | 5 +++-- test/platform_peer_connection_test.cpp | 7 +++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/doc/trystero.adoc b/doc/trystero.adoc index fcd4f06..a423750 100644 --- a/doc/trystero.adoc +++ b/doc/trystero.adoc @@ -21,7 +21,7 @@ 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 diff --git a/include/webcpp/trystero/protocol/relays.hpp b/include/webcpp/trystero/protocol/relays.hpp index d29ff16..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; diff --git a/test/platform_peer_connection_test.cpp b/test/platform_peer_connection_test.cpp index 1bb5b3b..1227571 100644 --- a/test/platform_peer_connection_test.cpp +++ b/test/platform_peer_connection_test.cpp @@ -5,10 +5,9 @@ // 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 +// 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. From c883bb5cfc2048d68ff7d43178abe2389b0a3218 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:51:57 -0300 Subject: [PATCH 077/116] trystero: the guide and AGENTS.md on the reviewed relays, TLS and randomness The guide says what holds of a wss:// relay's TLS on each target (verify_peer on the stream on both, what a page's stream refuses, what tls_context() configures), that a relay's first texts are bounded too and a binary message dropped, that a page's randomness is crypto.getRandomValues behind JavaScript that catches, and that a Web Crypto settlement is read only as an ArrayBuffer. "What stays outside the resource" lists exactly what a relay allocates outside the room's resource on each target, which guarantee 5 names with its tests, and guarantee 8 says which test checks the 4 MiB. testing.adoc names the new tests and the IPv6 case that does not apply where the kernel has no socket of IPv6's family; CONVERSION.md maps the old native_sealer cases to platform_sealer's steps. --- AGENTS.md | 59 ++++++++++++++++++++------- doc/allocation.adoc | 40 +++++++++++++++---- doc/design.adoc | 4 +- doc/guarantees.adoc | 23 +++++++---- doc/overview.adoc | 2 +- doc/platform.adoc | 97 +++++++++++++++++++++++++++++---------------- doc/testing.adoc | 71 ++++++++++++++++++++++----------- test/CONVERSION.md | 12 +++++- 8 files changed, 216 insertions(+), 92 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 80b6d1b..e507194 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,8 +51,10 @@ holds only what is specific to trystero. 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 `getentropy`, which - Emscripten draws from `crypto.getRandomValues`. Without randomness + 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 @@ -184,12 +186,25 @@ holds only what is specific to trystero. 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. Each refusal reports a close. Natively, over TLS the - connection sets `verify_peer` on its stream whatever the program's context - says, 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. On Windows the system's authorities are + 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 @@ -240,7 +255,9 @@ holds only what is specific to trystero. 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. Every event and every page call + 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. @@ -250,7 +267,8 @@ holds only what is specific to trystero. 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` and every `platform_page*`) run under + `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 @@ -321,7 +339,9 @@ holds only what is specific to trystero. `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 targets, in a page before it is copied into - WebAssembly (webcpp::beast's `read_message_max`). A relay that stops + 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 @@ -692,10 +712,19 @@ holds only what is specific to trystero. handshake's request and response with their fields, and a non-101 response's body up to Beast's default 8 MiB, which no option of its stream lowers, the verify callback and its copy of the host, the timers' - waits 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 outside it (in a page the stream's own state - is there too, made with `std::allocator_arg` and the room's allocator); + 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` or document's own `operator new`; on Emscripten, the C library's `select()`, which Asio's reactor calls on diff --git a/doc/allocation.adoc b/doc/allocation.adoc index c6118c3..5b6d698 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -281,14 +281,38 @@ nothing. 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; 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 a message allocates nothing - outside it (measured with a stack for each `operator new` on the room's - thread: a hundred texts sent and received made none but the write - buffer's, at the first); in a page the stream's own state is there too, - and the page's `WebSocket` makes the handshake; + 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` or document's own `operator new`, the user's choice; diff --git a/doc/design.adoc b/doc/design.adoc index 4765a8d..23faa22 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -40,8 +40,8 @@ | `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 `getentropy` in a - page; and, in a page, `page_call` and `js_string` + 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 diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index 263e441..669a86b 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -46,9 +46,15 @@ file transfers of the `interop` lane. resources,* but what <> lists: from its construction until its `io_context` has drained, the global `operator new` sees only webcpp::document's working state while it reads or writes a JSON -text, each piece freed before that call returns, and the C library nothing. -_Held by_ `allocation`, natively and on emscripten, and, for a page's sealer, -`platform_page_sealer_allocation`. +text, each piece freed before that call returns, and the C library nothing; +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 @@ -70,11 +76,12 @@ 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_ `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 on emscripten by -`platform_page_websocket_bound`, where the page's `WebSocket` holds what is -unsent, and `platform_page_websocket_late_events`, where the session's queue -does, with exceptions and without them, which also check 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/overview.adoc b/doc/overview.adoc index b6014d3..99b07d6 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -60,7 +60,7 @@ out. The backend is a header of its own, beside a page's: 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` (<>) + `crypto.subtle` and `crypto.getRandomValues` (<>) | `` | emscripten diff --git a/doc/platform.adoc b/doc/platform.adoc index 8eb2602..853f512 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -18,8 +18,8 @@ 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 `getentropy`, which Emscripten draws from -`crypto.getRandomValues`. Its clocks are the standard library's on both: +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()`. @@ -120,15 +120,21 @@ 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 -(<>), and a message allocates nothing outside it; in a -page the stream's own state is there too. Natively what Beast, Asio and -OpenSSL allocate of their own, which takes no allocator, stays outside it, -for each connection: 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 (<>). A write that -fails ends the connection, which reports its close at once. The WebSockets -are Beast's rather than libdatachannel's own, so the relays run on the -room's executor like everything else. +(<>); 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 @@ -157,15 +163,24 @@ a newline or a backslash anywhere in the URL, which a page drops or reads as a slash. 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, 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 whatever the verify mode of the context, 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. 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 against the authorities it -trusts, as a page's `WebSocket` always verifies; the context itself is left -as it is. By default the backend makes its TLS context with +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 @@ -196,13 +211,17 @@ The backend takes the context as `make_tls_client_context` returns it, a 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. +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. + 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 @@ -237,16 +256,22 @@ Each drop reports one close, and the room reconnects with its backoff 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, `getentropy` in a page. When it has none, -`random()` aborts the program, since nothing is safe without it, and a seal -fails with `error::backend_failure`. +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. +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 @@ -394,11 +419,14 @@ is made to carry either. ==== No JavaScript exception enters WebAssembly The backend makes every call into JavaScript that can throw, a `WebSocket` -constructor or `send`, a Web Crypto method, 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, and 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. +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} @@ -415,9 +443,10 @@ stops it. (`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, and its socket's - `bufferedAmount` and its texts waiting for the executor too - (<>); a page has no idle timeout. +* 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 diff --git a/doc/testing.adoc b/doc/testing.adoc index 438de21..2e9a066 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -124,33 +124,47 @@ include::{library-root}/test/Jamfile[tag=allocation] already queued. | `platform_backend`, `platform_sealer`, `platform_websocket_unreachable`, - and each `_no_exceptions` + `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, 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, and completes after the call that started it, never - inside it; 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, or of a port on 127.0.0.1 or - `::1` where nothing listens, reports exactly one close, after the call - that made it. + 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, reads URLs as a page - does, 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, keeps a TLS context's error in the backend, 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. + 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 (<>). | `platform_peer_connection`, `platform_room`, and each `_no_exceptions` | Natively, two connections of the backend's WebRTC, over webcpp::webrtc's @@ -167,14 +181,21 @@ include::{library-root}/test/Jamfile[tag=allocation] 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_allocation`, and each `_no_exceptions` + `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; over webcpp::webrtc's browser + 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 @@ -185,10 +206,14 @@ include::{library-root}/test/Jamfile[tag=allocation] 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; the relay socket's - and the sealer's handlers run outside the page's events; and a seal and - an open allocate nothing outside the room's resource, neither with - `operator new` nor with the C library's functions. + 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 platform backend's tests run on each target that builds them, and once diff --git a/test/CONVERSION.md b/test/CONVERSION.md index 074eee6..a1f115e 100644 --- a/test/CONVERSION.md +++ b/test/CONVERSION.md @@ -177,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 | @@ -272,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. From 14e965ab1d941000bc8ba61d88c966b7059291ee Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:52:16 -0300 Subject: [PATCH 078/116] trystero: the changelog and the guide name WP7's breaking changes and what a JSON payload's text holds The changelog's Unreleased lines, ten still, merge what they held and add WP7's breaking changes: JSON payloads as webcpp::document's, with Boost.Charconv linked; payload without copy assignment, and without exceptions without a copy constructor, as document has no default constructor then; read_signal, nostr::read_relay_message and append_value on webcpp::document's values; append_string returning its error, a local candidate that is not UTF-8 dropped. The usage page names the same where payloads are described, and says what of JSON.stringify's text holds: every value JavaScript can hold, a number a double cannot hold being sent exact. The protocol page names a payload's depth and lone-surrogate refusal, and the appendix records both as differences. --- doc/changelog.adoc | 32 +++++++++++++++++++------------- doc/differences.adoc | 10 ++++++++++ doc/protocol.adoc | 14 +++++++++----- doc/usage.adoc | 27 ++++++++++++++++++++------- 4 files changed, 58 insertions(+), 25 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index f03c939..3d80f20 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -22,20 +22,26 @@ link `/webcpp/trystero//platform` on both targets. * *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`, or +`pmr_document` in a resource, for `boost::json::value` and `json_resource`; +programs link Boost.Charconv too. +* *Breaking change:* Changed `payload` to lose copy assignment, and without +exceptions its copy constructor and the default one of +`webcpp::document::document`; make documents with `create()` or `parse`. +* *Breaking change:* Changed `read_signal`, `nostr::read_relay_message` and +`append_value` to take webcpp::document's values, `make_id` to `random_id`, +and `proposal::size` to `std::uint64_t`. +* *Breaking change:* Changed `protocol::json::append_string` to return its +error on text that is not UTF-8; such a local candidate is dropped, such a +self id set aside. * *Breaking change:* Removed the backends' own connection and channel classes -for webcpp::webrtc's, and `browser::event_loop`. -* *Breaking change:* Changed the backend to throw nothing; `tls_context()` -returns a `boost::system::result`. -* *Breaking change:* Changed `protocol::make_id` to `protocol::random_id`, and -`protocol::proposal::size` to `std::uint64_t`. -* Changed a page's relays to the native ones' webcpp::beast session, which -refuses `http://` relay URLs and bounds what the page holds unsent. -* Added `backend_config::memory` for the backend's own state, and -`backend_config::runtime`, at most 256 connections at once, on both targets. -* Fixed relays at an IPv6 address being unreachable, and pages ignoring a -failed `getentropy`. -* Fixed 32-bit receivers, pages among them, misreading transfer offers of 4 GiB -or more. +for webcpp::webrtc's, and `browser::event_loop`; the backend throws nothing, +and `tls_context()` returns a `boost::system::result`. +* Changed a page's relays to the native webcpp::beast session, refusing +`http://` URLs and bounding unsent text; added `backend_config::memory` and +`backend_config::runtime`, at most 256 connections at once. +* Fixed relays at an IPv6 address being unreachable, pages ignoring a failed +`getentropy`, and 32-bit receivers misreading transfer offers of 4 GiB or more. * Fixed rooms slowed by relays' event ids chosen to collide; channels keep frames that arrive before a handler, 64 for 10 s. // end::unreleased[] diff --git a/doc/differences.adoc b/doc/differences.adoc index 1ca8d8a..4f6518c 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -117,6 +117,10 @@ has nothing of it to run beside its twin. | 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 | impossible: 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 + | 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) |=== @@ -539,4 +543,10 @@ its reason. | 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. + +| A JSON payload's number that a double cannot hold +| No Trystero JS program holds such a number, so no twin could send it; the `protocol` test writes one exact beside what `JSON.stringify` writes of the same text. + +| A JSON payload nested deeper than 256, or holding a lone surrogate +| What differs is a message the {cpp} room does not deliver, which a program would show only as nothing printed; webcpp::document's `parse` test holds both refusals. |=== diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 5926b37..ecfad14 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -110,14 +110,18 @@ hundred times its length, is refused once the parse has filled that bound. 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 has no bound of -its own but the room's `max_receive_bytes` and document's 64 MiB of image. +its own but the room's `max_receive_bytes` and document's defaults: 64 MiB of +image and 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 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: 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`. +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 diff --git a/doc/usage.adoc b/doc/usage.adoc index 1ab566a..686bfda 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -205,10 +205,23 @@ messages travel and how they are received: A JSON payload is webcpp::document's: a `webcpp::document::document` the program builds or parses, or a `pmr_document`, whose image is a buffer of a -memory resource, the room's when it is received. A text that does not parse -is not delivered. A {cpp} peer sends what `JSON.stringify` writes of the -document, the bytes Trystero JS sends of the same value. The room test sends -one: +memory resource, the room's when it is received. 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 (<>). + +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 `webcpp::document::document` a default constructor there, +where a program makes one with `webcpp::document::document::create()` or +`webcpp::document::parse`, each of which returns a result. The room test +sends one: [source] ---- @@ -266,9 +279,9 @@ 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 written at once, as `JSON.stringify` -writes it, 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 +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] From c78bd49b3f6ac970ef45c38addf6bde8c7f543df Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:52:16 -0300 Subject: [PATCH 079/116] trystero: long lines wrapped, read_signal's Doc Comment, and what the allocation test asserts build.jam's comment, overview.adoc's requirements, which name Boost.Charconv now, and allocation.adoc's paragraphs are wrapped as the files are. The allocation page no longer gives a count of global allocations that the test neither asserts nor could, since it depends on timing: it says the test asserts none is left at the drain. The allocation test's Jamfile comment names webcpp::document's working state, which operator new sees. --- build.jam | 6 ++--- doc/allocation.adoc | 25 ++++++++++++--------- doc/overview.adoc | 18 ++++++++------- include/webcpp/trystero/protocol/signal.hpp | 9 ++++---- test/Jamfile | 8 ++++--- 5 files changed, 37 insertions(+), 29 deletions(-) diff --git a/build.jam b/build.jam index 9d20c44..7f4834a 100644 --- a/build.jam +++ b/build.jam @@ -53,9 +53,9 @@ rule platform-dependencies ( properties * ) } # 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. +# 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. # tag::trystero[] alias trystero : : @trystero-dependencies : : include /boost//headers /webcpp/document//document diff --git a/doc/allocation.adoc b/doc/allocation.adoc index c6118c3..3398ecf 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -26,8 +26,9 @@ own state. * `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, the documents of the JSON texts it reads, 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 @@ -233,8 +234,9 @@ allocator: Boost.JSON's parser stack, the path and the pending key and text of the value being read, the tree's record of each change, which places a value, and the writer's stack. Each is freed before the parse or the write that made it returns, so none is left at any moment the room's executor is -between handlers. Measured natively with the LLVM standard library, each text a room reads -costs `operator new` about seven allocations a value: a relay's event +between handlers. Measured natively with the LLVM standard library, each +text a room reads costs `operator new` about seven allocations a value: a +relay's event carrying an offer, 1,581 bytes and 14 values, 93; a relay's `OK`, 5 values, 32; a signal, 4 values, 26; a handshake message, 3 values, 20; a candidate, 5 values, 32. Writing and reading back a JSON payload of 7 values costs 48. @@ -342,10 +344,12 @@ is kept, by its address, in a table of a fixed size until it is freed. 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 webcpp::document's working state alone, as the rooms - and the relay read and write their JSON texts (2,320 allocations, measured - natively), none of it left at the drain, 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. + and the relay read and write their JSON texts, and the C library nothing. + How many texts they read depends on the timing of the run, so the test + asserts no number of allocations: it asserts that none is left at the + drain. 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 @@ -357,8 +361,9 @@ is kept, by its address, in a table of a fixed size until it is freed. 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 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 +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 diff --git a/doc/overview.adoc b/doc/overview.adoc index b6014d3..08c8078 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -33,8 +33,8 @@ The library provides: 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; +* 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 the @@ -75,12 +75,14 @@ on both. Every name is in the namespace `webcpp::trystero`. === Requirements * A {cpp}20 compiler. -* Boost 1.92: Asio, Assert, Circular Buffer, Container (its `pmr` base - class), Endian, Hash2, JSON (the parser webcpp::document uses), 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 (<>). +* 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. diff --git a/include/webcpp/trystero/protocol/signal.hpp b/include/webcpp/trystero/protocol/signal.hpp index c8eb77f..8accea9 100644 --- a/include/webcpp/trystero/protocol/signal.hpp +++ b/include/webcpp/trystero/protocol/signal.hpp @@ -224,11 +224,10 @@ struct signal_message { * @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. + * `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 json::const_value& document) { // Trystero ignores a text that names a member `peer`, which its own rooms keep for a peer diff --git a/test/Jamfile b/test/Jamfile index 18d79ce..0dfd654 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -122,9 +122,11 @@ webcpp.run platform_room_no_exceptions : platform_room_test.cpp # 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, but webcpp::document's working state +# while it reads or writes a JSON text, which the global operator new sees, +# none of it left once the call returns; 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. # tag::allocation[] webcpp.run allocation : allocation_test.cpp : emscripten:-sALLOW_MEMORY_GROWTH ; # end::allocation[] From 46b4e9323f0d113b7517babb379b3ce69163dc5a Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:55:50 -0300 Subject: [PATCH 080/116] trystero: a JSON payload's Doc Comments say what of JSON.stringify's text holds pmr_document and the payload traits of both documents wrote that a value is written as JSON.stringify writes it: so is every value JavaScript can hold, and a number a double cannot hold is written exact. --- include/webcpp/trystero/room.hpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 5eaf03a..5ec14e8 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -94,7 +94,8 @@ using pmr_bytes = std::pmr::vector; * * A message received as `pmr_document` is parsed into a buffer of the room's effective * `room_options::memory`, which must outlive the value, with every value of the document in that - * buffer. One sent is written once, as `JSON.stringify` writes it, into the room's resource. + * buffer. One sent is written once into the room's resource, as `JSON.stringify` writes every + * value JavaScript can hold; a number a double cannot hold is written exact. * * @see "Allocation", in the guide. */ @@ -268,8 +269,8 @@ 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` does, into a shared string of the room's - * resource. */ + /** 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); @@ -301,8 +302,8 @@ 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` does, into a shared string of the room's - * resource. */ + /** 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 pmr_document& v, std::pmr::memory_resource* memory) { std::pmr::string text(memory); protocol::json::append_value(text, v.root()); From bf631da14ff7d21ff6056906d5baed6ff1cfa4da Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:06:40 -0300 Subject: [PATCH 081/116] trystero: the new tests and the candidate writer to the pinned clang-tidy The signaling test records a published signal by designated members and holds its strategy const, the handshake case compares with std::string_view::npos, and candidate_json's quoted results are const, as misc-const-correctness asks. --- include/webcpp/trystero/webrtc/peer_connection.hpp | 6 +++--- test/shared_test.cpp | 2 +- test/signaling_test.cpp | 8 ++++++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp index 7f0b662..5baf56d 100644 --- a/include/webcpp/trystero/webrtc/peer_connection.hpp +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -54,13 +54,13 @@ inline webcpp::document::result candidate_json( std::optional sdp_m_line_index, std::string_view username_fragment, std::pmr::memory_resource* memory) { std::pmr::string json(R"({"candidate":)", memory); - if (auto quoted = protocol::json::append_string(json, candidate); !quoted) { + 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 (auto quoted = protocol::json::append_string(json, sdp_mid); !quoted) { + } else if (const auto quoted = protocol::json::append_string(json, sdp_mid); !quoted) { return quoted.error(); } json += R"(,"sdpMLineIndex":)"; @@ -71,7 +71,7 @@ inline webcpp::document::result candidate_json( } if (!username_fragment.empty()) { json += R"(,"usernameFragment":)"; - if (auto quoted = protocol::json::append_string(json, username_fragment); !quoted) { + if (const auto quoted = protocol::json::append_string(json, username_fragment); !quoted) { return quoted.error(); } } diff --git a/test/shared_test.cpp b/test/shared_test.cpp index 280c946..6ba1545 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -1873,7 +1873,7 @@ void a_handshake_message_past_its_bound_fails() { } 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")") != text.npos) { + text.find(R"("__trystero_pw":"response")") != std::string_view::npos) { ++proofs; } return trystero::test::memory_network::verdict::drop; diff --git a/test/signaling_test.cpp b/test/signaling_test.cpp index b99ee40..ade19e9 100644 --- a/test/signaling_test.cpp +++ b/test/signaling_test.cpp @@ -248,7 +248,11 @@ struct answerer { .claim = {}, .publish = [this](std::size_t relay, std::string_view topic, std::string_view content) { - published.push_back({relay, std::string(topic), std::string(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, @@ -385,7 +389,7 @@ void a_relay_text_past_its_bound_is_dropped() { const std::pmr::string url("wss://relay.test", memory()); const std::string_view topic = "the-room-topic"; std::vector contents; - auto strategy = std::make_shared( + 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()); }, From 502f4f1d78cd3aec16b9f598c211e7df57bef4ba Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:08:43 -0300 Subject: [PATCH 082/116] trystero: the guide names the path characters a relay's URL may not hold The URL rules list a character RFC 3986 allows in no path, which a page escapes and Boost.URL refuses; transfer_handler's comment says that the type-erased handler is what the session used before; AGENTS.md's lines within 80 columns. --- AGENTS.md | 15 ++++++++------- doc/platform.adoc | 11 ++++++----- include/webcpp/trystero/platform/websocket.hpp | 10 +++++----- 3 files changed, 19 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e507194..eb56449 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,9 +204,9 @@ holds only what is specific to trystero. 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 + `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 @@ -257,10 +257,11 @@ holds only what is specific to trystero. 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. + `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, diff --git a/doc/platform.adoc b/doc/platform.adoc index 853f512..3e60931 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -19,8 +19,8 @@ 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 +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()`. @@ -158,9 +158,10 @@ 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; and a tab, -a newline or a backslash anywhere in the URL, which a page drops or reads as -a slash. A refused URL makes the relay report a close, as an unreachable one +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, diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index eb82285..821be79 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -566,11 +566,11 @@ class websocket_session : public std::enable_shared_from_this Date: Sat, 14 Nov 2026 23:09:05 -0300 Subject: [PATCH 083/116] trystero: every JSON text is parsed into a webcpp::document::pmr::document protocol::json::document, the owner of an external document in a buffer of the room's resource, goes with its doubling retry loop: each protocol text is read by webcpp::document::parse into a pmr::document of the room's resource (the app's for a candidate), within protocol_limits of its caller's bound, its image growing in place. trystero::pmr_document is removed: an action of webcpp::document::pmr::document receives in the room's resource, and a JSON payload of either document type is parsed within twice its own size and 64 KiB of image. A rejected async_receive completes with an empty value in the room's resource, a document holding null. The allocation test expects no global allocation again: each payload exchange and each protocol text sees none, as the long cases, and a planted allocation shows the counts see one. --- .../webcpp/trystero/detail/nostr_strategy.hpp | 6 +- include/webcpp/trystero/detail/signaling.hpp | 7 +- include/webcpp/trystero/protocol/json.hpp | 262 +---------------- include/webcpp/trystero/room.hpp | 176 +++++++----- .../trystero/webrtc/peer_connection.hpp | 6 +- test/allocation_test.cpp | 271 ++++++++++-------- test/protocol_test.cpp | 140 ++++----- test/room_test.cpp | 76 ++++- test/support/memory_backend.hpp | 7 +- test/support/rooms.hpp | 6 +- 10 files changed, 437 insertions(+), 520 deletions(-) diff --git a/include/webcpp/trystero/detail/nostr_strategy.hpp b/include/webcpp/trystero/detail/nostr_strategy.hpp index 597d88e..0fa4443 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -18,6 +18,8 @@ #include #include +#include + #include #include #include @@ -457,9 +459,9 @@ class nostr_strategy : public std::enable_shared_from_this { void on_relay_message(std::size_t index, std::string_view text) { // A text past its bound is dropped as a malformed one is, before it is read. - const auto document = protocol::json::parse( + const auto document = webcpp::document::parse( text, protocol::json::protocol_limits(protocol::nostr::max_parsed_relay_text_bytes), - memory_); + std::pmr::polymorphic_allocator(memory_)); if (!document.has_value()) { return; } diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index a620353..36382ba 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -22,6 +22,8 @@ #include #include +#include + #include #include #include @@ -156,8 +158,9 @@ class signaling : public std::enable_shared_from_this { return; } // A signal past its bound is dropped as a malformed one is, before it is read. - const auto document = protocol::json::parse( - content, protocol::json::protocol_limits(protocol::max_parsed_signal_bytes), memory_); + 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_) { diff --git a/include/webcpp/trystero/protocol/json.hpp b/include/webcpp/trystero/protocol/json.hpp index aad2ac0..579e711 100644 --- a/include/webcpp/trystero/protocol/json.hpp +++ b/include/webcpp/trystero/protocol/json.hpp @@ -12,240 +12,50 @@ #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 on webcpp::document, with every value in the - * resource the caller gives. A text is read into a document whose image is a buffer of that - * resource; a text the protocol writes is a fixed shape of a few strings and numbers, so it is + * 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. - * - * Tip: document's parser and writer keep their working state (Boost.JSON's parser stack, the path - * and the pending text, the tree's record of each change, the writer's stack) in the standard - * allocator, each freed before the call that made it returns: the guide's "Allocation" lists it - * outside the resource, measured. */ namespace webcpp::trystero::protocol::json { /** The traits of every document trystero reads and writes: document's defaults, UTF-8. */ using traits = webcpp::document::default_traits; -/** The read-only handle of a value of a @ref document. */ -using const_value = webcpp::document::basic_const_value; - -/** The handle of a value of a @ref document, which reads and writes. */ -using value = webcpp::document::basic_value; - -class document; - -webcpp::document::result parse(std::string_view text, - const webcpp::document::parse_options& options, - std::pmr::memory_resource* memory); - -/** - * A JSON document whose image is a buffer of a memory resource: every value in it, strings - * included, lives in that buffer, which the document owns and gives back when it goes. - * - * The buffer never grows: a change that needs more room returns `errc::capacity`, as document's - * external storage does. @ref parse sizes it for the text it reads. It is move-only; moving keeps - * the buffer where it is, so the handles of its values stay valid. - * - * @see "Allocation", in the guide. - */ -class document { -public: - /** The document over the buffer: document's external storage. */ - using document_type = webcpp::document::basic_document; - - /** A document that holds no image, as one moved from does. */ - document() noexcept = default; - - /** - * Takes the image and the buffer of `other`, which holds nothing after it. - * - * @param other The document. - */ - document(document&& other) noexcept - : memory_(std::exchange(other.memory_, nullptr)), - buffer_(std::exchange(other.buffer_, nullptr)), - size_(std::exchange(other.size_, 0)), - document_(std::move(other.document_)) { - other.document_.reset(); - } - - /** - * Gives this document's buffer back, then takes the image and the buffer of `other`. - * - * @param other The document. - * @return This document. - */ - document& operator=(document&& other) noexcept { - if (this != &other) { - release(); - memory_ = std::exchange(other.memory_, nullptr); - buffer_ = std::exchange(other.buffer_, nullptr); - size_ = std::exchange(other.size_, 0); - document_ = std::move(other.document_); - other.document_.reset(); - } - return *this; - } - - /** A document is not copied: `get().clone()` copies its content into an owned document. */ - document(const document&) = delete; - - /** A document is not copied: `get().clone()` copies its content into an owned document. */ - document& operator=(const document&) = delete; - - /** Gives the buffer back to its resource. */ - ~document() { release(); } - - /** - * Makes a new document holding `null`, in a buffer of `bytes` from `memory`. - * - * @param bytes The size of the buffer, which every change of the document must fit; rounded up - * to 16. - * @param memory The resource the buffer comes from; it must outlive the document. - * @return The document; `errc::capacity` when `bytes` cannot hold an empty document. - */ - static webcpp::document::result create(std::size_t bytes, - std::pmr::memory_resource* memory) { - document made(memory, bytes); - auto formatted = webcpp::document::format(made.buffer()); - if (!formatted.has_value()) { - return formatted.error(); - } - made.document_.emplace(std::move(formatted).unsafe_value()); - return made; - } - - /** - * Whether it holds an image: false for one default-constructed or moved from. - * - * @return Whether there is a value to read. - */ - [[nodiscard]] bool has_value() const noexcept { return document_.has_value(); } - - /** - * The handle of the document's value. - * - * @return The handle; one that names nothing, which reads `undefined`, when it holds no image. - */ - [[nodiscard]] const_value root() const noexcept { - return document_.has_value() ? std::as_const(*document_).root() : const_value(); - } - - /** - * The handle of the document's value, which writes in the buffer. - * - * @return The handle; one that names nothing when it holds no image. - */ - [[nodiscard]] value root() noexcept { - return document_.has_value() ? document_->root() : value(); - } - - /** - * document's own document over the buffer, for what the handles do not do, such as `clone` - * and `image`. - * - * @return The document; it must hold an image. - */ - [[nodiscard]] const document_type& get() const noexcept { - BOOST_ASSERT(document_.has_value()); - return *document_; // NOLINT(bugprone-unchecked-optional-access): asserted - } - - /** - * document's own document over the buffer, which writes. - * - * @return The document; it must hold an image. - */ - [[nodiscard]] document_type& get() noexcept { - BOOST_ASSERT(document_.has_value()); - return *document_; // NOLINT(bugprone-unchecked-optional-access): asserted - } - - /** - * The resource the buffer comes from. - * - * @return The resource; null when it holds no image. - */ - [[nodiscard]] std::pmr::memory_resource* resource() const noexcept { return memory_; } - - /** - * The size of the buffer, the most the image can take. - * - * @return The bytes; 0 when it holds no image. - */ - [[nodiscard]] std::size_t capacity() const noexcept { return size_; } - -private: - friend webcpp::document::result parse(std::string_view text, - const webcpp::document::parse_options& options, - std::pmr::memory_resource* memory); - - /** The alignment of document's images. */ - static constexpr std::size_t alignment = 16; - - /** `bytes` rounded up to the alignment. */ - static constexpr std::size_t aligned(std::size_t bytes) noexcept { - return (bytes + alignment - 1) / alignment * alignment; - } - - /** A document with a buffer of `bytes`, rounded up to 16, from `memory`, and no image yet. */ - document(std::pmr::memory_resource* memory, std::size_t bytes) - : memory_(memory), - buffer_(static_cast(memory->allocate(aligned(bytes), alignment))), - size_(aligned(bytes)) {} - - /** The buffer. */ - [[nodiscard]] std::span buffer() const noexcept { return {buffer_, size_}; } +/** The read-only handle of a value of a `webcpp::document::pmr::document`. */ +using const_value = webcpp::document::basic_const_value; - /** Ends the document, then gives its buffer back. */ - void release() noexcept { - document_.reset(); - if (buffer_ != nullptr) { - memory_->deallocate(buffer_, size_, alignment); - } - memory_ = nullptr; - buffer_ = nullptr; - size_ = 0; - } - - std::pmr::memory_resource* memory_ = nullptr; - std::byte* buffer_ = nullptr; - std::size_t size_ = 0; - std::optional document_; -}; +/** The handle of a value of a `webcpp::document::pmr::document`, which reads and writes. */ +using value = webcpp::document::basic_value; /** - * The limits of a protocol text's parse: at most `max_bytes` of text, into an image at most twice - * that and 64 KiB more. + * The limits of a JSON text's parse: at most `max_bytes` of text, 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 parse has - * filled the bound, so that no text costs a room more than a multiple of its bound to read. + * 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. * * @param max_bytes The longest text the caller reads. * @return The options. @@ -257,54 +67,6 @@ constexpr webcpp::document::parse_options protocol_limits(std::uint64_t max_byte return o; } -/** - * `JSON.parse(text)` into a @ref document in a buffer of `memory`, as webcpp::document reads it: a - * key written twice keeps the last value in the first one's place, and a lone surrogate is - * refused. - * - * The buffer is first sized for a text of a few values, twice the text and 4 KiB; a parse that - * fills it is made again in a buffer twice the size, up to `options.max_document_bytes`. - * - * @param text The text. - * @param options The limits: `max_bytes` of text, checked before anything is read, - * `max_document_bytes` of buffer, and `max_depth`. - * @param memory The resource the buffer comes from; it must outlive the document. - * @return The document; `errc::capacity` for a text longer than `max_bytes`, nested deeper than - * `max_depth`, or whose image needs more than `max_document_bytes`, `errc::syntax` for malformed - * text, `errc::range` for a number document refuses. - */ -inline webcpp::document::result parse(std::string_view text, - const webcpp::document::parse_options& options, - std::pmr::memory_resource* memory) { - if (text.size() > options.max_bytes) { - return webcpp::document::errc::capacity; - } - constexpr std::size_t first_spare = std::size_t{4} << 10U; - const auto most = static_cast(std::min( - options.max_document_bytes, std::numeric_limits::max() / 4)); - std::size_t bytes = std::min((2 * text.size()) + first_spare, most); - for (;;) { - document made(memory, bytes); - webcpp::document::basic_parser parser(made.buffer(), - options); - const webcpp::document::result written = parser.write(text); - auto finished = written.has_value() - ? parser.finish() - : webcpp::document::result(written.error()); - if (finished.has_value()) { - made.document_.emplace(std::move(finished).unsafe_value()); - return made; - } - // A full buffer is errc::capacity without a cause of Boost.JSON's, which a text nested past - // max_depth has. - const bool full = finished.error() == webcpp::document::errc::capacity && !parser.cause(); - if (!full || bytes >= most) { - return finished.error(); - } - bytes = std::min(2 * bytes, most); - } -} - /** * The text a value holds. * diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 8b9774c..766adb6 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -38,9 +38,12 @@ #include // lint-world: posts handlers only #include +#include #include +#include #include +#include #include #include @@ -48,6 +51,7 @@ #include #include #include +#include #include #include #include @@ -89,23 +93,15 @@ using bytes = std::vector; */ using pmr_bytes = std::pmr::vector; -/** - * A JSON document in a memory resource, an action's JSON payload in the room's resource. - * - * A message received as `pmr_document` is parsed into a buffer of the room's effective - * `room_options::memory`, which must outlive the value, with every value of the document in that - * buffer. One sent is written once, as `JSON.stringify` writes it, into the room's resource. - * - * @see "Allocation", in the guide. - */ -using pmr_document = protocol::json::document; - /** * 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 `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; @@ -170,20 +166,23 @@ inline std::string_view as_text(std::span data) { * 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, `pmr_document` in a buffer of it; the standard - * types allocate with `std::allocator`, as the user chose, and so does an owned document. + * 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 protocol::json::protocol_limits + * of its own size. * - * | 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, in an image of its own | - * | trystero::pmr_document | JSON | parsed, in a buffer of 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 | + * | 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; @@ -262,6 +261,14 @@ struct payload_traits { } }; +/** + * The limits of a received JSON payload's parse: its own size, and an image that grows to at most + * twice that and 64 KiB, as a protocol text's (@ref protocol::json::protocol_limits). + */ +inline webcpp::document::parse_options json_payload_limits(std::string_view text) noexcept { + return protocol::json::protocol_limits(text.size()); +} + /** How an action of `webcpp::document::document`, Trystero's JSON payload, travels. */ template <> struct payload_traits { @@ -278,16 +285,17 @@ struct payload_traits { } /** - * The message's payload as this type: the parsed text, an owned document, whose image comes - * from the global `operator new` as document's own does; 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*/) { if (m.format != protocol::payload_format::json) { return std::nullopt; } - auto v = webcpp::document::parse(as_text(m.payload())); + const std::string_view text = as_text(m.payload()); + auto v = webcpp::document::parse(text, json_payload_limits(text)); if (!v.has_value()) { return std::nullopt; } @@ -295,31 +303,34 @@ struct payload_traits { } }; -/** How an action of `trystero::pmr_document`, Trystero's JSON payload, travels. */ +/** How an action of `webcpp::document::pmr::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; /** Writes the value once, as `JSON.stringify` does, into a shared string of the room's * resource. */ - static encoded_payload encode(const pmr_document& v, std::pmr::memory_resource* memory) { + 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, in a buffer of the room's resource, as - * large as document's limits let a parse grow (`parse_options::max_document_bytes`); nothing - * for another format or a text that does not parse. + * 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, std::pmr::memory_resource* memory) { + static std::optional decode( + incoming& m, std::pmr::memory_resource* memory) { if (m.format != protocol::payload_format::json) { return std::nullopt; } - auto v = - protocol::json::parse(as_text(m.payload()), webcpp::document::parse_options(), memory); + const std::string_view text = as_text(m.payload()); + auto v = webcpp::document::parse(text, json_payload_limits(text), + std::pmr::polymorphic_allocator(memory)); if (!v.has_value()) { return std::nullopt; } @@ -449,6 +460,36 @@ struct payload_traits { } }; +/** An owned document `create` made, or `std::bad_alloc` when its allocator had no room for it. */ +template +Document made_or_bad_alloc(webcpp::document::result made) { + if (!made.has_value()) { + // As a std::pmr container fails when its resource has no room. + boost::throw_exception(std::bad_alloc()); + } + return std::move(made).unsafe_value(); +} + +/** + * The value `async_receive` completes with when it decodes no message: an empty one, in the room's + * resource for a `std::pmr` type, and for a JSON document one holding `null`, the + * `webcpp::document::pmr::document` in the room's resource; `std::bad_alloc` when the resource + * has no room for that document. + */ +template +T empty_payload(std::pmr::memory_resource* memory) { + if constexpr (std::is_same_v) { + return made_or_bad_alloc(webcpp::document::pmr::document::create( + std::pmr::polymorphic_allocator(memory))); + } else if constexpr (std::is_same_v) { + return made_or_bad_alloc(webcpp::document::document::create()); + } else if constexpr (std::is_same_v || std::is_same_v) { + 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 @@ -1249,8 +1290,9 @@ class room_impl final : public std::enable_shared_from_this, public r return; } // A message past its bound fails the handshake as one of the wrong shape does. - const auto value = protocol::json::parse( - data, protocol::json::protocol_limits(protocol::max_handshake_bytes), memory_); + 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(); @@ -1711,9 +1753,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`, - * `webcpp::document::document`, @ref pmr_document, @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. @@ -1805,7 +1846,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 @@ -1879,8 +1922,11 @@ 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, a JSON document holding `null`, 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. @@ -1896,25 +1942,27 @@ class action { // The decoding step is allocated as the user's handler is, which it carries. const auto allocator = webcpp::asio::get_associated_allocator(handler); impl->receive( - name, - impl->template erase( - webcpp::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 { + 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) + : detail::empty_payload(memory), + std::move(info)); + }))); }, token); } diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp index 9b9a338..59c4f5d 100644 --- a/include/webcpp/trystero/webrtc/peer_connection.hpp +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -25,6 +25,8 @@ #include // lint-world: binds an allocator only #include // lint-world: posts handlers only +#include + #include #include @@ -275,9 +277,9 @@ class peer_connection : public backend::peer_connection, 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 = protocol::json::parse( + const auto document = webcpp::document::parse( candidate_json, protocol::json::protocol_limits(protocol::max_sealed_candidate_bytes), - memory_); + 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"]; diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index d93d8a0..3831af9 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -6,10 +6,9 @@ // While two rooms over the memory relays exchange a message, every allocation // they make goes through the resources of their configurations: the counting -// resources see them, and the global operator new, replaced here, sees only -// webcpp::document's working state while it reads or writes a JSON text, each -// freed before the call returns, nor do the C library's allocation functions -// where the platform lets a program count them (doc: #trystero-allocation). +// resources see them, and the global operator new, replaced here, sees none, +// nor do the C library's allocation functions where the platform lets a +// program count them (doc: #trystero-allocation). #include @@ -24,6 +23,9 @@ #include #include +#include +#include + #include #include #include @@ -526,13 +528,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 @@ -566,30 +571,42 @@ trystero::room join(trystero::app& a, std::string_view room_id, return std::move(*r); } +/** 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; + /** - * What webcpp::document's working state costs the global operator new for a JSON payload: writing - * it as a sending room does and reading the text back as a receiving room does, into `memory`. - * Freed before each call returns, and counted here outside any window. + * 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. */ -std::size_t document_cost(const trystero::pmr_document& payload, - std::pmr::memory_resource* memory) { - std::pmr::string text(memory); - global_allocations = 0; - counting = true; - tp::json::append_value(text, payload.root()); - const bool read = tp::json::parse(text, webcpp::document::parse_options(), memory).has_value(); - counting = false; - BOOST_TEST(read); - BOOST_TEST_EQ(live_count, 0U); - return std::exchange(global_allocations, 0); +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 - * operator new sees exactly what `cost` says webcpp::document's working state takes for it. + * 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, Cost cost) { +template +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; @@ -598,7 +615,7 @@ void exchange_allocates_through_the_rooms_resources(Make make, Cost cost) { // 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"; - const trystero::test::memory_relay& relay_state = network.relay(relay); + network.relay(relay); trystero::app a_app(io.get_executor(), network, { .app_id = "allocation", @@ -616,11 +633,17 @@ void exchange_allocates_through_the_rooms_resources(Make make, Cost cost) { 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 auto send = [&](Payload value) { - from_a.async_send(std::move(value), + [&](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), webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_memory), [](boost::system::error_code /*ec*/) {})); }; @@ -628,68 +651,83 @@ void exchange_allocates_through_the_rooms_resources(Make make, Cost cost) { // 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(make(&a_memory)); + send(); if (!BOOST_TEST(run_until(io, [&] { return received == 1; }))) { - return; + return {}; } - // A window in which the relay carries a text, an announcement the rooms read, sees that - // parse too; such a window is opened again, five times at most. - bool quiet = false; - for (std::size_t window = 0; window < 5 && !quiet; ++window) { - Payload value = make(&a_memory); - const std::size_t expected = cost(value, &z_memory); - const std::size_t texts = relay_state.texts; - const std::size_t before = a_memory.allocations + z_memory.allocations; - const std::size_t wanted = received + 1; - global_allocations = 0; - c_allocations = 0; - counting = true; - send(std::move(value)); - const bool arrived = run_until(io, [&] { return received == wanted; }); - counting = false; - BOOST_TEST(arrived); - quiet = relay_state.texts == texts; - if (!quiet) { - continue; - } - explain_global_allocations(expected); - BOOST_TEST_EQ(global_allocations, expected); - BOOST_TEST_EQ(live_count, 0U); - BOOST_TEST_EQ(c_allocations, 0U); - BOOST_TEST_GT(a_memory.allocations + z_memory.allocations, before); - } - BOOST_TEST(quiet); - BOOST_TEST_EQ(a_memory.foreign + z_memory.foreign, 0U); + 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(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); + return window; } -/** How many values a document holds, its own included. */ -// Recursive as deep as the document nests, which its parse bounded. -// NOLINTNEXTLINE(misc-no-recursion) -std::size_t values_in(const tp::json::const_value& v) { - std::size_t n = 1; - if (v.is_array()) { - for (const tp::json::const_value element : v) { - n += values_in(element); - } - } else if (v.is_object()) { - for (const tp::json::const_value member : v.values()) { - n += values_in(member); - } - } - return n; +/** 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); } /** - * webcpp::document's working state for each text a room reads, counted: Boost.JSON's parser - * stack, the path and the pending text, and the tree's record of each value it places, from the - * global operator new, all freed before the parse returns, and at most 8 allocations a value and - * 16 more; the document itself is in the resource it is given (doc: #trystero-allocation). + * 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_costs_the_heap_a_bounded_working_state() { +void reading_a_text_allocates_through_its_resource() { counting_resource memory; std::array secret{}; secret.fill(7); @@ -735,24 +773,27 @@ void reading_a_text_costs_the_heap_a_bounded_working_state() { for (const text& t : texts) { const std::size_t outstanding = memory.outstanding; global_allocations = 0; + c_allocations = 0; counting = true; - auto document = tp::json::parse(t.json, tp::json::protocol_limits(t.bound), &memory); - counting = false; - const std::size_t cost = std::exchange(global_allocations, 0); - if (!BOOST_TEST(document.has_value())) { - continue; + { + 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); } - const std::size_t values = values_in(document->root()); - BOOST_TEST_LE(cost, 16 + (8 * values)); - BOOST_TEST_EQ(live_count, 0U); - // The image is the resource's, and goes back with the document. - BOOST_TEST_GT(memory.outstanding, outstanding); - document = webcpp::document::result(tp::json::document()); + 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(c_allocations, 0U); BOOST_TEST_EQ(memory.foreign, 0U); - c_allocations = 0; } /** Runs io for about `duration`, whatever happens, in slices of 10 ms. */ @@ -813,10 +854,9 @@ 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 - * webcpp::document's working state alone, while the rooms and the relay read and - * write JSON texts, and nothing of it is left at the drain; the C library sees - * 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; @@ -904,8 +944,8 @@ 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); - // The global operator new saw webcpp::document's working state alone, each piece freed before - // the parse or the write that made it returned. + 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); @@ -916,11 +956,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 - * webcpp::document's working state, none of it left at the drain, 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; @@ -993,7 +1032,8 @@ void rooms_of_one_app_allocate_through_their_resources() { } counting = false; } - // webcpp::document's working state alone, freed as the long case's. + 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); @@ -1081,29 +1121,8 @@ int main() { #endif the_replaced_operators_serve_every_alignment(); the_counts_see_an_allocation(); - const auto nothing = [](const auto& /*payload*/, std::pmr::memory_resource* /*memory*/) { - return std::size_t{0}; - }; - exchange_allocates_through_the_rooms_resources( - [](std::pmr::memory_resource* memory) { - return std::pmr::string("a text that no small string holds", memory); - }, - nothing); - exchange_allocates_through_the_rooms_resources>( - [](std::pmr::memory_resource* memory) { - return std::pmr::vector(4096, 7, memory); - }, - nothing); - exchange_allocates_through_the_rooms_resources( - [](std::pmr::memory_resource* memory) { - auto made = tp::json::parse( - R"({"drink":"a text that no small string holds","ice":[1,2.5,true,null]})", - webcpp::document::parse_options(), memory); - webcpp::test::require(BOOST_TEST(made.has_value())); - return std::move(made).unsafe_value(); - }, - &document_cost); - reading_a_text_costs_the_heap_a_bounded_working_state(); + exchanges_allocate_through_the_rooms_resources(); + reading_a_text_allocates_through_its_resource(); a_room_allocates_through_its_resource_from_join_to_destruction(); rooms_of_one_app_allocate_through_their_resources(); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index 086177a..9236900 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -7,7 +7,8 @@ // 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. The fixture is read with webcpp::document, and every text -// the protocol writes is read back as a room reads it, with protocol::json::parse and its bounds. +// 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 @@ -20,6 +21,7 @@ #include #include #include +#include #include #include @@ -31,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -70,42 +73,45 @@ 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 buffer of `memory`. */ -wd::result parse_text( +/** 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 tp::json::parse(text, tp::json::protocol_limits(max_bytes), memory); + return wd::parse(text, tp::json::protocol_limits(max_bytes), + std::pmr::polymorphic_allocator(memory)); } -/** A resource that counts what it gives: its buffers, their bytes, and what is still out. */ +/** + * 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. */ std::size_t allocations = 0; - /** How many of them are not yet returned. */ - std::size_t outstanding = 0; - /** The bytes of all its allocations. */ - std::size_t allocated = 0; /** The bytes of its largest allocation. */ std::size_t largest = 0; - /** Its last allocation. */ - void* last = nullptr; - /** The bytes of its last allocation. */ - std::size_t last_bytes = 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 { ++allocations; - ++outstanding; - allocated += bytes; largest = std::max(largest, bytes); - last_bytes = bytes; - last = std::pmr::new_delete_resource()->allocate(bytes, alignment); - return last; + 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; } void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { - --outstanding; + bytes_out -= bytes; + live.erase(p); std::pmr::new_delete_resource()->deallocate(p, bytes, alignment); } @@ -516,14 +522,13 @@ void envelopes(const fixture_value& fixture) { } void signals() { - tp::json::document document; // the views read_signal returns point into it + 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; } - document = std::move(parsed).value(); - return tp::read_signal(std::as_const(document).root()); + 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())) { @@ -653,14 +658,14 @@ void wide_fields_are_big_endian() { // 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() { - tp::json::document document; + std::optional document; const auto read = [&document](const tp::signal_message& m) { auto parsed = parse_text(tp::write_signal(m), tp::max_parsed_signal_bytes); if (!parsed.has_value()) { return false; } - document = std::move(parsed).value(); - return tp::read_signal(std::as_const(document).root()).has_value(); + return tp::read_signal(std::as_const(document.emplace(std::move(parsed).value())).root()) + .has_value(); }; std::array iv{}; iv.fill(255); @@ -926,11 +931,15 @@ std::string event_with(std::string_view members) { // 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 fills the bound; and what the -// parse took from the resource, its doubling buffers, sums to less than three times the bound. +// 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) { @@ -940,7 +949,7 @@ void parse_cost() { } counting_resource keyed; { - const auto document = tp::json::parse(event_with(keys), limits, &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()); @@ -950,8 +959,8 @@ void parse_cost() { } } BOOST_TEST_LE(keyed.largest, bound); - BOOST_TEST_LT(keyed.allocated, 3 * bound); - BOOST_TEST_EQ(keyed.outstanding, 0U); + 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)"; @@ -961,52 +970,48 @@ void parse_cost() { return event_with(text + "]"); }; counting_resource few; - BOOST_TEST(tp::json::parse(values(100), limits, &few).has_value()); + 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 = tp::json::parse(text, limits, &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.allocated, 3 * bound); - BOOST_TEST_EQ(many.outstanding, 0U); + BOOST_TEST_LT(many.peak, 2 * bound); + BOOST_TEST(many.live.empty()); } } -// A text nested past max_depth is refused at once: Boost.JSON's parser stops at the 257th level, -// which the parse does not take for a full buffer, so it makes no larger one to try again. The -// texts are padded so that their first buffer holds the 256 levels a room reads; unpadded, the -// same nesting fills the first buffers, which do grow. +// A text nested past max_depth is refused: Boost.JSON's parser stops at the 257th 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, 256U); - const auto nested = [](std::size_t levels, std::size_t size) { - std::string text(size - (2 * levels), ' '); - text.append(levels, '['); + const auto nested = [](std::size_t levels) { + std::string text(levels, '['); text.append(levels, ']'); return text; }; - const std::size_t size = tp::nostr::max_parsed_relay_text_bytes; counting_resource deepest; - BOOST_TEST(tp::json::parse(nested(depth, size), limits, &deepest).has_value()); - BOOST_TEST_EQ(deepest.allocations, 1U); + 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 = tp::json::parse(nested(depth + 1, size), limits, &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_EQ(deeper.allocations, 1U); - BOOST_TEST_EQ(deeper.outstanding, 0U); - counting_resource growing; - BOOST_TEST(tp::json::parse(nested(depth, 2 * depth), limits, &growing).has_value()); - BOOST_TEST_GT(growing.allocations, 1U); + BOOST_TEST(deeper.live.empty()); } -// A parse's image is one buffer of the resource it is given, the only thing it holds there once -// the parse succeeds: the strings read from it point into it, a move keeps it where it is, and the -// resource has nothing out once the document goes. +// 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\"}"}])"; @@ -1016,13 +1021,14 @@ void parse_resource() { if (!BOOST_TEST(parsed.has_value())) { return; } - tp::json::document document = std::move(parsed).value(); - BOOST_TEST(document.resource() == &memory); - BOOST_TEST_EQ(memory.outstanding, 1U); - BOOST_TEST_EQ(memory.last_bytes, document.capacity()); - const auto image = document.get().image(); - BOOST_TEST(static_cast(image.data()) == memory.last); - BOOST_TEST_EQ(image.size(), document.capacity()); + 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) { @@ -1036,16 +1042,16 @@ void parse_resource() { BOOST_TEST(inside(e->subscription) && inside(e->id) && inside(e->topic) && inside(e->content)); } - const tp::json::document moved = std::move(document); + const wd::pmr::document moved = std::move(document); // A document moved from holds no image. - BOOST_TEST(!document.has_value()); // NOLINT(bugprone-use-after-move) - const auto moved_image = moved.get().image(); - BOOST_TEST(static_cast(moved_image.data()) == memory.last); + 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.allocations, 1U); - BOOST_TEST_EQ(memory.outstanding, 1U); + BOOST_TEST_EQ(memory.live.size(), 1U); } - BOOST_TEST_EQ(memory.outstanding, 0U); + BOOST_TEST(memory.live.empty()); } void text() { diff --git a/test/room_test.cpp b/test/room_test.cpp index e95f2d1..32ff323 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -1224,10 +1225,10 @@ void long_peer_ids_are_bounded() { trystero::protocol::json::append_key(text, "peerId"); trystero::protocol::json::append_string(text, id); text += '}'; - auto parsed = trystero::protocol::json::parse( + auto parsed = webcpp::document::parse( text, trystero::protocol::json::protocol_limits(trystero::protocol::max_parsed_signal_bytes), - std::pmr::get_default_resource()); + std::pmr::polymorphic_allocator(std::pmr::get_default_resource())); webcpp::test::require(BOOST_TEST(parsed.has_value())); return std::move(*parsed); }; @@ -1307,6 +1308,75 @@ void async_receive_works_in_a_coroutine() { 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, +// within twice its own size and 64 KiB of image, whatever type receives it: an array of 100 zeros +// is delivered, one of 1,000, whose nodes would need some 190 KB, is not, and the messages after it +// are. +void json_payloads_are_read_in_the_rooms_resource_within_their_size() { + 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{.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 document_of(text + "]"); + }; + for (const char* name : {"pmr", "std"}) { + auto to_z = a.make_action(name); + for (const std::size_t n : {100, 1000, 3}) { + to_z.async_send(zeros(n), asio::detached); + } + } + // A data channel keeps its order: the last of each action arrives after the other two. + BOOST_TEST(run_until(f.io, [&] { return in_resource.size() >= 2 && in_heap.size() >= 2; })); + const std::vector delivered{100, 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 message of another format than a document action's completes its receive with +// error::transfer_rejected and a document holding null, in the room's resource. +void a_rejected_document_receive_holds_null_in_the_rooms_resource() { + 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}); + bool completed = false; + z.make_action("doc").async_receive( + [&](boost::system::error_code ec, webcpp::document::pmr::document v, + const trystero::message_info& info) { + completed = true; + BOOST_TEST(ec == trystero::error::transfer_rejected); + BOOST_TEST(v.root().is_null()); + BOOST_TEST(v.get_allocator().resource() == &z_memory); + BOOST_TEST_EQ(info.from, "VVVVVVVVVVVVVVVVVVVV"); + }); + BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; })); + a.make_action("doc").async_send("not JSON", asio::detached); + BOOST_TEST(run_until(f.io, [&] { return completed; })); +} + void view_handlers_read_the_frame_without_copying() { fixture f; trystero::app a_app(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR")); @@ -1625,6 +1695,8 @@ int main() { counter_announcements_are_paced(); three_peers_form_a_mesh(); async_receive_works_in_a_coroutine(); + json_payloads_are_read_in_the_rooms_resource_within_their_size(); + a_rejected_document_receive_holds_null_in_the_rooms_resource(); 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(); diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index 809948e..aa9ea5e 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -21,6 +21,8 @@ #include #include +#include + #include #include #include @@ -326,8 +328,9 @@ inline void memory_relay::receive(const std::shared_ptr& from, ++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 = protocol::json::parse( - text, protocol::json::protocol_limits(protocol::max_relay_message_bytes), from->memory()); + 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; } diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp index 2cd94c2..dfc5201 100644 --- a/test/support/rooms.hpp +++ b/test/support/rooms.hpp @@ -268,15 +268,15 @@ struct relayed { * could be sent. */ inline std::optional relayed_signal(std::string_view text) { const auto limits = protocol::json::protocol_limits(protocol::max_relay_message_bytes); - const auto parsed = protocol::json::parse(text, limits, std::pmr::get_default_resource()); + 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 = - protocol::json::parse(event->content, limits, std::pmr::get_default_resource()); + 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; From db15a94a857e7f9e7c6fe4e7fb84d46235b467f9 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:23:09 -0300 Subject: [PATCH 084/116] trystero: the guide on documents in the room's resource The allocation page, the guarantees, the design, the protocol, the usage and the testing pages and AGENTS.md describe every JSON text parsed by webcpp::document::parse into a pmr::document of the room's resource, whose image grows in place, and webcpp::document::pmr::document in place of pmr_document. document's working state leaves the list of what stays outside the resource, and the proof's counts are zero again. A JSON payload whose document needs more than twice its length and 64 KiB is a difference of its own. A handle keeps document's rule: it refers to its document object, and moving the document invalidates it. --- AGENTS.md | 103 +++++++++++++++++++++-------------------- doc/allocation.adoc | 108 ++++++++++++++++++++----------------------- doc/design.adoc | 20 ++++++-- doc/differences.adoc | 5 ++ doc/guarantees.adoc | 7 +-- doc/protocol.adoc | 39 ++++++++++------ doc/testing.adoc | 3 +- doc/usage.adoc | 34 ++++++++++---- 8 files changed, 178 insertions(+), 141 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 34fcc5e..6efa6fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -634,39 +634,45 @@ 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`). - - **webcpp::document** keeps a document's image in one buffer, and its - external storage leaves that buffer to its user: every value, strings - included, is allocated inside it by Boost.Interprocess's - `rbtree_best_fit` heap, with offsets for pointers. trystero gives each - text it reads such a buffer of the room's resource - (`protocol::json::document`, of the app's for a remote candidate), - sized for a text of a few values, twice the text and 4 KiB, and made - again twice as large when the parse fills it, up to the caller's bound - (`protocol::json::protocol_limits`: twice its text bound and 64 KiB). 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** 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`, 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 is bounded the same way by its own size. 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. What document's parser - and writer use while they work stays in the standard allocator: - Boost.JSON's parser stack, the path and the pending key and text of the - value being read, the tree's record of each change, which places a - value, and the writer's stack. Each is freed before the parse or the - write that made it returns, so none is left at any moment the room's - executor is between handlers (measured natively with the LLVM standard - library: about seven allocations a value for each text a room reads, - and 48 to write and read back a JSON payload of 7 values). + 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 `pmr_document` in a buffer of - it. `std::string`, `bytes`, `webcpp::document::document` and `payload` - stay as they are, with `std::allocator` or document's own - `operator new`: 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; a received `webcpp::document::document` is an image of its - own, from the global `operator new`, as document's owned documents are. + the `std::pmr` types are built in it, `webcpp::document::pmr::document` + among them, and a rejected `async_receive` completes with an empty one + there (a document holding `null`), through `detail::empty_payload`. + `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 @@ -680,10 +686,7 @@ holds only what is specific to trystero. - **Outside the resource**, stated on the page: libdatachannel's and 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; webcpp::document's working state while it reads or writes a JSON - text (its parser's stack, path and pending text, its tree's record of - each change, its writer's stack), each piece freed before the call - returns; Asio's own once-per-context allocations + 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, which webcpp::webrtc's completions get, through `any_io_executor`; @@ -701,8 +704,7 @@ holds only what is specific to trystero. a message allocates nothing outside it (in a page the stream's own state is there too, made with `std::allocator_arg` and the room's allocator); the payload types `std::string`, `bytes`, `webcpp::document::document` - and `payload`, with `std::allocator` or document's own `operator new`; - on Emscripten, the C library's `select()`, which Asio's reactor calls on + 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 @@ -722,26 +724,25 @@ holds only what is specific to trystero. 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 `pmr_document` in turn: for the first two - `operator new` sees nothing, for the document exactly what writing it - and reading its text back cost webcpp::document's working state, counted - apart beforehand on the same value, and nothing left; the C library - sees nothing, and the counting resources of the two configurations see - the rooms'. 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 in a - counting resource, which holds its image until the document goes, and - document's working state costs `operator new` at most 8 allocations a - value and 16 more, none left after the parse. 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 webcpp::document's working state alone, none - of it live at the drain, and the C library nothing, and the rooms' + `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 count sees only webcpp::document's working - state, nothing live at the drain, and all resources return to zero. + 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 diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 3398ecf..2724a22 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -44,9 +44,11 @@ own state. 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. - A JSON text is parsed into a buffer of the room's resource, a remote - candidate into one of the app's, and a `pmr_document` payload into one of - the room's resource, every value of the document in that buffer. + 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` @@ -67,7 +69,8 @@ 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 `pmr_document` 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 @@ -136,9 +139,11 @@ user's choice of `std::allocator`: `trystero::bytes`, a `std::vector`, and `trystero::payload`, a variant of `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 an image -of its own, from the global `operator new`, as document's owned documents -are. +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 @@ -217,29 +222,24 @@ 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* keeps a document's image in one buffer, and its external -storage leaves that buffer to its user: every value, strings included, is -allocated inside it by Boost.Interprocess's `rbtree_best_fit` heap, with -offsets for pointers. trystero gives each text it reads such a buffer of the -room's resource (`protocol::json::document`), sized for a text of a few -values, twice the text and 4 KiB, and made again twice as large when the -parse fills it, up to the caller's bound. 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. - -What document's parser and writer use while they work stays in the standard -allocator: Boost.JSON's parser stack, the path and the pending key and text -of the value being read, the tree's record of each change, which places a -value, and the writer's stack. Each is freed before the parse or the write -that made it returns, so none is left at any moment the room's executor is -between handlers. Measured natively with the LLVM standard library, each -text a room reads costs `operator new` about seven allocations a value: a -relay's event -carrying an offer, 1,581 bytes and 14 values, 93; a relay's `OK`, 5 values, -32; a signal, 4 values, 26; a handshake message, 3 values, 20; a candidate, -5 values, 32. Writing and reading back a JSON payload of 7 values costs 48. +*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; 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 @@ -255,9 +255,6 @@ nothing. natively, webcpp::webrtc's copies of what libdatachannel's threads report, in the standard allocator; * what `emscripten::val` holds, in the JavaScript heap; -* webcpp::document's working state while it reads or writes a JSON text, - freed before the call returns (above): its parser's stack, path and - pending text, its tree's record of each change, its writer's stack; * 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 @@ -292,8 +289,7 @@ nothing. buffer's, at the first); in a page the stream's own state is there too, and the page's `WebSocket` makes the handshake; * the payload types `std::string`, `bytes`, `webcpp::document::document` and - `payload`, with `std::allocator` or document's own `operator new`, the - user's choice; + `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; @@ -327,36 +323,32 @@ 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 `pmr_document` in turn. For the - first two `operator new` sees nothing; for the document, exactly what - writing it and reading its text back cost webcpp::document's working - state, counted apart beforehand on the same value, and nothing left; the C - library sees nothing, and the counting resources of the two - configurations see the rooms'. A window in which the relay carried a text, - an announcement the rooms read, is opened again. + `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 in a - counting resource: its image is the resource's, and goes back with the - document, and document's working state costs `operator new` at most 8 - allocations a value and 16 more, none left after the parse. + `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 webcpp::document's working state alone, as the rooms - and the relay read and write their JSON texts, and the C library nothing. - How many texts they read depends on the timing of the run, so the test - asserts no number of allocations: it asserts that none is left at the - drain. 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 - webcpp::document's working state, none of it left, 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. diff --git a/doc/design.adoc b/doc/design.adoc index 4765a8d..16e682d 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -210,14 +210,26 @@ 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. * Every JSON text is webcpp::document's. Signals, relay messages, handshake - messages and candidates are parsed into a document whose image is a buffer - of the room's or the app's resource, and read as views into it; each - caller bounds its text (<>). The JSON the room + 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. + 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. diff --git a/doc/differences.adoc b/doc/differences.adoc index 4f6518c..58ce4aa 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -121,6 +121,8 @@ has nothing of it to run beside its twin. | 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 needs more than twice its length and 64 KiB of image: an array of more than 345 zeros, 352 numbers of three digits, 287 short strings or 101 objects of two members | delivered: `JSON.parse` takes any | not delivered | each value of a document is a node of some 200 bytes of image, so the image's bound is tied to the payload's length, as a protocol text's to its bound (<>), and a payload of many small values costs the room no more than a multiple of its length + | 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) |=== @@ -549,4 +551,7 @@ its reason. | A JSON payload nested deeper than 256, or holding a lone surrogate | What differs is a message the {cpp} room does not deliver, which a program would show only as nothing printed; webcpp::document's `parse` test holds both refusals. + +| A JSON payload whose document needs more than twice its length and 64 KiB +| What differs is a message the {cpp} room does not deliver, which a program would show only as nothing printed; the `room` test holds the bound, an array of 100 zeros delivered and one of 1,000 not. |=== diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index 263e441..778f3d8 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -44,9 +44,10 @@ 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 webcpp::document's working state while it reads or writes a JSON -text, each piece freed before that call returns, and the C library nothing. +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`. _Held by_ `allocation`, natively and on emscripten, and, for a page's sealer, `platform_page_sealer_allocation`. . [[trystero-invariant-6]]*No unit test reaches beyond the loopback.* The diff --git a/doc/protocol.adoc b/doc/protocol.adoc index ecfad14..4220c37 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -88,11 +88,12 @@ after the peer advertised that room's token itself on the connection. === JSON texts Every JSON text a room reads or writes is webcpp::document's. A text is read -by `protocol::json::parse` into a `protocol::json::document`, whose image is a -buffer of the room's resource, or of the app's for a candidate, 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, and drops a longer -text before reading it, as it drops a malformed one: +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"] |=== @@ -104,16 +105,24 @@ text before reading it, as it drops a malformed one: | a remote candidate | 16 KiB | the bound of a sealed candidate, which its opened JSON never passes |=== -The image is at most twice the text and 64 KiB: 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 the parse has filled that bound. 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 has no bound of -its own but the room's `max_receive_bytes` and document's defaults: 64 MiB of -image and 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. +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 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 bounded the same way by +its own size: its image grows to at most twice the payload and 64 KiB, so +that a payload of many small values, each a node of some 200 bytes, costs the +room no more than a multiple of its length; an array of 345 zeros is read, +and one of 346 is not, nor one of more than 101 objects such as +`{"x":12,"y":34}` (<>). Its 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 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 diff --git a/doc/testing.adoc b/doc/testing.adoc index 515b764..b40b520 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -96,7 +96,8 @@ include::{library-root}/test/Jamfile[tag=allocation] 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. + coroutines and view handlers, JSON payloads read in the room's resource + within their size's bound, and a rejected document receive. | `app_impl` | Configuration copying and validation, a self id that is not UTF-8 set diff --git a/doc/usage.adoc b/doc/usage.adoc index 686bfda..ebada31 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -196,7 +196,7 @@ messages travel and how they are received: | `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 | `webcpp::document::document` | JSON | parsed into a document of its own, with the standard allocator -| `trystero::pmr_document` | JSON | parsed into a buffer of the room's resource +| `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 @@ -204,8 +204,10 @@ messages travel and how they are received: |=== A JSON payload is webcpp::document's: a `webcpp::document::document` the -program builds or parses, or a `pmr_document`, whose image is a buffer of a -memory resource, the room's when it is received. A {cpp} peer sends 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 @@ -214,14 +216,24 @@ 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 (<>). +which `JSON.parse` takes, nor one whose document would need more than twice +its length and 64 KiB of image, an array of more than 345 zeros among them +(<>). 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 `webcpp::document::document` a default constructor there, -where a program makes one with `webcpp::document::document::create()` or -`webcpp::document::parse`, each of which returns a result. The room test -sends one: +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] ---- @@ -250,7 +262,11 @@ 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, in the room's resource for a +`std::pmr` type, and a document holding `null` for a JSON one, in the room's +resource for a `webcpp::document::pmr::document`. 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. From 644d265777a9b4901a42c10475072f24206ae648 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:35:43 -0300 Subject: [PATCH 085/116] trystero: programs show a JSON payload's exact numbers and the payloads a room refuses The two rows of the appendix "Differences" that no program showed get their programs, in the lane relayed, and their twins on Trystero 0.26.0, which diverge with their own .expected, written by update-expected. diff_json_numbers: a room sends the payload a JSON text makes, and the other peer prints each number it receives. A C++ peer sends 9007199254740993, a decimal of 34 digits and 1e999 exact; Trystero JS sends the nearest doubles and null. diff_json_refused: the other peer sends a payload nested 257 deep, one holding a lone surrogate and a last one; the C++ room delivers the last alone, Trystero JS all three. No C++ peer writes a lone surrogate, so the other peer sends each JSON text as a text payload, which the backend its app is given marks as JSON on the wire, as a Trystero JS page sends it. The page gives each its section, moves both rows out of the table of differences no program shows, and says what Trystero JS sends of such a number. Its counts are computed: 11 divergent twins of 14 programs. --- doc/differences.adoc | 86 +++++- example/Jamfile | 2 + example/diff_json_numbers.cpp | 106 ++++++++ example/diff_json_numbers.expected | 3 + example/diff_json_refused.cpp | 272 +++++++++++++++++++ example/diff_json_refused.expected | 3 + test/oracle/twins/diff_json_numbers.expected | 3 + test/oracle/twins/diff_json_numbers.mjs | 40 +++ test/oracle/twins/diff_json_refused.expected | 3 + test/oracle/twins/diff_json_refused.mjs | 51 ++++ 10 files changed, 562 insertions(+), 7 deletions(-) create mode 100644 example/diff_json_numbers.cpp create mode 100644 example/diff_json_numbers.expected create mode 100644 example/diff_json_refused.cpp create mode 100644 example/diff_json_refused.expected create mode 100644 test/oracle/twins/diff_json_numbers.expected create mode 100644 test/oracle/twins/diff_json_numbers.mjs create mode 100644 test/oracle/twins/diff_json_refused.expected create mode 100644 test/oracle/twins/diff_json_refused.mjs diff --git a/doc/differences.adoc b/doc/differences.adoc index 4f6518c..345512b 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -117,7 +117,7 @@ has nothing of it to run beside its twin. | 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 | impossible: 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'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 @@ -470,6 +470,84 @@ include::{twins}/diff_send_to_absent_peer.expected[] 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, or holding a lone surrogate + +Trystero JS:: `JSON.parse` reads a payload nested deeper than 256, and a +string that holds a lone surrogate, `"\ud800"`, as `JSON.stringify` writes +one, so a room delivers both. +trystero:: A room reads a JSON payload with webcpp::document's defaults, and +delivers neither: a text nested deeper than 256 is refused, and so is a lone +surrogate. 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. + +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 @@ -543,10 +621,4 @@ its reason. | 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. - -| A JSON payload's number that a double cannot hold -| No Trystero JS program holds such a number, so no twin could send it; the `protocol` test writes one exact beside what `JSON.stringify` writes of the same text. - -| A JSON payload nested deeper than 256, or holding a lone surrogate -| What differs is a message the {cpp} room does not deliver, which a program would show only as nothing printed; webcpp::document's `parse` test holds both refusals. |=== diff --git a/example/Jamfile b/example/Jamfile index 8e859e8..74cf7cc 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -32,6 +32,8 @@ webcpp.drive quick_start : quick_start.cpp # tag::differences[] local differences = diff_already_joined + diff_json_numbers + diff_json_refused diff_passwords diff_peer_join diff_peers 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..619b251 --- /dev/null +++ b/example/diff_json_refused.cpp @@ -0,0 +1,272 @@ +// 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, or holding a lone surrogate. Trystero JS delivers both, as JSON.parse reads them; a +// room here delivers neither, since it reads a JSON payload with webcpp::document's defaults, at +// most 256 deep, and strings that are UTF-8. 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 { + 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()); + 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 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, and a last one sent after them. + const auto payloads = std::to_array>({ + {"nested 257 deep", std::string(256, '[') + std::string(256, ']')}, + {"holding a lone surrogate", R"("\ud800")"}, + {"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..5a34858 --- /dev/null +++ b/example/diff_json_refused.expected @@ -0,0 +1,3 @@ +the payload nested 257 deep: not delivered +the payload holding a lone surrogate: not delivered +the payload sent after them: delivered 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..821dc3a --- /dev/null +++ b/test/oracle/twins/diff_json_refused.expected @@ -0,0 +1,3 @@ +the payload nested 257 deep: delivered +the payload holding a lone surrogate: 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..691388a --- /dev/null +++ b/test/oracle/twins/diff_json_refused.mjs @@ -0,0 +1,51 @@ +// 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, and a last one sent after them. +const payloads = [ + ['nested 257 deep', '['.repeat(256) + ']'.repeat(256)], + ['holding a lone surrogate', '"\\ud800"'], + ['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]) From f5e5caaf75b9636e4227c89ecdc71bc459c7ad29 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:46:07 -0300 Subject: [PATCH 086/116] trystero: diff_json_refused shows a payload of many small values refused An array of 1,000 zeros joins the payloads the program's other peer sends: a room reads a JSON payload into an image of at most twice its length and 64 KiB, which its nodes, some 200 bytes each, pass, so it is not delivered, where Trystero JS delivers it, as its twin prints. The differences page shows it in that program's section. --- doc/differences.adoc | 26 ++++++++++++-------- doc/protocol.adoc | 8 +++--- example/diff_json_refused.cpp | 16 +++++++++--- example/diff_json_refused.expected | 1 + test/oracle/twins/diff_json_refused.expected | 1 + test/oracle/twins/diff_json_refused.mjs | 4 ++- 6 files changed, 37 insertions(+), 19 deletions(-) diff --git a/doc/differences.adoc b/doc/differences.adoc index 00b5679..a1f626b 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -121,7 +121,7 @@ has nothing of it to run beside its twin. | 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 needs more than twice its length and 64 KiB of image: an array of more than 345 zeros, 352 numbers of three digits, 287 short strings or 101 objects of two members | delivered: `JSON.parse` takes any | not delivered | each value of a document is a node of some 200 bytes of image, so the image's bound is tied to the payload's length, as a protocol text's to its bound (<>), and a payload of many small values costs the room no more than a multiple of its length +| A JSON payload whose document needs more than twice its length and 64 KiB of image: an array of more than 345 zeros, 352 numbers of three digits, 287 short strings or 101 objects of two members | delivered: `JSON.parse` takes any | not delivered (<>) | each value of a document is a node of some 200 bytes of image, so the image's bound is tied to the payload's length, as a protocol text's to its bound (<>), and a payload of many small values costs the room no more than a multiple of its length | 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) @@ -511,15 +511,21 @@ include::{examples}/diff_json_numbers.expected[] ---- [#trystero-differences-json-refused] -==== A JSON payload nested deeper than 256, or holding a lone surrogate - -Trystero JS:: `JSON.parse` reads a payload nested deeper than 256, and a -string that holds a lone surrogate, `"\ud800"`, as `JSON.stringify` writes -one, so a room delivers both. -trystero:: A room reads a JSON payload with webcpp::document's defaults, and -delivers neither: a text nested deeper than 256 is refused, and so is a lone -surrogate. 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. +==== A JSON payload nested deeper than 256, holding a lone surrogate, or of many small values + +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 1,000 zeros, so a room delivers all three. +trystero:: A room reads a JSON payload with webcpp::document's defaults, into +an image of at most twice the payload and 64 KiB, 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 would need some 190 KB. 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 some 200 bytes of image, so +the image's bound is tied to the payload's length, as a protocol text's to +its bound (<>), and a payload of many small values +costs the room no more than a multiple of its length. 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 diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 4220c37..b1bf6b3 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -119,10 +119,10 @@ its own size: its image grows to at most twice the payload and 64 KiB, so that a payload of many small values, each a node of some 200 bytes, costs the room no more than a multiple of its length; an array of 345 zeros is read, and one of 346 is not, nor one of more than 101 objects such as -`{"x":12,"y":34}` (<>). Its 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. +`{"x":12,"y":34}` (<>). Its 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 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 diff --git a/example/diff_json_refused.cpp b/example/diff_json_refused.cpp index 619b251..1fe2b14 100644 --- a/example/diff_json_refused.cpp +++ b/example/diff_json_refused.cpp @@ -5,9 +5,11 @@ // https://www.boost.org/LICENSE_1_0.txt) // A difference from Trystero (doc: #trystero-differences-behaviour): a JSON payload nested deeper -// than 256, or holding a lone surrogate. Trystero JS delivers both, as JSON.parse reads them; a -// room here delivers neither, since it reads a JSON payload with webcpp::document's defaults, at -// most 256 deep, and strings that are UTF-8. A Trystero JS page sends such payloads, and a C++ +// than 256, holding a lone surrogate, or of many small values. 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 twice the payload and 64 KiB, which an array of 1,000 zeros, a node of some 200 bytes each, +// passes. 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 @@ -237,10 +239,16 @@ int main() { }; // 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, and a last one sent after them. + // nested 257 deep, one holding a lone surrogate, an array of 1,000 zeros, 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. diff --git a/example/diff_json_refused.expected b/example/diff_json_refused.expected index 5a34858..875a407 100644 --- a/example/diff_json_refused.expected +++ b/example/diff_json_refused.expected @@ -1,3 +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/test/oracle/twins/diff_json_refused.expected b/test/oracle/twins/diff_json_refused.expected index 821dc3a..069074d 100644 --- a/test/oracle/twins/diff_json_refused.expected +++ b/test/oracle/twins/diff_json_refused.expected @@ -1,3 +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 index 691388a..e207ef4 100644 --- a/test/oracle/twins/diff_json_refused.mjs +++ b/test/oracle/twins/diff_json_refused.mjs @@ -15,10 +15,12 @@ const config = { 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, and a last one sent after them. +// 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 From b313c8879c161d3bc06e98b6e298a681b2e79883 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:51:46 -0300 Subject: [PATCH 087/116] trystero: AGENTS.md names the one std::bad_alloc a room raises A rejected async_receive of a document completes with a document holding null in the room's resource, and a resource with no room for it raises std::bad_alloc through boost::throw_exception, as a std::pmr container of the room does. --- AGENTS.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6efa6fe..b7fe784 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,10 +83,12 @@ holds only what is specific to trystero. 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. + trystero raises nothing of its own but `std::bad_alloc`, through + `boost::throw_exception`, when a room's resource has no room for the + `null` document a rejected `async_receive` of a document completes with, + as a `std::pmr` container of the room raises it (`detail::empty_payload`); + 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 From 1ba81cb82ee2c51ca5c37f97bb744c343cd98b05 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:59:05 -0300 Subject: [PATCH 088/116] trystero: the reviewed relays' code and tests to the pinned clang-tidy Trailing commas where the initializer spans lines, none where it does not; an accept's error_code read; a const reference where nothing changes; auto for as(). --- .../webcpp/trystero/platform/websocket.hpp | 12 +++++++---- test/platform_page_call_test.cpp | 2 +- test/platform_page_websocket_ingress_test.cpp | 6 +++--- test/platform_page_websocket_tls_test.cpp | 6 +++++- test/platform_websocket_allocation_test.cpp | 3 +-- test/platform_websocket_unreachable_test.cpp | 20 +++++++++---------- 6 files changed, 28 insertions(+), 21 deletions(-) diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 821be79..a1155cc 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -593,8 +593,10 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this(), - .member = &websocket_session::on_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) { @@ -634,8 +636,10 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this(), - .member = &websocket_session::on_write}); + 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*/) { diff --git a/test/platform_page_call_test.cpp b/test/platform_page_call_test.cpp index 24a0852..7e8434b 100644 --- a/test/platform_page_call_test.cpp +++ b/test/platform_page_call_test.cpp @@ -132,7 +132,7 @@ std::optional read_int32(const val& value) { if (!value.isNumber()) { return std::nullopt; } - const double number = value.as(); + 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)) { diff --git a/test/platform_page_websocket_ingress_test.cpp b/test/platform_page_websocket_ingress_test.cpp index 56a7452..aecdcc9 100644 --- a/test/platform_page_websocket_ingress_test.cpp +++ b/test/platform_page_websocket_ingress_test.cpp @@ -134,7 +134,7 @@ void verdict(state& s) { /** 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)(state&)) { + void (*on_message)(const state&)) { return { .open = [&into] { ++into.opens; }, .message = @@ -151,13 +151,13 @@ trystero::backend::websocket::handlers recording(state& s, reports& into, } /** A text reached the binary socket, the one after its binary message: it is closed. */ -void close_binary(state& s) { +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(state& s) { +void close_oversized(const state& s) { s.oversized->close(); } diff --git a/test/platform_page_websocket_tls_test.cpp b/test/platform_page_websocket_tls_test.cpp index 10dffd2..51df7cf 100644 --- a/test/platform_page_websocket_tls_test.cpp +++ b/test/platform_page_websocket_tls_test.cpp @@ -108,7 +108,11 @@ enum class refused : std::uint8_t { }; constexpr std::array refusals{ - refused::authority, refused::certificate, refused::option, refused::method, refused::callback, + 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. */ diff --git a/test/platform_websocket_allocation_test.cpp b/test/platform_websocket_allocation_test.cpp index 2963185..7c676a6 100644 --- a/test/platform_websocket_allocation_test.cpp +++ b/test/platform_websocket_allocation_test.cpp @@ -153,8 +153,7 @@ class echo_relay { void serve() { boost::system::error_code ec; tcp::socket socket(io_); - acceptor_.accept(socket, ec); - if (ec) { + if (acceptor_.accept(socket, ec)) { return; } beast::websocket::stream ws(std::move(socket)); diff --git a/test/platform_websocket_unreachable_test.cpp b/test/platform_websocket_unreachable_test.cpp index b364bf6..dd43f54 100644 --- a/test/platform_websocket_unreachable_test.cpp +++ b/test/platform_websocket_unreachable_test.cpp @@ -78,16 +78,16 @@ struct relay_url { * 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{{ - {.url = "ftp://relay.invalid", .attempted = false}, - {.url = "wss://relay.invalid/#fragment", .attempted = false}, - {.url = "not a url", .attempted = false}, - {.url = "/relative", .attempted = false}, - {.url = "http://127.0.0.1:9", .attempted = false}, - {.url = "https://127.0.0.1:9", .attempted = false}, - {.url = "ws://127.0.0.1:9", .attempted = true}, - {.url = "ws://[::1]:9", .attempted = true}, -}}; +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; From ace65d7c3d2fada1419d90c3b92460fcc9193bd7 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 23:31:21 -0300 Subject: [PATCH 089/116] trystero: a relay's refusal body is not read, a test that fails until the bounded handshake A relay that refuses the upgrade with a body of 4 MiB has the room's thread allocate 4,199,353 bytes with operator new today (measured), Beast's own parser reading the body whole; the case asks for less than 64 KiB, with the close reported and no open. It passes once the session's next layer is webcpp::beast's bounded_handshake_stream with a body limit of 0, which needs libs/beast at handshake-limit (40e5f3d): this commit is on a branch of its own until then. --- test/platform_websocket_allocation_test.cpp | 110 +++++++++++++++++++- 1 file changed, 105 insertions(+), 5 deletions(-) diff --git a/test/platform_websocket_allocation_test.cpp b/test/platform_websocket_allocation_test.cpp index 7c676a6..9fb6880 100644 --- a/test/platform_websocket_allocation_test.cpp +++ b/test/platform_websocket_allocation_test.cpp @@ -17,13 +17,22 @@ // 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. // -// main runs the io_context once; each echo sends the next text, and the last closes the socket. +// 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. Without 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. +// +// 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 @@ -54,11 +63,14 @@ namespace { 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); @@ -83,6 +95,7 @@ void* operator new(std::size_t size) { 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); @@ -175,6 +188,57 @@ class echo_relay { 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; @@ -210,9 +274,8 @@ void on_echo(state& s) { s.socket->send(s.text); } -} // namespace - -int main() { +/** 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( @@ -226,11 +289,48 @@ int main() { 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::report_errors(); + 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(); } From 9d178149c521ab118638ee50ae699ae8aa93b37e Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:12:31 -0300 Subject: [PATCH 090/116] trystero: a JSON payload up to the room's bound, protocol texts 16 deep A JSON payload is read into an image of at most 96 times its length and 64 KiB, which every valid text fits, a value of one character with its comma being a node of 192 bytes (protocol::json::payload_limits, the factor measured and pinned by the protocol test), or the room's new room_options::max_json_document_bytes, webcpp::document's 64 MiB by default, the smaller: a payload of 1,000 numbers is delivered, as Trystero JS delivers it, and a program bounds what a peer's JSON may take of its room's resource. The payload traits decode with the room's detail::decoding, its resource and that bound. A protocol text nests at most 16 deep (protocol::json::max_protocol_depth), where Trystero's nest 4, and a relay's text one level deeper is dropped. diff_json_refused's room sets the bound to 64 KiB, which its 1,000 zeros pass; the room test reads payloads up to the bound and refuses one a zero past it. A TODO names document's basic_document::nothing for the rejected receive. --- AGENTS.md | 27 ++++--- doc/allocation.adoc | 8 +- doc/differences.adoc | 37 +++++---- doc/protocol.adoc | 34 ++++---- doc/testing.adoc | 7 +- doc/usage.adoc | 10 ++- example/diff_json_refused.cpp | 20 +++-- include/webcpp/trystero/options.hpp | 14 ++++ include/webcpp/trystero/protocol/json.hpp | 39 +++++++++- include/webcpp/trystero/room.hpp | 94 +++++++++++++---------- test/protocol_test.cpp | 52 ++++++++++++- test/room_test.cpp | 37 ++++++--- test/signaling_test.cpp | 53 +++++++++++++ 13 files changed, 323 insertions(+), 109 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b7fe784..7fa3945 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -647,10 +647,16 @@ holds only what is specific to trystero. 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`, 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 is bounded the same way by its own size. A text the room writes + 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. 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 @@ -662,11 +668,14 @@ holds only what is specific to trystero. 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, `webcpp::document::pmr::document` - among them, and a rejected `async_receive` completes with an empty one - there (a document holding `null`), through `detail::empty_payload`. + 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` (a document holding `null` until + webcpp::document's `basic_document::nothing` lands, then one with no + image, which allocates nothing). `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 diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 2724a22..24e4739 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -232,8 +232,12 @@ 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; a text given whole -leaves Boost.JSON's parser no state to suspend. A text the room writes is +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 diff --git a/doc/differences.adoc b/doc/differences.adoc index a1f626b..e16175a 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -115,13 +115,15 @@ has nothing of it to run beside its twin. | 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 needs more than twice its length and 64 KiB of image: an array of more than 345 zeros, 352 numbers of three digits, 287 short strings or 101 objects of two members | delivered: `JSON.parse` takes any | not delivered (<>) | each value of a document is a node of some 200 bytes of image, so the image's bound is tied to the payload's length, as a protocol text's to its bound (<>), and a payload of many small values costs the room no more than a multiple of its length +| 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) @@ -511,21 +513,30 @@ include::{examples}/diff_json_numbers.expected[] ---- [#trystero-differences-json-refused] -==== A JSON payload nested deeper than 256, holding a lone surrogate, or of many small values +==== 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 1,000 zeros, so a room delivers all three. +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 twice the payload and 64 KiB, 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 would need some 190 KB. The room goes on, and -delivers the payloads sent after them. +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 some 200 bytes of image, so -the image's bound is tied to the payload's length, as a protocol text's to -its bound (<>), and a payload of many small values -costs the room no more than a multiple of its length. +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 @@ -624,8 +635,8 @@ its reason. | 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 -| 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` test holds the bounds. +| 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/protocol.adoc b/doc/protocol.adoc index b1bf6b3..cfa1473 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -109,20 +109,26 @@ 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 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 bounded the same way by -its own size: its image grows to at most twice the payload and 64 KiB, so -that a payload of many small values, each a node of some 200 bytes, costs the -room no more than a multiple of its length; an array of 345 zeros is read, -and one of 346 is not, nor one of more than 101 objects such as -`{"x":12,"y":34}` (<>). Its 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. +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 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 diff --git a/doc/testing.adoc b/doc/testing.adoc index b40b520..8fd9fdb 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -87,8 +87,9 @@ include::{library-root}/test/Jamfile[tag=allocation] | `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, and a signal or a relay's text read at its bound and - dropped one byte past it. + 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` | Whole rooms in one process, over the memory relays: every payload format, @@ -97,7 +98,7 @@ include::{library-root}/test/Jamfile[tag=allocation] 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, JSON payloads read in the room's resource - within their size's bound, and a rejected document receive. + up to its bound, and a rejected document receive. | `app_impl` | Configuration copying and validation, a self id that is not UTF-8 set diff --git a/doc/usage.adoc b/doc/usage.adoc index ebada31..9cd0040 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. |=== @@ -216,9 +219,10 @@ 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 would need more than twice -its length and 64 KiB of image, an array of more than 345 zeros among them -(<>). +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 diff --git a/example/diff_json_refused.cpp b/example/diff_json_refused.cpp index 1fe2b14..5c1050b 100644 --- a/example/diff_json_refused.cpp +++ b/example/diff_json_refused.cpp @@ -5,11 +5,12 @@ // 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 of many small values. 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 twice the payload and 64 KiB, which an array of 1,000 zeros, a node of some 200 bytes each, -// passes. A Trystero JS page sends such payloads, and a C++ +// 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 @@ -227,7 +228,10 @@ int main() { trystero::app other_app(io.get_executor(), marking_backend, config()); auto other = other_app.join("lobby"); trystero::app app(io.get_executor(), backend, config()); - auto joined = app.join("lobby"); + // 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; @@ -239,8 +243,8 @@ int main() { }; // 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, and a last one sent - // after them. + // 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"; 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/protocol/json.hpp b/include/webcpp/trystero/protocol/json.hpp index a48aeb7..d837342 100644 --- a/include/webcpp/trystero/protocol/json.hpp +++ b/include/webcpp/trystero/protocol/json.hpp @@ -48,14 +48,19 @@ using const_value = webcpp::document::basic_const_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 JSON text's parse: at most `max_bytes` of text, into an image that grows to at - * most twice that and 64 KiB more. + * 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. + * 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. @@ -63,10 +68,38 @@ using value = webcpp::document::basic_value= (most - spare) / image_bytes_per_text_byte + ? most + : (image_bytes_per_text_byte * text_bytes) + spare; + return o; +} + /** * The text a value holds. * diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index d28676d..05a70e5 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -161,15 +161,26 @@ 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 + * 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 protocol::json::protocol_limits - * of its own size. + * `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 | @@ -204,7 +215,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; } @@ -229,11 +240,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); } }; @@ -252,8 +263,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; } @@ -262,11 +272,13 @@ struct payload_traits { }; /** - * The limits of a received JSON payload's parse: its own size, and an image that grows to at most - * twice that and 64 KiB, as a protocol text's (@ref protocol::json::protocol_limits). + * 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) noexcept { - return protocol::json::protocol_limits(text.size()); +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. */ @@ -289,13 +301,12 @@ struct payload_traits { * 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; } const std::string_view text = as_text(m.payload()); - auto v = webcpp::document::parse(text, json_payload_limits(text)); + auto v = webcpp::document::parse(text, json_payload_limits(text, to)); if (!v.has_value()) { return std::nullopt; } @@ -323,14 +334,13 @@ struct payload_traits { * 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, std::pmr::memory_resource* memory) { + 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), - std::pmr::polymorphic_allocator(memory)); + auto v = webcpp::document::parse(text, json_payload_limits(text, to), + std::pmr::polymorphic_allocator(to.memory)); if (!v.has_value()) { return std::nullopt; } @@ -355,7 +365,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; } @@ -381,15 +391,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); } }; @@ -409,8 +419,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; } @@ -438,20 +448,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; @@ -478,6 +488,9 @@ Document made_or_bad_alloc(webcpp::document::result made) { */ template T empty_payload(std::pmr::memory_resource* memory) { + // TODO(document): webcpp::document's basic_document::nothing(alloc), which has no image, + // allocates nothing and cannot fail, lands on its branch pmr; the two documents below take it + // then, made_or_bad_alloc goes, and a rejected receive neither allocates nor raises. if constexpr (std::is_same_v) { return made_or_bad_alloc(webcpp::document::pmr::document::create( std::pmr::polymorphic_allocator(memory))); @@ -548,6 +561,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_), @@ -712,6 +726,9 @@ 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_, options_.max_json_document_bytes}; } + /** An allocator of the room's resource. */ std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } @@ -1857,14 +1874,14 @@ 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); } })); @@ -1947,20 +1964,19 @@ class action { allocator, [impl, handler = std::move(handler)](boost::system::error_code ec, detail::incoming m) mutable { - auto* const memory = impl->memory(); + const detail::decoding to = impl->decoding(); message_info info{ .from = std::move(m.peer), - .metadata = std::pmr::string(m.metadata(), memory), + .metadata = std::pmr::string(m.metadata(), to.memory), }; - auto value = - ec ? std::nullopt - : detail::payload_traits::decode(m, 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(memory), + : detail::empty_payload(to.memory), std::move(info)); }))); }, diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index c707ff2..55d4506 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -887,6 +887,18 @@ 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 @@ -1024,12 +1036,12 @@ void parse_cost() { } } -// A text nested past max_depth is refused: Boost.JSON's parser stops at the 257th level, and the -// resource has nothing out after it. +// 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, 256U); + BOOST_TEST_EQ(depth, 16U); const auto nested = [](std::size_t levels) { std::string text(levels, '['); text.append(levels, ']'); @@ -1047,6 +1059,39 @@ void parse_depth() { 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 @@ -1138,6 +1183,7 @@ int main(int argc, char* argv[]) { parse_bounds(); parse_cost(); parse_depth(); + payload_image_per_text_byte(); parse_resource(); text(); return boost::report_errors(); diff --git a/test/room_test.cpp b/test/room_test.cpp index acfdbe1..ef09b8f 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -1309,16 +1309,18 @@ void async_receive_works_in_a_coroutine() { } // A JSON payload is parsed in the receiving room's resource, as a webcpp::document::pmr::document, -// within twice its own size and 64 KiB of image, whatever type receives it: an array of 100 zeros -// is delivered, one of 1,000, whose nodes would need some 190 KB, is not, and the messages after it -// are. -void json_payloads_are_read_in_the_rooms_resource_within_their_size() { +// 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{.memory = &z_memory}); + 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; @@ -1337,17 +1339,28 @@ void json_payloads_are_read_in_the_rooms_resource_within_their_size() { for (std::size_t i = 1; i < n; ++i) { text += ",0"; } - return document_of(text + "]"); + 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(); + }; + std::size_t at_bound = 1000; + while (fits(at_bound + 1)) { + ++at_bound; + } + 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 : {100, 1000, 3}) { - to_z.async_send(zeros(n), asio::detached); + 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 two. - BOOST_TEST(run_until(f.io, [&] { return in_resource.size() >= 2 && in_heap.size() >= 2; })); - const std::vector delivered{100, 3}; + // 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); @@ -1695,7 +1708,7 @@ int main() { counter_announcements_are_paced(); three_peers_form_a_mesh(); async_receive_works_in_a_coroutine(); - json_payloads_are_read_in_the_rooms_resource_within_their_size(); + json_payloads_are_read_in_the_rooms_resource_up_to_its_bound(); a_rejected_document_receive_holds_null_in_the_rooms_resource(); view_handlers_read_the_frame_without_copying(); a_rate_limited_relay_does_not_stop_discovery(); diff --git a/test/signaling_test.cpp b/test/signaling_test.cpp index ade19e9..32d4302 100644 --- a/test/signaling_test.cpp +++ b/test/signaling_test.cpp @@ -419,6 +419,58 @@ void a_relay_text_past_its_bound_is_dropped() { 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[]) { @@ -435,5 +487,6 @@ int main(int argc, char* argv[]) { 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()); } From c91035b39e5f03a748008823b14818ca03c42f17 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:22:00 -0300 Subject: [PATCH 091/116] trystero: a room delivers a JSON payload nested 256 deep The room test sends an array nested 256 deep, document's default depth, to both document types, and finds the bound's longest array of zeros by bisection, which keeps the test within its time on emscripten. --- test/room_test.cpp | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/test/room_test.cpp b/test/room_test.cpp index ef09b8f..136d071 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -1347,9 +1347,12 @@ void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() { 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; - while (fits(at_bound + 1)) { - ++at_bound; + 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"}) { @@ -1366,6 +1369,33 @@ void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() { 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. +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 holding null, in the room's resource. void a_rejected_document_receive_holds_null_in_the_rooms_resource() { @@ -1709,6 +1739,7 @@ int main() { three_peers_form_a_mesh(); async_receive_works_in_a_coroutine(); json_payloads_are_read_in_the_rooms_resource_up_to_its_bound(); + a_json_payload_nested_256_deep_is_delivered(); a_rejected_document_receive_holds_null_in_the_rooms_resource(); view_handlers_read_the_frame_without_copying(); a_rate_limited_relay_does_not_stop_discovery(); From 25ccc3ede80a9e5b5b232f74d0fc3f632e4f9260 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:25:07 -0300 Subject: [PATCH 092/116] trystero: the flood test runs on the virtual clock a_flood_of_announcements_is_bounded ran on the memory backend's wall clock, 100 times faster, and failed on a loaded machine. With 14 copies of room at once beside 40 busy loops (a load of 150 to 240), 28 runs of 28 failed, each on the same three checks: the message sent after the second flood was not heard within run_until's 10 s, so heard.size() was 1, not 2, and the memory was then measured with the flood still queued in the room's resource (second <= first + first / 2, 1420464 <= 980676 and the like). The case alone, 12 copies beside 24 loops (a load of about 100), failed 3 runs of 24 on the first two. The room is not at fault: the message was heard every time, late. The case waited for each thousand announcements only until the relay had received them, which left the deliveries to the rooms and the relay's replies queued ahead of the message: its 10 s of wall clock bounded an amount of work, which the room does not promise to do in any time. Idle, the message after the second flood came 2.8 s after it was sent, behind 6,300 relay texts; under load 22 to 25 s, behind 11,000 to 17,000, since the slower the machine ran, the more often the rooms' timers fired meanwhile (announcements, offer retries and expiries, new offers). The same dependence on speed moved what the case compares: the peak of connections reached its bound, 70 of 70, in 15 runs of 28. The case now runs on the virtual clock. The clock stands still while the rooms handle a thousand announcements, every queued completion included, moves a minute, longer than an offer's 57.3 s, before the next thousand, and the case waits a minute of it for the last offers to expire. Each run sees the same: each thousand makes 32 offers, the peak is the connections held plus 32, and the second flood leaves 1.043 times what the first left. The peak is now held to max_unconnected_peers beyond the connections held, not twice that: the second half allowed for closed connections that completions queued behind the relays kept alive on a loaded machine, and the virtual clock moves only once none is queued. The case still fails without the room's bounds (measured): without the bound on negotiations the room fills its window of 64 (66 <= 34, then 70 <= 38) and the second flood leaves 2.6 times what the first left; without the bound on the event ids remembered too, 2.95 times. After the change, the same 14 copies beside 40 busy loops (a load of 166 to 174) passed 28 runs of 28. --- test/room_test.cpp | 50 ++++++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/test/room_test.cpp b/test/room_test.cpp index 1028ab3..b628fdc 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -400,8 +400,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 @@ -412,9 +418,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)); @@ -429,49 +436,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)); From ab5658115691c2146d0f0b07a6d38056756b3d09 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:44:04 -0300 Subject: [PATCH 093/116] trystero: a relay's refusal has its header read alone, through beast's bounded handshake Natively the session's next layer is webcpp::beast's bounded_handshake_stream over the transport, made with the room's allocator, with a body limit of 0: a relay that refuses the upgrade has its response's header read, at most 8 KiB, and no byte of its body, where Beast's own parser read a body of up to 8 MiB outside the room's resource. The TLS stream is one layer further down (tls_stream()); a page keeps its transport, whose WebSocket reads its own response. platform_websocket_allocation's refusal of 4 MiB: 4,199,353 bytes of operator new on the room's thread before, 5,144 now. The guide, the allocation page and AGENTS.md drop the 8 MiB refusal body. --- AGENTS.md | 11 ++-- doc/allocation.adoc | 12 ++-- doc/platform.adoc | 19 ++++--- doc/testing.adoc | 5 +- .../webcpp/trystero/platform/websocket.hpp | 56 +++++++++++++++---- test/platform_websocket_allocation_test.cpp | 5 +- 6 files changed, 76 insertions(+), 32 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 067f0ef..4442a90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,7 +173,9 @@ holds only what is specific to trystero. 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 and + 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 @@ -714,9 +716,10 @@ holds only what is specific to trystero. 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, and a non-101 - response's body up to Beast's default 8 MiB, which no option of its - stream lowers, the verify callback and its copy of the host, the timers' + 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 diff --git a/doc/allocation.adoc b/doc/allocation.adoc index e696876..e0486a4 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -274,11 +274,13 @@ nothing. 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, the header fields of both and, for a - response that is not 101, its body, which Beast's own parser reads up to - Beast's default limit for a response, 8 MiB, that no option of its stream - lowers (measured: an 8 MiB body held about 18 MiB at its peak, as its - string grew); over TLS, the verify callback Asio's `set_verify_callback` + 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: diff --git a/doc/platform.adoc b/doc/platform.adoc index 3e60931..35ab0ce 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -232,14 +232,17 @@ hold: 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 - can have Boost.Beast read a body of up to 8 MiB, its default limit for a - response, outside the room's resource, before the connection reports its - close (measured: an 8 MiB body held about 18 MiB at its peak, as the - string that holds it grew); it is freed then, and the room retries with - its backoff. Beast's WebSocket stream reads the response with a parser of - its own, inside its handshake, and none of its options, nor its handshake - that returns the response, reaches that parser's limit, so the backend - cannot lower it. In a page the browser makes the handshake. + 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 diff --git a/doc/testing.adoc b/doc/testing.adoc index d7cdb5f..67243d9 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -171,7 +171,10 @@ include::{library-root}/test/Jamfile[tag=allocation] | `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 (<>). + `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 diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index a1155cc..0952207 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -25,6 +25,8 @@ #include // lint-world: the relays' WebSockets #ifndef WEBCPP_TARGET_EMSCRIPTEN +#include // lint-world: the relays' WebSockets + #include #include #endif @@ -309,9 +311,10 @@ inline std::optional parse_url( * 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, the header fields of both and, for a response that is not - * 101, its body, which Beast's own parser reads up to Beast's default limit for a response, 8 MiB, - * that no option of its stream lowers; the verify callback Asio's `set_verify_callback` makes with + * 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 @@ -331,10 +334,24 @@ class websocket_session : public std::enable_shared_from_this, 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; @@ -434,16 +451,25 @@ class websocket_session : public std::enable_shared_from_this allocator(memory); if constexpr (Secure) { - return stream_type(ex, *tls); + return stream_type(std::allocator_arg, allocator, ex, *tls); } else { (void)tls; - return stream_type(ex); + 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 { @@ -472,7 +498,7 @@ class websocket_session : public std::enable_shared_from_thisshared_from_this()](const boost::system::error_code& ec) { @@ -749,9 +781,9 @@ class websocket_handle : public backend::websocket { * `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; among it, a relay that answers the handshake with a status other - * than 101 can have Beast read a body of up to 8 MiB, Beast's default limit for a response, which - * no option of its stream lowers, before the connection reports its close. In a page, the page + * 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. diff --git a/test/platform_websocket_allocation_test.cpp b/test/platform_websocket_allocation_test.cpp index 9fb6880..62bbba8 100644 --- a/test/platform_websocket_allocation_test.cpp +++ b/test/platform_websocket_allocation_test.cpp @@ -19,9 +19,10 @@ // // 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. Without webcpp::beast's bounded handshake layer, Beast's own +// 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. +// 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. From 40b8f35c3abfbbb3a840f9c648b1250ffd5da703 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:47:06 -0300 Subject: [PATCH 094/116] trystero: a rejected receive holds nothing, and Asyncify's parse fits 256 A rejected async_receive of a document completes with webcpp::document's nothing(), a document with no image whose root reads undefined, which allocates nothing and raises nothing; an empty std::pmr container allocates nothing either, so trystero raises nothing of its own again. Under Asyncify, /webcpp/trystero//trystero links -sASYNCIFY_REMOVE=@asyncify-remove.json, which leaves Boost.JSON's recursive descent uninstrumented, since it never suspends: instrumented, a level of a cold debug parse took some 6.5 KB of node's stack, and a peer's first payload nested 256 deep overflowed it at about 150 levels. The room test now sends such a payload first, while the parser is cold. --- AGENTS.md | 23 ++++++++++++--------- asyncify-remove.json | 1 + build.jam | 15 +++++++++++++- doc/protocol.adoc | 10 +++++++++ doc/usage.adoc | 7 ++++--- include/webcpp/trystero/room.hpp | 34 +++++++++---------------------- test/room_test.cpp | 35 ++++++++++++++++++++++---------- 7 files changed, 76 insertions(+), 49 deletions(-) create mode 100644 asyncify-remove.json diff --git a/AGENTS.md b/AGENTS.md index 7fa3945..4f18b59 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,12 +83,10 @@ holds only what is specific to trystero. 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 but `std::bad_alloc`, through - `boost::throw_exception`, when a room's resource has no room for the - `null` document a rejected `async_receive` of a document completes with, - as a `std::pmr` container of the room raises it (`detail::empty_payload`); - natively the platform backend keeps a TLS context OpenSSL cannot make as - an error value (`tls_context()`), and its `wss://` relays report a close. + 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 @@ -656,7 +654,12 @@ holds only what is specific to trystero. 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. A text the room writes + 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. 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 @@ -673,9 +676,9 @@ holds only what is specific to trystero. 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` (a document holding `null` until - webcpp::document's `basic_document::nothing` lands, then one with no - image, which allocates nothing). + `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 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 7f4834a..ee039df 100644 --- a/build.jam +++ b/build.jam @@ -56,10 +56,23 @@ rule platform-dependencies ( properties * ) # 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 this alias under Asyncify; under JSPI +# nothing is left out. +path-constant WEBCPP_TRYSTERO_ROOT : . ; # tag::trystero[] alias trystero : : @trystero-dependencies : : include /boost//headers /webcpp/document//document - /webcpp/config//config /webcpp/asio//asio secp256k1 ; + /webcpp/config//config /webcpp/asio//asio secp256k1 + emscripten,asyncify:"-sASYNCIFY_REMOVE=@\"$(WEBCPP_TRYSTERO_ROOT)/asyncify-remove.json\"" + ; # end::trystero[] # The platform backend, one for both targets: its WebRTC is webcpp::webrtc's, diff --git a/doc/protocol.adoc b/doc/protocol.adoc index cfa1473..b896bca 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -130,6 +130,16 @@ 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, `basic_parser`'s `parse_*` functions, 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 diff --git a/doc/usage.adoc b/doc/usage.adoc index 9cd0040..a3d2173 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -268,9 +268,10 @@ 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; a message of another format, or a JSON text that does not parse, completes it with -`error::transfer_rejected` and an empty value, in the room's resource for a -`std::pmr` type, and a document holding `null` for a JSON one, in the room's -resource for a `webcpp::document::pmr::document`. Frames of an action that +`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. diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 05a70e5..82e395c 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -43,7 +43,6 @@ #include #include -#include #include #include @@ -51,7 +50,6 @@ #include #include #include -#include #include #include #include @@ -470,33 +468,20 @@ struct payload_traits { } }; -/** An owned document `create` made, or `std::bad_alloc` when its allocator had no room for it. */ -template -Document made_or_bad_alloc(webcpp::document::result made) { - if (!made.has_value()) { - // As a std::pmr container fails when its resource has no room. - boost::throw_exception(std::bad_alloc()); - } - return std::move(made).unsafe_value(); -} - /** - * The value `async_receive` completes with when it decodes no message: an empty one, in the room's - * resource for a `std::pmr` type, and for a JSON document one holding `null`, the - * `webcpp::document::pmr::document` in the room's resource; `std::bad_alloc` when the resource - * has no room for that document. + * 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) { - // TODO(document): webcpp::document's basic_document::nothing(alloc), which has no image, - // allocates nothing and cannot fail, lands on its branch pmr; the two documents below take it - // then, made_or_bad_alloc goes, and a rejected receive neither allocates nor raises. +T empty_payload(std::pmr::memory_resource* memory) noexcept { if constexpr (std::is_same_v) { - return made_or_bad_alloc(webcpp::document::pmr::document::create( - std::pmr::polymorphic_allocator(memory))); + return T::nothing(std::pmr::polymorphic_allocator(memory)); } else if constexpr (std::is_same_v) { - return made_or_bad_alloc(webcpp::document::document::create()); + 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{}; @@ -1940,7 +1925,8 @@ class action { * * Completes with `(error_code, T, message_info)`; a message of another payload format than * `T`'s, or a JSON text that does not parse, completes with `error::transfer_rejected` and an - * empty value, a JSON document holding `null`, and leaving the room with `error::room_left`. + * 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. diff --git a/test/room_test.cpp b/test/room_test.cpp index 136d071..68f5feb 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -1371,7 +1371,7 @@ void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() { // 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. +// 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")); @@ -1397,27 +1397,38 @@ void a_json_payload_nested_256_deep_is_delivered() { } // A message of another format than a document action's completes its receive with -// error::transfer_rejected and a document holding null, in the room's resource. -void a_rejected_document_receive_holds_null_in_the_rooms_resource() { +// 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}); - bool completed = false; - z.make_action("doc").async_receive( + 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 = true; + ++completed; BOOST_TEST(ec == trystero::error::transfer_rejected); - BOOST_TEST(v.root().is_null()); + 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("doc").async_send("not JSON", asio::detached); - BOOST_TEST(run_until(f.io, [&] { return completed; })); + 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() { @@ -1705,6 +1716,9 @@ void the_errors_have_their_values() { } // namespace int main() { + // 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. + a_json_payload_nested_256_deep_is_delivered(); two_peers_join_and_exchange_every_payload_format(); large_payloads_travel_in_chunks_both_ways(); ping_measures_a_round_trip(); @@ -1739,8 +1753,7 @@ int main() { three_peers_form_a_mesh(); async_receive_works_in_a_coroutine(); json_payloads_are_read_in_the_rooms_resource_up_to_its_bound(); - a_json_payload_nested_256_deep_is_delivered(); - a_rejected_document_receive_holds_null_in_the_rooms_resource(); + a_rejected_document_receive_holds_nothing(); 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(); From f70da8ea686be36189e96a1c940a0cae35c15c16 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 01:02:03 -0300 Subject: [PATCH 095/116] trystero: protocol.adoc names Boost.JSON's parse functions as Asciidoctor keeps them --- doc/protocol.adoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/protocol.adoc b/doc/protocol.adoc index b896bca..0afabd6 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -131,8 +131,8 @@ 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, `basic_parser`'s `parse_*` functions, out of -Asyncify's instrumentation (`asyncify-remove.json`, which +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 From 1649f3c76d9d4b04a603357fe2507a014fe617c9 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 01:05:20 -0300 Subject: [PATCH 096/116] trystero: the room test's last timing cases on the virtual clock Five cases of room still ran on the memory backend's wall clock, 10 or 100 times faster: signals_that_do_not_open_are_reported_once_per_interval, a_replayed_answer_is_refused, a_replayed_offer_is_refused, a_reflected_offer_is_refused_as_an_offer (10 times) and a_relay_that_closes_at_once_is_tried_less_and_less_often (100 times). Each now runs on the virtual clock, as chapter 15 decided for timing cases, and what each proves is unchanged. Load alone did not break them: 24 copies of the five at once beside 80 busy loops (a load of 96 to 222) passed 96 runs of 96. A pause does, which a loaded runner gives a process: with each copy stopped (SIGSTOP) for a random span between short runs, - the backoff case, with 5 ms runs and pauses of up to 1.5 s, failed 2 runs of 64, its bounds 3333, 3333, 6666, ... and not 3333, 6666, 13332, ...: a pause of 0.6 s between a relay's open and its close, 60 s of its clock, made a connection closed at once one that had lasted, which brings the bound back down; - the replayed answer, replayed offer and reflected offer cases, with 10 ms runs and pauses of up to 1.5 s, failed 2, 2 and 1 runs of 24, and with 5 ms runs and pauses of up to 3 s, 72 of 72: a join did not complete within run_until's 10 s of wall clock; - the reports case failed none (16 runs, 30 ms runs and pauses of up to 1.5 s; 48 runs of the five, 20 ms runs and pauses of up to 0.5 s). After the change, the same settings failed none: 96 runs under load, 48 with pauses of up to 0.5 s, 96 of the four with pauses of up to 1.5 s, 64 of the backoff case and 72 of the three with pauses of up to 3 s, and 16 of the reports case. The reports case moves the clock 250 ms after every twenty offers, once everything ready ran, so that the flood spans 25 s, two and a half intervals; the replayed offer is sent every 0.5 s of the virtual clock; the backoff case waits up to 2 minutes for its six bounds and its lasting connection, and 1 for the reconnection. It now waits for 5 announcements after the reconnection, not 6: the warm-up's first went as the connection opened, before the clock moved, so 6 waited for the second steady announcement, 127 s after the open, not the first, 67 s after it. On the wall clock, which of the two it was depended on whether run_until's 20 ms slice ended before the relay took the first. Each case still catches its defect, planted in a scratch copy of the headers, as the wall-clock one did: every failed open reported at once (2000 reports, against at most 4), the interval's report never made (the count never reaches 2000), a used answer applied (B never joins again), a used offer answered (B never joins; the reflected offer is answered), the reconnection bound never brought back down (60000, not 3333), brought down after any connection, or never doubled (3333 again and again). The five took 6.9 s of wall clock in one run at a load of 89, and now take 2.7 s, the reports case's own work. --- test/room_test.cpp | 74 +++++++++++++++++++++------------------------- 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/test/room_test.cpp b/test/room_test.cpp index b628fdc..75adc01 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -544,12 +544,11 @@ void forged_offers_make_no_connection() { // 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 std::size_t flood = 2000; - fixture f; - f.net.time_scale = 10; + 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"); @@ -570,8 +569,8 @@ void signals_that_do_not_open_are_reported_once_per_interval() { 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. + // 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), @@ -579,10 +578,10 @@ void signals_that_do_not_open_are_reported_once_per_interval() { .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; @@ -591,7 +590,7 @@ void signals_that_do_not_open_are_reported_once_per_interval() { } return sum; }; - BOOST_TEST(run_until(f.io, [&] { return counted() == flood; })); + 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())) { @@ -896,24 +895,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)); @@ -953,7 +950,7 @@ 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(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; @@ -961,12 +958,10 @@ void a_replayed_answer_is_refused() { } // 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)); @@ -989,14 +984,14 @@ void a_replayed_offer_is_refused() { trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id)); const auto b = join(b_app, "replayo"); std::size_t replays = 0; - const auto end = std::chrono::steady_clock::now() + 10s; - while (joined.size() < 2 && std::chrono::steady_clock::now() < end) { + 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, 1U); @@ -1034,10 +1029,8 @@ void a_reflected_offer_is_refused_as_an_answer() { // 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"; @@ -1075,10 +1068,10 @@ 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(run_until(f, [&] { return joined.size() == 1; })); BOOST_TEST_GE(reflected, 1U); BOOST_TEST_EQ(answered_reflections, 0U); } @@ -1135,11 +1128,11 @@ void a_reflected_answer_is_refused_as_an_answer() { // 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"); @@ -1155,23 +1148,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; })); + 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 std::size_t before = reconnections; - BOOST_TEST(run_until(f.io, [&] { return reconnections > before; })); + 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); } From 541102b2f2f50ac744c65c35f438f13cee43d31a Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 01:08:28 -0300 Subject: [PATCH 097/116] trystero: the room test asks node for 300 s Its forty cases of two or three apps each take about 115 s under Asyncify in a debug build alone, near node's default bound of 120 s, and past it on a loaded machine. --- test/room_test.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/room_test.cpp b/test/room_test.cpp index 68f5feb..3b90f6a 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -1716,6 +1716,9 @@ void the_errors_have_their_values() { } // namespace int main() { + // Some forty cases of two or three apps each: under Asyncify a debug build runs them in about + // 115 s alone (measured), near node's default bound of 120 s, and past it on a loaded machine. + webcpp::test::bound(std::chrono::seconds(300)); // 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. a_json_payload_nested_256_deep_is_delivered(); From 9c3d71ce9808d072a1c8eb4877dd2de4a68d67ff Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 01:12:03 -0300 Subject: [PATCH 098/116] trystero: the memory backend's scaled wall clock removed memory_network::time_scale ran the memory backend's timers and its steady_now a given number of times faster than the wall clock. No test sets it any more: the six cases of room that did, the flood test and the five of the commit before, now run on the virtual clock, since a case on a scaled wall clock fails when the process pauses, as chapter 15 records. A timer of the memory backend that is not on the virtual clock now waits its delay, and steady_now is the time since the network was made, so that a timing case has only the virtual clock to use. --- test/support/memory_backend.hpp | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index 0ab31bf..73ee86f 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -85,11 +85,10 @@ class memory_timer : public backend::timer { public: /** A timer on the virtual clock `clock`, or on Asio's when `clock` is empty. */ memory_timer(webcpp::asio::io_context& io, std::pmr::memory_resource* memory, - std::uint32_t time_scale = 1, std::weak_ptr clock = {}) + std::weak_ptr clock = {}) : io_(io), timer_(io), memory_(memory), - time_scale_(time_scale), on_clock_(!clock.expired()), clock_(std::move(clock)), waits_( @@ -112,7 +111,7 @@ class memory_timer : public backend::timer { return; } const std::uint64_t wait = ++*waits_; - timer_.expires_after(delay / time_scale_); + timer_.expires_after(delay); timer_.async_wait(webcpp::asio::bind_allocator( std::pmr::polymorphic_allocator<>(memory_), [waits = std::weak_ptr(waits_), wait, @@ -156,7 +155,6 @@ class memory_timer : public backend::timer { webcpp::asio::io_context& io_; webcpp::asio::steady_timer timer_; std::pmr::memory_resource* memory_; - std::uint32_t time_scale_; bool on_clock_; std::weak_ptr clock_; std::optional key_; @@ -730,13 +728,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_)); } @@ -757,14 +755,13 @@ class memory_network : public backend::factory { std::chrono::floor(steady_now().time_since_epoch()); } - /** The virtual clock's time, or the time since the network was made, `time_scale` times - * faster; from the steady clock's epoch. */ + /** 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 : std::chrono::steady_clock::time_point(); } - return std::chrono::steady_clock::time_point((std::chrono::steady_clock::now() - start_) * - time_scale); + return std::chrono::steady_clock::time_point(std::chrono::steady_clock::now() - start_); } std::shared_ptr find(std::size_t id) { @@ -783,8 +780,6 @@ class memory_network : public backend::factory { std::size_t peak_connections = 0; /** How many random bytes were drawn. */ std::size_t random_bytes = 0; - /** How much faster than real time the timers and the clock run, for tests of long timeouts. */ - std::uint32_t time_scale = 1; /** How many of the next peer connections to refuse, as a browser at its limit does. */ std::size_t refuse_peer_connections = 0; /** Whether to record the URL of every ICE server a peer connection is made with. */ From 2af790654aa661162cbb855b5cc8e7eaff341a06 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 01:20:10 -0300 Subject: [PATCH 099/116] trystero: the decoding context and the payload factor test to the pinned clang-tidy --- include/webcpp/trystero/room.hpp | 4 +++- test/protocol_test.cpp | 10 ++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 82e395c..106bfab 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -712,7 +712,9 @@ class room_impl final : public std::enable_shared_from_this, public r std::pmr::memory_resource* memory() const { return memory_; } /** What the room decodes a received payload with. */ - detail::decoding decoding() const { return {memory_, options_.max_json_document_bytes}; } + 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_}; } diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index 55d4506..ad5f18b 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -1080,8 +1080,14 @@ void payload_image_per_text_byte() { 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)}) { + 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)); From 54765f664242162a849d5c794c2013e08c4fe199 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 01:40:54 -0300 Subject: [PATCH 100/116] trystero: three room cases wait for what they check forged_offers_make_no_connection ran 200 ms of wall clock "for the opens" and then found no connection made, which held as well when the opens had not run. With a planted defect, an offer that does not open acted on, it failed idle (1 connection), but with each copy stopped (SIGSTOP) for random spans of up to 1.5 s between runs of 10 ms it passed 47 runs of 48: the 200 ms ended before the opens, and the one failure was its wait for the relay. It now counts the offers the room could not open, which the room logs once each, waits until it has every one, and then finds no connection: with the defect it fails every run, 48 of 48 under the same pauses. The offers come twenty at a time, each twenty refused before the next comes 1 ms later, so that the id that evicts a negotiation evicts one already refused: sent at one instant, a later id evicts the first in id order among those idle as long, whose offer may still be opening, and the room drops that offer unopened. the_same_password_joins_and_another_does_not waited a fixed 1500 ms of wall clock for the intruder to be refused. Under the same pauses it failed 21 runs of 48: the intruder had refused nothing yet, so its reports were empty. Its comment said both sides report the intruder; only the intruder reports, since A and B, lower, offer to it and it cannot open their offers. It now waits until the intruder has reported both, the first at once and the other with its interval's report, 10 s later. A planted room key without the password, which the room's password proof still refuses after a connection, passed the old case and fails the new one, which checks that the key keeps the intruder out before it connects. counter_announcements_are_paced held asked <= 1 + elapsed / 5.333 s on the clock the room reads, which is consistent, but its strength was the machine's: idle, the flood took less than 5.3 s, so the case checked only that the room asked once, and an interval of 1 s or one that asks again only after 5.333 s passed it. Under the pauses its 10 s wait for the relay failed 26 runs of 48. On the virtual clock the interval is checked at its end, exactly: a flood of 300 at once asks once, a fresh id 5332 ms later asks nothing, and one at 5333 ms asks again. Both planted intervals fail it, as does no pace at all, which the old case caught too. Under load alone, 24 copies of the three at once beside 80 busy loops (a load of 125 to 180), the old and the new cases passed 96 runs of 96, and with pauses of up to 0.5 s between runs of 20 ms 48 of 48. With pauses of up to 1.5 s between runs of 10 ms, the old ones failed 33 runs of 48 and the new ones none of 48. --- test/room_test.cpp | 79 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 55 insertions(+), 24 deletions(-) diff --git a/test/room_test.cpp b/test/room_test.cpp index 75adc01..7c478e6 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -222,26 +222,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()); @@ -524,21 +530,36 @@ void a_forged_answer_changes_nothing() { } // 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 (std::size_t i = 0; i < 200; ++i) { + // Twenty at a time, each twenty refused before the next comes, 1 ms later. A new id beyond the + // room's 32 negotiations evicts the one idle longest, which is then one already refused: sent + // at once, or at one instant, the later ids would evict negotiations whose offers were still + // opening, and the room drops an offer whose negotiation is gone unopened. + 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) { + if (!BOOST_TEST(run_until(f, [&] { return refused == i + 1; }))) { + break; + } + advance(f, 1ms); + } } - 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 + BOOST_TEST_EQ(refused, flood); BOOST_TEST_EQ(f.net.made_connections, 0U); } @@ -1173,9 +1194,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) { @@ -1184,14 +1207,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 From ff40d04635ad4c8a7c0b527fe57691940e5aef83 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 02:26:35 -0300 Subject: [PATCH 101/116] trystero: an offer being opened keeps its negotiation's place A room holds at most 32 negotiations with peers it is not connected to, and a new peer beyond them took the place of the one idle longest. A negotiation counted as idle as soon as it held no connection, so also while the sealer was still opening its peer's offer, an asynchronous step (Web Crypto in a page). At one instant, which a page's coarse clock makes of close arrivals, every negotiation had been idle as long as any other, and the tie went to the first in id order: new ids arriving while honest offers were being opened took their places, and the room dropped those offers unopened, with no log. Measured on the memory backend's virtual clock: two peers offering while 32 new ids announced joined only 2 s later, on their offer sent again; 33 to 64 honest peers joining a room at once had 31 answered at once instead of 32; and 200 forged offers from fresh ids at one instant were all opened at once, 168 of them dropped unaccounted for. A negotiation is now idle only when it holds no connection and no offer of its peer is being opened (negotiation::offers_opening); of those idle as long, the one the room took first gives its place (negotiation::admitted), whatever the ids. An opened offer finds its negotiation by that order too, so an open that outlived its negotiation (the peer left, or the room closed) changes nothing. The bound keeps its purpose under a flood: the offers opened at once come from at most 32 peers, and every other new id is refused at the bound and logged. The memory backend can hold its sealers' opens (hold_sealer_opens, release_sealer_opens, held_sealer_opens), as Web Crypto's take their time in a page. room's an_offer_being_opened_keeps_its_place and a_flood_of_offers_at_one_instant_is_bounded failed before the change; the case of forged offers now sends its batches at one instant, with no clock moved between them. The bound is written in protocol.adoc, the testing page and AGENTS.md. --- AGENTS.md | 11 +- doc/protocol.adoc | 8 +- doc/testing.adoc | 12 +- include/webcpp/trystero/detail/signaling.hpp | 127 +++++++++++++------ test/room_test.cpp | 127 +++++++++++++++++-- test/support/memory_backend.hpp | 62 +++++++-- 6 files changed, 279 insertions(+), 68 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5dbb348..6353a98 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -310,7 +310,16 @@ 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::offers_opening`): 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, and the + offers opened at once come from at most 32 peers (`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 room makes at most `max_connections_per_window` (64) connections in any 57 s, however soon they end. The platform backend makes at most `backend_config::max_peer_connections_per_minute` (256) in any minute, diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 0afabd6..3d29b20 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -260,7 +260,13 @@ 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; and the offers opened at once come from at most 32 peers. * A room makes at most `max_connections_per_window` (64) connections in any 57 s, however soon they end; the platform backend makes at most 256 a minute on both targets (<>), and a page holds at diff --git a/doc/testing.adoc b/doc/testing.adoc index 17e8ea2..7baffea 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 @@ -96,9 +99,10 @@ include::{library-root}/test/Jamfile[tag=allocation] 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, JSON payloads read in the room's resource - up to its bound, and a rejected document receive. + signals, offers being opened that keep their places when new ids arrive + at the same instant, 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` | Configuration copying and validation, a self id that is not UTF-8 set diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index 36382ba..041f29f 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include @@ -75,14 +76,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 @@ -93,7 +95,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 from fresh ids too. */ static constexpr std::size_t max_unconnected_peers = 32; @@ -174,7 +177,7 @@ 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; @@ -207,7 +210,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); @@ -256,8 +259,9 @@ 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), + offer(a), offer_id(a), sealed_offer(a), offer_relays(a), @@ -273,9 +277,16 @@ class signaling : public std::enable_shared_from_this { 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. time_point last_message{}; + // How many of the peer's offers the sealer is opening: until each completes, the + // negotiation is not idle, and keeps its place. + std::size_t offers_opening = 0; // 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 @@ -308,6 +319,8 @@ class signaling : public std::enable_shared_from_this { 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_); } @@ -327,30 +340,57 @@ class signaling : public std::enable_shared_from_this { 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.offers_opening == 0; + } + /** * 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_message < idle->second.last_message)) { - 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)) { @@ -392,10 +432,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); } } @@ -569,29 +608,38 @@ class signaling : public std::enable_shared_from_this { } // 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.offers_opening; 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); - } - })); + offer, + bind( + [weak, relay, peer = copy(peer), admitted = n.admitted, 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, admitted, offer_id, offer, 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 an offer the sealer opened for the negotiation taken in `admitted`-th: makes the + * answering connection and applies the offer as its remote description. 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::size_t relay, std::string_view peer, std::uint64_t admitted, + std::string_view offer_id, std::string_view offer, + boost::system::error_code ec, std::string_view sdp) { + auto* found = find(peer, admitted); + if (found == nullptr) { return; } auto& n = *found; + --n.offers_opening; + if (n.connected) { + return; + } if (ec) { failed_open(peer, n, "offer"); return; @@ -1147,7 +1195,8 @@ 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_{memory_}; // per relay diff --git a/test/room_test.cpp b/test/room_test.cpp index c2a3466..d193219 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -545,23 +545,119 @@ void forged_offers_make_no_connection() { const auto a = join(a_app, "offers"); flooder attacker(f, "offers"); const auto a_topic = trystero::protocol::peer_topic(app_id, "offers", "zzzzzzzzzzzzzzzzzzzz"); - // Twenty at a time, each twenty refused before the next comes, 1 ms later. A new id beyond the - // room's 32 negotiations evicts the one idle longest, which is then one already refused: sent - // at once, or at one instant, the later ids would evict negotiations whose offers were still - // opening, and the room drops an offer whose negotiation is gone unopened. + // 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) { - if (!BOOST_TEST(run_until(f, [&] { return refused == i + 1; }))) { - break; - } - advance(f, 1ms); + 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 the + // room receives each offer on both relays, four opens that wait. + 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", + }); + } + 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; })); } // Unsealed offers from 2000 fresh ids, which anyone who reads the relays can send: the room reports @@ -590,9 +686,9 @@ void signals_that_do_not_open_are_reported_once_per_interval() { const auto a_topic = trystero::protocol::peer_topic(app_id, "reports", a_id); 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, 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. + // 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), @@ -638,8 +734,9 @@ void sealed_offers_that_fail_at_once_are_bounded() { 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)); @@ -1773,6 +1870,8 @@ int main() { a_refused_peer_is_logged_once(); a_forged_answer_changes_nothing(); forged_offers_make_no_connection(); + an_offer_being_opened_keeps_its_place(); + a_flood_of_offers_at_one_instant_is_bounded(); signals_that_do_not_open_are_reported_once_per_interval(); sealed_offers_that_fail_at_once_are_bounded(); announcements_with_forged_answers_are_bounded(); diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index c7241ae..4004e01 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -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 { @@ -810,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. */ @@ -849,6 +858,7 @@ class memory_network : public backend::factory { 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 { @@ -856,6 +866,15 @@ 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 @@ -874,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_; }; @@ -1176,9 +1196,18 @@ inline std::size_t memory_network::scheduled() const { * opens it. */ class memory_sealer : public backend::sealer { public: - memory_sealer(webcpp::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 { @@ -1200,12 +1229,20 @@ 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: + memory_network& net_; webcpp::asio::io_context& io_; std::array key_; std::pmr::memory_resource* memory_; @@ -1213,8 +1250,15 @@ class memory_sealer : public backend::sealer { 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 From cad22009b2af624af3482f7efed0a1bd22b578cb Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 02:41:35 -0300 Subject: [PATCH 102/116] trystero: each test case in a frame of its own, and the deepest in release under Asyncify Under Asyncify, b2's release build, compiled with -O3 and linked without optimization, saves every local of every frame from main down at each suspension, in webcpp::asio's 8,192 bytes. -O3 inlined the room test's cases into its main, which saved 29,776 bytes at each suspension, so that the test stopped at its first; app_impl's main saved 8,884 bytes, and allocation's main and largest case 7,788 together. A room's own work is never on that stack, since it runs in handlers between the run's waits: in that build the chat's two pages suspended at most 1,292 bytes deep, the interop page 2,344 and the page tests 1,660, so the library asks for no more than webcpp::asio's 8,192. A test whose cases suspend now runs each through webcpp::test::run_case (test/cases.hpp), which is never inlined and calls the case through a pointer, so that main holds none of their locals. The deepest suspensions in release become 3,096, 2,140 and 5,592 bytes, and the room test runs in 22 s rather than 200 s. room_asyncify_release, app_impl_asyncify_release and allocation_asyncify_release run the three in that build; each stopped at its first suspension before. --- AGENTS.md | 17 +++++- doc/platform.adoc | 13 +++++ doc/testing.adoc | 27 ++++++++-- test/Jamfile | 21 ++++++++ test/allocation_test.cpp | 15 +++--- test/app_impl_test.cpp | 35 +++++++------ test/cases.hpp | 34 ++++++++++++ test/platform_backend_test.cpp | 14 +++-- test/room_test.cpp | 95 ++++++++++++++++++---------------- test/timer_test.cpp | 12 +++-- 10 files changed, 201 insertions(+), 82 deletions(-) create mode 100644 test/cases.hpp diff --git a/AGENTS.md b/AGENTS.md index 5dbb348..7a7ff15 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,8 +120,21 @@ holds only what is specific to trystero. 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. There is one timer, the core's `detail::timer` over webcpp::asio's - `steady_timer`, on both targets, which `timer` tests on both. + 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 release, the deepest + build, the chat's pages measured 1,292 bytes, the interop page 2,344, the + page tests 1,660 at most). A test's cases are on that stack, since each + calls the run family itself, and a release build, linked without + optimization, saves every local of every frame there: 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, or `-O3` inlines every + case into `main`, whose frame 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 them in that build. 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) remains an external installation, found through `webcpp.external` and `webcpp.external-found` at `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=`, then diff --git a/doc/platform.adoc b/doc/platform.adoc index 35ab0ce..09af426 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -479,6 +479,19 @@ connection. 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 `release` + 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,292 bytes deep, the interop test's page in its 26 scenarios at most + 2,344, and the tests of a page's program at most 1,660 (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. diff --git a/doc/testing.adoc b/doc/testing.adoc index 17e8ea2..23f55ef 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -91,7 +91,7 @@ include::{library-root}/test/Jamfile[tag=allocation] 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 @@ -100,7 +100,7 @@ include::{library-root}/test/Jamfile[tag=allocation] 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`, `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, @@ -122,7 +122,7 @@ include::{library-root}/test/Jamfile[tag=allocation] 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 (<>). @@ -242,6 +242,27 @@ include::{library-root}/test/Jamfile[tag=page] include::{library-root}/test/Jamfile[tag=no-exceptions] ---- +Under Asyncify the deepest build is `release`: compiled with `-O3`, it is +linked without optimization, as b2's emscripten toolset links it, so that +each suspension saves every local of every frame 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; a case that `main` alone calls is otherwise +inlined into it, and the room test's `main`, which held every case's locals +so, saved 29,776 bytes at each suspension and stopped at its first. The +room, `app_impl` and allocation tests, whose cases hold whole apps, run once +more in that build, with webcpp::asio's 8,192 bytes, where their deepest +suspensions wrote 3,096, 2,140 and 5,592 bytes (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 diff --git a/test/Jamfile b/test/Jamfile index 343236f..aea01fb 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -140,6 +140,27 @@ webcpp.run platform_room_no_exceptions : platform_room_test.cpp webcpp.run allocation : allocation_test.cpp : emscripten:-sALLOW_MEMORY_GROWTH ; # end::allocation[] +# Under Asyncify the deepest build is release: compiled with -O3, linked +# without optimization, as b2's emscripten toolset links it, so that each +# suspension saves every local of every frame from main down, in +# webcpp::asio's 8,192 bytes. A test whose cases suspend runs each in a frame +# of its own (cases.hpp): -O3 inlined the room test's cases into its main, +# which saved 29,776 bytes at each suspension and stopped at its first +# (given 262,144 bytes, it passed in 200 s, against 22 s now). The deepest +# suspension, as the bytes its unwind wrote, measured on 2026-11-15 with +# Emscripten 6.0.11: in release, room 3,096, app_impl 2,140 and allocation +# 5,592, whose largest case alone saves 4,680; in debug, 2,332, 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 ; +# 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 diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 3831af9..b3b4645 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -12,6 +12,7 @@ #include +#include "cases.hpp" #include "require.hpp" #include "support/memory_backend.hpp" @@ -1119,11 +1120,13 @@ int main() { !defined(WEBCPP_TARGET_EMSCRIPTEN) malloc_logger = &count_c_allocation; #endif - the_replaced_operators_serve_every_alignment(); - the_counts_see_an_allocation(); - exchanges_allocate_through_the_rooms_resources(); - reading_a_text_allocates_through_its_resource(); - a_room_allocates_through_its_resource_from_join_to_destruction(); - rooms_of_one_app_allocate_through_their_resources(); + // 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 c1ea125..8d9b84d 100644 --- a/test/app_impl_test.cpp +++ b/test/app_impl_test.cpp @@ -35,6 +35,7 @@ #include #include +#include "cases.hpp" #include "require.hpp" namespace asio = webcpp::asio; @@ -706,22 +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(); - a_self_id_that_is_not_utf8_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(); + // 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/cases.hpp b/test/cases.hpp new file mode 100644 index 0000000..ea68848 --- /dev/null +++ b/test/cases.hpp @@ -0,0 +1,34 @@ +// 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. +// Under Asyncify each suspension saves every frame from main down to the call that suspends, each +// with the locals its instrumentation keeps, which a program linked without optimization, as b2's +// release variant is on emscripten, keeps whole. A case that main alone calls is inlined into it +// at -O3, so that main would keep the locals of every case 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 wrote 3,096 (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/platform_backend_test.cpp b/test/platform_backend_test.cpp index 347871b..5cb8981 100644 --- a/test/platform_backend_test.cpp +++ b/test/platform_backend_test.cpp @@ -37,6 +37,8 @@ #include #include +#include "cases.hpp" + namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; using namespace std::chrono_literals; @@ -165,10 +167,12 @@ void its_executor_and_tls_context_are_there() { } // namespace int main() { - its_own_state_is_in_its_memory(); - its_clocks_are_the_standard_librarys(); - its_randomness_fills_and_differs(); - its_randomness_fills_more_than_a_piece(); - its_executor_and_tls_context_are_there(); + // 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/room_test.cpp b/test/room_test.cpp index 890d408..3f1dbe6 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -42,6 +42,7 @@ #include #include +#include "cases.hpp" #include "require.hpp" #include "support/memory_backend.hpp" #include "support/rooms.hpp" @@ -1725,54 +1726,56 @@ int main() { // Some forty cases of two or three apps each: under Asyncify a debug build runs them in about // 115 s alone (measured), near node's default bound of 120 s, and past it on a loaded machine. 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. - a_json_payload_nested_256_deep_is_delivered(); - 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(); - recent_event_ids_drop_a_repeat_and_forget_the_oldest(); - event_ids_other_than_nip01_ones_are_never_remembered(); - the_event_id_hash_is_keyed(); - a_strategy_draws_the_key_of_its_event_ids(); - a_forged_event_under_a_genuine_id_hides_nothing(); - classes_over_a_pmr_circular_buffer_do_not_move(); - 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(); - json_payloads_are_read_in_the_rooms_resource_up_to_its_bound(); - a_rejected_document_receive_holds_nothing(); - 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(); + 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(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/timer_test.cpp b/test/timer_test.cpp index 98c007a..1b312a6 100644 --- a/test/timer_test.cpp +++ b/test/timer_test.cpp @@ -22,6 +22,8 @@ #include #include +#include "cases.hpp" + namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; using namespace std::chrono_literals; @@ -123,9 +125,11 @@ void a_restarted_timer_fires_only_its_new_wait() { } // 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(); + // 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()); } From e037e94f1f083fdd8f2d3095e685aa19ef7ec8ef Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 02:41:41 -0300 Subject: [PATCH 103/116] trystero: the room test's node bound, measured again With the flood test and five timing cases on the virtual clock, the room test still takes 54 s of the processor under Asyncify in a debug build, more than a third of node's default bound of 120 s, and 74 to 168 s on a loaded machine (18 cores at load averages of 50 to 230), past it; under JSPI 34 s, and 44 to 51 s. The bound stays at 300 s, with the new measurement beside it. --- test/room_test.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/room_test.cpp b/test/room_test.cpp index 3f1dbe6..5352047 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -1723,8 +1723,10 @@ void the_errors_have_their_values() { } // namespace int main() { - // Some forty cases of two or three apps each: under Asyncify a debug build runs them in about - // 115 s alone (measured), near node's default bound of 120 s, and past it on a loaded machine. + // 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; From 37e16de5294a0327b93d3676759f1478b3726ef3 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 02:57:04 -0300 Subject: [PATCH 104/116] trystero: a negotiation opens one offer of its peer at a time Every offer sent in a peer's name while none was answered started an open of its own, each holding its copy of the offer, up to 64 KiB, in the room's resource until it completed: the bound on negotiations bounded the peers whose offers were opened at once, not the offers, which only the relays' rate bounded. Measured on the memory backend: 40 offers of 48 KiB in one name at one instant held 42 opens and 1,976,152 bytes, and the same offer again through the other relay made an open that was then dropped, so the answer went through the first relay alone. Trystero 0.26.0 answers one offer of a peer at a time: handleOffer makes its answering peer before it decrypts the offer, and while it answers, an offer that is not the same is ignored, and the same one records its relay for the answer (dist/signal-handler.mjs:264-323). A negotiation now does the same. It opens one offer at a time, keeping its id, its sealed text and the relays it came through (negotiation::opening_offer), and the open's handler holds no copy of its own; while it is opened, the same offer through another relay adds that relay, where the answer goes too, and any other offer in that name is ignored. 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 (measured). room's offers_in_one_name_are_opened_one_at_a_time failed before the change: 42 opens, 1,976,152 bytes, the answer through one relay. The flooder of the tests can now use the second relay and give a signal a nonce. The honest-peer case's comment now says what its four opens are, two offers and two candidates: a signal comes through both relays as one event, which the room acts on once. Setting up the answer moves from on_offer_opened to start_answer, within the lint's cognitive complexity. --- AGENTS.md | 14 ++- doc/protocol.adoc | 9 +- doc/testing.adoc | 7 +- include/webcpp/trystero/detail/signaling.hpp | 100 +++++++++++++------ test/room_test.cpp | 68 ++++++++++++- test/support/rooms.hpp | 15 +-- 6 files changed, 167 insertions(+), 46 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6353a98..87cd274 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -311,15 +311,23 @@ holds only what is specific to trystero. 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. Idle means no connection and no offer of the - peer being opened (`negotiation::offers_opening`): the one idle longest + 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, and the - offers opened at once come from at most 32 peers (`room`'s + 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. The platform backend makes at most `backend_config::max_peer_connections_per_minute` (256) in any minute, diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 3d29b20..516482f 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -266,7 +266,14 @@ what each costs a room. 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; and the offers opened at once come from at most 32 peers. + 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; the platform backend makes at most 256 a minute on both targets (<>), and a page holds at diff --git a/doc/testing.adoc b/doc/testing.adoc index 7baffea..550f5a3 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -100,9 +100,10 @@ include::{library-root}/test/Jamfile[tag=allocation] 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, offers being opened that keep their places when new ids arrive - at the same instant, 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. + 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` | Configuration copying and validation, a self id that is not UTF-8 set diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index 041f29f..1f6bd21 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -51,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 | @@ -96,7 +97,7 @@ class signaling : public std::enable_shared_from_this { /** * 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, or its offer - * sent again. It bounds the offers opened at once from fresh ids too. + * sent again. It bounds the offers opened at once too, one per negotiation. */ static constexpr std::size_t max_unconnected_peers = 32; @@ -261,6 +262,9 @@ class signaling : public std::enable_shared_from_this { struct negotiation { 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), @@ -284,9 +288,13 @@ class signaling : public std::enable_shared_from_this { bool connected = false; // When the peer last sent a message, for the eviction of an idle negotiation. time_point last_message{}; - // How many of the peer's offers the sealer is opening: until each completes, the - // negotiation is not idle, and keeps its place. - std::size_t offers_opening = 0; + // 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 @@ -357,7 +365,7 @@ class signaling : public std::enable_shared_from_this { * offer of its peer is being opened. */ static bool idle(const negotiation& n) { - return !n.connected && !n.offer.pc && !n.answer.pc && n.offers_opening == 0; + return !n.connected && !n.offer.pc && !n.answer.pc && n.opening_offer.empty(); } /** @@ -606,37 +614,53 @@ 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.offers_opening; + 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), admitted = n.admitted, 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, admitted, 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 for the negotiation taken in `admitted`-th: makes the - * answering connection and applies the offer as its remote description. An offer that did not - * open changes nothing, nor one whose negotiation the room no longer holds: the peer left, or - * the room closed. + * 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::uint64_t admitted, - std::string_view offer_id, std::string_view offer, + 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; - --n.offers_opening; + // 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; } @@ -651,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[relay] = steady_now(factory_); - 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( diff --git a/test/room_test.cpp b/test/room_test.cpp index d193219..c5d33d7 100644 --- a/test/room_test.cpp +++ b/test/room_test.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -595,8 +596,9 @@ void an_offer_being_opened_keeps_its_place() { 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 the - // room receives each offer on both relays, four opens that wait. + // 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"); @@ -660,6 +662,67 @@ void a_flood_of_offers_at_one_instant_is_bounded() { 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. On the virtual @@ -1872,6 +1935,7 @@ int main() { forged_offers_make_no_connection(); an_offer_being_opened_keeps_its_place(); a_flood_of_offers_at_one_instant_is_bounded(); + offers_in_one_name_are_opened_one_at_a_time(); signals_that_do_not_open_are_reported_once_per_interval(); sealed_offers_that_fail_at_once_are_bounded(); announcements_with_forged_answers_are_bounded(); diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp index dfc5201..321a698 100644 --- a/test/support/rooms.hpp +++ b/test/support/rooms.hpp @@ -173,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 = @@ -205,11 +207,12 @@ class flooder { 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_, detail::unix_now(f_.net), topic, - protocol::write_signal(m), aux)); + protocol::write_signal(m, nonce), aux)); } /** `plain` sealed under the room key of `room`, with no password, as the memory sealer seals. From 203cff2f5e03955d51991fd477ff7b67ecc66078 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 03:35:54 -0300 Subject: [PATCH 105/116] trystero: the changelog's ten lines for the whole refactor Unreleased merges the refactor's lines into ten, breaking changes first: the one platform backend, webcpp::asio, document's two JSON payload types, the relays' stricter TLS, URLs and binary messages, the backend's std::chrono clocks and the protocol's functions; then the relays' and offers' attacks fixed, max_json_document_bytes and the bounded JSON texts, the other fixes, and the examples with their twins. Changes made and undone within the refactor, as pmr_document and the 256-deep payload under Asyncify, are left out, since no release had them. --- doc/changelog.adoc | 52 ++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 3d80f20..8238cf6 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,34 +16,36 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* *Breaking change:* Changed `native::backend` and `browser::backend` to one -`platform::backend`; include `` and -link `/webcpp/trystero//platform` on both targets. +* *Breaking change:* Changed `native::` and `browser::` to one +`platform::backend`, with `backend_config::memory` and `runtime`, whose +`tls_context()` is a `boost::system::result`; include +``, link `/webcpp/trystero//platform`. * *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`, or -`pmr_document` in a resource, for `boost::json::value` and `json_resource`; -programs link Boost.Charconv too. -* *Breaking change:* Changed `payload` to lose copy assignment, and without -exceptions its copy constructor and the default one of -`webcpp::document::document`; make documents with `create()` or `parse`. -* *Breaking change:* Changed `read_signal`, `nostr::read_relay_message` and -`append_value` to take webcpp::document's values, `make_id` to `random_id`, -and `proposal::size` to `std::uint64_t`. -* *Breaking change:* Changed `protocol::json::append_string` to return its -error on text that is not UTF-8; such a local candidate is dropped, such a -self id set aside. -* *Breaking change:* Removed the backends' own connection and channel classes -for webcpp::webrtc's, and `browser::event_loop`; the backend throws nothing, -and `tls_context()` returns a `boost::system::result`. -* Changed a page's relays to the native webcpp::beast session, refusing -`http://` URLs and bounding unsent text; added `backend_config::memory` and -`backend_config::runtime`, at most 256 connections at once. -* Fixed relays at an IPv6 address being unreachable, pages ignoring a failed -`getentropy`, and 32-bit receivers misreading transfer offers of 4 GiB or more. -* Fixed rooms slowed by relays' event ids chosen to collide; channels keep -frames that arrive before a handler, 64 for 10 s. +* *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 a backend's clocks to `std::chrono`: +`steady_now()` and `unix_now()` replace `now_ms()` and `unix_seconds()`. +* *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`. +* 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 written or read unlike Trystero's, +32-bit receivers misreading 4 GiB offers, and pages ignoring a failing +`crypto.getRandomValues` or dropping a channel's early frames. +* 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] From 6f35b38961cb95359fb35a689b3c5ca053334300 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 03:37:17 -0300 Subject: [PATCH 106/116] trystero: the allocation test's comment says document's working state is in the resource --- test/Jamfile | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/Jamfile b/test/Jamfile index aea01fb..f96f04c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -131,11 +131,10 @@ webcpp.run platform_room_no_exceptions : platform_room_test.cpp # end::platform[] # Every allocation of two rooms that exchange a payload goes through the -# resources of their configurations, but webcpp::document's working state -# while it reads or writes a JSON text, which the global operator new sees, -# none of it left once the call returns; 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[] From 370bbb2a380eb8800a01b2f21530e348c0434644 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 05:03:57 -0300 Subject: [PATCH 107/116] trystero: the Asyncify measurements under the release link at -O3 The superproject now links an emscripten release program at its compile's level, -O3, where b2 linked it without optimization. Measured again on 2026-11-15 with Emscripten 6.0.11, the deepest suspensions of the room, app_impl and allocation tests write 564, 440 and 408 bytes in release, and 2,344, 2,068 and 2,020 in debug, now the deepest build; a room in a page needs at most 1,032 bytes in debug (the chat's pages), 920 (the interop page) and 1,600 (the page tests), and 328, 348 and 384 in release. run_case stays the rule: it keeps the cases' locals out of main's frame whatever the link. With main calling its cases directly, the release runs pass at -O3 (616, 496 and 400 bytes), so they no longer catch an inlined main, which still stops the room test at its first suspension when linked with -O0 (33,580 bytes). They stay as trystero's only programs that the CI's emscripten lane, building JSPI, runs under Asyncify, in the build a page ships. The texts say so, and give the unoptimized link as history where the reason needs it. --- AGENTS.md | 30 +++++++++++++++++------------- doc/platform.adoc | 20 ++++++++++---------- doc/testing.adoc | 24 ++++++++++++++---------- test/Jamfile | 24 +++++++++++++----------- test/cases.hpp | 17 +++++++++-------- 5 files changed, 63 insertions(+), 52 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7de7f2b..a01779a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,19 +122,23 @@ holds only what is specific to trystero. 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 release, the deepest - build, the chat's pages measured 1,292 bytes, the interop page 2,344, the - page tests 1,660 at most). A test's cases are on that stack, since each - calls the run family itself, and a release build, linked without - optimization, saves every local of every frame there: 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, or `-O3` inlines every - case into `main`, whose frame 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 them in that build. There is one timer, the core's - `detail::timer` over webcpp::asio's `steady_timer`, on both targets, which - `timer` tests on both. + 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) remains an external installation, found through `webcpp.external` and `webcpp.external-found` at `-sSECP256K1_ROOT=` or `-sSECP256K1_EMSCRIPTEN_ROOT=`, then diff --git a/doc/platform.adoc b/doc/platform.adoc index 09af426..da15050 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -482,16 +482,16 @@ connection. * 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 `release` - 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,292 bytes deep, the interop test's page in its 26 scenarios at most - 2,344, and the tests of a page's program at most 1,660 (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 - (<>). + 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. diff --git a/doc/testing.adoc b/doc/testing.adoc index 72fb764..6eb87ae 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -247,20 +247,24 @@ include::{library-root}/test/Jamfile[tag=page] include::{library-root}/test/Jamfile[tag=no-exceptions] ---- -Under Asyncify the deepest build is `release`: compiled with `-O3`, it is -linked without optimization, as b2's emscripten toolset links it, so that -each suspension saves every local of every frame from `main` down to the -call that suspends, in webcpp::asio's 8,192 bytes (webcpp::asio's guide, +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; a case that `main` alone calls is otherwise -inlined into it, and the room test's `main`, which held every case's locals -so, saved 29,776 bytes at each suspension and stopped at its first. The -room, `app_impl` and allocation tests, whose cases hold whole apps, run once -more in that build, with webcpp::asio's 8,192 bytes, where their deepest -suspensions wrote 3,096, 2,140 and 5,592 bytes (measured on 2026-11-15 with +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, which the CI's emscripten lane, building JSPI, +runs no other way; 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] diff --git a/test/Jamfile b/test/Jamfile index f96f04c..3f01e8e 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -139,17 +139,19 @@ webcpp.run platform_room_no_exceptions : platform_room_test.cpp webcpp.run allocation : allocation_test.cpp : emscripten:-sALLOW_MEMORY_GROWTH ; # end::allocation[] -# Under Asyncify the deepest build is release: compiled with -O3, linked -# without optimization, as b2's emscripten toolset links it, so that each -# suspension saves every local of every frame from main down, in -# webcpp::asio's 8,192 bytes. A test whose cases suspend runs each in a frame -# of its own (cases.hpp): -O3 inlined the room test's cases into its main, -# which saved 29,776 bytes at each suspension and stopped at its first -# (given 262,144 bytes, it passed in 200 s, against 22 s now). The deepest -# suspension, as the bytes its unwind wrote, measured on 2026-11-15 with -# Emscripten 6.0.11: in release, room 3,096, app_impl 2,140 and allocation -# 5,592, whose largest case alone saves 4,680; in debug, 2,332, 2,068 and -# 2,020. +# 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: the +# CI's emscripten lane builds JSPI, and these are trystero's only programs it +# runs under Asyncify. 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 ; diff --git a/test/cases.hpp b/test/cases.hpp index ea68848..106d3a7 100644 --- a/test/cases.hpp +++ b/test/cases.hpp @@ -4,14 +4,15 @@ // 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. -// Under Asyncify each suspension saves every frame from main down to the call that suspends, each -// with the locals its instrumentation keeps, which a program linked without optimization, as b2's -// release variant is on emscripten, keeps whole. A case that main alone calls is inlined into it -// at -O3, so that main would keep the locals of every case 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 wrote 3,096 (measured on 2026-11-15 -// with Emscripten 6.0.11). +// 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 From 16c00a158131ebee38c1d674ba00e333375ec897 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 06:42:56 -0300 Subject: [PATCH 108/116] trystero: no colon after a reference in a Doc Comment MrDocs drops the colon that follows a reference, and the lint's Doc Comments rule refuses one. The first platform::backend constructor's TLS context is make_tls_context's, which natively verifies relays against the system's authorities, now after a comma; payload_traits' decode reads a message with the room's decoding, and the view types' lifetime is a sentence of its own. --- include/webcpp/trystero/platform/backend.hpp | 4 ++-- include/webcpp/trystero/room.hpp | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index cc56996..70efe1b 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -131,8 +131,8 @@ 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: natively it verifies relays against the system's certificate - * authorities, and in a page the browser verifies them against its own. + * 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. diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 106bfab..5c57abe 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -173,12 +173,12 @@ struct decoding { /** * 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 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. + * 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 | From b2cb954387d6e0dcb86e856cbc78a84862b5af6f Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 06:42:56 -0300 Subject: [PATCH 109/116] trystero: the Asyncify list of Boost.JSON's parser only where JSON is parsed /webcpp/trystero//trystero links -sASYNCIFY_REMOVE=@asyncify-remove.json under Asyncify, whose pattern names Boost.JSON's basic_parser<...>::parse_*. 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) has none of those functions, and Binaryen warned at each link that the pattern matched nothing. build.jam now declares parts, trystero's headers and dependencies, and platform-parts, the backend over parts; trystero is parts and the list, and platform is platform-parts and trystero, so every program of the rooms keeps the list, and a page's first 256-deep payload still fits a debug build's stack. The tests of those parts link parts or platform-parts in place of the project's trystero ($(part) and $(platform-part) in test/Jamfile), and their links print nothing. The guide's building and testing chapters and AGENTS.md say so. --- AGENTS.md | 23 +++++++++++++++++------ build.jam | 26 +++++++++++++++++++------- doc/building.adoc | 17 ++++++++++++++--- doc/testing.adoc | 8 +++++++- test/Jamfile | 26 +++++++++++++++++--------- 5 files changed, 74 insertions(+), 26 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a01779a..a0d8390 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,13 +147,22 @@ holds only what is specific to trystero. installation leaves trystero out unless `webcpp-require-external=on`. MSVC links its static `libsecp256k1.lib` with `SECP256K1_STATIC`. `/webcpp/trystero//trystero` (`build.jam`'s `tag::trystero[]`) is the - rooms alone, the core: its headers, Boost, webcpp::document + 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; on no target does it - bring webcpp::webrtc, and the tests over the memory relays use it alone. + 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, alternatives by `emscripten`, which a - native program and a page's program both name. Its WebRTC is + 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 @@ -716,7 +725,9 @@ holds only what is specific to trystero. 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. A text the room writes + 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 diff --git a/build.jam b/build.jam index ee039df..a22be2e 100644 --- a/build.jam +++ b/build.jam @@ -64,13 +64,20 @@ rule platform-dependencies ( properties * ) # 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 this alias under Asyncify; under JSPI +# 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 : : @trystero-dependencies +alias parts : : @trystero-dependencies : : include /boost//headers /webcpp/document//document - /webcpp/config//config /webcpp/asio//asio secp256k1 + /webcpp/config//config /webcpp/asio//asio secp256k1 ; +alias trystero : : : : parts emscripten,asyncify:"-sASYNCIFY_REMOVE=@\"$(WEBCPP_TRYSTERO_ROOT)/asyncify-remove.json\"" ; # end::trystero[] @@ -85,12 +92,17 @@ alias trystero : : @trystero-dependencies # (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 : : emscripten - : : trystero /webcpp/webrtc//webrtc +alias platform-parts : : emscripten + : : parts /webcpp/webrtc//webrtc /webcpp/beast//browser /webcpp//boost_url ; -alias platform : : @platform-dependencies - : : trystero /webcpp/webrtc//webrtc +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/building.adoc b/doc/building.adoc index 98ba8fb..e6815a1 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -90,6 +90,14 @@ own, as trystero's tests run whole rooms over the memory relays include::{library-root}/build.jam[tag=trystero] ---- +`/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 @@ -98,8 +106,10 @@ 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, with an -alternative for each target. Natively it adds webcpp::webrtc, with +`/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 @@ -132,7 +142,8 @@ include::{examples}/Jamfile[tag=quick-start] ---- and as trystero's own tests of the platform backend do, on each target that -builds them, once without exceptions too: +builds them, once without exceptions too, a test of a part that parses no +JSON over `platform-parts` (`$(platform-part)`): [listing] ---- diff --git a/doc/testing.adoc b/doc/testing.adoc index 6eb87ae..ab11d2d 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -63,6 +63,10 @@ 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 @@ -238,7 +242,9 @@ include::{library-root}/test/Jamfile[tag=allocation] 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: +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] ---- diff --git a/test/Jamfile b/test/Jamfile index 3f01e8e..dea32a2 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -27,6 +27,14 @@ rule native-threads ( properties * ) } } 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 @@ -81,7 +89,7 @@ webcpp.run connection : connection_test.cpp ; 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 ; +webcpp.run timer : timer_test.cpp : $(part) ; # end::both-targets[] # The platform backend's own tests, on each target that builds them. On both: @@ -104,7 +112,7 @@ 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) ; +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 @@ -121,7 +129,7 @@ webcpp.run platform_sealer_no_exceptions : platform_sealer_test.cpp 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) off ; + : $(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 @@ -189,18 +197,18 @@ webcpp.run platform_page : platform_page_test.cpp : $(platform) : emscripten ; # 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) : emscripten ; + : $(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) : emscripten ; +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) : emscripten ; +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 ; @@ -226,13 +234,13 @@ 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) off : emscripten ; + : $(platform-part) off : emscripten ; webcpp.run platform_page_sealer_no_exceptions : platform_page_sealer_test.cpp - : $(platform) off : emscripten ; + : $(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) off : emscripten ; + : $(platform-part) off : emscripten ; webcpp.run platform_page_handlers_no_exceptions : platform_page_handlers_test.cpp : $(platform) off : emscripten ; # end::no-exceptions[] From 781f7baba26330d3dcc4eaf7ec5f5be677215b43 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 10:32:15 -0300 Subject: [PATCH 110/116] trystero: the release Asyncify tests form the own lane asyncify A target that names asyncify composes js, a feature only the emscripten toolset defines, so declared outside a lane of emscripten's it stopped every build with no emscripten configured, the CI's native lanes among them. --- doc/testing.adoc | 10 +++++++--- test/Jamfile | 12 +++++++++--- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/doc/testing.adoc b/doc/testing.adoc index ab11d2d..e40b758 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -268,8 +268,11 @@ 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, which the CI's emscripten lane, building JSPI, -runs no other way; their deepest suspensions wrote 564, 440 and 408 bytes +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): @@ -464,7 +467,8 @@ that dependent archives precede OpenSSL in the link order. The continuous integration runs trystero's tests in lanes, one toolset each, 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`, plus the +`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/test/Jamfile b/test/Jamfile index dea32a2..88e0536 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -148,9 +148,13 @@ webcpp.run allocation : allocation_test.cpp : emscripten:-sA # end::allocation[] # 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: the -# CI's emscripten lane builds JSPI, and these are trystero's only programs it -# runs under Asyncify. A test whose cases suspend runs each in a frame of its +# 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 @@ -168,6 +172,8 @@ webcpp.run app_impl_asyncify_release : app_impl_test.cpp 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 From 191cf99dbad0d1a46380c2dc132769830b800757 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 19:11:05 -0300 Subject: [PATCH 111/116] trystero: abandoning a relay session allocates nothing, and the JSON diff example reads alike over libstdc++ The handle's destructor abandons its session, which cancelled the resolver: Asio's cancel allocates a new cancellation token, so clang-tidy over libstdc++ found bad_alloc escaping the destructor (bugprone-exception-escape). abandon() no longer cancels; on_resolve drops a resolution's result once closing, as before. The diff_json_refused example takes its channel by rvalue reference and keeps its moved connection non-const with the reason. --- example/diff_json_refused.cpp | 6 +++++- include/webcpp/trystero/platform/websocket.hpp | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/example/diff_json_refused.cpp b/example/diff_json_refused.cpp index 5c1050b..9634d2f 100644 --- a/example/diff_json_refused.cpp +++ b/example/diff_json_refused.cpp @@ -102,7 +102,7 @@ class json_marking_channel final : public trystero::backend::data_channel { // 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) { +channel_ptr marking(channel_ptr&& channel, std::pmr::memory_resource* memory) { if (!channel) { return nullptr; } @@ -173,6 +173,10 @@ class json_marking_backend final : public trystero::backend::factory { 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; diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 0952207..0172296 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -434,7 +434,9 @@ class websocket_session : public std::enable_shared_from_this Date: Sun, 15 Nov 2026 19:13:13 -0300 Subject: [PATCH 112/116] trystero: a kept room frame advertises its room, as the peer's presence does A room bound a peer over a shared connection only once the peer's presence for the room had come on that connection. 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: in the interop lane's delayed-open scenario, run in 2-CPU Linux containers, Chrome logged "Send failed INVALID_STATE" for both presence frames and the native peer's SCTP received neither, 8 runs of 240. The room whose own connection the page closed as the second then never bound: the page's frames of that room were kept and expired, and its announcements were claimed by the live connection and bound nothing. That is the CI failure of webcpporg/webcpp#19. A room frame of a local room's token that the connection keeps now records the token as the remote's advertisement, below the bound of 64 tokens (a frame never ends the connection for a 65th), and the room binds on it. Only the peer writes to its connection, so a forged announcement still binds nothing. Without the change, connection's a_kept_frame_advertises_its_token fails, and so do shared's a_lost_presence_is_replaced_by_the_peers_frames, which replaces binding_needs_the_peers_own_presence, and frames_before_presence_bind_their_room, which replaces frames_before_presence_are_kept; connection's a_kept_frame_never_advertises_a_65th_token holds the bound. A kept @_leave still discards what came before it where a room keeps frames without binding, during the lower id's refusal, which a_kept_leave_discards_what_came_before now sets up. The scenario then passed 480 runs of 480 in the same containers. --- AGENTS.md | 14 ++- doc/differences.adoc | 5 + doc/protocol.adoc | 10 +- doc/usage.adoc | 3 +- include/webcpp/trystero/detail/connection.hpp | 17 ++- include/webcpp/trystero/room.hpp | 7 +- test/connection_test.cpp | 37 ++++++ test/shared_test.cpp | 117 +++++++++--------- 8 files changed, 144 insertions(+), 66 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a0d8390..7626543 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -272,6 +272,17 @@ holds only what is specific to trystero. 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/asio//asio` adds as a linker flag, and `/webcpp/trystero//trystero` brings: `on`, b2's own feature, is not free, and b2 ignores it @@ -433,7 +444,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 diff --git a/doc/differences.adoc b/doc/differences.adoc index e16175a..a3c948c 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -81,6 +81,8 @@ has nothing of it to run beside its twin. | 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 @@ -608,6 +610,9 @@ its reason. | 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. diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 516482f..086d258 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -185,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 diff --git a/doc/usage.adoc b/doc/usage.adoc index a3d2173..bbfdfaf 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -175,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 diff --git a/include/webcpp/trystero/detail/connection.hpp b/include/webcpp/trystero/detail/connection.hpp index 6c7e870..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); } @@ -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)); } } diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index 5c57abe..c83c85f 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -770,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. */ @@ -1117,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; diff --git a/test/connection_test.cpp b/test/connection_test.cpp index def37ee..60859b3 100644 --- a/test/connection_test.cpp +++ b/test/connection_test.cpp @@ -274,6 +274,41 @@ 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); @@ -832,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(); diff --git a/test/shared_test.cpp b/test/shared_test.cpp index 6ba1545..9dc7486 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -365,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 @@ -1126,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; @@ -1153,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 auto joined = t.f.net.steady_now(); + 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(t.f.net.steady_now() - joined == 21s); + 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); } @@ -1307,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"); @@ -1317,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 @@ -2018,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}, @@ -2047,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}, From 3820d62c78b7668f4c504af50351c744c6ca8eb3 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 19:33:54 -0300 Subject: [PATCH 113/116] trystero: the changelog names the room that never bound after a lost presence --- doc/changelog.adoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 8238cf6..86866f0 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -41,9 +41,9 @@ 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 written or read unlike Trystero's, -32-bit receivers misreading 4 GiB offers, and pages ignoring a failing -`crypto.getRandomValues` or dropping a channel's early frames. +* 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[] From 0d21db6540843fb887f2412b9d76986357bc80ef Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 21:14:20 -0300 Subject: [PATCH 114/116] trystero: tests count allocations without a standard container's own MSVC's debug STL allocates a proxy for each container when it is constructed or moved, through the container's allocator: the protocol test's refusals made before reading and the platform backend's moved address counted them. test/bookkeeping.hpp measures that block once, on an empty std::pmr::vector, as document's tests do, and both tests leave it out. --- test/bookkeeping.hpp | 75 ++++++++++++++++++++++++++++++++++ test/platform_backend_test.cpp | 10 +++-- test/protocol_test.cpp | 8 +++- 3 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 test/bookkeeping.hpp 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/platform_backend_test.cpp b/test/platform_backend_test.cpp index 5cb8981..dc43d1a 100644 --- a/test/platform_backend_test.cpp +++ b/test/platform_backend_test.cpp @@ -37,6 +37,7 @@ #include #include +#include "bookkeeping.hpp" #include "cases.hpp" namespace asio = webcpp::asio; @@ -48,14 +49,17 @@ 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. */ + /** 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. */ + /** 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 { - ++allocations; + if (!webcpp::test::is_bookkeeping(bytes, alignment)) { + ++allocations; + } ++outstanding; return std::pmr::new_delete_resource()->allocate(bytes, alignment); } diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp index ad5f18b..6b77dc2 100644 --- a/test/protocol_test.cpp +++ b/test/protocol_test.cpp @@ -44,6 +44,8 @@ #include #include +#include "bookkeeping.hpp" + namespace wd = webcpp::document; namespace tp = webcpp::trystero::protocol; @@ -87,7 +89,7 @@ wd::result parse_text( */ class counting_resource final : public std::pmr::memory_resource { public: - /** How many allocations it made. */ + /** 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; @@ -100,7 +102,9 @@ class counting_resource final : public std::pmr::memory_resource { private: void* do_allocate(std::size_t bytes, std::size_t alignment) override { - ++allocations; + if (!webcpp::test::is_bookkeeping(bytes, alignment)) { + ++allocations; + } largest = std::max(largest, bytes); bytes_out += bytes; peak = std::max(peak, bytes_out); From 3b06b735357f5c42392e86089a1ef61c5f207002 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 16 Nov 2026 11:24:22 -0300 Subject: [PATCH 115/116] trystero: the refactor's functions that return a result are [[nodiscard]] main asked for the nodiscard results rule; the refactor's platform backend added four such functions: tls_context, make_tls_context, peer_connection::make and make_connection. --- include/webcpp/trystero/platform/backend.hpp | 2 +- include/webcpp/trystero/platform/websocket.hpp | 2 +- include/webcpp/trystero/webrtc/peer_connection.hpp | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index 70efe1b..d2f38a8 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -218,7 +218,7 @@ class backend : public trystero::backend::factory { * @return The context every `wss://` connection of the backend is made with, or the error that * kept it from being made. */ - boost::system::result tls_context() { + [[nodiscard]] boost::system::result tls_context() { if (!tls_) { return tls_.error(); } diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 0172296..81d5cda 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -121,7 +121,7 @@ inline boost::system::error_code openssl_error() { * authorities. * @see "The relays", in the guide. */ -inline boost::system::result make_tls_context() { +[[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(); diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp index 88cdd3a..b6f2c3d 100644 --- a/include/webcpp/trystero/webrtc/peer_connection.hpp +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -155,7 +155,7 @@ class peer_connection : public backend::peer_connection, * `operation_error` for another refusal. */ // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - static boost::system::result> make( + [[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) { @@ -181,7 +181,7 @@ class peer_connection : public backend::peer_connection, * @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. */ - static boost::system::result make_connection( + [[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) { From 2eb1c89f35051a05de9470bc146d7bffbed1bc7a Mon Sep 17 00:00:00 2001 From: R Date: Mon, 16 Nov 2026 11:30:16 -0300 Subject: [PATCH 116/116] trystero: the changelog's clocks line keeps its code spans whole An apostrophe after a code span ('std::chrono's') becomes Asciidoctor's typographic one and joins two spans, which the rendered check refuses. --- doc/changelog.adoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 01535ad..49c3753 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -18,8 +18,8 @@ of every version are on webcpp's index page. // tag::unreleased[] * *Breaking change:* Changed `native::` and `browser::` to one `platform::backend` (link `/webcpp/trystero//platform`), and a backend's -`now_ms()` and `unix_seconds()` to `std::chrono`'s `steady_now()` and -`unix_now()`. +`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`.