WebFront uses the C++26 sender vocabulary through networking::ex = ::stdnet::ex.
The current stdnet dependency selects stdexec; switching that implementation to
std::execution remains stdnet's responsibility. Network operations still come
from stdnet, rather than a standard networking library.
The implementation uses P2300 algorithms and environments, task, and the
P3149 structured scope facilities:
counting_scope, spawn, and join. Sender implementation headers enter only
through networking/SenderHeaders.hpp, which protects them from CEF macros.
The HTTP server owns one networking::TaskScope for the accept loop, HTTP
connections and upgraded WebSocket read/write loops. Each WebSocket also has its
own stop source, linked to the server's stop source. Closing one connection
therefore does not cancel other connections. The scope belongs to the server,
rather than a WebSocket: the final operation can release the socket before
releasing its scope association.
stop() can be called from another thread. It requests cancellation and stops
the context. After the thread running the context has returned, the owner calls
drain(): close the scope, request stop, wait for in-flight spawn() calls to
finish starting their senders, restart the context, and pump one
completion at a time until join() completes. Socket cleanup still runs on the
context thread. Joining tracks the complete operation lifetime, including its
destruction, and does not require unrelated context work to finish. If run_one()
reports no work while tasks remain, drain() throws std::logic_error instead
of spinning. The startup wait prevents a concurrent scope association from
being mistaken for a stalled task before its sender has started or queued work.
Sender startup and stop callbacks run without holding the spawn admission mutex,
so cleanup can attempt another spawn and receive a rejection.
It retains the join operation, allowing a low-level owner to
complete the external operation and retry. The scope still must be joined
before destruction. Application tasks must cooperate with cancellation;
shutdown cannot safely abandon a suspended coroutine and its captures. The destructor
uses a nonthrowing join path: it logs a stalled join once and retries with a short
sleep until the operations finish, keeping their owners alive. It can therefore
wait indefinitely for a non-cooperative operation, but does not spin or propagate
a drain exception. Explicit shutdown() keeps reporting the error so its caller
can complete the external operation and retry. An external completion in flight
can also make the explicit no-work check report a pending join. The server's own
workers (route handlers, file reads) are not such an operation: Server::drain()
(so shutdown()) waits while one of them runs or ended since the check, and reports
the error only for a scope that stays idle while they did nothing.
Low-level users constructing WebSocket::create or WebLink directly now pass
an external TaskScope&. That scope and the context must outlive their tasks;
stop/destroy the links and drain the scope before destroying their dependencies.
BasicWF does this for application users. An internal scope owned by a
WebSocket is deliberately avoided: its last task could destroy it before
releasing the scope association.
The accepted API adds an explicitly typed sender form alongside the existing future form:
auto result = co_await ui.jsFunctionSender<double>("Math.sqrt")(81);webfront::Task is the public coroutine type. app.spawn(task) or
ui.spawn(task) starts it on the server context, owns it until completion and
cancels it during application shutdown. No scheduler, scope or context is
needed. For example:
webfront::Task showSquareRoot(webfront::UI ui) {
auto result = co_await ui.jsFunctionSender<double>("Math.sqrt")(81);
co_await ui.jsFunctionSender("console.log")("sqrt(81) =", result);
}auto handle = app.spawn(showSquareRoot(ui));
// Later: cancel this task, leaving other tasks and the connection active.
handle.requestStop();ui.writesAtMost(limit) returns a sender completing once at most limit frames
wait for the network on that browser's connection, woken by the write that brings
them down (no polling), or at once when the browser is gone. A closing connection
or a released link also completes it, after the closure was reported; it observes
the task's stop token. It paces output to a browser that reads slower than written.
app.resumeAfter(duration) and ui.resumeAfter(duration) return a sender that
completes on the server context once the duration has elapsed. Awaited in a task,
it observes the task's stop token: TaskHandle::requestStop() or shutdown
completes it stopped at once, so a waiting coroutine never delays shutdown.
app.subscribeUIClosed(handler) calls the handler on the server thread when a
browser closes its connection or the connection fails (a failed write included),
for as long as the returned UISubscription lives; shutdown, which stops every
connection itself, notifies no handler. The connection is then released by a task
on the server context; a call made meanwhile on another thread keeps the link alive
until it returns (findLink shares it). Afterwards, an untyped jsFunction call to that UI is
dropped, a typed call returns a future that throws Browser connection closed,
a jsFunctionSender completes with an error when started, and addScript throws
ConnectionError. The 16-bit identifier of a released connection is reused after
65,536 later connections, but each connection also has a 64-bit generation, never reused,
that the UI carries with it (#428). It never crosses the wire.
A UI is an assignable value: it can be kept in a std::vector (removed with
std::erase_if) or a std::optional, and assigned. Two values are equal when they
belong to the same application and have the same id() and connection generation. A
value kept after its connection closed reaches no browser even once its identifier is
reused, and equals no later connection's value. Removing kept values in the
subscribeUIClosed handler is still advisable, to free them. A value
must not outlive its application, and assigning one is not atomic: a
container of values shared between threads needs a lock.
app.spawn(task) and ui.spawn(task) may be called from any thread while the
application object remains alive, including concurrently with stop/shutdown.
Coroutine bodies and their resumptions execute on the server context. Synchronize
object destruction with callers; pass owned arguments into coroutine functions.
TaskHandle::requestStop() is also callable from any thread.
Discarding a TaskHandle keeps its task running. A retained handle remains safe
after application destruction. app.stop() requests shutdown;
app.shutdown() also joins owned work before returning, and is called by the
destructor. A call rejected by stop/shutdown returns an already stopped handle without
starting the coroutine. A task accepted before shutdown can start and then be
cancelled. The stop callback is installed before scope association, and that
association decision determines acceptance. Call shutdown() outside server callbacks and after any external
callers of run()/runOne() have returned. Objects referenced by coroutine
parameters must outlive the task; pass values or owned captures when needed.
Use coroutine functions whose arguments own their data; a temporary capturing
coroutine lambda can leave its captures dangling after its closure is destroyed.
jsFunctionSender(name) defaults to void; use jsFunctionSender<R>(name)
when a return value is needed. Unhandled task errors are logged; ordinary
try/catch inside the coroutine handles browser failures. Cancellation
unwinds the coroutine rather than resuming beyond its co_await.
Calling the function object encodes and owns its arguments, including data from string views and spans; encoding errors throw at that point. Connecting the sender creates an operation. Starting it allocates a correlation ID and sends the frame. A sender can be connected repeatedly; each operation is a separate browser call. It holds weak connection references, so starting after the link is destroyed reports an error without accessing the application. Creating the function object still requires a live UI/application.
Completions are set_value(R) (or set_value() for void),
set_error(std::exception_ptr) for JavaScript errors, malformed returns or
disconnection, and set_stopped() for cancellation through the receiver's stop
token. co_await propagates a task's token. TaskHandle::requestStop() cancels
one application task; low-level users may still manage their own scope.
Completion runs on the
thread delivering the result, disconnection or stop request; callers must
synchronize shared application state. No scheduler hop is promised by this
sender itself. Application tasks spawned by WebFront resume on its server
context. Neither sender calls nor future calls have a delivery acknowledgement
for the write queue or an automatic response deadline. An unsuccessful write
that does not report closure can leave a call pending until disconnection;
sender waits can also be ended by task cancellation or application shutdown.
A delay can bound the wait: jsFunctionSender<R>(name).timeout(d) and jsFunction<R>(name).timeout(d), or
WebFrontConfig::callTimeout for every typed call (zero, the default, never expires). An expired call fails with a
BridgeError of code webfront.timeout, distinct from a disconnection; the connection stays open and the late response
is discarded. The delay runs from the start of the call on the server context, so a future.get() that blocks that
context also blocks its expiry.
Cancellation before start sends no frame. Cancellation after dispatch stops waiting locally; JavaScript already running continues, and its late response is discarded. No cancellation command is sent to the browser: only the browser can abandon a call to C++ (below). Cancellation removes the registry's reference to the receiver; the caller may destroy the operation inside its completion. The cancelled 32-bit ID remains reserved until the response or disconnection. Discarding a registration also checks its operation owner, so an obsolete completion cannot cancel a replacement using the same wire ID.
Result, disconnection and stop may race: exactly one terminal completion wins. A receiver may destroy the operation inside that completion. Registering an already-stopped token also completes safely, without dispatching.
ui.jsFunction<R>(name)(...) remains an eager std::future<R> call, with a delay but no
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.
A page abandons a call with webFront.cppFunction(name, {signal}) (an AbortSignal) or {timeout: milliseconds}
(default webFront.defaultTimeout, 0). The Promise rejects with the signal's reason (AbortError by default) or with an
Error of code webfront.timeout, and C++ is told: the ResultTask answering that call is asked to stop and sends
nothing. A synchronous callback already running finishes and its response is ignored.
A function registered with cppFunction may return a sender, in practice a coroutine webfront::ResultTask<R>
(ResultTask<void> for no value), instead of its result: the JavaScript Promise settles when it completes, not when
the callback returns. The callback itself runs at once on the server context and only builds the task; the task is
spawned in the server's scope and tracked by its connection. When the browser disconnects its tasks are asked to stop
and their late answers are dropped; shutting the application down stops and joins them. Completing stopped without a
stop request rejects with webfront.cancelled. Calls are correlated by the identifier JavaScript chose, so several can
be in flight per connection; a call that reuses an identifier still in flight is dropped on reception, for any function, without being run and without an answer (an answer could settle the wrong Promise). The answer is sent from the server
context, whichever thread the awaited operation completed on.
app.cppFunction("slowSquare", [&app](int value) -> webfront::ResultTask<int> {
co_await app.resumeAfter(std::chrono::seconds(1));
co_return value * value;
});WebFront runs its HTTP/WebSocket server on one thread: the thread show() or start() starts, or
the thread that calls run() or runOne(). An application that keeps its own loop instead of
giving its thread to show() follows host integration. That server thread is the only one that runs:
cppFunctioncallbacks,onUIStarted,subscribeUIStartedandsubscribeUIClosedhandlers;- DOM event callbacks and the bodies of tasks started with
app.spawnorui.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 ajsFunctionSender;ui.addScript,ui.pendingWrites,ui.writesAtMostandui.spawn;app.broadcast(name)(...),app.forEachUI,app.connectedBrowsers,app.spawn,app.stopandapp.requestClose.
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 ajsFunction<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.
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.
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.
Cold gzip identity fallback is a sender backed by one lazy, owned worker per HTTP server. The worker reads owned compressed bytes and fills preallocated output; it never calls filesystem providers or manipulates network objects. Completion resumes on the connection's I/O scheduler, where validation results enter the cache and HTTP headers/body are finalized. Bounded response leases survive through the network send, including cache-hit responses and HEAD consumers.
Stop closes admission; queued work without live consumers is skipped. An active decode runs to completion before cancellation is delivered locally. Peer disconnects are discovered at the subsequent write. After external run callers return, server drain joins CPU work before pumping and joining its existing task scope. No CPU task or encoded/decoded buffer is detached from its owner. See HTTP asset encoding for 503 backpressure, memory reservations and remaining synchronous provider-read and non-interruptible-decode limits.
A callback may return a webfront::Stream<T>, an ordered sequence of values of a bridge type:
app.cppFunction("progress", [](std::uint32_t steps) {
return webfront::Stream<std::uint32_t>{[steps](webfront::StreamWriter<std::uint32_t> out) -> webfront::ResultTask<void> {
for (std::uint32_t step = 0; step < steps; ++step)
co_await out.write(step);
}};
});for await (const step of webFront.cppStream("progress")(100)) show(step);writesends the values in order and suspends the producer while the connection has more thanStream::windowframes (16 by default, 0 to wait for each) awaiting the network.publishsends a state: an unsent one is replaced. A producer that only publishes must suspend on its own, as it runs on the server context.- The loop ends when
producereturns and throws what it throws, aBridgeErrorwith its code. break(the iterator'sreturn()), thesignalofcppStream(name, {signal})or the disconnection stop the producer through its stop token: its nextwritecompletes stopped. Frames already queued are discarded by the page. Shutdown stops and joins the producer.- The back-pressure is that of the network. Values received and not yet read accumulate in the page; with
{latest: true}only the last one is kept. - As for any cancelled call, the page keeps the identifier of an abandoned stream until the connection closes, a few bytes each: C++ sends nothing for it, so nothing would say when it is free again.
- The call is sent at the first
next(). A stream has no delay:defaultTimeoutdoes not apply to it.
A lost connection stays lost unless the page asks otherwise:
webFront.reconnect = true; // or {attempts: 20, delay: 250, maxDelay: 10000}
webFront.onDisconnect(error => showOffline());
webFront.onReconnect(() => resynchronize());
webFront.onConnectionChange(connection => {}); // "connecting", "connected", "reconnecting", "closed"- Waits double from
delayup tomaxDelay, each drawn between half of it and all of it. Afterattemptsfailures in a rowconnectionis"closed"for good.webFront.reconnect = nullstops trying. - Only a connection that was linked is opened again:
readystays the promise of the first one and rejects as before when that one fails.boundis renewed for each connection. - The calls and streams pending at the loss reject with
webfront.disconnected, as do those made while disconnected. Nothing is replayed: a call is not idempotent by default. - For C++ a reconnection is a new
UI:onUIStartedruns again, and what belonged to the former one (functions it was sent, documents, stores) is gone.ui.pageId()is the same for every connection of one page load, so an application may keep state under it and attach it again. The page chooses it: it is no authentication. Without that, or after the server restarted, the page gives its own state back, asexamples/life/react/does with its last snapshot. - The DOM interpreter empties the islands and connects again by itself.
- A page whose server closed it on purpose cannot tell that from a failure: it tries again, within
attempts.