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..012ca320 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -164,6 +164,100 @@ 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. + +"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 +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 `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. 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}); +// 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 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. 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. + +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. + +`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. + +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 d734c588..ff6dda79 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- Add `app.broadcast(name, options)(...)` and `app.forEachUI(function)` (#401): calls to every browser + 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; 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 exit, which also keeps the status of an exit that completes meanwhile), then retries files pending deletion for 2 s. diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp new file mode 100644 index 00000000..ecabf617 --- /dev/null +++ b/include/webfront/Broadcast.hpp @@ -0,0 +1,94 @@ +// 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/CallFrame.hpp" +#include "weblink/Messages.hpp" +#include "weblink/WebLink.hpp" + +#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 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, 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, 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{}; +}; + +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. 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; + +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; + 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(detail::BroadcastCall{std::move(frame).share(), name, maxPending}); + } + +private: + std::string name; + WebFront& webFront; + std::optional maxPending; +}; + +} // 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 742a3387..5e611cc6 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 = link, .thread = std::this_thread::get_id(), .closed = false, .stage = Connection::Stage::handshaking, .deferred = {}}); } link->start(); // registered first: every event it dispatches finds it }); @@ -449,6 +452,39 @@ class BasicWF { private: template friend class BasicUI; + template + friend class Broadcast; + + /// 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; + { + 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) + call.deferInto(connection.deferred); + } + } + // 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. std::shared_ptr domState(WebLinkId id) { std::shared_ptr> link; @@ -484,12 +520,36 @@ 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(); } + /// 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; + { + 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 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}; + } + /// Whether a C++ function of that name is registered. [[nodiscard]] bool hasCppFunction(std::string_view functionName) const { return cppFunctions.contains(functionName); @@ -663,6 +723,9 @@ class BasicWF { std::shared_ptr> link; 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 }; std::map webLinks; WebLinkId idsCounter{0}; @@ -738,21 +801,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 (const auto& call : deferred) { + try { + call.sendTo(*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.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..6c9529ae 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -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,19 @@ 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; + }; + using LatestGroups = std::map>; + LatestGroups latestGroups; // a key is forgotten once nothing is queued for it + struct PendingFrame { + 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; std::shared_ptr stopSource{std::make_shared()}; struct StopConnection { @@ -520,12 +569,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 +597,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(*group); + } + } + 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 new file mode 100644 index 00000000..385698e9 --- /dev/null +++ b/test/unit/BroadcastTests.cpp @@ -0,0 +1,489 @@ +// 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("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"}); + 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]") { + 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(); +} + +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; + +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; + 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, but its document needs the server thread") { + REQUIRE(visited.size() == 2); + REQUIRE(documentRefused); + 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 d02fd04e..b2e730d9 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/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; 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'); });