From 8d4df61d04a934c31ac7d9cd144ca14038958190 Mon Sep 17 00:00:00 2001 From: R Date: Fri, 20 Nov 2026 13:42:40 -0300 Subject: [PATCH] trystero: a second connection to a peer is held until the peer shows which it keeps, so that a crossed pair no longer makes a Trystero JS page report a peer error The interop lane's "one room leaving" scenario failed on main (run 44726002584) with "console.error Trystero peer error: OperationError" before any room left: its two rooms negotiated at once, the two channels opened in one order on the page and in the other natively, and each side kept the one that opened first on its side, as Trystero's rule says. The native app then closed its second connection at once, which was the one the page kept, just as the page sent its first frames on it. libdatachannel ends an association with a stream reset and a SHUTDOWN, its ABORT a moment later, where a browser's ABORT follows its reset at once: Chrome's channel completed the closing procedure (or saw the SHUTDOWN) with a send failed in between, closed with that failure ("data-channel-failure", or "Failure to send data"), and Trystero JS, which ignores only an abort, logged a peer error. Chrome's log showed the reset, "Send failed INVALID_STATE", then the error, ahead of the ABORT; in 1,800 two-room meetings the page reported 6 such errors among 46 crossed pairs. The app now holds such a second connection, unused, until the peer shows which it keeps: a frame on the first, which closes the second as the peer closes its own (and a connection opened after the peer sent on the first is closed at once); the peer closing the first, which Trystero JS does in a crossed pair, after which the second replaces the first with the frames it received; or, for the higher id, a frame on the second, which then replaces the first, since a peer of this port holds its second too. One the peer leaves alone is closed after 2 s by the higher id and after 10 s by the lower id. No connection the peer uses is closed, so the 1,800 meetings showed no error, and the scenario passed 600 runs of 600. The memory relays now hold a frame that reaches an end before it opens until it opens, as a real channel delivers what follows its opening message; the crossed-pair test now checks the lower id keeps the peer throughout. --- doc/changelog.adoc | 5 +- doc/differences.adoc | 6 +- doc/testing.adoc | 4 +- include/webcpp/trystero/detail/app_impl.hpp | 228 +++++++++++++++++- include/webcpp/trystero/detail/connection.hpp | 46 +++- test/app_impl_test.cpp | 138 ++++++++++- test/connection_test.cpp | 47 ++++ test/memory_backend_test.cpp | 23 ++ test/shared_test.cpp | 10 +- test/support/memory_backend.hpp | 18 +- 10 files changed, 497 insertions(+), 28 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 0221c2d..5d44e3e 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -43,8 +43,9 @@ offers, and MSVC 14.52 builds. every JSON text is read in the room's resource within bounds, and a self id not UTF-8 is replaced by a random one. * Fixed unreachable IPv6 relays, signals unlike Trystero's, 32-bit receivers -misreading 4 GiB offers, pages ignoring a failing `crypto.getRandomValues` or -dropping early frames, and rooms never binding after a lost presence. +misreading 4 GiB offers, pages ignoring failing `crypto.getRandomValues` or +dropping early frames, unbound rooms after lost presence, and crossed-connection +peer errors. * Changed the quick start to one native program, and added programs showing differences beside Trystero JS's output. // end::unreleased[] diff --git a/doc/differences.adoc b/doc/differences.adoc index a3c948c..9c7aa8c 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -109,7 +109,7 @@ has nothing of it to run beside its twin. | 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 +| Duplicate connections | the first registered wins at each side and the other is closed at once; crossed, both lose and meet again | the first registered wins at each side; the other is held, unused, until the peer shows which it keeps: closed once the peer sends on the first, or after 2 s (higher id) or 10 s (lower id) when the peer does neither; it replaces the first when the peer closes the first, or, for the higher id, when the peer sends on it | libdatachannel ends an association with a stream reset and a SHUTDOWN, its ABORT a moment later, where a browser's ABORT follows its reset at once: closing at once the connection a Trystero JS peer kept, as it starts sending on it, made Chrome fail those sends and Trystero JS report a peer error. Following the peer's choice closes no connection the peer uses, keeps a crossed pair's rooms on the connection the peer kept, and still agrees with Trystero's rule | 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 @@ -634,8 +634,8 @@ its reason. | 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. +| Duplicate connections +| Only two connections whose channels open within a millisecond of each other, from two rooms meeting the peer at once, make a pair that is crossed, which no program sets up on demand: the interop lane's two-room scenarios meet one now and then, and the `app_impl` and `shared` tests hold each outcome over the memory relays. | 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. diff --git a/doc/testing.adoc b/doc/testing.adoc index 32eab88..c231633 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -370,8 +370,8 @@ before a shared-binding scenario begins; the proof-pacing scenario first authenticates the shared password domain, then corrupts room proofs after the initial announcement burst. -The adoption scenarios allow crossed duplicates to retry, but fail with -connection counts if either side constructs more than four. Transient +The adoption scenarios allow a crossed pair of connections to resolve, but +fail with connection counts if either side constructs more than four. Transient recovery accounts for JS reuse during the higher id's dropping window (<>). diff --git a/include/webcpp/trystero/detail/app_impl.hpp b/include/webcpp/trystero/detail/app_impl.hpp index 771568b..fb7f106 100644 --- a/include/webcpp/trystero/detail/app_impl.hpp +++ b/include/webcpp/trystero/detail/app_impl.hpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -101,7 +102,8 @@ class app_impl : public std::enable_shared_from_this { idle_timeout_(config.idle_timeout), setup_reports_(memory_), rooms_(memory_), - connections_(memory_) { + connections_(memory_), + seconds_(memory_) { if (self_id_.size() > protocol::max_peer_id_bytes) { self_id_.clear(); set_aside("self_id is longer than any peer accepts, so the app uses a random one"); @@ -178,6 +180,13 @@ class app_impl : public std::enable_shared_from_this { /** The relays configured once for the app. */ [[nodiscard]] std::span relay_urls() const { return relay_urls_; } + /** How long the higher id holds a second connection to a peer that neither sends on it nor + * closes it (`hold_second`). */ + static constexpr std::chrono::milliseconds second_wait_higher{2'000}; + /** How long the lower id holds a second connection to a peer that neither sends on the first + * nor closes one of them (`hold_second`). */ + static constexpr std::chrono::milliseconds second_wait_lower{10'000}; + /** The validated ICE servers used for every negotiation. */ [[nodiscard]] std::span ice_servers() const { return ice_servers_; } @@ -242,6 +251,10 @@ class app_impl : public std::enable_shared_from_this { for (auto& [peer, c] : connections) { c->end("the app has no room left"); } + auto seconds = std::exchange(seconds_, decltype(seconds_)(memory_)); + for (auto& [peer, second] : seconds) { + close_second(*second); + } } /** How many rooms the registry holds. */ @@ -283,8 +296,9 @@ 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, as in Trystero's - * dist/shared-peer.mjs:105-108. + * a live one to that peer, the existing one is returned, as in Trystero's + * dist/shared-peer.mjs:105-108, and the new one is held as the peer's second connection + * (`hold_second`). * * Tip: a stale connection to the peer, one whose channel is closing, ends first, as Trystero * clears it (dist/shared-peer.mjs:142-149): the rooms hear its end before the new @@ -309,6 +323,16 @@ class app_impl : public std::enable_shared_from_this { } private: + /** A second connection to a peer, held unused until the peer shows which of the two it keeps: + * the frames its channel received meanwhile, in their order, and its deadline. */ + struct second_connection { + std::pmr::string peer; + std::shared_ptr pc; + std::shared_ptr channel; + std::pmr::deque frames; + std::shared_ptr deadline; + }; + // Its implicit move assignment, which insert_or_assign uses, may allocate: a std::pmr member // copies when the two resources differ, which bugprone-exception-escape reports. Every entry // is in the app's resource, so it never does. @@ -325,11 +349,7 @@ class app_impl : public std::enable_shared_from_this { std::shared_ptr channel) { // NOLINTEND(performance-unnecessary-value-param) if (auto existing = find(peer)) { - channel->set_handlers({}); - pc->set_handlers({}); - channel->close(); - pc->close(); - log_("webrtc", "a second connection with ", peer, " closed: the first is shared"); + hold_or_close(peer, *existing, std::move(pc), std::move(channel)); return existing; } const auto weak = weak_from_this(); @@ -367,6 +387,13 @@ class app_impl : public std::enable_shared_from_this { self->on_connection_end(owner->lock(), p, reason); } }), + .used = bind([weak](std::string_view p) { + if (const auto self = weak.lock()) { + if (const auto it = self->seconds_.find(p); it != self->seconds_.end()) { + self->forget_second(*it->second, "the peer keeps the first"); + } + } + }), }, log_, memory_); *owner = c; @@ -379,6 +406,167 @@ class app_impl : public std::enable_shared_from_this { return c; } + /** A connection to `peer` opened while `first` is live: held as the second + * (`hold_second`) while the peer has sent nothing on the first and none is held, else + * closed. */ + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + void hold_or_close(std::string_view peer, const connection& first, + std::shared_ptr pc, + std::shared_ptr channel) { + // NOLINTEND(performance-unnecessary-value-param) + if (!first.used() && !seconds_.contains(peer)) { + hold_second(peer, std::move(pc), std::move(channel)); + return; + } + channel->set_handlers({}); + pc->set_handlers({}); + channel->close(); + pc->close(); + log_("webrtc", "another connection with ", peer, + " closed: ", first.used() ? "the peer keeps the first" : "a second is held already"); + } + + /** Holds a second connection to `peer`, opened while the first was live and before the peer + * sent anything on the first, until the peer shows which of the two it keeps, rather than + * closing it at once as Trystero does. + * + * Each side keeps the connection whose channel opened first on its side (Trystero's + * dist/shared-peer.mjs:105-108), so the two sides of a crossed pair keep different ones, and + * a side sends only on the one it keeps. A frame on the first shows the peer keeps it: the + * second is closed, as the peer closes its own. Trystero JS closes its other connection at + * once, so that in a crossed pair the first ends, and the second, the one the peer keeps, + * replaces it (`on_connection_end`) with the frames it received meanwhile. A peer that holds + * its second, as this app does, closes neither, so the higher id gives way: a frame on its + * second makes the second replace its first (`switch_to_second`), whose end closes the lower + * id's second. A second the peer neither sends on nor closes is closed after + * `second_wait_higher` by the higher id, and after `second_wait_lower` by the lower id. + * + * Closing the second at once, as Trystero does, closes in a crossed pair the connection the + * peer keeps, just as the peer starts sending on it. libdatachannel ends an association with + * a stream reset and a SHUTDOWN, and its ABORT comes a moment later, where a browser's ABORT + * follows its reset at once: Chrome fails a send made in between and closes the channel with + * that failure, which Trystero JS reports as a peer error. */ + void hold_second(std::string_view peer, std::shared_ptr pc, + std::shared_ptr channel) { + auto second = std::allocate_shared( + allocator(), second_connection{ + .peer = std::pmr::string(peer, memory_), + .pc = std::move(pc), + .channel = std::move(channel), + .frames = std::pmr::deque(memory_), + .deadline = factory_.make_timer(memory_), + }); + const auto weak = weak_from_this(); + const std::weak_ptr held = second; + second->channel->set_handlers({ + .open = {}, + .message = bind([weak, held](backend::bytes frame) { + const auto self = weak.lock(); + const auto s = held.lock(); + if (!self || !s) { + return; + } + if (s->frames.size() >= connection::max_kept_frames) { + self->forget_second(*s, "it received more frames than are kept"); + return; + } + s->frames.push_back(std::move(frame)); + // Posted: the switch replaces the handlers this call runs in. + if (std::string_view(self->self_id_) > s->peer && s->frames.size() == 1) { + post(self->ex_, self->memory_, [weak, held] { + const auto app = weak.lock(); + if (const auto second = held.lock(); app && second) { + app->switch_to_second(*second); + } + }); + } + }), + .close = bind([weak, held] { + const auto self = weak.lock(); + const auto s = held.lock(); + if (self && s) { + self->forget_second(*s, "its channel closed"); + } + }), + .buffered_amount_low = {}, + }); + second->pc->set_handlers({ + .ice_candidate = {}, + .data_channel = {}, + .state = bind( + [weak, held](backend::connection_state state) { + const auto self = weak.lock(); + const auto s = held.lock(); + if (self && s && + (state == backend::connection_state::failed || + state == backend::connection_state::closed)) { + self->forget_second(*s, "its connection ended"); + } + }), + }); + second->deadline->start( + std::string_view(self_id_) > peer ? second_wait_higher : second_wait_lower, + bind([weak, held] { + const auto self = weak.lock(); + const auto s = held.lock(); + if (self && s) { + self->forget_second(*s, "the peer kept neither"); + } + })); + seconds_.insert_or_assign(std::pmr::string(peer, memory_), second); + log_("webrtc", "a second connection with ", peer, + " held until the peer shows which one it keeps"); + } + + /** The peer sends on the second connection the higher id holds, which it keeps: the second + * replaces the first, which ends, and takes the frames it received. As in + * `on_connection_end`, the second takes the first's place before the rooms hear of the end, + * and its frames come after. */ + void switch_to_second(second_connection& s) { + const auto it = seconds_.find(s.peer); + if (it == seconds_.end() || it->second.get() != &s) { + return; + } + const auto second = it->second; + seconds_.erase(it); + const std::pmr::string peer(second->peer, memory_); + second->deadline.reset(); + auto frames = std::exchange(second->frames, std::pmr::deque(memory_)); + std::shared_ptr first; + if (const auto at = connections_.find(peer); at != connections_.end()) { + first = at->second; + connections_.erase(at); + } + log_("webrtc", "the second connection with ", peer, + " replaces the first: the peer keeps it"); + const auto replacement = share_or_adopt(peer, second->pc, second->channel); + if (first) { + first->end("the peer keeps the second connection"); + } + replacement->replay(std::move(frames)); + } + + /** Closes a held second connection and forgets it, if it is still the one held. */ + void forget_second(second_connection& s, std::string_view why) { + const auto it = seconds_.find(s.peer); + if (it == seconds_.end() || it->second.get() != &s) { + return; + } + const auto keep = it->second; // `s` lives until this call returns + seconds_.erase(it); + log_("webrtc", "the second connection with ", keep->peer, " closed: ", why); + close_second(*keep); + } + + /** Closes a second connection without reporting its close. */ + static void close_second(second_connection& s) { + s.deadline.reset(); + s.channel->set_handlers({}); + s.pc->set_handlers({}); + s.channel->close(); + s.pc->close(); + } + [[nodiscard]] std::shared_ptr room_of(std::string_view token) const { const auto it = rooms_.find(token); return it == rooms_.end() ? nullptr : it->second.room.lock(); @@ -396,6 +584,26 @@ class app_impl : public std::enable_shared_from_this { it != connections_.end() && it->second == ended) { connections_.erase(it); } + // The second connection held to the peer replaces the first when the peer or the network + // ended the first, which is how Trystero JS keeps the second of a crossed pair; it is + // closed when this side ended the first. It takes the first's place before the rooms hear + // of the end, so that none looks for the peer again, and its frames come after, once the + // rooms let the peer go, so that they bind it again over the second. + std::shared_ptr replacement; + std::pmr::deque frames(memory_); + if (const auto it = seconds_.find(peer); it != seconds_.end()) { + const auto second = it->second; + seconds_.erase(it); + if (ended->ended_by_transport() && second->channel->is_open() && !find(peer)) { + second->deadline.reset(); + frames = std::move(second->frames); + log_("webrtc", "the second connection with ", peer, " replaces the first"); + replacement = share_or_adopt(peer, second->pc, second->channel); + } else { + log_("webrtc", "the second connection with ", peer, " closed: the first ended"); + close_second(*second); + } + } // A room may leave the registry from inside the call: the rooms are locked first, each // kept alive across its call. std::pmr::vector> rooms(memory_); @@ -407,6 +615,9 @@ class app_impl : public std::enable_shared_from_this { for (const auto& room : rooms) { room->connection_ended(ended, peer, reason); } + if (replacement) { + replacement->replay(std::move(frames)); + } } /** Hands every report not yet delivered to the current handler, one at a time: a handler may @@ -442,6 +653,7 @@ class app_impl : public std::enable_shared_from_this { std::size_t delivered_reports_ = 0; // the setup reports handed to a handler, in their order std::pmr::map> rooms_; std::pmr::map, std::less<>> connections_; + std::pmr::map, std::less<>> seconds_; std::size_t users_ = 0; }; diff --git a/include/webcpp/trystero/detail/connection.hpp b/include/webcpp/trystero/detail/connection.hpp index 7fa01b0..5258e7b 100644 --- a/include/webcpp/trystero/detail/connection.hpp +++ b/include/webcpp/trystero/detail/connection.hpp @@ -46,6 +46,9 @@ struct connection_callbacks { handler kept; /** The connection ended, with the reason; called once. */ handler ended; + /** The remote sent its first frame, which shows that it keeps this connection; called once, + * and may be empty. */ + handler used; }; // clang-tidy reports a class's destructor at its first declaration: binding is final, and nothing @@ -135,7 +138,7 @@ class connection : public std::enable_shared_from_this { allocator, [weak] { if (const auto self = weak.lock()) { - self->end("data channel closed"); + self->end_by_transport("data channel closed"); } }, }, @@ -246,6 +249,25 @@ class connection : public std::enable_shared_from_this { * connection and its channel closed, `ended` called last. */ void end(std::string_view reason); + /** Whether the remote sent a frame on it, which shows that it keeps it. */ + [[nodiscard]] bool used() const { return used_; } + + /** Whether it ended because its channel or its connection closed or failed, which the remote + * or the network did, rather than because this side ended it. */ + [[nodiscard]] bool ended_by_transport() const { return ended_by_transport_; } + + /** Handles, in their order, the frames its channel received before `start`, as if they came + * now: those a second connection received while the app held it for the remote's choice. */ + void replay(std::pmr::deque frames) { + const auto self = shared_from_this(); + for (auto& frame : frames) { + if (ended_) { + return; + } + on_message(std::move(frame)); + } + } + private: friend class binding; void remove(binding& b); @@ -255,6 +277,13 @@ class connection : public std::enable_shared_from_this { void keep(std::string_view token, backend::bytes&& frame); void forget_kept_if_empty(); + void end_by_transport(std::string_view reason) { + if (!ended_) { + ended_by_transport_ = true; + } + end(reason); + } + backend::factory& factory_; std::pmr::memory_resource* memory_; std::pmr::string peer_; @@ -274,6 +303,8 @@ class connection : public std::enable_shared_from_this { std::pmr::map attached_; // by id: in the order of attachment std::uint64_t next_binding_id_ = 0; bool ended_ = false; + bool ended_by_transport_ = false; + bool used_ = false; }; /** @@ -506,6 +537,14 @@ inline void connection::end(std::string_view reason_view) { /** Routes a decoded envelope to presence handling, its binding or the bounded keep queue. */ inline void connection::on_message(backend::bytes&& frame) { + if (!std::exchange(used_, true) && cb_.used) { + // The app may end this connection from inside the call. + const auto self = shared_from_this(); + cb_.used(peer_); + if (ended_) { + return; + } + } const auto envelope = protocol::decode_envelope(frame); if (!envelope) { end("invalid or incompatible room frame"); @@ -584,7 +623,8 @@ inline void connection::forget_kept_if_empty() { inline void connection::on_state(backend::connection_state state) { using backend::connection_state; if (state == connection_state::failed || state == connection_state::closed) { - end(state == connection_state::failed ? "connection failed" : "connection closed"); + end_by_transport(state == connection_state::failed ? "connection failed" + : "connection closed"); } else if (state == connection_state::disconnected) { // Trystero waits five seconds before treating a disconnection as the end. if (!disconnect_timer_) { @@ -594,7 +634,7 @@ inline void connection::on_state(backend::connection_state state) { {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), [weak = weak_from_this()] { if (const auto self = weak.lock()) { - self->end("connection lost"); + self->end_by_transport("connection lost"); } }}); } else if (disconnect_timer_) { diff --git a/test/app_impl_test.cpp b/test/app_impl_test.cpp index 8d9b84d..257cb03 100644 --- a/test/app_impl_test.cpp +++ b/test/app_impl_test.cpp @@ -375,7 +375,8 @@ void the_registry_holds_rooms_by_a_weak_reference() { } // An adopted connection advertises every registered room's token, is found by its peer and is -// live; a second connection to the same peer is closed, and the first returned. +// live; a second connection to the same peer is held, and the first returned; once the peer sends +// on the first, the second is closed. void adopt_starts_one_connection_per_peer() { asio::io_context io; trystero::test::memory_network net(io); @@ -397,14 +398,131 @@ void adopt_starts_one_connection_per_peer() { presence("T2", true)})); const auto second = negotiate(io, net); BOOST_TEST(app->adopt("B", second.local_pc, second.local) == c); - BOOST_TEST(!second.local->is_open()); + settle(io); + BOOST_TEST(second.local->is_open()); BOOST_TEST(c->live()); BOOST_TEST_EQ(app->live_connections().size(), 1U); + first.remote->send(trystero::protocol::presence_frame("T1", true)); + BOOST_TEST(run_until(io, [&] { return !second.local->is_open(); })); + BOOST_TEST(c->live()); + BOOST_TEST(app->find("B") == c); + BOOST_TEST( + log == + (lines{ + "webrtc: connection with B adopted", + "webrtc: a second connection with B held until the peer shows which one it keeps", + "webrtc: the second connection with B closed: the peer keeps the first", + })); + BOOST_TEST(r1->events == (std::vector{"+B"})); + BOOST_TEST(r2->events.empty()); +} + +// A connection opened once the peer sent on the first is closed at once: the peer keeps the +// first, and closes its own other one. +void another_connection_after_the_peers_first_frame_is_closed() { + asio::io_context io; + trystero::test::memory_network net(io); + lines log; + const auto app = make_app(io, net, log); + app->register_room("r1", "T1", std::make_shared()); + const auto first = negotiate(io, net); + const auto c = app->adopt("B", first.local_pc, first.local); + first.remote->send(trystero::protocol::presence_frame("T1", true)); + webcpp::test::require(BOOST_TEST(run_until(io, [&] { return c->used(); }))); + const auto second = negotiate(io, net); + BOOST_TEST(app->adopt("B", second.local_pc, second.local) == c); + BOOST_TEST(!second.local->is_open()); BOOST_TEST(log == (lines{ "webrtc: connection with B adopted", - "webrtc: a second connection with B closed: the first is shared", + "webrtc: another connection with B closed: the peer keeps the first", })); - BOOST_TEST(r1->events.empty() && r2->events.empty()); +} + +/** An app of self id `self`, whose timers run on the virtual clock of `net`. */ +std::shared_ptr make_app_as(asio::io_context& io, + trystero::test::memory_network& net, lines& log, + std::string_view self) { + net.virtual_clock = true; + return make_app(io, net, log, [self](trystero::app_config& c) { c.self_id = self; }); +} + +// The lower id holds the second until the peer closes the first, as Trystero JS closes the other +// connection of a crossed pair: the second then takes the first's place, after the rooms heard +// the first's end, and hands them the frames it received meanwhile. +void the_second_replaces_a_first_the_peer_closes() { + asio::io_context io; + trystero::test::memory_network net(io); + lines log; + const auto app = make_app_as(io, net, log, "A"); + const auto room = std::make_shared(); + app->register_room("r1", "T1", room); + const auto first = negotiate(io, net); + const auto c = app->adopt("B", first.local_pc, first.local); + const auto second = negotiate(io, net); + app->adopt("B", second.local_pc, second.local); + second.remote->send(trystero::protocol::presence_frame("T1", true)); + settle(io); + BOOST_TEST(app->find("B") == c); // the lower id waits for the peer + BOOST_TEST(room->events.empty()); + first.remote->close(); + webcpp::test::require(BOOST_TEST(run_until(io, [&] { return app->find("B") != c; }))); + const auto replacement = app->find("B"); + webcpp::test::require(BOOST_TEST(replacement != nullptr)); + BOOST_TEST(replacement->live()); + BOOST_TEST(replacement->advertised("T1")); + BOOST_TEST(room->events == (std::vector{"ended B: data channel closed", "+B"})); + BOOST_TEST(run_until(io, [&] { return second.received->size() == 1; })); + BOOST_TEST(second.received->at(0) == presence("T1", true)); // the replacement advertises + BOOST_TEST_EQ(app->live_connections().size(), 1U); +} + +// The higher id gives way: the peer's first frame on the second makes the second replace the +// first, which ends and so closes the peer's second. +void the_higher_id_takes_the_second_the_peer_sends_on() { + asio::io_context io; + trystero::test::memory_network net(io); + lines log; + const auto app = make_app_as(io, net, log, "Z"); + const auto room = std::make_shared(); + app->register_room("r1", "T1", room); + const auto first = negotiate(io, net); + const auto c = app->adopt("B", first.local_pc, first.local); + const auto second = negotiate(io, net); + app->adopt("B", second.local_pc, second.local); + second.remote->send(trystero::protocol::presence_frame("T1", true)); + webcpp::test::require(BOOST_TEST(run_until(io, [&] { return app->find("B") != c; }))); + BOOST_TEST(!c->live()); + BOOST_TEST(run_until(io, [&] { return !first.remote->is_open(); })); + BOOST_TEST(app->find("B")->advertised("T1")); + BOOST_TEST(room->events == + (std::vector{"ended B: the peer keeps the second connection", "+B"})); + BOOST_TEST_EQ(app->live_connections().size(), 1U); +} + +// A second the peer neither sends on nor closes, while it sends nothing on the first either, is +// closed after 2 s by the higher id and after 10 s by the lower id; the first stays. +void a_second_the_peer_leaves_alone_is_closed_in_time() { + for (const auto& [self, wait] : + {std::pair{std::string_view("Z"), 2'000ms}, std::pair{std::string_view("A"), 10'000ms}}) { + asio::io_context io; + trystero::test::memory_network net(io); + lines log; + const auto app = make_app_as(io, net, log, self); + app->register_room("r1", "T1", std::make_shared()); + const auto first = negotiate(io, net); + const auto c = app->adopt("B", first.local_pc, first.local); + const auto second = negotiate(io, net); + app->adopt("B", second.local_pc, second.local); + BOOST_TEST(net.advance(wait - 1ms)); + settle(io); + BOOST_TEST(second.local->is_open()); + BOOST_TEST(net.advance(1ms)); + settle(io); + BOOST_TEST(!second.local->is_open()); + BOOST_TEST(c->live()); + BOOST_TEST_EQ(log.back(), + "webrtc: the second connection with B closed: the peer kept neither"); + } } // The remote's presence reaches the room of its token, a frame of a room not bound is kept when @@ -510,8 +628,9 @@ 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(), dist/shared-peer.mjs:210-212). +// replacement the outer adoption brought is held as the second, and the room's is the one kept, +// so the peer has one connection, whose end by this side closes the second too and 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); @@ -533,7 +652,7 @@ void an_adoption_from_inside_a_stale_end_is_the_one_kept() { const auto outer = app->adopt("B", second.local_pc, second.local); webcpp::test::require(BOOST_TEST(nested != nullptr)); BOOST_TEST(outer == nested); - BOOST_TEST(!second.local->is_open()); + BOOST_TEST(second.local->is_open()); BOOST_TEST(nested->live()); BOOST_TEST_EQ(app->live_connections().size(), 1U); settle(io); @@ -542,6 +661,7 @@ void an_adoption_from_inside_a_stale_end_is_the_one_kept() { nested->end("test"); BOOST_TEST(app->find("B") == nullptr); BOOST_TEST(app->live_connections().empty()); + BOOST_TEST(!second.local->is_open()); BOOST_TEST_EQ(room->events.back(), "ended B: test"); } @@ -716,6 +836,10 @@ int main() { 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(another_connection_after_the_peers_first_frame_is_closed); + run_case(the_second_replaces_a_first_the_peer_closes); + run_case(the_higher_id_takes_the_second_the_peer_sends_on); + run_case(a_second_the_peer_leaves_alone_is_closed_in_time); 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); diff --git a/test/connection_test.cpp b/test/connection_test.cpp index 60859b3..4409ad7 100644 --- a/test/connection_test.cpp +++ b/test/connection_test.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -72,6 +73,7 @@ struct side { /** `kept` takes the kept frames of its token, then reads the token. */ bool take_in_kept = false; std::size_t taken = 0; + std::size_t used = 0; // the calls of `used` }; detail::connection_callbacks callbacks(side& s) { @@ -114,6 +116,12 @@ detail::connection_callbacks callbacks(side& s) { a, [&s](std::string_view, std::string_view why) { s.ended = why; }, }, + .used = + { + std::allocator_arg, + a, + [&s](std::string_view) { ++s.used; }, + }, }; } @@ -837,6 +845,43 @@ void the_end_closes_the_connection_and_frees_the_kept_frames() { BOOST_TEST(refused && *refused == make_error_code(trystero::error::backend_failure)); } +// The remote's first frame says it uses the connection, once; an end by this side is not the +// transport's, and a channel the remote closes is. +void the_first_frame_says_the_remote_uses_it() { + const std::array tokens{"T1"}; + link_pair p(tokens, tokens); + webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 1; }))); + BOOST_TEST(p.b.c->used()); + BOOST_TEST_EQ(p.b.used, 1U); + p.a.c->send_presence("T2", true); + BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 2; })); + BOOST_TEST_EQ(p.b.used, 1U); + p.a.c->end("test"); + BOOST_TEST(!p.a.c->ended_by_transport()); + BOOST_TEST(run_until(p.io, [&] { return !p.b.ended.empty(); })); + BOOST_TEST_EQ(p.b.ended, "data channel closed"); + BOOST_TEST(p.b.c->ended_by_transport()); +} + +// Frames replayed are handled in their order as if they came now, and stop at an end. +void replayed_frames_are_handled_in_order() { + const std::array tokens{"T1"}; + link_pair p(tokens, tokens); + webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 1; }))); + auto* m = std::pmr::get_default_resource(); + std::pmr::deque frames(m); + for (const auto* token : {"T2", "T3"}) { + const auto f = trystero::protocol::presence_frame(token, true, m); + frames.emplace_back(f.begin(), f.end()); + } + frames.emplace_back(3, std::uint8_t{9}); // malformed: ends the connection + const auto t4 = trystero::protocol::presence_frame("T4", true, m); + frames.emplace_back(t4.begin(), t4.end()); + p.b.c->replay(std::move(frames)); + BOOST_TEST(p.b.presence == (std::vector{"+T1", "+T2", "+T3"})); + BOOST_TEST_EQ(p.b.ended, "invalid or incompatible room frame"); +} + // A disconnection ends the connection after 5 s, as Trystero's; a reconnection before then // cancels it. void a_disconnection_ends_after_5_s_unless_it_reconnects() { @@ -864,6 +909,8 @@ void a_disconnection_ends_after_5_s_unless_it_reconnects() { int main() { start_advertises_every_token(); + the_first_frame_says_the_remote_uses_it(); + replayed_frames_are_handled_in_order(); a_withdrawn_token_is_forgotten(); a_bound_token_reaches_its_binding_and_another_is_kept(); a_withdrawn_token_drops_its_kept_frames(); diff --git a/test/memory_backend_test.cpp b/test/memory_backend_test.cpp index c2ba605..3ba2f4e 100644 --- a/test/memory_backend_test.cpp +++ b/test/memory_backend_test.cpp @@ -177,6 +177,28 @@ void deferred_opens_open_one_end_at_a_time() { BOOST_TEST(run_until(io, [&] { return p.answer_end && p.answer_end->is_open(); })); } +// What one end sends before the other end opened reaches it once it opens, in order, as a real +// channel's opening message comes first on its stream. +void a_frame_before_the_far_end_opens_waits_for_it() { + asio::io_context io; + memory_network net{io}; + net.defer_opens = true; + pair p; + connect(net, p); + run_until(io, [] { return false; }, 100ms); + net.open(p.offerer_id); + webcpp::test::require(BOOST_TEST(run_until(io, [&] { return p.offer_end->is_open(); }))); + const std::array a{'A'}; + const std::array b{'B'}; + p.offer_end->send(a); + p.offer_end->send(b); + run_until(io, [] { return false; }, 100ms); + BOOST_TEST(p.at_answerer.empty()); + net.open(p.answerer_id); + BOOST_TEST(run_until(io, [&] { return p.at_answerer.size() == 2; })); + BOOST_TEST(p.at_answerer.at(0).at(0) == 'A' && p.at_answerer.at(1).at(0) == 'B'); +} + void an_injected_frame_reaches_the_end_named() { asio::io_context io; memory_network net{io}; @@ -533,6 +555,7 @@ int main() { a_held_frame_holds_every_later_frame_of_its_end(); a_dropped_frame_is_gone(); deferred_opens_open_one_end_at_a_time(); + a_frame_before_the_far_end_opens_waits_for_it(); an_injected_frame_reaches_the_end_named(); a_failed_connection_reports_failed_then_closes(); a_disconnection_and_a_reconnection_are_reported(); diff --git a/test/shared_test.cpp b/test/shared_test.cpp index 9dc7486..3a3bba1 100644 --- a/test/shared_test.cpp +++ b/test/shared_test.cpp @@ -1337,12 +1337,16 @@ void a_kept_leave_discards_what_came_before() { 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 -// sides lose both, then both rooms join again within 15 s of virtual time, over one connection. +// crossed connections recover: A's end of r1's pair and B's end of r2's open first, so each side +// keeps another connection and holds the other as its second. B, the higher id, takes its second +// once A sends on it, and its first's end closes A's second: both rooms join within 15 s of +// virtual time, over one connection, and A never loses the peer. void crossed_connections_recover() { fixture f{true}; auto a_config = app_config("AAAAAAAAAAAAAAAAAAF1"); a_config.ice_servers = {{.urls = {"stun:a.test"}, .username = {}, .credential = {}}}; + std::vector a_log; + a_config.log = [&a_log](std::string_view, std::string_view text) { a_log.emplace_back(text); }; auto b_config = app_config("ZZZZZZZZZZZZZZZZZZF2"); b_config.ice_servers = {{.urls = {"stun:b.test"}, .username = {}, .credential = {}}}; trystero::app a(f.io.get_executor(), f.net, std::move(a_config)); @@ -1382,6 +1386,8 @@ void crossed_connections_recover() { 15s)); BOOST_TEST(f.net.steady_now() - opened <= 15s); BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 2U; })); + BOOST_TEST(std::ranges::none_of( + a_log, [](const std::string& line) { return line.find(" gone: ") != std::string::npos; })); } // A native channel can close on its transport thread during the adoption log, before the diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp index 4004e01..62529c0 100644 --- a/test/support/memory_backend.hpp +++ b/test/support/memory_backend.hpp @@ -487,9 +487,16 @@ class memory_data_channel : public backend::data_channel, void opened() { open_ = true; + opened_ = true; if (h_.open) { h_.open(); } + // What arrived before this end opened, in its order, as a real channel delivers what the + // other end sent once it opened: the opening message comes first on the stream. + for (auto& frame : + std::exchange(early_, decltype(early_)(node_allocator(memory_)))) { + receive(std::move(frame)); + } } std::size_t bytes_sent = 0; @@ -504,6 +511,10 @@ class memory_data_channel : public backend::data_channel, std::weak_ptr remote_; handlers h_; bool open_ = false; + bool opened_ = false; + // The frames that arrived before this end opened, delivered once it opens. + std::list> early_{ + node_allocator(memory_)}; memory_network* net_ = nullptr; // Alive exactly while the network is: a channel that outlives it sends nothing. std::weak_ptr registry_; @@ -804,7 +815,8 @@ class memory_network : public backend::factory { /** Delivers the frames held for `to`, in the order they were sent, each then filtered again; * those whose sending end is gone are dropped. */ void release(std::size_t to); - /** When true, a pair's channels open only through open(), one end at a time. */ + /** When true, a pair's channels open only through open(), one end at a time; what reaches an + * end before it opens waits for it. */ bool defer_opens = false; /** Opens the channel of `pc`, whose pair is connected. */ void open(std::size_t pc); @@ -971,6 +983,10 @@ inline void memory_data_channel::send(std::span frame) { } inline void memory_data_channel::receive(backend::bytes frame) { + if (!opened_) { + early_.push_back(std::move(frame)); + return; + } post_in(io_, memory_, [self = shared_from_this(), frame = std::move(frame)]() mutable { if (self->open_ && self->h_.message) { self->h_.message(std::move(frame));