From 654f3b416adaaf9e89d00650e9e19f13ffc28d1e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:04:25 +0100 Subject: [PATCH 1/7] Broadcast to every connected browser and document the threads [#401] app.broadcast(name, options)(...) calls a JavaScript function on every browser whose handshake completed, from any thread, encoding its arguments once. BroadcastOptions::maxPendingWrites holds a call back for a browser that has that many frames waiting and keeps only the latest for it, sent as soon as the browser catches up, in order. app.forEachUI(function) visits the same browsers outside every WebFront lock. docs/ASYNC_EXECUTION.md gains a Threads section: callbacks run one at a time on the server thread, browser calls never wait for it, and only waiting for the server thread under a lock a callback takes deadlocks. No wire format change; a Jasmine spec receives a broadcast made from another thread. --- README.md | 2 +- docs/ASYNC_EXECUTION.md | 57 ++++ docs/CHANGELOG.md | 6 + include/webfront/Broadcast.hpp | 152 +++++++++++ include/webfront/WebFront.hpp | 39 ++- test/unit/BroadcastTests.cpp | 332 ++++++++++++++++++++++++ test/unit/CMakeLists.txt | 2 +- test/web/JasmineTest.cpp | 8 + test/web/suite/specs/webfront-specs.mjs | 14 + 9 files changed, 609 insertions(+), 3 deletions(-) create mode 100644 include/webfront/Broadcast.hpp create mode 100644 test/unit/BroadcastTests.cpp diff --git a/README.md b/README.md index 9095980a..a793fe8e 100644 --- a/README.md +++ b/README.md @@ -319,7 +319,7 @@ CI runs one combined C++ / native-browser job per desktop platform on each code ## Contracts and limitations -- WebFront owns an HTTP/WebSocket server on a background thread. Callbacks run there; avoid blocking it. Native windows must be created and shown on the main thread. Application coroutines use `app.spawn(task)` or `ui.spawn(task)`; see [execution and cancellation](docs/ASYNC_EXECUTION.md). +- WebFront owns an HTTP/WebSocket server on a background thread. Callbacks run there, one at a time; avoid blocking it. Browser calls (`jsFunction`, `app.broadcast(name)(...)`) can be made from any thread and never wait for it; see [threads](docs/ASYNC_EXECUTION.md#threads). Native windows must be created and shown on the main thread. Application coroutines use `app.spawn(task)` or `ui.spawn(task)`; see [execution and cancellation](docs/ASYNC_EXECUTION.md). - JavaScript calls to C++ always return Promises. C++ `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction(name)(...)` returns `std::future`. Missing functions, exceptions, malformed replies and disconnects fail the typed call. - The binary bridge supports scalars, strings, tuples, numeric typed arrays and packed bitsets. Arbitrary objects do not cross it. Strings have a 16-bit encoded length limit. - Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index fc718e32..1628851b 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -164,6 +164,63 @@ cancellation API. The untyped `ui.jsFunction(name)` remains fire-and-forget. JavaScript-to-C++ calls still always return Promises. None of these changes adds richer bridge result types or remote Promise cancellation. +## Threads + +WebFront runs its HTTP/WebSocket server on one thread: the thread `show()` starts, or the thread +that calls `run()` or `runOne()`. That server thread is the only one that runs: + +- `cppFunction` callbacks, `onUIStarted`, `subscribeUIStarted` and `subscribeUIClosed` handlers; +- DOM event callbacks and the bodies of tasks started with `app.spawn` or `ui.spawn`. + +They run one at a time, in the order of the events that cause them, and never in parallel with one +another. A long callback delays every browser, so do blocking work on another thread or in a task. + +From any thread, while the application lives, you can call: + +- `ui.jsFunction(name)(...)`, `ui.jsFunction(name)(...)` and starting a `jsFunctionSender`; +- `ui.addScript`, `ui.pendingWrites`, `ui.writesAtMost` and `ui.spawn`; +- `app.broadcast(name)(...)`, `app.forEachUI`, `app.connectedBrowsers`, `app.spawn` and `app.stop`. + +These calls never wait for the server thread. They take short internal locks, queue the frame, +and the server thread writes it. Only `ui.document()` and its nodes are confined to the server +thread. Register `cppFunction` callbacks and set `onUIStarted` before the server starts. You can +add or remove subscriptions at any time. + +WebFront never holds one of its own locks while it calls application code. A thread can therefore +call WebFront while it holds an application lock that a `cppFunction` callback also takes. The +callback waits for that lock, and the call it waits for does not depend on the callback. What +deadlocks is waiting for the server thread itself: + +- the `get()` of a `jsFunction` future inside a callback (the server thread reads the reply); +- the same wait on another thread under a lock that a callback takes; +- `app.shutdown()` or the destruction of the application under such a lock. + +Inside a task, await `jsFunctionSender` instead. + +## Broadcasting to every browser + +`app.broadcast(name)` returns a function object that calls the JavaScript function `name` on every +browser whose handshake has completed (those `onUIStarted` was called for) and whose closure was +not reported yet. Like the untyped `jsFunction`, the call is fire-and-forget. The application keeps +no table of its browsers: those that connect later receive the next calls, and a browser that +closes stops receiving them. The arguments are encoded once for all the browsers. + +```cpp +auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 2}); +// On a thread of the application, about 30 times per second: +onState(stateJson); +``` + +`BroadcastOptions::maxPendingWrites` protects a browser that reads slower than the application +writes. A call is queued for a browser only while fewer frames than that await its network. Otherwise +the call is held back, and a newer call replaces it. The held call is queued as soon as the browser +catches up, so the browser skips the intermediate states but always receives the latest one. Calls +made one after the other reach each browser in that order. Without the option, every call is queued for every browser. Keep +the function object between calls, because it holds the calls that are waiting. Copies share them. + +`app.forEachUI(function)` calls `function(ui)` for the same browsers, on the calling thread, outside +every WebFront lock, for per-browser arguments or typed calls. + ## HTTP gzip CPU work Cold gzip identity fallback is a sender backed by one lazy, owned worker per HTTP server. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ea173bc5..fbc3827a 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- Add `app.broadcast(name, options)(...)` and `app.forEachUI(function)` (#401): calls to every browser + whose handshake completed, from any thread, with no table of browsers kept by the application. + `BroadcastOptions::maxPendingWrites` holds a call back for a browser that has that many frames + waiting, and keeps only the latest for it. Document the threads of callbacks and browser calls + ([threads](ASYNC_EXECUTION.md#threads)). No wire format change. + - Add awaitable DOM events (#384): `co_await node.next(name, options)` completes with the value of the element's next event, for sequential dialogs and wizards. Starting the sender subscribes with the flags declared then; the event unsubscribes. It completes stopped through the task's stop token, diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp new file mode 100644 index 00000000..792e9c0f --- /dev/null +++ b/include/webfront/Broadcast.hpp @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +/// @brief A JavaScript function called on every connected browser (BasicWF::broadcast). +#pragma once +#include "http/WebSocket.hpp" +#include "weblink/Messages.hpp" +#include "weblink/WebLink.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront { + +/// How a broadcast treats a browser that reads slower than it is written. +struct BroadcastOptions { + /// Without a value, every call is queued for every browser. With one, a call is queued for a browser only while + /// fewer frames than this await its network; otherwise it replaces the call held back for that browser, queued as + /// soon as fewer frames await: a slow browser skips intermediate calls but always receives the latest. Must be > 0. + std::optional maxPendingWrites{}; +}; + +/// Calls a JavaScript function on each browser connected at the time of the call, fire-and-forget, from any thread. +/// The arguments are encoded once. Copies share the calls held back for slow browsers; the object must not outlive +/// its application. +template +class Broadcast { + using Net = typename WebFront::Net; + using Link = WebLink; + using Message = std::shared_ptr>; + + // The call held back for one browser; guarded by State::mutex. Holds no strong reference to its link, so that + // no link can be destroyed, and wake its write waiters, under that mutex. + struct Slot { + std::weak_ptr link; + Message held; + bool sending = false; // a thread or a write waiter is queuing 'held' + }; + struct State { + std::mutex mutex; + std::map> slots; + }; + +public: + Broadcast(std::string_view functionName, WebFront& wf, BroadcastOptions options = {}) + : name(functionName), webFront(wf), maxPending(options.maxPendingWrites) { + if (maxPending && *maxPending == 0) + throw std::invalid_argument("BroadcastOptions::maxPendingWrites must be at least 1"); + } + + void operator()(auto&&... ts) const { + msg::FunctionCall command; + websocket::Frame frame{std::span(reinterpret_cast(command.header().data()), command.header().size())}; + command.encodeParameter(name, frame); + ((command.encodeParameter(std::forward(ts), frame)), ...); + command.setParametersCount(static_cast(1 + sizeof...(ts))); + const auto message = std::make_shared>(payload(frame)); + + // The links are shared while used, and released after the loop, outside every lock. + const auto links = webFront.connectedLinks(); + if (!maxPending) { + for (const auto& [id, link] : links) + link->sendFrame(websocket::Frame{std::span(*message)}); + return; + } + for (const auto& [id, link] : links) + offer(state, id, link, message, *maxPending); + forgetAbsent(links); + } + +private: + std::string name; + WebFront& webFront; + std::optional maxPending; + std::shared_ptr state = std::make_shared(); + + static std::vector payload(const websocket::Frame& frame) { + std::vector bytes; + const auto buffers = frame.toBuffers(); + for (auto buffer = std::next(buffers.begin()); buffer != buffers.end(); ++buffer) { // after the frame header + const auto* first = static_cast(buffer->data()); + bytes.insert(bytes.end(), first, first + buffer->size()); + } + return bytes; + } + + static void offer(const std::shared_ptr& state, WebLinkId id, const std::shared_ptr& link, Message message, std::size_t limit) { + std::shared_ptr slot; + { + std::scoped_lock lock{state->mutex}; + auto& entry = state->slots[id]; + // A reused identifier names another connection: what was held for the former one is dropped. + if (!entry || entry->link.owner_before(link) || link.owner_before(entry->link)) + entry = std::make_shared(Slot{link, nullptr, false}); + entry->held = std::move(message); + if (entry->sending) + return; // its sender will queue this newer call instead of the one it replaces + entry->sending = true; + slot = entry; + } + send(state, slot, link, limit); + } + + // Queues the held call while fewer than `limit` frames await the browser, then waits for room. Only one sender per + // slot runs at a time, so the browser receives the calls in order. + static void send(const std::shared_ptr& state, const std::shared_ptr& slot, const std::shared_ptr& link, std::size_t limit) { + for (;;) { + Message message; + { + std::scoped_lock lock{state->mutex}; + if (!slot->held) { + slot->sending = false; + return; + } + // The waiter runs outside the link's locks, on the thread whose write makes room, or when the link + // closes or is destroyed. + const auto waiter = link->whenWritesAtMost(limit - 1, [state, slot, weak = std::weak_ptr(link), limit] { + if (const auto alive = weak.lock()) { + send(state, slot, alive, limit); + return; + } + std::scoped_lock gone{state->mutex}; + slot->held = nullptr; + slot->sending = false; + }); + if (waiter != 0) + return; // the waiter now sends + message = std::move(slot->held); + } + // Outside the mutex: a write completing at once may wake the waiter of another broadcast. + link->sendFrame(websocket::Frame{std::span(*message)}); + } + } + + void forgetAbsent(const std::vector>>& links) const { + std::scoped_lock lock{state->mutex}; + std::erase_if(state->slots, [&](const auto& entry) { + return !entry.second->sending && std::ranges::find(links, entry.first, &std::pair>::first) == links.end(); + }); + } +}; + +} // namespace webfront diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 742a3387..18cb9017 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -4,6 +4,7 @@ /// @brief WebFront UI main objet #pragma once +#include "Broadcast.hpp" #include "dom/Document.hpp" #include "frontend/Frontend.hpp" #include "http/HTTPServer.hpp" @@ -20,6 +21,7 @@ #include "weblink/WebLink.hpp" #include +#include #include #include #include @@ -34,6 +36,7 @@ #include #include #include +#include namespace webfront { @@ -360,7 +363,7 @@ class BasicWF { }, httpServer.taskScope(), false); { std::scoped_lock lock{linksMutex}; - webLinks.emplace(id, Connection{link, std::this_thread::get_id(), false}); + webLinks.emplace(id, Connection{link, std::this_thread::get_id(), false, false}); } link->start(); // registered first: every event it dispatches finds it }); @@ -449,6 +452,20 @@ class BasicWF { private: template friend class BasicUI; + template + friend class Broadcast; + + /// The links of the browsers whose handshake completed and that were not reported closed, shared with the caller. + [[nodiscard]] std::vector>>> connectedLinks() const { + std::vector>>> links; + std::scoped_lock lock{linksMutex}; + links.reserve(webLinks.size()); + for (const auto& [id, connection] : webLinks) + if (connection.linked && !connection.closed) + links.emplace_back(id, connection.link); + return links; + } + /// Internal DOM document storage, confined to the server thread. std::shared_ptr domState(WebLinkId id) { std::shared_ptr> link; @@ -490,6 +507,20 @@ class BasicWF { return webLinks.size(); } + /// Calls `function(ui)` for each browser started (see onUIStarted) and not reported closed when the call starts. Callable from + /// any thread; `function` runs on the calling thread, outside every WebFront lock, so it may call the UI. + template Function> + void forEachUI(Function&& function) { + for (const auto& [id, link] : connectedLinks()) + std::invoke(function, UI{*this, id}); + } + + /// A function object calling `functionName` on every connected browser, fire-and-forget, from any thread; see + /// BroadcastOptions for slow browsers. Keep it between calls: it holds what it keeps back for them. + [[nodiscard]] Broadcast broadcast(std::string_view functionName, BroadcastOptions options = {}) { + return Broadcast{functionName, *this, options}; + } + /// Whether a C++ function of that name is registered. [[nodiscard]] bool hasCppFunction(std::string_view functionName) const { return cppFunctions.contains(functionName); @@ -663,6 +694,7 @@ class BasicWF { std::shared_ptr> link; std::thread::id thread; bool closed; + bool linked; // its handshake completed: onUIStarted was called }; std::map webLinks; WebLinkId idsCounter{0}; @@ -741,6 +773,11 @@ class BasicWF { void onEvent(WebLinkEvent event) { switch (event.code) { case WebLinkEvent::Code::linked: + { + std::scoped_lock lock{linksMutex}; + if (auto found = webLinks.find(event.webLinkId); found != webLinks.end()) + found->second.linked = true; + } if (uiStartedHandler) uiStartedHandler(UI{*this, event.webLinkId}); uiSubscribers->notify(UI{*this, event.webLinkId}); diff --git a/test/unit/BroadcastTests.cpp b/test/unit/BroadcastTests.cpp new file mode 100644 index 00000000..46846ac0 --- /dev/null +++ b/test/unit/BroadcastTests.cpp @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +/// @brief Broadcasting to every connected browser, and the threads of callbacks and browser calls (#401). +#include "InjectableNetworking.hpp" +#include +#include +#include +#include + +#ifdef _WIN32 + #include +#else + #include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace webfront; +using namespace std::chrono_literals; + +namespace { +const std::string upgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + +// The payload of a browser's call to a C++ function, without a reply (call identifier 0). +template +std::vector callPayload(const std::string& name) { + msg::FunctionCall<> message; + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(name, frame); + frame.freeze(); + return testing::messagePayload(frame); +} + +struct OneBrowserNet : testing::InjectableNetworking { + static inline bool accepted{}; + static auto Accept(Acceptor&) { + return networking::ex::then(networking::ex::just(), []() -> Socket { + if (std::exchange(accepted, true)) + throw std::system_error(std::make_error_code(std::errc::operation_canceled)); + return Socket{}; + }); + } +}; +} // namespace + +SCENARIO("A broadcast keeps only the latest call for a browser with too many pending writes", "[broadcast]") { + using Socket = testing::InjectableSocket; + Socket::reset(); + OneBrowserNet::accepted = false; + BasicWF app{WebFrontConfig{.port = "0"}}; + auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); + auto every = app.broadcast("onEvent"); + Socket::receive(std::as_bytes(std::span(upgradeRequest))); + REQUIRE(app.connectedBrowsers() == 1); + + GIVEN("a browser whose handshake has not completed") { + latest(std::string{"before-handshake"}); + THEN("it is not started yet and receives nothing") { + REQUIRE_FALSE(Socket::wrote("before-handshake")); + } + } + GIVEN("a started browser whose network completes writes only when the test says so") { + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + Socket::deferWrites(); + Socket::completeDeferredWrites(); // the handshake acknowledgement + + WHEN("three states are broadcast while the first one is still being written") { + latest(std::string{"state-1"}); + latest(std::string{"state-2"}); + latest(std::string{"state-3"}); + THEN("only the first is written before the network completes it") { + REQUIRE(Socket::wrote("state-1")); + REQUIRE_FALSE(Socket::wrote("state-3")); + } + AND_WHEN("the network completes the writes") { + while (Socket::completeDeferredWrites() != 0) {} + THEN("the latest state follows and the intermediate one was skipped") { + REQUIRE(Socket::wrote("state-3")); + REQUIRE_FALSE(Socket::wrote("state-2")); + } + THEN("a later state is written at once") { + latest(std::string{"state-4"}); + REQUIRE(Socket::wrote("state-4")); + } + } + } + WHEN("events are broadcast without a limit while the first one is still being written") { + every(std::string{"event-1"}); + every(std::string{"event-2"}); + every(std::string{"event-3"}); + while (Socket::completeDeferredWrites() != 0) {} + THEN("every one is written") { + REQUIRE(Socket::wrote("event-1")); + REQUIRE(Socket::wrote("event-2")); + REQUIRE(Socket::wrote("event-3")); + } + } + Socket::deferWrites(false); + while (Socket::completeDeferredWrites() != 0) {} + } + app.shutdown(); + Socket::reset(); +} + +SCENARIO("A broadcast limit must allow at least one pending write", "[broadcast]") { + BasicWF app{WebFrontConfig{.port = "0"}}; + REQUIRE_THROWS_AS(app.broadcast("onState", {.maxPendingWrites = 0}), std::invalid_argument); +} + +namespace { +using Stdnet = networking::TCPStdnet; + +void waitUntil(auto condition) { + for (int i = 0; i < 500 && !condition(); ++i) + std::this_thread::sleep_for(10ms); +} + +// A browser connected over loopback: it upgrades, completes the bridge handshake and records what it receives. +class Browser { +public: + explicit Browser(std::string_view port) : socket(context) { + socket.connect(Stdnet::Resolve("127.0.0.1", port)); + socket.send(std::as_bytes(std::span(upgradeRequest))); + REQUIRE(receiveUntil("\r\n\r\n")); + const std::array + handshake{0x82, 0x82, 0, 0, 0, 0, static_cast(msg::Command::handshake), static_cast(msg::JSEndian::little)}; + socket.send(Stdnet::ConstBuffer(handshake.data(), handshake.size())); + } + + void call(const std::string& name) { + const auto frame = testing::clientFrame(callPayload(name)); + socket.send(Stdnet::ConstBuffer(frame.data(), frame.size())); + } + + /// True once the server sent these bytes, false after the deadline. + bool receiveUntil(std::string_view text, std::chrono::milliseconds timeout = 5s) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (received.find(text) == std::string::npos) { + const auto remaining = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()).count(); + if (remaining <= 0) + return false; + ::pollfd descriptor{}; + descriptor.fd = socket.native_handle(); + descriptor.events = POLLIN; +#ifdef _WIN32 + const int ready = ::WSAPoll(&descriptor, 1, static_cast(remaining)); +#else + const int ready = ::poll(&descriptor, 1, static_cast(remaining)); +#endif + if (ready <= 0) + return false; + std::array buffer{}; + const auto size = socket.receive(Stdnet::Buffer(buffer)); + if (size == 0) + return false; + received.append(buffer.data(), size); + } + return true; + } + +private: + Stdnet::IoContext context; + Stdnet::Socket socket; + std::string received; +}; + +// What the callbacks observed: the threads they ran on, and how many ran at once. +struct Observed { + std::mutex mutex; + std::vector threads; + std::atomic running{0}; + std::atomic maxRunning{0}; + std::atomic started{0}; + std::atomic calls{0}; + std::atomic closed{0}; + + void record() { + const auto now = ++running; + for (auto max = maxRunning.load(); now > max && !maxRunning.compare_exchange_weak(max, now);) {} + std::this_thread::sleep_for(1ms); // overlap with a callback another thread might be running + { + std::scoped_lock lock{mutex}; + threads.push_back(std::this_thread::get_id()); + } + --running; + } +}; +} // namespace + +SCENARIO("Callbacks run one at a time on the server thread, and browser calls are made from any thread", "[broadcast]") { + using App = BasicWF; + App app{WebFrontConfig{.port = "0"}}; + Observed observed; + std::mutex applicationLock; // also taken by a callback + app.onUIStarted([&](App::UI) { + observed.record(); + ++observed.started; + }); + auto closedSubscription = app.subscribeUIClosed([&](App::UI) { + observed.record(); + ++observed.closed; + }); + app.cppFunction("report", [&](App::UI ui) { + observed.record(); + std::scoped_lock lock{applicationLock}; + ui.jsFunction("reported")(std::string{"reported-ack"}); + ++observed.calls; + }); + std::promise unblock; + auto unblocked = unblock.get_future().share(); + std::atomic blocking{false}; + app.cppFunction("block", [&] { + blocking = true; + unblocked.wait(); + }); + std::thread server([&] { + app.run(); + }); + const auto serverThread = server.get_id(); + + auto first = std::make_unique(app.port()); + auto second = std::make_unique(app.port()); + waitUntil([&] { + return observed.started == 2; + }); + REQUIRE(observed.started == 2); + + WHEN("another thread broadcasts a state") { + auto onState = app.broadcast("siliconForge.onState"); + onState(std::string{"broadcast-state"}); + THEN("every started browser receives it") { + REQUIRE(first->receiveUntil("broadcast-state")); + REQUIRE(second->receiveUntil("broadcast-state")); + } + } + WHEN("another thread calls each browser through forEachUI") { + std::vector visited; + app.forEachUI([&](App::UI ui) { + visited.push_back(ui.id()); + ui.jsFunction("each")(std::string{"each-ui-" + std::to_string(ui.id())}); + }); + THEN("each started browser is visited once and receives its call") { + REQUIRE(visited.size() == 2); + REQUIRE(first->receiveUntil("each-ui-")); + REQUIRE(second->receiveUntil("each-ui-")); + } + } + WHEN("both browsers call C++ while another thread broadcasts under a lock the callback also takes") { + auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 2}); + for (int i = 0; i < 20; ++i) { + first->call("report"); + second->call("report"); + std::scoped_lock lock{applicationLock}; + onState(std::string{"locked-state"}); + app.forEachUI([](App::UI ui) { + ui.jsFunction("locked")(std::string{"locked-call"}); + }); + } + waitUntil([&] { + return observed.calls == 40; + }); + THEN("no call deadlocks and the callbacks never overlap") { + REQUIRE(observed.calls == 40); + REQUIRE(observed.maxRunning == 1); + REQUIRE(first->receiveUntil("reported-ack")); + REQUIRE(second->receiveUntil("locked-call")); + } + } + WHEN("a callback blocks the server thread") { + first->call("block"); + waitUntil([&] { + return blocking.load(); + }); + REQUIRE(blocking); + auto calls = std::async(std::launch::async, [&] { + auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 1}); + onState(std::string{"while-blocked"}); + onState(std::string{"while-blocked"}); + app.forEachUI([](App::UI ui) { + ui.jsFunction("blocked")(std::string{"while-blocked"}); + static_cast(ui.pendingWrites()); + }); + }); + const auto status = calls.wait_for(5s); + unblock.set_value(); + THEN("browser calls from another thread return without waiting for it") { + REQUIRE(status == std::future_status::ready); + REQUIRE(second->receiveUntil("while-blocked")); + } + } + if (blocking == false) + unblock.set_value(); + + WHEN("a browser disconnects") { + second.reset(); + waitUntil([&] { + return observed.closed == 1; + }); + THEN("its closure is reported, and a broadcast reaches the remaining browser") { + REQUIRE(observed.closed == 1); + app.broadcast("siliconForge.onState", {.maxPendingWrites = 1})(std::string{"after-close"}); + REQUIRE(first->receiveUntil("after-close")); + } + } + first.reset(); + second.reset(); + waitUntil([&] { + return app.connectedBrowsers() == 0; + }); + app.stop(); + server.join(); + app.shutdown(); + THEN("every callback ran on the server thread") { + std::scoped_lock lock{observed.mutex}; + REQUIRE_FALSE(observed.threads.empty()); + REQUIRE(std::ranges::all_of(observed.threads, [&](std::thread::id id) { + return id == serverThread; + })); + } +} diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 9e35ce6d..f1d0592c 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -28,7 +28,7 @@ list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServe list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) -list(APPEND TESTS_LIST WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) +list(APPEND TESTS_LIST BroadcastTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp JasmineConsumerTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) list(APPEND TESTS_LIST FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index b1c0557c..0d18a5fc 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -525,6 +525,14 @@ class BrowserIntegrationTest { uiSubscription = webFront->subscribeUIStarted([this](TestWF::UI) { state.subscriberNotified = true; }); + // From another thread, which the callback joins: a broadcast does not wait for the server thread (#401). + webFront->cppFunction("broadcastFromThread", [this](const string& token) { + auto onState = webFront->broadcast("webfrontTests.receiveBroadcast", {.maxPendingWrites = 1}); + std::thread caller([&] { + onState(token, 401); + }); + caller.join(); + }); webFront->cppFunction("callBackCaller", [](TestWF::UI caller, const string& token) { caller.jsFunction("webfrontTests.receiveFromCaller")(token); return "cpp-result:" + token; diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index 58a52894..312b50c5 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -77,6 +77,11 @@ const callerCall = new Promise((resolve) => { resolveCallerCall = resolve; }); +let resolveBroadcast; +const broadcastCall = new Promise((resolve) => { + resolveBroadcast = resolve; +}); + let resolveCppResult; const cppResultCall = new Promise((resolve) => { resolveCppResult = resolve; @@ -137,6 +142,10 @@ globalThis.webfrontTests = { resolveCallerCall(token); }, + receiveBroadcast(token, number) { + resolveBroadcast([token, number]); + }, + returnToCpp(value) { const result = `js-result:${value}`; resolveCppResult(result); @@ -273,6 +282,11 @@ describe('WebFront browser integration', () => { await expectAsync(callerCall).toBeResolvedTo('caller-token'); }); + it('receives a call that C++ broadcast to every browser from another thread', async () => { + await expectAsync(webFront.cppFunction('broadcastFromThread')('broadcast-token')).toBeResolved(); + await expectAsync(broadcastCall).toBeResolvedTo(['broadcast-token', 401]); + }); + it('allows C++ to await a JavaScript result', async () => { await expectAsync(cppResultCall).toBeResolvedTo('js-result:from-cpp'); }); From 9701e7de67ca70e2685caab5d512501209534463 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:21:34 +0100 Subject: [PATCH 2/7] Address review of the broadcast: coalesce in the write queue, defer while starting [#401] The latest-only limit moves into the WebSocket write queue (writeLatest): held calls belong to each connection, keyed by function name, so a temporary Broadcast coalesces too, a failed write releases them, and no write waiter re-registers on a closed link. The limit counts only the calls of that function, not logs or other calls. Each call is encoded once into a frame shared by every browser (Frame::share()). A browser is started once its onUIStarted handlers return: a broadcast made meanwhile is sent right after them, and forEachUI skips it. One encoding helper (detail::encodeCall) serves JsFunction, JsFunctionSender and Broadcast. The limit scenario resets the injectable network. --- docs/ASYNC_EXECUTION.md | 27 ++++-- docs/CHANGELOG.md | 8 +- include/webfront/Broadcast.hpp | 126 ++++--------------------- include/webfront/JsFunction.hpp | 6 +- include/webfront/JsFunctionSender.hpp | 6 +- include/webfront/WebFront.hpp | 98 +++++++++++++++---- include/webfront/http/WebSocket.hpp | 86 ++++++++++++++--- include/webfront/weblink/CallFrame.hpp | 24 +++++ include/webfront/weblink/WebLink.hpp | 8 ++ test/unit/BroadcastTests.cpp | 74 ++++++++++++++- test/unit/InjectableNetworking.hpp | 8 ++ test/unit/WebSocketTests.cpp | 53 +++++++++++ 12 files changed, 363 insertions(+), 161 deletions(-) create mode 100644 include/webfront/weblink/CallFrame.hpp diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index 1628851b..35d61755 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -200,10 +200,12 @@ Inside a task, await `jsFunctionSender` instead. ## Broadcasting to every browser `app.broadcast(name)` returns a function object that calls the JavaScript function `name` on every -browser whose handshake has completed (those `onUIStarted` was called for) and whose closure was +browser whose `onUIStarted` and `subscribeUIStarted` handlers have returned and whose closure was not reported yet. Like the untyped `jsFunction`, the call is fire-and-forget. The application keeps no table of its browsers: those that connect later receive the next calls, and a browser that -closes stops receiving them. The arguments are encoded once for all the browsers. +closes stops receiving them. A call made while a browser's handlers run reaches it right after +them, so what the handlers send, such as the initial state, arrives first. Each call encodes its +arguments once, into a frame that all the browsers share. ```cpp auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 2}); @@ -212,14 +214,19 @@ onState(stateJson); ``` `BroadcastOptions::maxPendingWrites` protects a browser that reads slower than the application -writes. A call is queued for a browser only while fewer frames than that await its network. Otherwise -the call is held back, and a newer call replaces it. The held call is queued as soon as the browser -catches up, so the browser skips the intermediate states but always receives the latest one. Calls -made one after the other reach each browser in that order. Without the option, every call is queued for every browser. Keep -the function object between calls, because it holds the calls that are waiting. Copies share them. - -`app.forEachUI(function)` calls `function(ui)` for the same browsers, on the calling thread, outside -every WebFront lock, for per-browser arguments or typed calls. +writes. A call is queued for a browser only while fewer calls of the same function than that await +its network. Otherwise the call is held back, and a newer call of that function replaces it. The +held call is queued as soon as the browser catches up, so the browser skips the intermediate +states but always receives the latest one. Calls of a function reach each browser in the order +they were made. Other frames, such as logs or other functions' calls, do not count toward the +limit and are never held back. Without the option, every call is queued for every browser. The +held calls belong to each browser's connection and go with it, so the function object holds no +state and may be a temporary. + +`app.forEachUI(function)` calls `function(ui)` on the calling thread, outside every WebFront lock, +for per-browser arguments or typed calls. It visits the browsers whose handlers had returned when +it started: unlike a broadcast, it skips a browser whose handlers are still running. As anywhere +else, `ui.document()` throws `std::logic_error` outside the server thread. ## HTTP gzip CPU work diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index fbc3827a..b3ebcc93 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,9 +3,11 @@ ## Unreleased - Add `app.broadcast(name, options)(...)` and `app.forEachUI(function)` (#401): calls to every browser - whose handshake completed, from any thread, with no table of browsers kept by the application. - `BroadcastOptions::maxPendingWrites` holds a call back for a browser that has that many frames - waiting, and keeps only the latest for it. Document the threads of callbacks and browser calls + whose `onUIStarted` handlers have returned, from any thread, with no table of browsers kept by the + application. A broadcast made while those handlers run follows what they sent. Each call is encoded + once into a frame shared by every browser. `BroadcastOptions::maxPendingWrites` holds a call back + for a browser that has that many calls of the function waiting, and keeps only the latest for it, + in the browser's connection. Document the threads of callbacks and browser calls ([threads](ASYNC_EXECUTION.md#threads)). No wire format change. - Add awaitable DOM events (#384): `co_await node.next(name, options)` completes with the value of diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp index 792e9c0f..3d7cf500 100644 --- a/include/webfront/Broadcast.hpp +++ b/include/webfront/Broadcast.hpp @@ -2,53 +2,35 @@ /// @brief A JavaScript function called on every connected browser (BasicWF::broadcast). #pragma once #include "http/WebSocket.hpp" +#include "weblink/CallFrame.hpp" #include "weblink/Messages.hpp" #include "weblink/WebLink.hpp" -#include #include -#include -#include -#include -#include #include -#include #include #include #include #include -#include namespace webfront { /// How a broadcast treats a browser that reads slower than it is written. struct BroadcastOptions { /// Without a value, every call is queued for every browser. With one, a call is queued for a browser only while - /// fewer frames than this await its network; otherwise it replaces the call held back for that browser, queued as - /// soon as fewer frames await: a slow browser skips intermediate calls but always receives the latest. Must be > 0. + /// fewer calls of this function than that await its network; otherwise it replaces the call of this function held + /// back for that browser, queued as soon as fewer await: a slow browser skips intermediate calls but always + /// receives the latest. Other frames, such as other functions' calls, do not count. Must be > 0. std::optional maxPendingWrites{}; }; -/// Calls a JavaScript function on each browser connected at the time of the call, fire-and-forget, from any thread. -/// The arguments are encoded once. Copies share the calls held back for slow browsers; the object must not outlive -/// its application. +/// Calls a JavaScript function on each started browser, fire-and-forget, from any thread. Each call encodes its +/// arguments once into a frame that every browser shares. The calls held back for a slow browser belong to its +/// connection, so the object holds no state: it may be a temporary, but must not outlive its application. template class Broadcast { - using Net = typename WebFront::Net; - using Link = WebLink; - using Message = std::shared_ptr>; - - // The call held back for one browser; guarded by State::mutex. Holds no strong reference to its link, so that - // no link can be destroyed, and wake its write waiters, under that mutex. - struct Slot { - std::weak_ptr link; - Message held; - bool sending = false; // a thread or a write waiter is queuing 'held' - }; - struct State { - std::mutex mutex; - std::map> slots; - }; + using Net = typename WebFront::Net; + using Link = WebLink; public: Broadcast(std::string_view functionName, WebFront& wf, BroadcastOptions options = {}) @@ -59,94 +41,20 @@ class Broadcast { void operator()(auto&&... ts) const { msg::FunctionCall command; - websocket::Frame frame{std::span(reinterpret_cast(command.header().data()), command.header().size())}; - command.encodeParameter(name, frame); - ((command.encodeParameter(std::forward(ts), frame)), ...); - command.setParametersCount(static_cast(1 + sizeof...(ts))); - const auto message = std::make_shared>(payload(frame)); - - // The links are shared while used, and released after the loop, outside every lock. - const auto links = webFront.connectedLinks(); - if (!maxPending) { - for (const auto& [id, link] : links) - link->sendFrame(websocket::Frame{std::span(*message)}); - return; - } - for (const auto& [id, link] : links) - offer(state, id, link, message, *maxPending); - forgetAbsent(links); + auto frame = detail::encodeCall(command, name, std::forward(ts)...); + // The sending may be deferred until a starting browser's onUIStarted handlers return: it owns what it uses. + webFront.sendToStartedLinks([shared = std::move(frame).share(), key = name, limit = maxPending](Link& link) { + if (limit) + link.sendLatest(shared, key, *limit); + else + link.sendFrame(shared); + }); } private: std::string name; WebFront& webFront; std::optional maxPending; - std::shared_ptr state = std::make_shared(); - - static std::vector payload(const websocket::Frame& frame) { - std::vector bytes; - const auto buffers = frame.toBuffers(); - for (auto buffer = std::next(buffers.begin()); buffer != buffers.end(); ++buffer) { // after the frame header - const auto* first = static_cast(buffer->data()); - bytes.insert(bytes.end(), first, first + buffer->size()); - } - return bytes; - } - - static void offer(const std::shared_ptr& state, WebLinkId id, const std::shared_ptr& link, Message message, std::size_t limit) { - std::shared_ptr slot; - { - std::scoped_lock lock{state->mutex}; - auto& entry = state->slots[id]; - // A reused identifier names another connection: what was held for the former one is dropped. - if (!entry || entry->link.owner_before(link) || link.owner_before(entry->link)) - entry = std::make_shared(Slot{link, nullptr, false}); - entry->held = std::move(message); - if (entry->sending) - return; // its sender will queue this newer call instead of the one it replaces - entry->sending = true; - slot = entry; - } - send(state, slot, link, limit); - } - - // Queues the held call while fewer than `limit` frames await the browser, then waits for room. Only one sender per - // slot runs at a time, so the browser receives the calls in order. - static void send(const std::shared_ptr& state, const std::shared_ptr& slot, const std::shared_ptr& link, std::size_t limit) { - for (;;) { - Message message; - { - std::scoped_lock lock{state->mutex}; - if (!slot->held) { - slot->sending = false; - return; - } - // The waiter runs outside the link's locks, on the thread whose write makes room, or when the link - // closes or is destroyed. - const auto waiter = link->whenWritesAtMost(limit - 1, [state, slot, weak = std::weak_ptr(link), limit] { - if (const auto alive = weak.lock()) { - send(state, slot, alive, limit); - return; - } - std::scoped_lock gone{state->mutex}; - slot->held = nullptr; - slot->sending = false; - }); - if (waiter != 0) - return; // the waiter now sends - message = std::move(slot->held); - } - // Outside the mutex: a write completing at once may wake the waiter of another broadcast. - link->sendFrame(websocket::Frame{std::span(*message)}); - } - } - - void forgetAbsent(const std::vector>>& links) const { - std::scoped_lock lock{state->mutex}; - std::erase_if(state->slots, [&](const auto& entry) { - return !entry.second->sending && std::ranges::find(links, entry.first, &std::pair>::first) == links.end(); - }); - } }; } // namespace webfront diff --git a/include/webfront/JsFunction.hpp b/include/webfront/JsFunction.hpp index 989c5fa1..b86eeeba 100644 --- a/include/webfront/JsFunction.hpp +++ b/include/webfront/JsFunction.hpp @@ -4,6 +4,7 @@ #pragma once #include "http/WebSocket.hpp" #include "tooling/HexDump.hpp" +#include "weblink/CallFrame.hpp" #include "weblink/WebLink.hpp" #include @@ -32,10 +33,7 @@ class JsFunction { auto operator()(auto&&... ts) { msg::FunctionCall command; - websocket::Frame frame{std::span(reinterpret_cast(command.header().data()), command.header().size())}; - command.encodeParameter(name, frame); - (((command.encodeParameter(std::forward(ts), frame))), ...); - command.setParametersCount(static_cast(1 + sizeof...(ts))); + auto frame = detail::encodeCall(command, name, std::forward(ts)...); // A browser whose connection closed is gone: a call to it is dropped, and a typed call fails. // The link is shared while used: a release on the server thread cannot destroy it meanwhile. diff --git a/include/webfront/JsFunctionSender.hpp b/include/webfront/JsFunctionSender.hpp index 180c00f2..f7e9143f 100644 --- a/include/webfront/JsFunctionSender.hpp +++ b/include/webfront/JsFunctionSender.hpp @@ -1,6 +1,7 @@ /// @brief Lazy, cancellable C++ to browser calls using C++26 sender completions. #pragma once #include "http/WebSocket.hpp" +#include "weblink/CallFrame.hpp" #include "weblink/PendingCalls.hpp" #include @@ -247,10 +248,7 @@ class JsFunctionSender { auto operator()(auto&&... arguments) const { msg::FunctionCall command; - websocket::Frame frame{std::span(reinterpret_cast(command.header().data()), command.header().size())}; - command.encodeParameter(name, frame); - (command.encodeParameter(std::forward(arguments), frame), ...); - command.setParametersCount(static_cast(1 + sizeof...(arguments))); + const auto frame = detail::encodeCall(command, name, std::forward(arguments)...); std::vector payload; payload.reserve(frame.size()); auto buffers = frame.toBuffers(); diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 18cb9017..96e07211 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -363,7 +363,7 @@ class BasicWF { }, httpServer.taskScope(), false); { std::scoped_lock lock{linksMutex}; - webLinks.emplace(id, Connection{link, std::this_thread::get_id(), false, false}); + webLinks.emplace(id, Connection{.link = link, .thread = std::this_thread::get_id(), .closed = false}); } link->start(); // registered first: every event it dispatches finds it }); @@ -455,15 +455,25 @@ class BasicWF { template friend class Broadcast; - /// The links of the browsers whose handshake completed and that were not reported closed, shared with the caller. - [[nodiscard]] std::vector>>> connectedLinks() const { - std::vector>>> links; - std::scoped_lock lock{linksMutex}; - links.reserve(webLinks.size()); - for (const auto& [id, connection] : webLinks) - if (connection.linked && !connection.closed) - links.emplace_back(id, connection.link); - return links; + /// Calls `send(link)` for each browser not reported closed whose onUIStarted handlers have returned: at once, on + /// the calling thread and outside every lock. For a browser whose handlers are running, `send` is kept and called + /// on the server thread as soon as they return, after what they sent and in the order of the calls. + void sendToStartedLinks(std::function&)> send) { + std::vector>> started; + { + std::scoped_lock lock{linksMutex}; + started.reserve(webLinks.size()); + for (auto& [id, connection] : webLinks) { + if (connection.closed) + continue; + if (connection.stage == Connection::Stage::started) + started.push_back(connection.link); + else if (connection.stage == Connection::Stage::starting) + connection.deferred.push_back(send); + } + } + for (const auto& link : started) + send(*link); } /// Internal DOM document storage, confined to the server thread. @@ -507,16 +517,24 @@ class BasicWF { return webLinks.size(); } - /// Calls `function(ui)` for each browser started (see onUIStarted) and not reported closed when the call starts. Callable from - /// any thread; `function` runs on the calling thread, outside every WebFront lock, so it may call the UI. + /// Calls `function(ui)` for each browser not reported closed whose onUIStarted handlers had returned when the call + /// started; a browser whose handlers are running is not visited. Callable from any thread; `function` runs on the + /// calling thread, outside every WebFront lock, so it may call the UI, but ui.document() needs the server thread. template Function> void forEachUI(Function&& function) { - for (const auto& [id, link] : connectedLinks()) + std::vector started; + { + std::scoped_lock lock{linksMutex}; + for (const auto& [id, connection] : webLinks) + if (!connection.closed && connection.stage == Connection::Stage::started) + started.push_back(id); + } + for (const auto id : started) std::invoke(function, UI{*this, id}); } - /// A function object calling `functionName` on every connected browser, fire-and-forget, from any thread; see - /// BroadcastOptions for slow browsers. Keep it between calls: it holds what it keeps back for them. + /// A function object calling `functionName` on every started browser, fire-and-forget, from any thread; see + /// BroadcastOptions for slow browsers. [[nodiscard]] Broadcast broadcast(std::string_view functionName, BroadcastOptions options = {}) { return Broadcast{functionName, *this, options}; } @@ -694,7 +712,9 @@ class BasicWF { std::shared_ptr> link; std::thread::id thread; bool closed; - bool linked; // its handshake completed: onUIStarted was called + enum class Stage { handshaking, starting, started }; + Stage stage = Stage::handshaking; // starting while its onUIStarted handlers run + std::vector&)>> deferred; // sendToStartedLinks() calls while starting }; std::map webLinks; WebLinkId idsCounter{0}; @@ -770,26 +790,66 @@ class BasicWF { return true; } + // After the onUIStarted handlers: the sends deferred meanwhile run in order, those arriving while they run too, + // and only then do new sends reach the browser directly. + void finishStarting(WebLinkId id) noexcept { + for (;;) { + std::vector&)>> deferred; + std::shared_ptr> link; + { + std::scoped_lock lock{linksMutex}; + const auto found = webLinks.find(id); + if (found == webLinks.end()) + return; + if (found->second.deferred.empty() || found->second.closed) { + found->second.deferred.clear(); + found->second.stage = Connection::Stage::started; + return; + } + deferred.swap(found->second.deferred); + link = found->second.link; + } + for (auto& send : deferred) { + try { + send(*link); + } catch (const std::exception& error) { + log::error("A broadcast to a starting browser failed: {}", error.what()); + } + } + } + } + void onEvent(WebLinkEvent event) { switch (event.code) { - case WebLinkEvent::Code::linked: + case WebLinkEvent::Code::linked: { { std::scoped_lock lock{linksMutex}; if (auto found = webLinks.find(event.webLinkId); found != webLinks.end()) - found->second.linked = true; + found->second.stage = Connection::Stage::starting; } + // Even when a handler throws: the browser must not keep collecting deferred sends. + struct Started { + BasicWF* app; + WebLinkId id; + ~Started() { + app->finishStarting(id); + } + } started{this, event.webLinkId}; if (uiStartedHandler) uiStartedHandler(UI{*this, event.webLinkId}); uiSubscribers->notify(UI{*this, event.webLinkId}); break; + } case WebLinkEvent::Code::closed: // Shutdown cancels the connections' writes, which then fail and report a closure: not a disconnection. if (httpServer.taskScope().stopRequested()) break; { std::scoped_lock lock{linksMutex}; - if (auto found = webLinks.find(event.webLinkId); found != webLinks.end()) + if (auto found = webLinks.find(event.webLinkId); found != webLinks.end()) { found->second.closed = true; + found->second.deferred.clear(); + } } if (auto found = domDocuments.find(event.webLinkId); found != domDocuments.end()) { found->second->close(); diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index 79af31ba..505f8741 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -2,11 +2,11 @@ /// @author Ambroise Leclerc /// @brief WebSocket protocol implementation - RFC6455 #pragma once -#include "BuffersPolicy.hpp" -#include "Encodings.hpp" -#include "../tooling/HexDump.hpp" #include "../networking/Tasks.hpp" +#include "../tooling/HexDump.hpp" #include "../tooling/Logger.hpp" +#include "BuffersPolicy.hpp" +#include "Encodings.hpp" #include #include @@ -14,11 +14,14 @@ #include #include #include +#include #include #include #include #include #include +#include +#include #include namespace webfront::websocket { @@ -167,6 +170,12 @@ struct Frame : public Header { borrowedBuffers.clear(); } + /// Owns the payload once, then shares the frame: several connections may write it, none copies it. + [[nodiscard]] std::shared_ptr share() && { + freeze(); + return std::make_shared(std::move(*this)); + } + /// @return size of added buffer size_t addBuffer(std::span buffer) { if (log::is(log::Debug)) // The dump is formatted before log::debug() tests the level. @@ -345,6 +354,34 @@ class WebSocket : public std::enable_shared_from_this> { void write(std::span data) { writeData(Frame(data)); } void write(std::span data, std::span data2) { writeData(Frame(data, data2)); } void write(Frame frame) { writeData(std::move(frame)); } + /// Queue a frame made by Frame::share(), without copying it. + void write(std::shared_ptr> frame) { + static_cast(enqueue(std::move(frame), std::numeric_limits::max())); + } + /// Queue a shared frame while fewer than `maxPending` frames of the same `key` await the network. Otherwise it + /// replaces the frame held back for that key, which is queued as soon as fewer do: the network skips intermediate + /// frames of a key but always gets the latest, and the frames of a key keep their order. Frames of other keys, + /// and the other writes, neither count nor are held. `maxPending` must be at least 1. + void writeLatest(std::shared_ptr> frame, std::string_view key, std::size_t maxPending) { + { + std::lock_guard lock(writeMutex); + auto group = latestGroups.find(key); + if (group == latestGroups.end()) + group = latestGroups.emplace(std::string(key), LatestGroup{}).first; + auto& latest = group->second; + latest.limit = maxPending; + if (latest.queued >= maxPending) { + latest.held = std::move(frame); + return; + } + latest.held = nullptr; // superseded, if a smaller limit held it back + ++latest.queued; + writeQueue.push_back({std::move(frame), &*group}); + if (writeQueue.size() > 1) + return; // the running writeFrames() task will get to it + } + spawn(writeFrames(this->shared_from_this())); + } /// Queue a droppable frame (a diagnostic) only while fewer than maxPending frames await the /// network, which may stop reading; false when refused. Other writes are never refused. [[nodiscard]] bool tryWrite(std::span data, std::span data2, std::size_t maxPending) { @@ -365,7 +402,18 @@ class WebSocket : public std::enable_shared_from_this> { std::function writeErrorHandler; std::function writtenHandler; mutable std::mutex writeMutex; - std::deque>> writeQueue; // the first frame is the one being written + // The frames of a writeLatest() key that are queued, and the one held back; guarded by writeMutex. + struct LatestGroup { + std::size_t queued = 0; + std::size_t limit = 0; + std::shared_ptr> held; + }; + std::map> latestGroups; // a key is forgotten once nothing is queued for it + struct PendingFrame { + std::shared_ptr> frame; + typename std::map>::value_type* group = nullptr; // for writeLatest() + }; + std::deque writeQueue; // the first frame is the one being written networking::TaskScope& taskScope; std::shared_ptr stopSource{std::make_shared()}; struct StopConnection { @@ -520,12 +568,14 @@ class WebSocket : public std::enable_shared_from_this> { void writeData(Frame frame) { static_cast(enqueue(std::move(frame), std::numeric_limits::max())); } bool enqueue(Frame frame, std::size_t maxPending) { - frame.freeze(); - auto pendingFrame = std::make_shared>(std::move(frame)); + return enqueue(std::move(frame).share(), maxPending); + } + + bool enqueue(std::shared_ptr> frame, std::size_t maxPending) { { std::lock_guard lock(writeMutex); if (writeQueue.size() >= maxPending) return false; - writeQueue.push_back(std::move(pendingFrame)); + writeQueue.push_back({std::move(frame)}); if (writeQueue.size() > 1) return true; // the running writeFrames() task will get to it } spawn(writeFrames(this->shared_from_this())); @@ -546,17 +596,31 @@ class WebSocket : public std::enable_shared_from_this> { { std::lock_guard lock(writeMutex); writeQueue.clear(); + latestGroups.clear(); // nothing will be written any more: the frames held back go too } onWriteFailed(error.code()); // reports the closure before the waiters for the queue resume if (writtenHandler) writtenHandler(); } } - // The frame to write, after having removed the written one if `written`; null when none remains. - std::shared_ptr> nextFrame(bool written) { + // The frame to write, after having removed the written one if `written`; null when none remains. A frame held + // back by writeLatest() is queued once its key has room. + std::shared_ptr> nextFrame(bool written) { std::lock_guard lock(writeMutex); - if (written) writeQueue.pop_front(); - return writeQueue.empty() ? nullptr : writeQueue.front(); + if (written) { + const auto group = writeQueue.front().group; + writeQueue.pop_front(); + if (group) { + auto& latest = group->second; + --latest.queued; + if (latest.held && latest.queued < latest.limit) { + ++latest.queued; + writeQueue.push_back({std::move(latest.held), group}); + } else if (latest.queued == 0) + latestGroups.erase(latestGroups.find(group->first)); + } + } + return writeQueue.empty() ? nullptr : writeQueue.front().frame; } /// The producer is detached before the diagnostic; the flag only gates the close sequence. diff --git a/include/webfront/weblink/CallFrame.hpp b/include/webfront/weblink/CallFrame.hpp new file mode 100644 index 00000000..777d37be --- /dev/null +++ b/include/webfront/weblink/CallFrame.hpp @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +/// @brief The frame of a C++ call to a JavaScript function, shared by every way of making one. +#pragma once +#include "../http/WebSocket.hpp" +#include "Messages.hpp" + +#include +#include +#include +#include +#include + +namespace webfront::detail { +/// The frame calling `name` with `arguments`. It borrows from `command` and from the arguments: send it while they +/// live, or own it first (Frame::freeze() or share()). +template +websocket::Frame encodeCall(msg::FunctionCall& command, const std::string& name, auto&&... arguments) { + websocket::Frame frame{std::span(reinterpret_cast(command.header().data()), command.header().size())}; + command.encodeParameter(name, frame); + (command.encodeParameter(std::forward(arguments), frame), ...); + command.setParametersCount(static_cast(1 + sizeof...(arguments))); + return frame; +} +} // namespace webfront::detail diff --git a/include/webfront/weblink/WebLink.hpp b/include/webfront/weblink/WebLink.hpp index f85d6511..c9da4d41 100644 --- a/include/webfront/weblink/WebLink.hpp +++ b/include/webfront/weblink/WebLink.hpp @@ -203,6 +203,14 @@ class WebLink { void sendCommand(const auto& message) { ws->write(message.header(), message.payload()); } void sendFrame(websocket::Frame frame) { ws->write(std::move(frame)); } + /// A frame shared with other links (websocket::Frame::share()), never copied. + void sendFrame(std::shared_ptr> frame) { + ws->write(std::move(frame)); + } + /// Keeps at most `maxPending` frames of `key` queued and only the latest of the others: see WebSocket::writeLatest. + void sendLatest(std::shared_ptr> frame, std::string_view key, std::size_t maxPending) { + ws->writeLatest(std::move(frame), key, maxPending); + } template std::pair> expectResult() { diff --git a/test/unit/BroadcastTests.cpp b/test/unit/BroadcastTests.cpp index 46846ac0..cf69eb23 100644 --- a/test/unit/BroadcastTests.cpp +++ b/test/unit/BroadcastTests.cpp @@ -96,6 +96,30 @@ SCENARIO("A broadcast keeps only the latest call for a browser with too many pen } } } + WHEN("states are broadcast through temporary function objects while the first one is still being written") { + app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-1"}); + app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-2"}); + app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-3"}); + while (Socket::completeDeferredWrites() != 0) { } + THEN("they share the browser's held call: the intermediate one was skipped") { + REQUIRE(Socket::wrote("temporary-1")); + REQUIRE(Socket::wrote("temporary-3")); + REQUIRE_FALSE(Socket::wrote("temporary-2")); + } + } + WHEN("states are broadcast while an event of another function is still being written") { + every(std::string{"event-0"}); + latest(std::string{"state-1"}); + latest(std::string{"state-2"}); + latest(std::string{"state-3"}); + while (Socket::completeDeferredWrites() != 0) { } + THEN("the event does not count toward the limit of the states") { + REQUIRE(Socket::wrote("event-0")); + REQUIRE(Socket::wrote("state-1")); + REQUIRE(Socket::wrote("state-3")); + REQUIRE_FALSE(Socket::wrote("state-2")); + } + } WHEN("events are broadcast without a limit while the first one is still being written") { every(std::string{"event-1"}); every(std::string{"event-2"}); @@ -115,8 +139,50 @@ SCENARIO("A broadcast keeps only the latest call for a browser with too many pen } SCENARIO("A broadcast limit must allow at least one pending write", "[broadcast]") { + testing::InjectableSocket::reset(); + OneBrowserNet::accepted = false; BasicWF app{WebFrontConfig{.port = "0"}}; REQUIRE_THROWS_AS(app.broadcast("onState", {.maxPendingWrites = 0}), std::invalid_argument); + app.shutdown(); + testing::InjectableSocket::reset(); +} + +SCENARIO("A browser receives a broadcast made while its onUIStarted handlers run after what they sent", "[broadcast]") { + using Socket = testing::InjectableSocket; + using App = BasicWF; + Socket::reset(); + OneBrowserNet::accepted = false; + App app{WebFrontConfig{.port = "0"}}; + auto onState = app.broadcast("onState", {.maxPendingWrites = 1}); + std::size_t visitedWhileStarting{}; + app.onUIStarted([&](App::UI ui) { + onState(std::string{"broadcast-while-starting"}); + app.forEachUI([&](App::UI) { + ++visitedWhileStarting; + }); + ui.jsFunction("initial")(std::string{"initial-state"}); + }); + Socket::receive(std::as_bytes(std::span(upgradeRequest))); + + WHEN("the browser completes its handshake") { + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + THEN("the handler's initial state comes first, then the broadcast") { + REQUIRE(Socket::wrote("initial-state")); + REQUIRE(Socket::wrote("broadcast-while-starting")); + REQUIRE(Socket::writtenAt("initial-state") < Socket::writtenAt("broadcast-while-starting")); + } + THEN("forEachUI skipped the browser while its handlers ran, and visits it afterwards") { + REQUIRE(visitedWhileStarting == 0); + std::size_t visited{}; + app.forEachUI([&](App::UI) { + ++visited; + }); + REQUIRE(visited == 1); + } + } + app.shutdown(); + Socket::reset(); } namespace { @@ -247,12 +313,18 @@ SCENARIO("Callbacks run one at a time on the server thread, and browser calls ar } WHEN("another thread calls each browser through forEachUI") { std::vector visited; + bool documentRefused = true; app.forEachUI([&](App::UI ui) { visited.push_back(ui.id()); ui.jsFunction("each")(std::string{"each-ui-" + std::to_string(ui.id())}); + try { + static_cast(ui.document()); + documentRefused = false; + } catch (const std::logic_error&) { } }); - THEN("each started browser is visited once and receives its call") { + THEN("each started browser is visited once and receives its call, but its document needs the server thread") { REQUIRE(visited.size() == 2); + REQUIRE(documentRefused); REQUIRE(first->receiveUntil("each-ui-")); REQUIRE(second->receiveUntil("each-ui-")); } diff --git a/test/unit/InjectableNetworking.hpp b/test/unit/InjectableNetworking.hpp index 68798e5a..9a505666 100644 --- a/test/unit/InjectableNetworking.hpp +++ b/test/unit/InjectableNetworking.hpp @@ -155,6 +155,14 @@ class InjectableSocket : public networking::SocketBaseMock { return std::search(written.begin(), written.end(), first, first + text.size()) != written.end(); } + /// Where the server first sent these bytes, or npos when it did not. + static std::size_t writtenAt(std::string_view text) { + std::lock_guard lock(mutex); + const auto* first = reinterpret_cast(text.data()); + const auto found = std::search(written.begin(), written.end(), first, first + text.size()); + return found == written.end() ? std::string_view::npos : static_cast(found - written.begin()); + } + static void failWrites(std::error_code error) { std::lock_guard lock(mutex); writeError = error; diff --git a/test/unit/WebSocketTests.cpp b/test/unit/WebSocketTests.cpp index fea4679f..ba388f42 100644 --- a/test/unit/WebSocketTests.cpp +++ b/test/unit/WebSocketTests.cpp @@ -66,6 +66,59 @@ SCENARIO("A failed write closes the WebSocket") { } } +SCENARIO("A WebSocket keeps only the latest frame of a key that has too many frames waiting") { + InjectableSocket::reset(); + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->start(); + InjectableSocket::deferWrites(); + const auto shared = [](std::string_view text) { + return websocket::Frame(text).share(); + }; + + GIVEN("another frame being written and a limit of one frame for the key") { + ws->write("other-frame"); + ws->writeLatest(shared("state-1"), "onState", 1); + const auto intermediate = shared("state-2"); + ws->writeLatest(intermediate, "onState", 1); + ws->writeLatest(shared("state-3"), "onState", 1); + + THEN("the other frame does not count, and the intermediate frame was released when replaced") { + REQUIRE(ws->pendingWrites() == 2); + REQUIRE(intermediate.use_count() == 1); + } + WHEN("the network completes the writes") { + while (InjectableSocket::completeDeferredWrites() != 0) { } + THEN("the first and latest frames are written in order, not the intermediate one") { + REQUIRE(InjectableSocket::wrote("other-frame")); + REQUIRE(InjectableSocket::wrote("state-1")); + REQUIRE(InjectableSocket::wrote("state-3")); + REQUIRE_FALSE(InjectableSocket::wrote("state-2")); + REQUIRE(ws->pendingWrites() == 0); + } + } + } + GIVEN("a frame held back behind a write that fails") { + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + ws->writeLatest(shared("state-1"), "onState", 1); + const auto held = shared("state-2"); + ws->writeLatest(held, "onState", 1); + REQUIRE(held.use_count() == 2); + + WHEN("the write fails") { + while (InjectableSocket::completeDeferredWrites() != 0) { } + THEN("the held frame is released with the queue") { + REQUIRE(held.use_count() == 1); + REQUIRE(ws->pendingWrites() == 0); + } + } + } + InjectableSocket::deferWrites(false); + while (InjectableSocket::completeDeferredWrites() != 0) { } + ws->stop(); + InjectableSocket::reset(); +} + SCENARIO("A WebSocket reassembles the messages a browser sends in several frames") { InjectableSocket::reset(); vector> binaryMessages; From 0dbc3065f3bb17120f41eceb85310d5d182ebffe Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:28:26 +0100 Subject: [PATCH 3/7] Name every field of a new connection, as GCC and Clang on Linux require [#401] --- include/webfront/WebFront.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 96e07211..16b7bcf2 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -363,7 +363,7 @@ class BasicWF { }, httpServer.taskScope(), false); { std::scoped_lock lock{linksMutex}; - webLinks.emplace(id, Connection{.link = link, .thread = std::this_thread::get_id(), .closed = false}); + webLinks.emplace(id, Connection{.link = link, .thread = std::this_thread::get_id(), .closed = false, .stage = Connection::Stage::handshaking, .deferred = {}}); } link->start(); // registered first: every event it dispatches finds it }); From cdf6909e024c7e804c0aa05e166ab6af04e3f55a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:36:40 +0100 Subject: [PATCH 4/7] Bound the broadcasts kept for a starting browser and document their order [#401] While a browser's onUIStarted handlers run, a broadcast was kept as a std::function for each call, whatever its limit: a slow handler under a 30 Hz broadcast accumulated every frame. The connection now keeps detail::BroadcastCall values, at most maxPendingWrites per function, the newest replacing the last one kept. The documentation states that a held call may follow later calls of other functions, and that calls of one function with different limits share the browser's queue, each applying its own; tests pin both. The include order of WebSocket.hpp is restored. --- docs/ASYNC_EXECUTION.md | 11 +++- docs/CHANGELOG.md | 2 +- include/webfront/Broadcast.hpp | 50 ++++++++++++++--- include/webfront/WebFront.hpp | 24 ++++---- include/webfront/http/WebSocket.hpp | 6 +- test/unit/BroadcastTests.cpp | 85 +++++++++++++++++++++++++++++ 6 files changed, 150 insertions(+), 28 deletions(-) diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index 35d61755..20eca931 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -219,9 +219,14 @@ its network. Otherwise the call is held back, and a newer call of that function held call is queued as soon as the browser catches up, so the browser skips the intermediate states but always receives the latest one. Calls of a function reach each browser in the order they were made. Other frames, such as logs or other functions' calls, do not count toward the -limit and are never held back. Without the option, every call is queued for every browser. The -held calls belong to each browser's connection and go with it, so the function object holds no -state and may be a temporary. +limit and are never held back. Order across functions is therefore not kept: a held call reaches +the browser after the frames written meanwhile. If the browser must see a state before a later +call of another function, send both through the same function or without a limit. Calls of one +function made with different limits share the browser's queue, and each call applies its own +limit. While a browser's handlers run, at most `maxPendingWrites` calls of the function are kept +for it, the newest replacing the last one kept. Without the option, every call is queued for +every browser. The held calls belong to each browser's connection and go with it, so the +function object holds no state and may be a temporary. `app.forEachUI(function)` calls `function(ui)` on the calling thread, outside every WebFront lock, for per-browser arguments or typed calls. It visits the browsers whose handlers had returned when diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index cbf5f759..092127ea 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,7 +7,7 @@ application. A broadcast made while those handlers run follows what they sent. Each call is encoded once into a frame shared by every browser. `BroadcastOptions::maxPendingWrites` holds a call back for a browser that has that many calls of the function waiting, and keeps only the latest for it, - in the browser's connection. Document the threads of callbacks and browser calls + in the browser's connection; such a held call may follow other functions' later calls. Document the threads of callbacks and browser calls ([threads](ASYNC_EXECUTION.md#threads)). No wire format change. - Stabilise the desktop-native tier (#416): before removing its temporary WebView2 profile, the automation owner diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp index 3d7cf500..b339e4d5 100644 --- a/include/webfront/Broadcast.hpp +++ b/include/webfront/Broadcast.hpp @@ -6,12 +6,16 @@ #include "weblink/Messages.hpp" #include "weblink/WebLink.hpp" +#include #include +#include +#include #include #include #include #include #include +#include namespace webfront { @@ -20,17 +24,50 @@ struct BroadcastOptions { /// Without a value, every call is queued for every browser. With one, a call is queued for a browser only while /// fewer calls of this function than that await its network; otherwise it replaces the call of this function held /// back for that browser, queued as soon as fewer await: a slow browser skips intermediate calls but always - /// receives the latest. Other frames, such as other functions' calls, do not count. Must be > 0. + /// receives the latest. Other frames, such as other functions' calls, do not count, and a held call may reach the + /// browser after them. Calls of one function with different limits share the browser's queue: each call applies + /// its own. Must be > 0. std::optional maxPendingWrites{}; }; +namespace detail { +/// One broadcast call: its frame, shared by every browser, and how to send it. +template +struct BroadcastCall { + std::shared_ptr> frame; + std::string function; + std::optional maxPendingWrites; + + void sendTo(auto& link) const { + if (maxPendingWrites) + link.sendLatest(frame, function, *maxPendingWrites); + else + link.sendFrame(frame); + } + + /// Keeps the call for a browser whose onUIStarted handlers run. With a limit, at most that many calls of the + /// function are kept: the newest replaces the last one kept, at the end of the calls. + void deferInto(std::vector& deferred) const { + if (maxPendingWrites) { + const auto sameFunction = [this](const BroadcastCall& call) { + return call.function == function; + }; + if (static_cast(std::ranges::count_if(deferred, sameFunction)) >= *maxPendingWrites) { + const auto last = std::ranges::find_if(deferred.rbegin(), deferred.rend(), sameFunction); + deferred.erase(std::next(last).base()); + } + } + deferred.push_back(*this); + } +}; +} // namespace detail + /// Calls a JavaScript function on each started browser, fire-and-forget, from any thread. Each call encodes its /// arguments once into a frame that every browser shares. The calls held back for a slow browser belong to its /// connection, so the object holds no state: it may be a temporary, but must not outlive its application. template class Broadcast { - using Net = typename WebFront::Net; - using Link = WebLink; + using Net = typename WebFront::Net; public: Broadcast(std::string_view functionName, WebFront& wf, BroadcastOptions options = {}) @@ -43,12 +80,7 @@ class Broadcast { msg::FunctionCall command; auto frame = detail::encodeCall(command, name, std::forward(ts)...); // The sending may be deferred until a starting browser's onUIStarted handlers return: it owns what it uses. - webFront.sendToStartedLinks([shared = std::move(frame).share(), key = name, limit = maxPending](Link& link) { - if (limit) - link.sendLatest(shared, key, *limit); - else - link.sendFrame(shared); - }); + webFront.sendToStartedLinks(detail::BroadcastCall{std::move(frame).share(), name, maxPending}); } private: diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 16b7bcf2..6dd6a08d 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -455,10 +455,10 @@ class BasicWF { template friend class Broadcast; - /// Calls `send(link)` for each browser not reported closed whose onUIStarted handlers have returned: at once, on - /// the calling thread and outside every lock. For a browser whose handlers are running, `send` is kept and called - /// on the server thread as soon as they return, after what they sent and in the order of the calls. - void sendToStartedLinks(std::function&)> send) { + /// Sends `call` to each browser not reported closed whose onUIStarted handlers have returned: at once, on the + /// calling thread and outside every lock. For a browser whose handlers are running, `call` is kept, within its + /// limit, and sent on the server thread as soon as they return, after what they sent and in the order of the calls. + void sendToStartedLinks(const detail::BroadcastCall& call) { std::vector>> started; { std::scoped_lock lock{linksMutex}; @@ -469,11 +469,11 @@ class BasicWF { if (connection.stage == Connection::Stage::started) started.push_back(connection.link); else if (connection.stage == Connection::Stage::starting) - connection.deferred.push_back(send); + call.deferInto(connection.deferred); } } for (const auto& link : started) - send(*link); + call.sendTo(*link); } /// Internal DOM document storage, confined to the server thread. @@ -713,8 +713,8 @@ class BasicWF { std::thread::id thread; bool closed; enum class Stage { handshaking, starting, started }; - Stage stage = Stage::handshaking; // starting while its onUIStarted handlers run - std::vector&)>> deferred; // sendToStartedLinks() calls while starting + Stage stage = Stage::handshaking; // starting while its onUIStarted handlers run + std::vector> deferred; // sendToStartedLinks() calls while starting }; std::map webLinks; WebLinkId idsCounter{0}; @@ -794,8 +794,8 @@ class BasicWF { // and only then do new sends reach the browser directly. void finishStarting(WebLinkId id) noexcept { for (;;) { - std::vector&)>> deferred; - std::shared_ptr> link; + std::vector> deferred; + std::shared_ptr> link; { std::scoped_lock lock{linksMutex}; const auto found = webLinks.find(id); @@ -809,9 +809,9 @@ class BasicWF { deferred.swap(found->second.deferred); link = found->second.link; } - for (auto& send : deferred) { + for (const auto& call : deferred) { try { - send(*link); + call.sendTo(*link); } catch (const std::exception& error) { log::error("A broadcast to a starting browser failed: {}", error.what()); } diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index 505f8741..4afacb23 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -2,11 +2,11 @@ /// @author Ambroise Leclerc /// @brief WebSocket protocol implementation - RFC6455 #pragma once -#include "../networking/Tasks.hpp" -#include "../tooling/HexDump.hpp" -#include "../tooling/Logger.hpp" #include "BuffersPolicy.hpp" #include "Encodings.hpp" +#include "../tooling/HexDump.hpp" +#include "../networking/Tasks.hpp" +#include "../tooling/Logger.hpp" #include #include diff --git a/test/unit/BroadcastTests.cpp b/test/unit/BroadcastTests.cpp index cf69eb23..385698e9 100644 --- a/test/unit/BroadcastTests.cpp +++ b/test/unit/BroadcastTests.cpp @@ -185,6 +185,91 @@ SCENARIO("A browser receives a broadcast made while its onUIStarted handlers run Socket::reset(); } +SCENARIO("A browser whose onUIStarted handlers run keeps only the latest calls within the limit", "[broadcast]") { + using Socket = testing::InjectableSocket; + using App = BasicWF; + Socket::reset(); + OneBrowserNet::accepted = false; + App app{WebFrontConfig{.port = "0"}}; + auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); + auto pair = app.broadcast("onState", {.maxPendingWrites = 2}); + auto every = app.broadcast("onEvent"); + app.onUIStarted([&](App::UI) { + latest(std::string{"starting-1"}); + every(std::string{"event-1"}); + latest(std::string{"starting-2"}); + every(std::string{"event-2"}); + latest(std::string{"starting-3"}); + }); + Socket::receive(std::as_bytes(std::span(upgradeRequest))); + + WHEN("the browser completes its handshake") { + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + THEN("only the latest limited call made meanwhile is sent, after the unlimited ones made before it") { + REQUIRE(Socket::wrote("starting-3")); + REQUIRE_FALSE(Socket::wrote("starting-1")); + REQUIRE_FALSE(Socket::wrote("starting-2")); + REQUIRE(Socket::wrote("event-1")); + REQUIRE(Socket::wrote("event-2")); + REQUIRE(Socket::writtenAt("event-2") < Socket::writtenAt("starting-3")); + } + } + WHEN("calls of one function use different limits while the first is still being written") { + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + Socket::deferWrites(); + Socket::completeDeferredWrites(); // the handshake acknowledgement + while (Socket::completeDeferredWrites() != 0) { } + pair(std::string{"pair-1"}); + pair(std::string{"pair-2"}); + latest(std::string{"single-3"}); + latest(std::string{"single-4"}); + pair(std::string{"pair-5"}); + while (Socket::completeDeferredWrites() != 0) { } + THEN("each call applies its own limit within the browser's queue of that function") { + REQUIRE(Socket::wrote("pair-1")); + REQUIRE(Socket::wrote("pair-2")); + REQUIRE_FALSE(Socket::wrote("single-3")); + REQUIRE_FALSE(Socket::wrote("single-4")); + REQUIRE(Socket::wrote("pair-5")); + REQUIRE(Socket::writtenAt("pair-2") < Socket::writtenAt("pair-5")); + } + Socket::deferWrites(false); + while (Socket::completeDeferredWrites() != 0) { } + } + app.shutdown(); + Socket::reset(); +} + +SCENARIO("A held broadcast reaches the browser after a later call of another function", "[broadcast]") { + using Socket = testing::InjectableSocket; + Socket::reset(); + OneBrowserNet::accepted = false; + BasicWF app{WebFrontConfig{.port = "0"}}; + auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); + auto every = app.broadcast("onReset"); + Socket::receive(std::as_bytes(std::span(upgradeRequest))); + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + Socket::deferWrites(); + Socket::completeDeferredWrites(); // the handshake acknowledgement + + WHEN("a state is held back, then another function is called") { + latest(std::string{"state-1"}); + latest(std::string{"state-2"}); + every(std::string{"reset-after-state-2"}); + while (Socket::completeDeferredWrites() != 0) { } + THEN("the other function's call is written before the held state, as documented") { + REQUIRE(Socket::writtenAt("reset-after-state-2") < Socket::writtenAt("state-2")); + } + } + Socket::deferWrites(false); + while (Socket::completeDeferredWrites() != 0) { } + app.shutdown(); + Socket::reset(); +} + namespace { using Stdnet = networking::TCPStdnet; From 3ce519ea10932dae9045948974915236728edd79 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:26:01 +0100 Subject: [PATCH 5/7] Document what forEachUI misses and keep an iterator per queued frame [#401] forEachUI skips a browser until it counts as started, a window that ends inside WebFront after the onUIStarted handlers return: a state sent that way can leave a starting browser on the handler's older state. The guide and the header now say so and send states through broadcast. The Threads section states that no call through a UI or a broadcast may still run when shutdown or destruction starts, and that connectedBrowsers() also counts connections that are not started yet or closed but not released. A queued writeLatest() frame keeps its group's iterator, so the group is erased without a lookup. The changelog entry is wrapped like the rest of the file. --- docs/ASYNC_EXECUTION.md | 16 ++++++++++++++++ docs/CHANGELOG.md | 5 +++-- include/webfront/Broadcast.hpp | 3 ++- include/webfront/WebFront.hpp | 4 +++- include/webfront/http/WebSocket.hpp | 13 +++++++------ 5 files changed, 31 insertions(+), 10 deletions(-) diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index 20eca931..689f95b7 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -186,6 +186,15 @@ and the server thread writes it. Only `ui.document()` and its nodes are confined thread. Register `cppFunction` callbacks and set `onUIStarted` before the server starts. You can add or remove subscriptions at any time. +"While the application lives" is stricter than "before it is destroyed": no such call may still +be running when `app.shutdown()` or the application's destructor starts. A `UI` or a broadcast +function object kept by a worker thread refers to the application. Stop that thread, or make sure +it no longer calls them, before shutting the application down. + +`app.connectedBrowsers()` counts every connection the server holds, including those still +completing their handshake or running their `onUIStarted` handlers, and those closed but not yet +released. It is not the number of browsers a broadcast or `forEachUI` reaches. + WebFront never holds one of its own locks while it calls application code. A thread can therefore call WebFront while it holds an application lock that a `cppFunction` callback also takes. The callback waits for that lock, and the call it waits for does not depend on the callback. What @@ -233,6 +242,13 @@ for per-browser arguments or typed calls. It visits the browsers whose handlers it started: unlike a broadcast, it skips a browser whose handlers are still running. As anywhere else, `ui.document()` throws `std::logic_error` outside the server thread. +So `forEachUI` does not keep a state in sync. Suppose a handler sends the state S0, and another +thread changes the state to S1 and calls `forEachUI` before the browser counts as started. That +browser is skipped and keeps S0 until the next change. The window ends inside WebFront, after the +handlers return, so no application lock can close it. Send states with `broadcast`: a call made +during that window reaches the browser after what its handlers sent. Keep `forEachUI` for calls +that a browser may miss while it starts, or that `onUIStarted` already covers. + ## HTTP gzip CPU work Cold gzip identity fallback is a sender backed by one lazy, owned worker per HTTP server. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8d8ba17d..ff6dda79 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,8 +7,9 @@ application. A broadcast made while those handlers run follows what they sent. Each call is encoded once into a frame shared by every browser. `BroadcastOptions::maxPendingWrites` holds a call back for a browser that has that many calls of the function waiting, and keeps only the latest for it, - in the browser's connection; such a held call may follow other functions' later calls. Document the threads of callbacks and browser calls - ([threads](ASYNC_EXECUTION.md#threads)). No wire format change. + in the browser's connection; such a held call may follow other functions' later calls. `forEachUI` + skips a starting browser, so states go through `broadcast`. Document the threads of callbacks and + browser calls ([threads](ASYNC_EXECUTION.md#threads)). No wire format change. - Stabilise the desktop-native tier (#416): before removing its temporary WebView2 profile, the automation owner waits up to 5 s for the browser processes it launched to exit and ends those still running (at once after a forced diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp index b339e4d5..ed0ddeed 100644 --- a/include/webfront/Broadcast.hpp +++ b/include/webfront/Broadcast.hpp @@ -64,7 +64,8 @@ struct BroadcastCall { /// Calls a JavaScript function on each started browser, fire-and-forget, from any thread. Each call encodes its /// arguments once into a frame that every browser shares. The calls held back for a slow browser belong to its -/// connection, so the object holds no state: it may be a temporary, but must not outlive its application. +/// connection, so the object holds no state: it may be a temporary. It refers to its application: no call may still +/// run when the application's shutdown() or destructor starts. template class Broadcast { using Net = typename WebFront::Net; diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 6dd6a08d..4a362b16 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -511,7 +511,8 @@ class BasicWF { } public: - /// The browsers connected now: a closed connection is released shortly after its closure. + /// The browsers connected now: a closed connection is released shortly after its closure. Counts connections still + /// in their handshake or onUIStarted handlers too: not the number of browsers a broadcast or forEachUI reaches. [[nodiscard]] std::size_t connectedBrowsers() const { std::scoped_lock lock{linksMutex}; return webLinks.size(); @@ -520,6 +521,7 @@ class BasicWF { /// Calls `function(ui)` for each browser not reported closed whose onUIStarted handlers had returned when the call /// started; a browser whose handlers are running is not visited. Callable from any thread; `function` runs on the /// calling thread, outside every WebFront lock, so it may call the UI, but ui.document() needs the server thread. + /// A starting browser that is skipped misses the call: send states that every browser must follow with broadcast(). template Function> void forEachUI(Function&& function) { std::vector started; diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index 4afacb23..6c9529ae 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -376,7 +376,7 @@ class WebSocket : public std::enable_shared_from_this> { } latest.held = nullptr; // superseded, if a smaller limit held it back ++latest.queued; - writeQueue.push_back({std::move(frame), &*group}); + writeQueue.push_back({std::move(frame), group}); if (writeQueue.size() > 1) return; // the running writeFrames() task will get to it } @@ -408,10 +408,11 @@ class WebSocket : public std::enable_shared_from_this> { std::size_t limit = 0; std::shared_ptr> held; }; - std::map> latestGroups; // a key is forgotten once nothing is queued for it + using LatestGroups = std::map>; + LatestGroups latestGroups; // a key is forgotten once nothing is queued for it struct PendingFrame { - std::shared_ptr> frame; - typename std::map>::value_type* group = nullptr; // for writeLatest() + std::shared_ptr> frame; + std::optional group{}; // for writeLatest(): valid while the frame is queued }; std::deque writeQueue; // the first frame is the one being written networking::TaskScope& taskScope; @@ -611,13 +612,13 @@ class WebSocket : public std::enable_shared_from_this> { const auto group = writeQueue.front().group; writeQueue.pop_front(); if (group) { - auto& latest = group->second; + auto& latest = (*group)->second; --latest.queued; if (latest.held && latest.queued < latest.limit) { ++latest.queued; writeQueue.push_back({std::move(latest.held), group}); } else if (latest.queued == 0) - latestGroups.erase(latestGroups.find(group->first)); + latestGroups.erase(*group); } } return writeQueue.empty() ? nullptr : writeQueue.front().frame; From c347fd02c3963d1b87b20c8a6551e2a0140057db Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:14:12 +0100 Subject: [PATCH 6/7] State which broadcast calls are ordered [#401] A broadcast returns once its call is queued or kept for every browser, so a call made after it on the same thread, or on a thread synchronized after it, follows it. Calls that overlap on several threads have no order, which the guide now says; sending under linksMutex would not order them and would hold a WebFront lock while the write starts. --- docs/ASYNC_EXECUTION.md | 9 ++++++--- include/webfront/WebFront.hpp | 3 +++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index 689f95b7..ca2a38e3 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -227,9 +227,12 @@ writes. A call is queued for a browser only while fewer calls of the same functi its network. Otherwise the call is held back, and a newer call of that function replaces it. The held call is queued as soon as the browser catches up, so the browser skips the intermediate states but always receives the latest one. Calls of a function reach each browser in the order -they were made. Other frames, such as logs or other functions' calls, do not count toward the -limit and are never held back. Order across functions is therefore not kept: a held call reaches -the browser after the frames written meanwhile. If the browser must see a state before a later +they were made: one call returns after it is queued, so a later call on the same thread, or on a +thread that the application synchronizes after it, follows it. Calls that overlap on several +threads have no order between them: serialize them in the application if it needs one. Other +frames, such as logs or other functions' calls, do not count toward the limit and are never held +back. Order across functions is therefore not kept: a held call reaches the browser after the +frames written meanwhile. If the browser must see a state before a later call of another function, send both through the same function or without a limit. Calls of one function made with different limits share the browser's queue, and each call applies its own limit. While a browser's handlers run, at most `maxPendingWrites` calls of the function are kept diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 4a362b16..72ec2a57 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -458,6 +458,9 @@ class BasicWF { /// Sends `call` to each browser not reported closed whose onUIStarted handlers have returned: at once, on the /// calling thread and outside every lock. For a browser whose handlers are running, `call` is kept, within its /// limit, and sent on the server thread as soon as they return, after what they sent and in the order of the calls. + /// Returns once `call` is queued or kept for every browser: a call that follows it (same thread, or synchronized + /// after it) comes after it. Overlapping calls are not ordered: holding linksMutex while writing would not order + /// them either, and would hold a WebFront lock while the write starts. void sendToStartedLinks(const detail::BroadcastCall& call) { std::vector>> started; { From f4d9636ea05438f72b6e874f7b63e932951d8fb7 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:29:43 +0100 Subject: [PATCH 7/7] Keep broadcasting past a browser whose send fails and document the limit's keys [#401] --- docs/ASYNC_EXECUTION.md | 18 ++++++++++++------ include/webfront/Broadcast.hpp | 3 ++- include/webfront/WebFront.hpp | 10 ++++++++-- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index ca2a38e3..012ca320 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -226,16 +226,22 @@ onState(stateJson); writes. A call is queued for a browser only while fewer calls of the same function than that await its network. Otherwise the call is held back, and a newer call of that function replaces it. The held call is queued as soon as the browser catches up, so the browser skips the intermediate -states but always receives the latest one. Calls of a function reach each browser in the order -they were made: one call returns after it is queued, so a later call on the same thread, or on a -thread that the application synchronizes after it, follows it. Calls that overlap on several +states but always receives the latest one. The calls that reach a browser arrive in the order they +were made (those that a newer call replaced never arrive): one call returns after it is queued, so +a later call on the same thread, or on a thread that the application synchronizes after it, +follows it. Calls that overlap on several threads have no order between them: serialize them in the application if it needs one. Other frames, such as logs or other functions' calls, do not count toward the limit and are never held back. Order across functions is therefore not kept: a held call reaches the browser after the frames written meanwhile. If the browser must see a state before a later -call of another function, send both through the same function or without a limit. Calls of one -function made with different limits share the browser's queue, and each call applies its own -limit. While a browser's handlers run, at most `maxPendingWrites` calls of the function are kept +call of another function, send both through the same function or without a limit. + +The limit is counted per function name, and the name is the only key: calls of +`ui.jsFunction(name)` with the same name are other frames and do not count. A browser holds at most +one call back per function. Calls of one function made with different limits share the browser's +queue and its single held call, and each call applies its own limit: a call that must be held +replaces the held call even if another limit held that one. A send that fails for one browser is +logged and does not prevent the others from receiving the call. While a browser's handlers run, at most `maxPendingWrites` calls of the function are kept for it, the newest replacing the last one kept. Without the option, every call is queued for every browser. The held calls belong to each browser's connection and go with it, so the function object holds no state and may be a temporary. diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp index ed0ddeed..ecabf617 100644 --- a/include/webfront/Broadcast.hpp +++ b/include/webfront/Broadcast.hpp @@ -26,7 +26,8 @@ struct BroadcastOptions { /// back for that browser, queued as soon as fewer await: a slow browser skips intermediate calls but always /// receives the latest. Other frames, such as other functions' calls, do not count, and a held call may reach the /// browser after them. Calls of one function with different limits share the browser's queue: each call applies - /// its own. Must be > 0. + /// its own, and a browser holds at most one call per function, which a call to hold replaces whatever limit held + /// the previous one. Only broadcasts count: `ui.jsFunction` calls of the same name are other frames. Must be > 0. std::optional maxPendingWrites{}; }; diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 72ec2a57..5e611cc6 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -475,8 +475,14 @@ class BasicWF { call.deferInto(connection.deferred); } } - for (const auto& link : started) - call.sendTo(*link); + // A browser whose send fails must not deprive the next ones of the call. + for (const auto& link : started) { + try { + call.sendTo(*link); + } catch (const std::exception& error) { + log::error("A broadcast to a browser failed: {}", error.what()); + } + } } /// Internal DOM document storage, confined to the server thread.