Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<R>(name)(...)` returns `std::future<R>`. 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.
Expand Down
94 changes: 94 additions & 0 deletions docs/ASYNC_EXECUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<R>(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<R>` 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<R>` 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.
Expand Down
9 changes: 9 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
94 changes: 94 additions & 0 deletions include/webfront/Broadcast.hpp
Original file line number Diff line number Diff line change
@@ -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 <algorithm>
#include <cstddef>
#include <iterator>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

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<std::size_t> maxPendingWrites{};
};

namespace detail {
/// One broadcast call: its frame, shared by every browser, and how to send it.
template <typename Net>
struct BroadcastCall {
std::shared_ptr<const websocket::Frame<Net>> frame;
std::string function;
std::optional<std::size_t> 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<BroadcastCall>& deferred) const {
if (maxPendingWrites) {
const auto sameFunction = [this](const BroadcastCall& call) {
return call.function == function;
};
if (static_cast<std::size_t>(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 <typename WebFront>
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<typename WebFront::BufferPolicy> command;
auto frame = detail::encodeCall<Net>(command, name, std::forward<decltype(ts)>(ts)...);
// The sending may be deferred until a starting browser's onUIStarted handlers return: it owns what it uses.
webFront.sendToStartedLinks(detail::BroadcastCall<Net>{std::move(frame).share(), name, maxPending});
}

private:
std::string name;
WebFront& webFront;
std::optional<std::size_t> maxPending;
};

} // namespace webfront
6 changes: 2 additions & 4 deletions include/webfront/JsFunction.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#pragma once
#include "http/WebSocket.hpp"
#include "tooling/HexDump.hpp"
#include "weblink/CallFrame.hpp"
#include "weblink/WebLink.hpp"

#include <algorithm>
Expand Down Expand Up @@ -32,10 +33,7 @@ class JsFunction {

auto operator()(auto&&... ts) {
msg::FunctionCall<typename WebFront::BufferPolicy> command;
websocket::Frame<typename WebFront::Net> frame{std::span(reinterpret_cast<const std::byte*>(command.header().data()), command.header().size())};
command.encodeParameter(name, frame);
(((command.encodeParameter(std::forward<decltype(ts)>(ts), frame))), ...);
command.setParametersCount(static_cast<std::uint8_t>(1 + sizeof...(ts)));
auto frame = detail::encodeCall<typename WebFront::Net>(command, name, std::forward<decltype(ts)>(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.
Expand Down
6 changes: 2 additions & 4 deletions include/webfront/JsFunctionSender.hpp
Original file line number Diff line number Diff line change
@@ -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 <cstddef>
Expand Down Expand Up @@ -247,10 +248,7 @@ class JsFunctionSender {

auto operator()(auto&&... arguments) const {
msg::FunctionCall<Policy> command;
websocket::Frame<Net> frame{std::span(reinterpret_cast<const std::byte*>(command.header().data()), command.header().size())};
command.encodeParameter(name, frame);
(command.encodeParameter(std::forward<decltype(arguments)>(arguments), frame), ...);
command.setParametersCount(static_cast<std::uint8_t>(1 + sizeof...(arguments)));
const auto frame = detail::encodeCall<Net>(command, name, std::forward<decltype(arguments)>(arguments)...);
std::vector<std::byte> payload;
payload.reserve(frame.size());
auto buffers = frame.toBuffers();
Expand Down
Loading
Loading