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 AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ The HTTP server connections and the WebSocket read/write loops are coroutines (`

Filesystems implement `open(std::filesystem::path) -> std::optional<fs::File>` and are composed with `fs::Multi<>`; the first provider returning a file wins. `NativeDebugFS` is development-only and must not be presented as a production sandbox.

Bridge calls are asynchronous, and the two directions differ. `webFront.cppFunction(name)(...)` always returns a JavaScript Promise (also for `void` callbacks), so tests and examples must await or handle it. On the C++ side, only the untyped `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction<R>(name)(...)` returns a `std::future<R>`. `ui.jsFunctionSender<R>(name)(...)` owns encoded arguments and dispatches at sender start; co_await propagates the receiver stop token. Cancellation completes stopped locally and discards a late reply; JavaScript continues running. See `docs/ASYNC_EXECUTION.md` for lifetime and completion-thread rules. On missing functions, callback exceptions, malformed returns, and disconnects, a C++ future completes exceptionally (`get()` throws) and a JavaScript Promise rejects. Result types are limited to the bridge's scalar, string, tuple, numeric typed-array, packed `std::bitset<N>` and list types. A list is a `std::vector` of strings, tuples, typed arrays or bitsets (JavaScript: `webFront.list(items)` of strings, typed arrays or tuples, received as an `Array`; numbers go as typed arrays; a plain short array is a tuple that a `std::vector` destination also accepts); elements are homogeneous and lists do not nest. Bitsets use `Uint8Array` with exactly `ceil(N / 8)` bytes, least-significant bit first in each byte, and zero high padding bits; decoding rejects wrong types, sizes and padding. JavaScript must know the logical bit count from the application contract. Strings of 65,536 bytes or more use the `longString` code (32-bit length), chosen by the encoder; the only bound is the buffers policy's `maxMessageSize` (64 MiB by default, JavaScript's `maxMessageBytes`): beyond it C++ throws `std::length_error` when it encodes, which rejects the Promise when it is a callback's result, and JavaScript throws a `RangeError` before sending. Callback signatures are deduced for ordinary lambdas, function pointers, and `std::function`; generic lambdas and overloaded call operators need explicit `cppFunction<R, Args...>`. Do not write tests or documentation that present JavaScript calls as fire-and-forget, imply an untyped C++ call returns a value, or suggest that richer objects cross the bridge (only the types above do). Registered callback objects must outlive their registration through owned storage; never capture a forwarding-reference parameter by reference in a stored handler.
Bridge calls are asynchronous, and the two directions differ. `webFront.cppFunction(name)(...)` always returns a JavaScript Promise (also for `void` callbacks), so tests and examples must await or handle it. On the C++ side, only the untyped `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction<R>(name)(...)` returns a `std::future<R>`. `ui.jsFunctionSender<R>(name)(...)` owns encoded arguments and dispatches at sender start; co_await propagates the receiver stop token. Cancellation completes stopped locally and discards a late reply; JavaScript continues running. See `docs/ASYNC_EXECUTION.md` for lifetime and completion-thread rules. On missing functions, callback exceptions, malformed returns, and disconnects, a C++ future completes exceptionally (`get()` throws) and a JavaScript Promise rejects. Result types are limited to the bridge's scalar, string, tuple, numeric typed-array, packed `std::bitset<N>` and list types. A list is a `std::vector` of strings, tuples, typed arrays or bitsets (JavaScript: `webFront.list(items)` of strings, typed arrays or tuples, received as an `Array`; numbers go as typed arrays; a plain short array is a tuple that a `std::vector` destination also accepts); elements are homogeneous and lists do not nest. Bitsets use `Uint8Array` with exactly `ceil(N / 8)` bytes, least-significant bit first in each byte, and zero high padding bits; decoding rejects wrong types, sizes and padding. JavaScript must know the logical bit count from the application contract. Strings of 65,536 bytes or more use the `longString` code (32-bit length), chosen by the encoder; the only bound is the buffers policy's `maxMessageSize` (64 MiB by default, JavaScript's `maxMessageBytes`): beyond it C++ throws `std::length_error` when it encodes, which rejects the Promise when it is a callback's result, and JavaScript throws a `RangeError` before sending. A `cppFunction` callback may return a sender (a `webfront::ResultTask<R>` coroutine): the Promise settles when it completes, the browser's disconnection stops it and drops its answer, and shutdown joins it. Callback signatures are deduced for ordinary lambdas, function pointers, and `std::function`; generic lambdas and overloaded call operators need explicit `cppFunction<R, Args...>`. Do not write tests or documentation that present JavaScript calls as fire-and-forget, imply an untyped C++ call returns a value, or suggest that richer objects cross the bridge (only the types above do). Registered callback objects must outlive their registration through owned storage; never capture a forwarding-reference parameter by reference in a stored handler.

The embedded `WebFront.js` wire format and C++ `Messages.hpp` implementation must evolve together. Any protocol change requires encoding/decoding unit tests and a real-browser regression test.

Expand Down
18 changes: 18 additions & 0 deletions docs/ASYNC_EXECUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,24 @@ 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.

## Callbacks that answer later

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; reusing an identifier still in flight is refused. The answer is sent from the server
context, whichever thread the awaited operation completed on.

```cpp
app.cppFunction("slowSquare", [&app](int value) -> webfront::ResultTask<int> {
co_await app.resumeAfter(std::chrono::seconds(1));
co_return value * value;
});
```

## Threads

WebFront runs its HTTP/WebSocket server on one thread: the thread `show()` starts, or the thread
Expand Down
15 changes: 13 additions & 2 deletions docs/adr/ADR-004-appels-asynchrones-et-erreurs.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
| 2.3 | 2026-10-13 | Acceptée | Ambroise Leclerc | Contrat explicite de l’asymétrie et couverture séparée des échecs dans les deux directions. | [aa7457b](https://github.com/ambroise-leclerc/WebFront/commit/aa7457ba98b6cf8109838e98345cfcfaa52d82f0) |
| 2.4 | 2026-10-18 | Acceptée | Ambroise Leclerc | API de senders différée et annulation locale, en complément des futures. | [0657923](https://github.com/ambroise-leclerc/WebFront/commit/0657923697ef697019f2a898754740971e79a79f) |
| 2.5 | 2026-11-05 | Proposée | Ambroise Leclerc | Erreurs typées : un rejet porte un code (`BridgeError`, `Error.code`) en plus de son message (#458, ADR-020). | À renseigner après intégration. |
| 2.6 | 2026-11-05 | Proposée | Ambroise Leclerc | Réponse différée : un callback `cppFunction` peut renvoyer un sender ou un `ResultTask<R>` (#459, ADR-020). | À renseigner après intégration. |

## État et chronologie

**Acceptée** jusqu'à la version 2.4 ; l'extension 2.5 est **proposée**. Décision initiale : **2022-02-06** (version 1.0).
Dernière révision : **2026-11-05** (version 2.5).
**Acceptée** jusqu'à la version 2.4 ; les extensions 2.5 et suivantes sont **proposées**. Décision initiale : **2022-02-06** (version 1.0).
Dernière révision : **2026-11-05** (version 2.6).
Le présent texte expose la décision en vigueur ; le tableau retrace ses états antérieurs.

## Contexte
Expand Down Expand Up @@ -47,6 +48,16 @@ le code générique `webfront.error`. Les codes `webfront.notFound` (fonction ab
résultat mal formé), `webfront.disconnected` (connexion fermée, y compris pour un appel sur un pont non connecté) et
`webfront.cancelled` sont réservés à WebFront et distincts de ceux des applications, qui ne peuvent ni les construire
(`std::invalid_argument`) ni les envoyer depuis JavaScript.
Un callback qui renvoie un sender, un `webfront::ResultTask<R>` (`ex::task<R>`) ou `ResultTask<void>`, répond quand il
se termine : la Promise se résout avec la valeur encodée, se rejette s'il échoue (message et code) et, s'il se termine
arrêté sans que l'appel l'ait été, avec `webfront.cancelled`. Le travail est possédé par la portée du serveur et par la
connexion : la fermeture de la connexion demande son arrêt et écarte la réponse tardive sans rien envoyer, l'arrêt de
l'application l'arrête et le joint. La réponse est émise sur le contexte du serveur. Plusieurs appels différés d'une
connexion sont simultanés, chacun identifié par l'identifiant sur 16 bits que choisit JavaScript (au plus 65 535 en
vol : au-delà, `Too many outstanding WebFront calls` rejette côté navigateur) ; un identifiant déjà en vol est refusé
(`webfront.malformed`, « already in use ») sans toucher à l'appel en cours. Une exception levée avant le retour du
sender rejette aussitôt. Aucun délai automatique : un sender qui ne se termine jamais laisse la Promise en attente
jusqu'à la déconnexion.
Les callbacks enregistrés sont possédés par le stockage de l’application. Les signatures
ordinaires sont déduites ; les lambdas génériques et opérateurs surchargés utilisent
`cppFunction<R, Args...>` explicitement.
Expand Down
19 changes: 6 additions & 13 deletions docs/adr/ADR-020-services-systeme.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,9 @@ différentes.

- Le serveur HTTP ne traite que `GET` et `HEAD` ; les écritures passent par le pont, par morceaux séquentiels
(modèle de l'installation `wf`, ADR-010).
- Les chaînes du pont sont bornées à 65 535 octets par leur en-tête (longueur sur 16 bits, `maxStringBytes`) ; ce
n'est pas une limite de WebSocket. Les tableaux typés ont une longueur sur 32 bits et un message est borné à 64 Mio
par défaut (`BuffersPolicy`). Le pont ne transporte ni liste de chaînes ni liste d'enregistrements, et un rejet ne
porte qu'un message (ADR-003, ADR-004).
- `cppFunction` encode immédiatement le résultat du callback et `webfront::Task` (`ex::task<void>`) n'est pas un
template : un callback ne peut pas différer sa réponse jusqu'à la fin d'une coroutine, d'un dialogue ou d'une lecture.
- Le pont transporte les chaînes jusqu'à la taille de message de la politique (`longString`, 32 bits), des listes de
chaînes, de tuples et de tableaux typés, des erreurs à code (`BridgeError`) et des réponses différées
(`cppFunction` acceptant un `webfront::ResultTask<R>`), depuis l'épique #448 (ADR-003, ADR-004).
- Un fournisseur (ADR-002) ne voit que `open(path)` et rend un `fs::File` ; il ne voit ni la requête (`Range`), ni la
connexion, ni des jetons émis à l'exécution. Le serveur copie le fichier entier dans la réponse avant l'envoi
(`readFile`) : la mémoire croît avec la taille du fichier, ce qui interdit les gros fichiers sur cible embarquée.
Expand Down Expand Up @@ -305,25 +302,21 @@ lève).

### 5. Appels depuis C++ et depuis JavaScript

Esquisse ; les noms ne sont pas contractuels avant l'implémentation. `cppFunction` répond aujourd'hui dès le retour
du callback : la forme ci-dessous suppose la **réponse différée** des préalables (un callback qui renvoie une tâche à
résultat, `ex::task<R>`). La Promise JavaScript se résout quand la tâche se termine, avec la valeur encodée ; elle se
Esquisse ; les noms de services ne sont pas contractuels avant l'implémentation. `cppFunction` accepte un callback qui
renvoie une tâche à résultat (`webfront::ResultTask<R>`, alias de `ex::task<R>`) et répond à la fin de la tâche. La Promise JavaScript se résout quand la tâche se termine, avec la valeur encodée ; elle se
rejette si la tâche lève (message et code d'erreur typé) ou se termine arrêtée (code d'annulation), et à la
déconnexion, qui demande l'arrêt de la tâche et écarte sa réponse.

```cpp
webfront::services::Files files{app, {.roots = {{"Données", dataDirectory}}, .backends = Backends::automatic}};

app.cppFunction("importer", [&](App::UI ui) -> ex::task<int> {
app.cppFunction("importer", [&](App::UI ui) -> webfront::ResultTask<int> {
auto picked = co_await files.open(ui, {.title = "Importer", .filters = {{"Images", {"*.png", "*.jpg"}}}});
for (auto& grant : picked) load(grant.path()); // C++ : autorisation complète
co_return static_cast<int>(picked.size()); // résout la Promise de la page
});
```

Sans cette extension, une application peut seulement lancer le travail avec `ui.spawn(task)` et répondre aussitôt ;
la Promise se résout alors avant la fin du dialogue, et le résultat comme les erreurs doivent revenir par un appel
`ui.jsFunction` séparé. Cette forme dégradée ne sert pas de contrat aux services.

```ts
import { files } from "@webfront/services/files";
Expand Down
2 changes: 1 addition & 1 deletion docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md).
| [ADR-001](ADR-001-coeur-cpp23-header-only.md) | A header-only C++23 core embedded in the application | Accepted | 2020-04-19 | 1.5 — 2026-10-13 |
| [ADR-002](ADR-002-systemes-de-fichiers-composables.md) | An abstract, composable filesystem as the foundation for portability | Accepted | 2023-03-16 | 2.6 — 2026-11-04 |
| [ADR-003](ADR-003-protocole-binaire-et-bornes.md) | A shared, typed and bounded binary protocol | Accepted through 1.13; 1.14 to 1.18 proposed | 2022-02-06 | 1.18 — 2026-11-05 |
| [ADR-004](ADR-004-appels-asynchrones-et-erreurs.md) | Asynchronous calls with deliberately asymmetric contracts | Accepted through 2.4; 2.5 proposed | 2022-02-06 | 2.5 — 2026-11-05 |
| [ADR-004](ADR-004-appels-asynchrones-et-erreurs.md) | Asynchronous calls with deliberately asymmetric contracts | Accepted through 2.4; 2.5 and 2.6 proposed | 2022-02-06 | 2.6 — 2026-11-05 |
| [ADR-005](ADR-005-evolution-reseau-asio-stdnet.md) | From standalone ASIO to stdnet: anticipating standard networking without blocking progress | Accepted through 3.1; 3.2 proposed | 2022-01-21 | 3.2 — 2026-10-26 |
| [ADR-006](ADR-006-taches-structurees-et-arret.md) | Owning, cancelling and joining every task | Accepted | 2026-10-13 | 2.1 — 2026-10-25 |
| [ADR-007](ADR-007-frontends-explicites.md) | Explicit frontend selection and a shared lifecycle contract | Accepted | 2026-05-31 | 1.10 — 2026-10-20 |
Expand Down
108 changes: 108 additions & 0 deletions include/webfront/DeferredCalls.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/// @brief The JavaScript calls a C++ callback has not answered yet, per browser connection.
#pragma once

#include "Task.hpp"
#include "weblink/Messages.hpp"

#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <mutex>
#include <set>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>

namespace webfront::detail {

template <class... Values>
struct single_value {
static_assert(sizeof...(Values) <= 1, "A deferred callback must complete with at most one value");
using type = void;
};
template <class Value>
struct single_value<Value> {
using type = std::decay_t<Value>;
};
template <class... Alternatives>
struct only_completion {
static_assert(sizeof...(Alternatives) == 1, "A deferred callback must have exactly one kind of value completion");
};
template <class Alternative>
struct only_completion<Alternative> {
using type = typename Alternative::type;
};

/// A callback answers later when it returns a sender (a `ResultTask<R>` among them) instead of the result itself.
template <typename Result>
concept deferred_result = !std::is_void_v<Result> && networking::ex::sender<std::remove_cvref_t<Result>>;

/// The value the sender completes with (`void` for none).
template <typename Sender>
using deferred_value_t = typename networking::ex::value_types_of_t<std::remove_cvref_t<Sender>, networking::ex::env<>, single_value, only_completion>;

/// The calls of one connection that a callback answers later, with the tasks that will answer them. The connection's
/// closure stops every one of them, and a call whose identifier is still in flight cannot be started again.
class DeferredCalls {
public:
/// Claims the identifier of a call (zero, which asks for no answer, is never in flight) and returns the key of its
/// entry, or 0 when the connection closed or a call of that identifier has not been answered yet.
[[nodiscard]] std::uint64_t reserve(msg::CallId callId) {
std::lock_guard lock(mutex);
if (closed || (callId != 0 && !inFlight.insert(callId).second))
return 0;
const auto key = ++lastKey;
tasks.emplace(key, std::optional<TaskHandle>{});
return key;
}

/// Remembers the task that will answer the reserved call, to stop it if the connection closes.
void attach(std::uint64_t key, TaskHandle handle) {
bool stop = false;
{
std::lock_guard lock(mutex);
if (auto found = tasks.find(key); found != tasks.end())
found->second = handle;
stop = closed;
}
if (stop)
handle.requestStop();
}

/// The call is answered, or dropped: its identifier can be used again.
void finish(msg::CallId callId, std::uint64_t key) {
std::lock_guard lock(mutex);
inFlight.erase(callId);
tasks.erase(key);
}

/// The connection closed: every unanswered call is stopped and its late answer will be dropped.
void close() {
std::vector<TaskHandle> stopping;
{
std::lock_guard lock(mutex);
closed = true;
for (const auto& [key, handle] : tasks)
if (handle)
stopping.push_back(*handle);
}
for (const auto& handle : stopping)
handle.requestStop();
}

[[nodiscard]] std::size_t pending() const {
std::lock_guard lock(mutex);
return tasks.size();
}

private:
mutable std::mutex mutex;
std::set<msg::CallId> inFlight;
std::map<std::uint64_t, std::optional<TaskHandle>> tasks;
std::uint64_t lastKey = 0;
bool closed = false;
};

} // namespace webfront::detail
5 changes: 5 additions & 0 deletions include/webfront/Task.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
namespace webfront {
using Task = networking::Task;

/** @brief A coroutine with a result: the type a callback registered with `cppFunction` returns to answer later.
* `co_return value;` resolves the JavaScript Promise with the value; an exception rejects it. */
template <typename Result>
using ResultTask = networking::ex::task<Result>;

/** @brief Requests cancellation of one spawned task. Discarding the handle does not stop it. */
class TaskHandle {
std::shared_ptr<networking::ex::inplace_stop_source> source{std::make_shared<networking::ex::inplace_stop_source>()};
Expand Down
Loading
Loading