diff --git a/AGENTS.md b/AGENTS.md index 79c98b9f..a2b209af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,7 +102,7 @@ The HTTP server connections and the WebSocket read/write loops are coroutines (` Filesystems implement `open(std::filesystem::path) -> std::optional` 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(name)(...)` returns a `std::future`. `ui.jsFunctionSender(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` 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`. 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(name)(...)` returns a `std::future`. `ui.jsFunctionSender(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` 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` 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`. 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. diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index c65cd70b..fda1f33b 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -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` +(`ResultTask` 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 { + 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 diff --git a/docs/adr/ADR-004-appels-asynchrones-et-erreurs.md b/docs/adr/ADR-004-appels-asynchrones-et-erreurs.md index 54f090f1..9095f663 100644 --- a/docs/adr/ADR-004-appels-asynchrones-et-erreurs.md +++ b/docs/adr/ADR-004-appels-asynchrones-et-erreurs.md @@ -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` (#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 @@ -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` (`ex::task`) ou `ResultTask`, 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` explicitement. diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 77ba6914..d0f18a9d 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -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`) 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`), 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. @@ -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`). 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`, alias de `ex::task`) 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 { +app.cppFunction("importer", [&](App::UI ui) -> webfront::ResultTask { 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(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"; diff --git a/docs/adr/README.md b/docs/adr/README.md index 2fe8c51e..77ba8383 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -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 | diff --git a/include/webfront/DeferredCalls.hpp b/include/webfront/DeferredCalls.hpp new file mode 100644 index 00000000..3c6a3b23 --- /dev/null +++ b/include/webfront/DeferredCalls.hpp @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::detail { + +template +struct single_value { + static_assert(sizeof...(Values) <= 1, "A deferred callback must complete with at most one value"); + using type = void; +}; +template +struct single_value { + using type = std::decay_t; +}; +template +struct only_completion { + static_assert(sizeof...(Alternatives) == 1, "A deferred callback must have exactly one kind of value completion"); +}; +template +struct only_completion { + using type = typename Alternative::type; +}; + +/// A callback answers later when it returns a sender (a `ResultTask` among them) instead of the result itself. +template +concept deferred_result = !std::is_void_v && networking::ex::sender>; + +/// The value the sender completes with (`void` for none). +template +using deferred_value_t = typename networking::ex::value_types_of_t, 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{}); + 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 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 inFlight; + std::map> tasks; + std::uint64_t lastKey = 0; + bool closed = false; +}; + +} // namespace webfront::detail diff --git a/include/webfront/Task.hpp b/include/webfront/Task.hpp index 550f9ef6..7b3db523 100644 --- a/include/webfront/Task.hpp +++ b/include/webfront/Task.hpp @@ -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 +using ResultTask = networking::ex::task; + /** @brief Requests cancellation of one spawned task. Discarding the handle does not stop it. */ class TaskHandle { std::shared_ptr source{std::make_shared()}; diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 8986b956..a3af8561 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -6,6 +6,7 @@ #include "BridgeError.hpp" #include "Broadcast.hpp" +#include "DeferredCalls.hpp" #include "dom/Document.hpp" #include "frontend/Frontend.hpp" #include "http/HTTPServer.hpp" @@ -354,6 +355,32 @@ websocket::Frame makeFailureFrame(msg::CallId callId, const std::exception& return frame; } +/// A self-contained return message carrying `value`, or the failure of its encoding (a string over the message size). +template +websocket::Frame makeValueFrame(msg::CallId callId, const Value& value) { + msg::FunctionReturn result; + result.setCallId(callId); + websocket::Frame frame{std::span(reinterpret_cast(result.header().data()), result.header().size())}; + try { + if constexpr (!std::is_void_v) + result.encodeParameter(value, frame); + frame.freeze(); + return frame; + } catch (const std::exception& error) { + return makeFailureFrame(callId, error); + } +} + +/// A return message without value. +template +websocket::Frame makeVoidFrame(msg::CallId callId) { + msg::FunctionReturn result; + result.setCallId(callId); + websocket::Frame frame{std::span(reinterpret_cast(result.header().data()), result.header().size())}; + frame.freeze(); + return frame; +} + template auto makeCppFunctionResponder(Callable&& callable) { return [callable = std::forward(callable)](std::span data, auto& link, msg::CallId callId, auto&&... caller) mutable { @@ -833,7 +860,9 @@ class BasicWF { */ template bool cppFunction(std::string functionName, auto&& function) { - if constexpr (detail::takes_caller::value) + if constexpr (detail::deferred_result) + return registerDeferred(std::move(functionName), std::forward(function)); + else if constexpr (detail::takes_caller::value) return registerWithCaller(std::move(functionName), std::forward(function)); else { auto callable = detail::makeCppFunctionHandler(std::forward(function)); @@ -966,6 +995,116 @@ class BasicWF { released.swap(webLinks); } + /// A callback that returns a sender (a ResultTask among them) answers when it completes, not when it returns: the + /// call is owned by the connection (its closure stops the work and drops the late answer) and by the server scope + /// (shutdown stops and joins it). The answer is sent on the server context. + template + bool registerDeferred(std::string functionName, auto&& function) { + // Naming the value type checks the contract at registration: one value at most, one kind of value completion. + using DeferredValue [[maybe_unused]] = detail::deferred_value_t; + const auto start = [this](auto invoke, WebLink& link, msg::CallId callId, UI caller) { + this->template startDeferred(std::move(invoke), link, callId, caller); + }; + if constexpr (detail::takes_caller::value) { + auto handler = registerDeferredHandler(std::forward(function)); + return cppFunctions + .try_emplace(std::move(functionName), + [start, handler](std::span data, WebLink& link, msg::CallId callId, UI caller) mutable { + start([&] { return handler(data, caller); }, link, callId, caller); + }) + .second; + } else { + auto handler = detail::makeCppFunctionHandler(std::forward(function)); + return cppFunctions + .try_emplace(std::move(functionName), + [start, handler](std::span data, WebLink& link, msg::CallId callId, UI caller) mutable { + start([&] { return handler(data); }, link, callId, caller); + }) + .second; + } + } + + template + auto registerDeferredHandler(auto&& function) { + return detail::makeCppFunctionHandler(detail::adaptCaller(std::forward(function))); + } + + /// Calls the callback, then hands the sender it returned to a task that answers when it completes. + template + void startDeferred(Invoke invoke, WebLink& link, msg::CallId callId, UI caller) { + std::optional> sender; + try { + sender.emplace(invoke()); + } catch (const std::exception& error) { + if (callId != 0) + link.sendFrame(detail::makeFailureFrame(callId, error)); + return; + } catch (...) { + if (callId != 0) + link.sendFrame(detail::makeFailureFrame(callId, std::runtime_error{"Unknown C++ exception"})); + return; + } + const auto [calls, generation] = deferredCallsOf(caller); + const auto key = calls ? calls->reserve(callId) : 0; + if (key == 0) { + // The connection closed, or the browser reused the identifier of a call that is still running. + if (callId != 0) + link.sendBridgeError(callId, calls ? "The call identifier is already in use" : "Browser connection closed", + calls ? bridge_code::malformed : bridge_code::disconnected); + return; + } + const auto handle = spawn(respondLater(caller, generation, calls, callId, key, std::move(*sender))); + if (handle.stopRequested()) { + // The server refused the task (it is shutting down): it never runs, so nothing would release the identifier. + calls->finish(callId, key); + return; + } + calls->attach(key, handle); + } + + std::pair, WebLinkGeneration> deferredCallsOf(const UI& caller) const { + std::scoped_lock lock{linksMutex}; + const auto found = webLinks.find(caller.id()); + if (found == webLinks.end() || found->second.closed) + return {nullptr, WebLinkGeneration{0}}; + return {found->second.deferredCalls, found->second.generation}; + } + + /// Awaits the sender of a deferred callback and sends its result, its failure, or `webfront.cancelled` when it + /// completed stopped by something other than this call's own stop request. When that request was made (the + /// connection closed, the application is stopping) nothing is sent: nobody is left to read it. + template + Task respondLater(UI caller, WebLinkGeneration generation, std::shared_ptr calls, msg::CallId callId, std::uint64_t key, Sender sender) { + struct Finish { + detail::DeferredCalls& calls; + msg::CallId callId; + std::uint64_t key; + ~Finish() { calls.finish(callId, key); } + } finish{*calls, callId, key}; + const auto token = co_await networking::ex::read_env(networking::ex::get_stop_token); + std::optional> answer; + try { + auto stoppable = networking::ex::stopped_as_error( + std::move(sender), std::make_exception_ptr(detail::makeBridgeError(bridge_code::cancelled, "The C++ callback was cancelled"))); + // One answer frame whether the sender completes with a value or without: the message is built where it completes. + auto framed = networking::ex::then(std::move(stoppable), [callId](auto&&... values) -> websocket::Frame { + if constexpr (sizeof...(values) == 0) + return detail::makeVoidFrame(callId); + else + return detail::makeValueFrame(callId, values...); + }); + answer.emplace(co_await std::move(framed)); + } catch (const std::exception& error) { + answer.emplace(detail::makeFailureFrame(callId, error)); + } catch (...) { + answer.emplace(detail::makeFailureFrame(callId, std::runtime_error{"Unknown C++ exception"})); + } + if (token.stop_requested() || callId == 0) + co_return; + if (const auto link = findLink(caller.id(), generation)) + link->sendFrame(std::move(*answer)); + } + template bool registerWithCaller(std::string functionName, auto&& function) { auto adapted = detail::adaptCaller(std::forward(function)); @@ -1001,6 +1140,7 @@ class BasicWF { std::vector> deferred; // sendToStartedLinks() calls while starting bool viewAssociated = false; // presented the launch secret of an embedded view bool loopbackPeer = false; // peer address was the loopback (read only with trustLoopbackClients) + std::shared_ptr deferredCalls = std::make_shared(); // calls a callback answers later }; std::map webLinks; WebLinkId idsCounter{0}; @@ -1150,14 +1290,20 @@ class BasicWF { if (httpServer.taskScope().stopRequested()) break; std::optional closedGeneration; + std::shared_ptr stoppedCalls; { std::scoped_lock lock{linksMutex}; if (auto found = webLinks.find(event.webLinkId); found != webLinks.end()) { found->second.closed = true; found->second.deferred.clear(); closedGeneration = found->second.generation; + stoppedCalls = found->second.deferredCalls; } } + // The calls a callback has not answered are stopped and their late answers dropped, outside the lock: a + // stop callback runs on this thread. + if (stoppedCalls) + stoppedCalls->close(); // Outside linksMutex: dropping the grants destroys their contexts, whose destructors may use the application. if (closedGeneration) readBinding->close(*closedGeneration); // its read URLs stop working at once diff --git a/include/webfront/weblink/WebLink.hpp b/include/webfront/weblink/WebLink.hpp index 02063f78..5e82d9e5 100644 --- a/include/webfront/weblink/WebLink.hpp +++ b/include/webfront/weblink/WebLink.hpp @@ -149,8 +149,9 @@ class WebLink { auto message = event.reason.empty() ? std::string("Browser connection closed") : std::string("Browser connection closed: ") + event.reason; rejectPending(std::make_exception_ptr(detail::disconnectedError(message))); // The WebSocket reports its closure once, and never when it is stopped by the server or the link. + const auto queue = writerQueue; // the event may release this link eventsHandler({WebLinkEvent::Code::closed, id}); - wakeAllWriters(); // after the closure is known: nothing will be written any more + wakeAll(*queue); // after the closure is known: nothing will be written any more }); }); @@ -189,21 +190,21 @@ class WebLink { /// the thread that writes the frame bringing them down, and returns its identifier for cancelWrites(). The waiters /// are also called when the connection closes or the link is destroyed: nothing is left to wait for. std::uint64_t whenWritesAtMost(std::size_t limit, std::function ready) { - std::lock_guard lock(writersMutex); + std::lock_guard lock(writerQueue->mutex); if (ws->pendingWrites() <= limit) return 0; - const auto waiter = ++lastWriter; - writers.emplace(waiter, Writer{limit, std::move(ready)}); + const auto waiter = ++writerQueue->last; + writerQueue->writers.emplace(waiter, Writer{limit, std::move(ready)}); return waiter; } /// Forgets a waiter of whenWritesAtMost() that was not called yet. void cancelWrites(std::uint64_t waiter) { std::function removed; // destroyed outside the lock - std::lock_guard lock(writersMutex); - if (auto found = writers.find(waiter); found != writers.end()) { + std::lock_guard lock(writerQueue->mutex); + if (auto found = writerQueue->writers.find(waiter); found != writerQueue->writers.end()) { removed = std::move(found->second.ready); - writers.erase(found); + writerQueue->writers.erase(found); } } @@ -354,36 +355,43 @@ class WebLink { std::size_t limit; std::function ready; }; - std::mutex writersMutex; - std::map writers; // waiters of whenWritesAtMost(), by identifier - std::uint64_t lastWriter = 0; + /// The waiters of whenWritesAtMost(), by identifier. Shared, so that the closure handler can wake them after its event + /// released the link (an application whose scheduler runs the release at once destroys the link inside that handler). + struct WriterQueue { + std::mutex mutex; + std::map writers; + std::uint64_t last = 0; + }; + std::shared_ptr writerQueue = std::make_shared(); // The queue shrank: the waiters it now satisfies are removed, then called outside the lock. void wakeWriters() { std::vector> ready; { - std::lock_guard lock(writersMutex); - if (writers.empty()) + std::lock_guard lock(writerQueue->mutex); + if (writerQueue->writers.empty()) return; const auto queued = ws->pendingWrites(); - for (auto writer = writers.begin(); writer != writers.end();) { + for (auto writer = writerQueue->writers.begin(); writer != writerQueue->writers.end();) { if (queued > writer->second.limit) { ++writer; continue; } ready.push_back(std::move(writer->second.ready)); - writer = writers.erase(writer); + writer = writerQueue->writers.erase(writer); } } for (auto& call : ready) call(); } - void wakeAllWriters() { + void wakeAllWriters() { wakeAll(*writerQueue); } + + static void wakeAll(WriterQueue& queue) { std::map ready; { - std::lock_guard lock(writersMutex); - ready.swap(writers); + std::lock_guard lock(queue.mutex); + ready.swap(queue.writers); } for (auto& [waiter, writer] : ready) writer.ready(); diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index a03da594..f9799092 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -29,7 +29,7 @@ list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp D list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp 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 HostTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) +list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp) list(APPEND TESTS_LIST FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) list(APPEND TESTS_LIST MddlogLoggerTests.cpp MddlogTransportTests.cpp) @@ -60,7 +60,7 @@ target_compile_definitions(tests PRIVATE WEBFRONT_HOST_PROBE="$ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace webfront; +using Socket = testing::InjectableSocket; + +namespace { + +const std::string deferredUpgradeRequest = "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"; + +struct DeferredNet : 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{}; + }); + } +}; + +using DeferredApp = BasicWF; + +/// The operations the test completes by hand, by the name of the call that awaits them. +struct DeferredGates { + std::vector open; + void release(std::size_t index) { open.at(index).complete({}, 0); } + void stopOne(std::size_t index) { open.at(index).stop(); } +}; +DeferredGates deferredGates; + +testing::ManualSender deferredGate() { + return testing::ManualSender([](testing::ManualSender::Completion completion) { deferredGates.open.push_back(std::move(completion)); }); +} + +ResultTask echoLater(std::string value) { + co_await deferredGate(); + co_return "answered:" + value; +} + +ResultTask failLater(std::string) { + co_await deferredGate(); + throw BridgeError("quota:exceeded", "the disk is full"); +} + +ResultTask voidLater() { + co_await deferredGate(); +} + +ResultTask watchedLater(std::weak_ptr* observed, std::shared_ptr lifetime) { + *observed = lifetime; + co_await deferredGate(); + co_return "late"; +} + +/// A call from the browser: the function, its identifier and one string argument. +std::vector deferredCallMessage(const std::string& name, msg::CallId callId, const std::string& argument = "") { + msg::FunctionCall<> message; + message.setCallId(callId); + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(name, frame); + if (!argument.empty()) + message.encodeParameter(argument, frame); + frame.freeze(); + return testing::clientFrame(testing::messagePayload(frame)); +} + +/// Resets the shared mock socket before the application accepts its connection. +struct DeferredFresh { + DeferredFresh() { + Socket::reset(); + deferredGates.open.clear(); + DeferredNet::accepted = false; + } +}; + +struct DeferredBrowser { + DeferredFresh fresh; + DeferredApp app{WebFrontConfig{.port = "0"}}; + + void connect() { + Socket::receive(std::as_bytes(std::span(deferredUpgradeRequest))); + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + } + void call(const std::string& name, msg::CallId callId, const std::string& argument = "") { + Socket::receive(deferredCallMessage(name, callId, argument)); + } + ~DeferredBrowser() { + app.shutdown(); + Socket::reset(); + deferredGates.open.clear(); + } +}; + +} // namespace + +SCENARIO("A callback that returns a task answers when the task completes", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.connect(); + + WHEN("the browser calls it") { + browser.call("echoLater", 5, "x"); + THEN("nothing is answered while the task is suspended") { + REQUIRE(deferredGates.open.size() == 1); + REQUIRE_FALSE(Socket::wrote("answered:x")); + } + AND_WHEN("the task completes") { + deferredGates.release(0); + THEN("its value is sent as the result of the call") { + REQUIRE(Socket::wrote("answered:x")); + } + } + } + WHEN("the call asks for no answer") { + browser.call("echoLater", 0, "x"); + deferredGates.release(0); + THEN("nothing is sent") { + REQUIRE_FALSE(Socket::wrote("answered:x")); + } + } +} + +SCENARIO("A deferred callback that fails rejects the call with its code", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction("failLater", &failLater); + browser.connect(); + browser.call("failLater", 9, "x"); + deferredGates.release(0); + THEN("the code and the message are sent") { + REQUIRE(Socket::wrote("quota:exceeded")); + REQUIRE(Socket::wrote("the disk is full")); + } +} + +SCENARIO("A deferred callback that throws before returning its task rejects the call at once", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction, std::string>("throwsNow", [](const std::string&) -> ResultTask { + throw BridgeError("early", "refused before it started"); + }); + browser.connect(); + browser.call("throwsNow", 4, "x"); + THEN("the rejection is sent without waiting") { + REQUIRE(Socket::wrote("early")); + REQUIRE(Socket::wrote("refused before it started")); + } +} + +SCENARIO("A deferred callback whose operation is stopped rejects the call as cancelled", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.connect(); + browser.call("echoLater", 3, "x"); + deferredGates.stopOne(0); + THEN("the cancellation code is sent") { + REQUIRE(Socket::wrote(std::string(bridge_code::cancelled))); + } +} + +SCENARIO("A callback may be a task without result", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction("voidLater", &voidLater); + browser.connect(); + Socket::discardWrites(); + const auto before = Socket::discardedBytes(); + browser.call("voidLater", 2); + REQUIRE(Socket::discardedBytes() == before); + deferredGates.release(0); + THEN("a return without value is sent") { + REQUIRE(Socket::discardedBytes() > before); + } +} + +SCENARIO("A callback taking the caller can answer later", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction, DeferredApp::UI, std::string>("withCaller", [](DeferredApp::UI, const std::string& value) -> ResultTask { + return echoLater(value); + }); + browser.connect(); + browser.call("withCaller", 6, "who"); + deferredGates.release(0); + THEN("the browser receives the value") { + REQUIRE(Socket::wrote("answered:who")); + } +} + +SCENARIO("Several deferred calls of one connection are answered independently", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.connect(); + browser.call("echoLater", 1, "first"); + browser.call("echoLater", 2, "second"); + browser.call("echoLater", 3, "third"); + REQUIRE(deferredGates.open.size() == 3); + deferredGates.release(2); + deferredGates.release(0); + THEN("each is answered when it completes, whatever the order") { + REQUIRE(Socket::wrote("answered:third")); + REQUIRE(Socket::wrote("answered:first")); + REQUIRE_FALSE(Socket::wrote("answered:second")); + deferredGates.release(1); + REQUIRE(Socket::wrote("answered:second")); + REQUIRE(Socket::writtenAt("answered:third") < Socket::writtenAt("answered:first")); + } +} + +SCENARIO("A call identifier that is still in flight cannot be reused", "[deferred]") { + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.connect(); + browser.call("echoLater", 7, "first"); + browser.call("echoLater", 7, "again"); + THEN("the second call is rejected and the first one still completes") { + REQUIRE(deferredGates.open.size() == 1); + REQUIRE(Socket::wrote("already in use")); + deferredGates.release(0); + REQUIRE(Socket::wrote("answered:first")); + } + AND_WHEN("it was answered") { + deferredGates.release(0); + browser.call("echoLater", 7, "later"); + THEN("the identifier is free again") { + REQUIRE(deferredGates.open.size() == 2); + } + } +} + +SCENARIO("The disconnection of the browser stops its deferred calls and drops their answers", "[deferred]") { + DeferredBrowser browser; + std::weak_ptr observed; + browser.app.cppFunction>("watched", [&observed]() -> ResultTask { + return watchedLater(&observed, std::make_shared(1)); + }); + browser.connect(); + browser.call("watched", 8); + REQUIRE_FALSE(observed.expired()); + + WHEN("the connection closes while the call is pending") { + Socket::fail(std::make_error_code(std::errc::connection_reset)); + THEN("the work is stopped and destroyed, and no answer is sent") { + REQUIRE(observed.expired()); + REQUIRE_FALSE(Socket::wrote("late")); + REQUIRE_FALSE(Socket::wrote(std::string(bridge_code::cancelled))); + } + } +} + +SCENARIO("Shutting the application down joins its pending deferred calls", "[deferred]") { + DeferredBrowser browser; + std::weak_ptr observed; + browser.app.cppFunction>("watched", [&observed]() -> ResultTask { + return watchedLater(&observed, std::make_shared(1)); + }); + browser.connect(); + browser.call("watched", 8); + REQUIRE_FALSE(observed.expired()); + browser.app.shutdown(); + THEN("the pending work is gone when shutdown returns") { + REQUIRE(observed.expired()); + REQUIRE_FALSE(Socket::wrote("late")); + } +} + +SCENARIO("The identifiers of in-flight calls are claimed once and released on finish", "[deferred]") { + detail::DeferredCalls calls; + const auto key = calls.reserve(5); + REQUIRE(key != 0); + REQUIRE(calls.reserve(5) == 0); + REQUIRE(calls.reserve(0) != 0); // zero asks for no answer: never in flight + REQUIRE(calls.reserve(0) != 0); + WHEN("the call finishes, as a task the server refused does at once") { + calls.finish(5, key); + THEN("the identifier can be claimed again") { + REQUIRE(calls.reserve(5) != 0); + } + } + WHEN("the connection closes") { + calls.close(); + THEN("nothing can be claimed any more") { + REQUIRE(calls.reserve(6) == 0); + } + } +} diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index 324413ec..3dd22c7e 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -329,7 +329,19 @@ class BrowserIntegrationTest { using Record = tuple>; + static ResultTask deferredEcho(TestWF* app, string value, int delayMs) { + co_await app->resumeAfter(chrono::milliseconds(delayMs)); + co_return "deferred:" + value; + } + static ResultTask deferredFailure(TestWF* app) { + co_await app->resumeAfter(chrono::milliseconds(20)); + throw BridgeError("late:failure", "rejected after a delay"); + } + void registerListCallbacks() { + webFront->cppFunction("deferredEcho", [this](string value, int delayMs) { return deferredEcho(webFront, std::move(value), delayMs); }); + webFront->cppFunction("deferredFailure", [this]() { return deferredFailure(webFront); }); + webFront->cppFunction("listEcho", [](const vector& value) { return value; }); diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index f7b6b98c..3ed831ce 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -368,6 +368,23 @@ describe('WebFront browser integration', () => { expect(error.code).toBe('webfront.disconnected'); }); + it('resolves a Promise when a C++ coroutine finishes later, and rejects it with its code', async () => { + const started = performance.now(); + await expectAsync(webFront.cppFunction('deferredEcho')('x', 150)).toBeResolvedTo('deferred:x'); + expect(performance.now() - started).toBeGreaterThanOrEqual(100); + const error = await webFront.cppFunction('deferredFailure')().then(() => null, failure => failure); + expect(error.code).toBe('late:failure'); + expect(error.message).toBe('rejected after a delay'); + }); + + it('answers concurrent deferred calls in the order they finish', async () => { + const echo = webFront.cppFunction('deferredEcho'); + const order = []; + const calls = [300, 50, 150].map(delay => echo(String(delay), delay).then(value => order.push(value))); + await Promise.all(calls); + expect(order).toEqual(['deferred:50', 'deferred:150', 'deferred:300']); + }); + it('rejects missing functions and C++ exceptions', async () => { await expectAsync(webFront.cppFunction('missingCppFunction')()) .toBeRejectedWithError(/was not found/);