diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index fed4365a..f0680827 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- HTTP server: dynamic routes (#454, ADR-020 prerequisite). `addRoute(prefix, handler)` on the application answers `GET` and + `HEAD` under an absolute prefix with a reply produced at run time (`http::RouteReply`: status, headers, exact or unknown + length, and a body read chunk by chunk). The handler and the reads run on a worker thread of the server, one chunk of + `emissionBufferSize` bytes at a time with back-pressure, so memory does not depend on the body's size; a closing connection + or a server stop ends the response. The route precedes the file providers and cannot cover `WebFront.js`; overlapping + prefixes are refused at registration; other methods get 405. Headers that could split the response, or that the server + owns (`Content-Length`, `Connection`, `Transfer-Encoding`), turn into a 500. Unencoded files of known size + (`fs::File::knownSize()`) are streamed the same way, so serving a large file no longer loads it into memory; encoded + files are still read whole. `Range` (#455) and the binding to a connection (#469) follow. + - Embedded frontends: `alert`, `confirm`, `prompt` and `beforeunload` (`beforeunload` is not handled under WKWebView, see `docs/FRONTENDS.md`; #452, ADR-020 rule 6). WKWebView implements the three `WKUIDelegate` panel methods (an `NSAlert` sheet of the window; without them these calls did nothing); WebKitGTK, CEF and WebView2 keep their engine's dialogs. A shared test injection (`frontend/ScriptDialogs.hpp`) answers the dialogs in each diff --git a/docs/HTTP_ASSETS.md b/docs/HTTP_ASSETS.md index f065affc..6815a478 100644 --- a/docs/HTTP_ASSETS.md +++ b/docs/HTTP_ASSETS.md @@ -30,6 +30,24 @@ coding nor identity is acceptable, or a custom provider uses an unsupported codi (such as Brotli) the client does not accept, the server returns HTTP 406. Custom codings can still be served directly to accepting clients. +## Streaming and dynamic routes (#454) + +An unencoded file whose size is known (`fs::File::knownSize()`: embedded data, or a native file on a seekable stream) is +announced with its `Content-Length` and sent in chunks of `emissionBufferSize` bytes, each read on the server's worker +thread and sent before the next is read: memory does not depend on the file's size, and `HEAD` reads nothing. Encoded files +are still read whole, since the coding negotiation and the gzip fallback need them. A failure after the status line (a +read error, a closing connection) cannot change the status: the connection is closed, which the client sees as a truncated +body. + +`app.addRoute(prefix, handler)` answers `GET` and `HEAD` under an absolute prefix ending with `/` with an +`http::RouteReply` produced at run time: status, headers, an exact `contentLength` (unset: the body ends when the +connection closes) and a `body` callback filling the next chunk (0 ends it). The handler and the callback run on the worker +thread, so a slow disk does not delay other connections. Route work runs on its own pool of 4 threads and the files of the providers on another of 2: a handler that blocks for seconds delays at most the routes queued behind four such handlers, never `WebFront.js` or a page. A route precedes the file providers, never masks the embedded +`WebFront.js`, and overlapping prefixes are refused when registered. Other methods get 405; a handler that throws, or sets a +header that could split the response or that the server owns (`Content-Length`, `Connection`, `Transfer-Encoding`), gets +500. The registration handle removes the route when destroyed; a request already running keeps its handler. `Range` +requests (#455) and the binding of a request to a connection (#469) are not part of this mechanism yet. + ## Validated representation cache Each server owns a bounded LRU cache through its `RequestHandler`. It is destroyed after diff --git a/docs/adr/ADR-002-systemes-de-fichiers-composables.md b/docs/adr/ADR-002-systemes-de-fichiers-composables.md index 0a46273d..02206ae9 100644 --- a/docs/adr/ADR-002-systemes-de-fichiers-composables.md +++ b/docs/adr/ADR-002-systemes-de-fichiers-composables.md @@ -14,11 +14,12 @@ | 2.2 | 2026-07-22 | Acceptée | Ambroise Leclerc | Page de repli embarquée prête pour le bridge. | [6e73219](https://github.com/ambroise-leclerc/WebFront/commit/6e73219a093c9bbe5c3f14bf0ac74e8e79e2803b) | | 2.3 | 2026-10-14 | Acceptée | Ambroise Leclerc | Composition facultative des ressources des composants avec DefaultFSWith. | [40f5621](https://github.com/ambroise-leclerc/WebFront/commit/40f5621928fdd188f230bf08ff062f9557619046) | | 2.4 | 2026-10-14 | Acceptée | Ambroise Leclerc | Fournisseur PackageFS et stockage transactionnel des outils installés. | [4bcfc28](https://github.com/ambroise-leclerc/WebFront/commit/4bcfc28c7b78672603a2114a72d9decf25d36387) | +| 2.5 | 2026-11-03 | Acceptée | Ambroise Leclerc | `fs::File::knownSize()` : taille connue avant lecture (données embarquées, fichier natif sur flux positionnable), pour annoncer `Content-Length` et envoyer le fichier en flux (#454). Les routes dynamiques passent après le `WebFront.js` protégé et ne peuvent pas le masquer. | Branche `454-dynamic-routes` | ## État et chronologie **Acceptée.** Décision initiale : **2023-03-16** (version 1.0). -Dernière révision : **2026-10-14** (version 2.4). +Dernière révision : **2026-11-03** (version 2.5). Le présent texte expose la décision en vigueur ; le tableau retrace ses états antérieurs. ## Contexte diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 0e2b2413..af906c76 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -7,6 +7,7 @@ | 1.0 | 2026-10-31 | Proposée | Ambroise Leclerc | Décision initiale : distinction hôte/client, préalables regroupés en épiques (#446 à #450), confinement des racines pendant la résolution et hypothèse de confiance face au déplacement d'un répertoire ouvert ou de la racine, autorisation attachée à l'emplacement déclaré, propriétaires admissibles des répertoires et des ancêtres, transport du navigateur système déclaré (`loopbackAttested`) plutôt que prouvé par un secret de lancement, jetons de lecture réutilisables liés à la connexion par un cookie, exposition des jetons et transport des lectures distantes, exception de confiance explicite, liaison HTTP par profil de navigateur avec cookies nommés par client, contenu actif neutralisé, transport déclaré et association de lancement du navigateur système, racines déclarées accessibles à tout script admis, services en composants facultatifs, sélection par l'utilisateur valant autorisation (poignées plutôt que chemins), backends natif, HTML et navigateur choisis par connexion, contenu des fichiers par HTTP à jeton ; état de l'art et inventaire des autres services. | À renseigner après intégration. | | 1.1 | 2026-11-02 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison partielle de l'étape 1 pour #451 (sélecteur de fichiers et téléchargements sous WebKitGTK, CEF, WKWebView et WebView2) ; #452 reste à faire. La section « État de l'étape 1 » distingue les preuves de validation par moteur et par révision ; `docs/FRONTENDS.md` précise les limites de couverture. | Branche `451-file-chooser-downloads` (PR #484), implémentation initiale `91049ab`, stockage privé WKWebView `52d8c68` | | 1.2 | 2026-11-03 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #452 (`alert`, `confirm`, `prompt` partout ; `beforeunload` sauf sous WKWebView, qui n'a pas de délégué public pour lui) : l'étape 1 n'est complète qu'avec cette limite. `docs/FRONTENDS.md` précise la couverture par moteur (WKWebView et WebView2 non exécutés localement ; `beforeunload` non exercé de bout en bout et jamais demandé à la fermeture de la fenêtre). | Branche `452-script-dialogs` | +| 1.3 | 2026-11-03 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #454 (étape 2) : routes HTTP dynamiques (`addRoute`, désinscription par handle, priorité après `WebFront.js` et avant les fournisseurs, collision de préfixes refusée), envoi en flux par morceaux bornés d'une réponse produite à l'exécution et des fichiers non encodés de taille connue (`fs::File::knownSize`), gestionnaire et lectures sur un thread de travail du serveur. Les plages `Range` (#455) et la liaison à la connexion (#469) restent à faire ; elles s'appuient sur ces routes. | Branche `454-dynamic-routes` | ## État et chronologie @@ -371,6 +372,8 @@ révisions indiquées ; ils ne qualifient pas automatiquement les changements ul des dialogues natifs reste partielle ; les injections de test ne la remplacent pas. `docs/FRONTENDS.md` détaille les limites par moteur. #452 est livré dans la version 1.2 (`beforeunload` n'est pas pris en charge sous WKWebView ; sous WebView2, la fermeture de la fenêtre elle-même ne le déclenche pas non plus, seules les navigations et les rechargements le font ; non vérifié sous WebKitGTK et CEF, voir `docs/FRONTENDS.md`) ; l'ADR reste proposée. +#454 est livré dans la version 1.3 : `addRoute(préfixe, gestionnaire)` répond aux `GET` et `HEAD` sous un préfixe absolu terminé par `/`, par une réponse (`http::RouteReply`) dont le corps est lu morceau par morceau sur un thread de travail du serveur, sans mémoire proportionnelle à sa taille (mesure : 128 Mio envoyés sans croissance du pic mémoire). Les fichiers non encodés des fournisseurs dont la taille est connue sont envoyés de la même façon ; les fichiers encodés restent lus en entier pour la négociation de codage (ADR-009). Le gestionnaire ne reçoit ni jeton ni identité de connexion : ils viennent de #469. + Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par des tableaux typés en morceaux ; leur ajout au serveur, utile aux très gros envois en flux et aux formulaires sans diff --git a/docs/adr/README.md b/docs/adr/README.md index 6550f1c7..576846f0 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -42,7 +42,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | ADR | Decision | Status | Initial creation | Current version | | --- | --- | --- | --- | --- | | [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.4 — 2026-10-14 | +| [ADR-002](ADR-002-systemes-de-fichiers-composables.md) | An abstract, composable filesystem as the foundation for portability | Accepted | 2023-03-16 | 2.5 — 2026-11-03 | | [ADR-003](ADR-003-protocole-binaire-et-bornes.md) | A shared, typed and bounded binary protocol | Accepted through 1.13; 1.14 proposed | 2022-02-06 | 1.14 — 2026-10-27 | | [ADR-004](ADR-004-appels-asynchrones-et-erreurs.md) | Asynchronous calls with deliberately asymmetric contracts | Accepted | 2022-02-06 | 2.4 — 2026-10-18 | | [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 | @@ -60,7 +60,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-017](ADR-017-acces-direct-aux-frontends.md) | Direct access to embedded frontends, with HTML kept normative | Proposed | 2026-10-24 | 1.1 — 2026-10-25 | | [ADR-018](ADR-018-acces-au-dom.md) | DOM access from C++ through a bounded mutation stream, without contesting the DOM of UI libraries | Proposed, partially superseded, partially delivered | 2026-10-26 | 1.5 — 2026-10-30 | | [ADR-019](ADR-019-developpement-automatisable-et-agents.md) | Automating the developer environment through shared operations and an optional local MCP adapter | Accepted | 2026-10-28 | 1.2 — 2026-10-29 | -| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.2 — 2026-11-03 | +| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.3 — 2026-11-03 | | [ADR-021](ADR-021-publication-de-l-environnement-developpeur.md) | Simplifying the publication of the developer environment: automate the release, keep pinned hashes, no dedicated server | Accepted (domain delivered; phase 1 to implement) | 2026-11-02 | 1.0 — 2026-11-02 | Numbering follows the reading topics; milestones and individual file histories provide diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 5e518a59..376dd2aa 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -428,6 +428,15 @@ class BasicWF { return httpServer.startTask(std::move(task)); } + /** @brief Answers the `GET` and `HEAD` requests under `prefix` (absolute, ending with '/') with a reply produced at + * run time and streamed in chunks of bounded size (see http::RouteReply). The handler runs on a worker thread, not on + * the server context. The route precedes the file providers, never masks the embedded `WebFront.js`, and lasts as long + * as the returned registration; an overlapping prefix throws std::invalid_argument. Thread-safe. + */ + [[nodiscard]] http::RouteTable::Registration addRoute(std::string prefix, http::RouteHandler handler) { + return httpServer.addRoute(std::move(prefix), std::move(handler)); + } + /** @brief A sender completing on the server context once the duration has elapsed. co_await propagates the * task's stop token: a stop request (TaskHandle::requestStop, shutdown) completes it stopped at once. */ diff --git a/include/webfront/http/BlockingWorker.hpp b/include/webfront/http/BlockingWorker.hpp new file mode 100644 index 00000000..7ebb8a7a --- /dev/null +++ b/include/webfront/http/BlockingWorker.hpp @@ -0,0 +1,168 @@ +/// @brief Server-owned thread running blocking application work (route handlers, file reads) off the I/O context. +#pragma once +#include "../networking/Tasks.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::http { + +/// Runs the work senders it hands out on lazily started threads, up to a fixed number: a job waits for a free +/// thread, so slow work delays only the jobs queued behind as many slow ones as there are threads. +/// +/// A sender completes on that thread: the awaiting task continues on the I/O context with `continues_on`. +/// Work still queued when the worker stops completes as stopped, so no task outlives the shutdown; the work +/// already running is not interrupted. A stop request of the awaiting task skips work not yet started. +class BlockingWorker { + struct Job { + virtual void run() noexcept = 0; + virtual void cancel() noexcept = 0; + + protected: + ~Job() = default; + }; + +public: + explicit BlockingWorker(std::size_t maxThreads = 1) : limit(maxThreads == 0 ? 1 : maxThreads) {} + BlockingWorker(const BlockingWorker&) = delete; + BlockingWorker& operator=(const BlockingWorker&) = delete; + ~BlockingWorker() { + stop(); + join(); + } + + /// Thread-safe. Refuses new work and lets the thread end once the queued work is cancelled. + void stop() noexcept { + { + std::lock_guard lock(mutex); + stopping = true; + } + changed.notify_all(); + } + + /// Waits for the running work; call after `stop()` and outside the worker's own thread. + void join() noexcept { + std::vector ending; + { + std::lock_guard lock(mutex); + ending.swap(threads); + } + for (auto& thread : ending) + if (thread.joinable()) thread.join(); + } + + struct Sender { + using sender_concept = networking::ex::sender_t; + using completion_signatures = networking::ex:: + completion_signatures; + + BlockingWorker* worker; + std::function work; + + template + struct Operation final : Job { + BlockingWorker* worker; + Receiver receiver; + std::function work; + Operation(BlockingWorker* owner, Receiver value, std::function function) + : worker(owner), receiver(std::move(value)), work(std::move(function)) {} + Operation(const Operation&) = delete; + Operation(Operation&&) = delete; + + void start() noexcept { + try { + if (worker->enqueue(this)) return; + } catch (...) { + networking::ex::set_error(std::move(receiver), std::current_exception()); + return; + } + networking::ex::set_stopped(std::move(receiver)); + } + // Completing may destroy this operation: nothing touches a member afterwards. + void run() noexcept override { + if (networking::ex::get_stop_token(networking::ex::get_env(receiver)).stop_requested()) { + networking::ex::set_stopped(std::move(receiver)); + return; + } + try { + work(); + } catch (...) { + networking::ex::set_error(std::move(receiver), std::current_exception()); + return; + } + networking::ex::set_value(std::move(receiver)); + } + void cancel() noexcept override { networking::ex::set_stopped(std::move(receiver)); } + }; + + template + auto connect(Receiver receiver) && { + return Operation(worker, std::move(receiver), std::move(work)); + } + }; + + /// A sender running `work` on the worker thread. State it touches must outlive the await. + [[nodiscard]] Sender run(std::function work) { return {this, std::move(work)}; } + +private: + std::mutex mutex; + std::condition_variable changed; + std::deque queue; + bool stopping = false; + std::vector threads; + std::size_t limit; + std::size_t idle = 0; + + bool enqueue(Job* job) { + { + std::lock_guard lock(mutex); + if (stopping) return false; + queue.push_back(job); + if (queue.size() > idle && threads.size() < limit) { + try { + threads.emplace_back([this] { loop(); }); + } catch (...) { + if (threads.empty()) { + queue.pop_back(); + throw; + } // else a running thread will take the job + } + } + } + changed.notify_one(); + return true; + } + + void loop() noexcept { + for (;;) { + Job* job = nullptr; + std::deque cancelled; + { + std::unique_lock lock(mutex); + ++idle; + changed.wait(lock, [this] { return stopping || !queue.empty(); }); + --idle; + if (stopping) { + cancelled.swap(queue); + } else { + job = queue.front(); + queue.pop_front(); + } + } + if (job) { + job->run(); + continue; + } + for (auto* pending : cancelled) pending->cancel(); + return; + } + } +}; + +} // namespace webfront::http diff --git a/include/webfront/http/Encodings.hpp b/include/webfront/http/Encodings.hpp index f739abb5..13ff2350 100644 --- a/include/webfront/http/Encodings.hpp +++ b/include/webfront/http/Encodings.hpp @@ -46,7 +46,8 @@ inline void appendPercentEncodedByte(std::string& encoded, unsigned char byte) { return encoded; } -[[nodiscard]] inline std::string decode(std::string_view uri) { +// @param plusAsSpace the form-encoding rule, which the file providers keep; a URL path leaves '+' literal. +[[nodiscard]] inline std::string decode(std::string_view uri, bool plusAsSpace = true) { std::string decoded; decoded.reserve(uri.size()); for (std::size_t index = 0; index < uri.size(); ++index) { @@ -65,7 +66,7 @@ inline void appendPercentEncodedByte(std::string& encoded, unsigned char byte) { else decoded += uri[index]; break; - case '+': decoded += ' '; break; + case '+': decoded += plusAsSpace ? ' ' : '+'; break; default: decoded += uri[index]; } } diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 0ca9082f..88f2463c 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -10,6 +10,7 @@ #include "../Task.hpp" #include "../tooling/HexDump.hpp" #include "AcceptEncoding.hpp" +#include "BlockingWorker.hpp" #include "BuffersPolicy.hpp" #include "Encodings.hpp" #include "GzipCache.hpp" @@ -28,8 +29,11 @@ #include #include #include +#include #include #include +#include +#include #include #include #include @@ -220,6 +224,7 @@ struct Response : Headers { badRequest = 400, forbidden = 403, notFound = 404, + methodNotAllowed = 405, notAcceptable = 406, internalServerError = 500, notImplemented = 501, @@ -269,12 +274,13 @@ struct Response : Headers { mutable std::string httpStatus; [[nodiscard]] static std::string toString(StatusCode code) { - static constexpr std::array, 10> names{ + static constexpr std::array, 11> names{ {{switchingProtocols, "Switching Protocols"}, {ok, "OK"}, {badRequest, "Bad Request"}, {forbidden, "Forbidden"}, {notFound, "Not Found"}, + {methodNotAllowed, "Method Not Allowed"}, {notAcceptable, "Not Acceptable"}, {internalServerError, "Internal Server Error"}, {notImplemented, "Not Implemented"}, @@ -288,6 +294,172 @@ struct Response : Headers { } }; +/// The request a dynamic route answers: the parsed request, its decoded path and its raw query. +struct RouteRequest { + const Request& request; + std::string_view path; ///< Percent-decoded, without the query; always starts with the route's prefix. + std::string_view query; ///< After the '?', undecoded; empty when there is none. +}; + +/// What a route handler produces. The server adds `Content-Length` (from `contentLength`) and `Connection`; +/// a handler sets the others (`Content-Type`, `Content-Range`, `Content-Disposition`, `Cache-Control`...). +struct RouteReply { + Response::StatusCode status = Response::ok; + std::vector> headers; + /// Exact size of the body. Unset with a body: the body ends when the connection closes. + std::optional contentLength; + /// Fills the buffer with the next bytes of the body and returns their count; 0 ends the body. Called on + /// the server's worker thread, one chunk at a time, so memory use does not depend on the body's size. + /// Never called for `HEAD`. A throw ends the response by closing the connection. + std::function)> body; +}; + +/// Answers `GET` and `HEAD` requests under a prefix. Runs on the server's worker thread, not on the I/O +/// context: it may block (disk, remote storage) without delaying other connections. A throw answers 500. +using RouteHandler = std::function; + +/// The dynamic routes of a server. Prefixes never overlap, so at most one route matches a path. +class RouteTable { +public: + struct Entry { + std::string prefix; + RouteHandler handler; + }; + +private: + struct State { + std::mutex mutex; + std::vector> entries; + }; + +public: + /// Removes its route when destroyed or reset, and stays safe after the table is gone. A request already + /// running keeps the handler it started with; no later request reaches it. + class Registration { + public: + Registration() = default; + Registration(const Registration&) = delete; + Registration& operator=(const Registration&) = delete; + Registration(Registration&& other) noexcept : state(std::move(other.state)), entry(std::move(other.entry)) {} + Registration& operator=(Registration&& other) noexcept { + if (this != &other) { + reset(); + state = std::move(other.state); + entry = std::move(other.entry); + } + return *this; + } + ~Registration() { reset(); } + + void reset() noexcept { + if (auto owner = state.lock()) { + std::lock_guard lock(owner->mutex); + std::erase(owner->entries, entry); + } + state.reset(); + entry.reset(); + } + [[nodiscard]] explicit operator bool() const noexcept { return !state.expired(); } + + private: + friend class RouteTable; + Registration(std::weak_ptr owner, std::shared_ptr route) : state(std::move(owner)), entry(std::move(route)) {} + std::weak_ptr state; + std::shared_ptr entry; + }; + + /// @param prefix absolute path ending with '/', such as "/webfront/services/files/"; "/" is refused, as is + /// anything that would cover the protected "/WebFront.js" (ADR-002). + /// @throws std::invalid_argument for a malformed prefix, an empty handler, or a prefix that contains + /// or is contained in a registered one. + [[nodiscard]] Registration add(std::string prefix, RouteHandler handler) { + if (!handler) throw std::invalid_argument("A route needs a handler"); + if (!validPrefix(prefix)) throw std::invalid_argument("Invalid route prefix '" + prefix + "'"); + auto entry = std::make_shared(Entry{std::move(prefix), std::move(handler)}); + std::lock_guard lock(state->mutex); + for (const auto& other : state->entries) + if (other->prefix.starts_with(entry->prefix) || entry->prefix.starts_with(other->prefix)) + throw std::invalid_argument("Route prefix '" + entry->prefix + "' collides with '" + other->prefix + "'"); + state->entries.push_back(entry); + return {state, std::move(entry)}; + } + + /// @return the route whose prefix starts the path, kept alive for as long as the caller holds it. + [[nodiscard]] std::shared_ptr find(std::string_view path) const { + std::lock_guard lock(state->mutex); + for (const auto& entry : state->entries) + if (path.starts_with(entry->prefix)) return entry; + return {}; + } + +private: + std::shared_ptr state = std::make_shared(); + + static bool validPrefix(std::string_view prefix) { + if (prefix.size() < 2 || !prefix.starts_with('/') || !prefix.ends_with('/')) return false; + if (prefix.find("..") != std::string_view::npos || prefix.find("//") != std::string_view::npos || prefix.find("/./") != std::string_view::npos) + return false; + return std::none_of(prefix.begin(), prefix.end(), [](char c) { + return static_cast(c) <= 32 || c == 127 || c == '?' || c == '#' || c == '%' || c == '\\'; + }); + } +}; + +namespace routing { + +/// The path without empty and "." segments, so that "/a//b/./c" reaches the route of "/a/b/c" instead of falling +/// through to the file providers, which would resolve it to the same file. A trailing slash is kept. +inline std::string collapseSegments(std::string path) { +#ifdef _WIN32 + std::replace(path.begin(), path.end(), '\\', '/'); // the providers resolve a backslash as a separator there +#endif + std::string collapsed; + for (std::size_t start = 0; start < path.size();) { + const auto end = path.find('/', start); + const auto segment = std::string_view(path).substr(start, end == std::string::npos ? std::string::npos : end - start); + if (!segment.empty() && segment != ".") { + collapsed += '/'; + collapsed += segment; + } + if (end == std::string::npos) break; + start = end + 1; + } + if (collapsed.empty() || path.ends_with('/')) collapsed += '/'; + return collapsed; +} + +/// The normalized path and raw query of an origin-form request target, or nothing when it is not a safe one. +/// The path is percent-decoded and a literal '+' stays a '+', as in any URL path. +inline std::optional> splitTarget(const std::string& uri) { + const auto mark = uri.find('?'); + const auto decoded = uri::decode(std::string_view(uri).substr(0, mark), false); + if (!decoded.starts_with('/') || decoded.find("..") != std::string::npos) return {}; + if (std::any_of(decoded.begin(), decoded.end(), [](char c) { return static_cast(c) < 32 || c == 127; })) return {}; + return std::pair{collapseSegments(decoded), mark == std::string::npos ? std::string{} : uri.substr(mark + 1)}; +} + +/// Refuses what could split a response or contradict the framing the server owns. +inline void validateReply(const RouteReply& reply) { + const auto isToken = [](std::string_view name) { + return !name.empty() && std::all_of(name.begin(), name.end(), [](char c) { + // RFC 9110 tchar, spelled out: std::isalnum depends on the locale and may accept non-ASCII bytes. + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || std::string_view("!#$%&'*+-.^_`|~").find(c) != std::string_view::npos; + }); + }; + for (const auto& [name, value] : reply.headers) { + if (!isToken(name)) throw std::runtime_error("Invalid response header name '" + name + "'"); + if (std::any_of(value.begin(), value.end(), [](char c) { return c == '\r' || c == '\n' || c == '\0'; })) + throw std::runtime_error("Invalid value for response header '" + name + "'"); + for (const auto reserved : {std::string_view("Content-Length"), std::string_view("Connection"), std::string_view("Transfer-Encoding")}) + if (std::ranges::equal(name, reserved, [](char a, char b) { + return std::tolower(static_cast(a)) == std::tolower(static_cast(b)); + })) + throw std::runtime_error("Response header '" + name + "' belongs to the server"); + } +} + +} // namespace routing + template class RequestHandler { public: @@ -307,6 +479,8 @@ class RequestHandler { bool needsDecode = false; bool head = false; bool identityFallback = false; + /// An unencoded file of known size, left unread to be streamed (asynchronous requests only). + std::unique_ptr file{}; std::size_t limit = maxDecodedAssetSize(); }; @@ -410,6 +584,14 @@ class RequestHandler { const bool fallback = file->isEncoded() && encoding::isGzip(file->getEncoding()) && !request.acceptsEncoding(file->getEncoding()) && request.acceptsEncoding("identity"); prepared.identityFallback = fallback; + if (asynchronous && !file->isEncoded()) { + if (const auto size = file->knownSize()) { + response.headers.emplace_back("Content-Length", std::to_string(*size)); + if (prepared.head) return {}; + prepared.file = std::make_unique(std::move(*file)); + return {}; + } + } const auto inputLimit = asynchronous && fallback ? maxEncodedAssetSize : std::numeric_limits::max(); std::array buffer{}; while (auto bytesRead = file->read(buffer)) { @@ -488,6 +670,8 @@ class Server { log::info("Stopping HTTP server..."); tasks.requestStop(); decodeExecutor.stop(); + routeWorker.stop(); + fileWorker.stop(); ioContext.stop(); } @@ -496,14 +680,24 @@ class Server { void drain() { decodeExecutor.stop(); decodeExecutor.join(); + // The cancelled tasks are pumped before the workers are joined: a handler may wait for what the cleanup + // of a cancelled task does, and the tasks awaiting a running job end when that job returns. + routeWorker.stop(); + fileWorker.stop(); tasks.drain(ioContext); + routeWorker.join(); + fileWorker.join(); } /** @brief Destructor-safe join, retaining ownership until every task has finished. */ void drainUntilJoined() noexcept { decodeExecutor.stop(); decodeExecutor.join(); + routeWorker.stop(); + fileWorker.stop(); tasks.drainUntilJoined(ioContext); + routeWorker.join(); + fileWorker.join(); } /** @brief Scope shared with upgraded connections; the server must outlive them. */ @@ -527,6 +721,13 @@ class Server { return Net::ResumeAfter(acceptor, duration); } + /// Answers the `GET` and `HEAD` requests under `prefix` with `handler` (see RouteTable::add for the + /// prefix rules). The route lasts as long as the returned registration; it never masks the embedded + /// `WebFront.js`, and takes precedence over the file providers. Thread-safe. + [[nodiscard]] RouteTable::Registration addRoute(std::string prefix, RouteHandler handler) { + return routes.add(std::move(prefix), std::move(handler)); + } + /// Called, on the context's thread, with the socket of a connection upgraded to a WebSocket. void onUpgrade(std::function&& handler) { upgradeHandler = std::move(handler); @@ -546,6 +747,11 @@ class Server { networking::TaskScope tasks; RequestHandler requestHandler; gzip::DecodeExecutor decodeExecutor; + RouteTable routes; + // Route handlers may block for as long as they like: they get their own threads, so that the files of the + // providers (WebFront.js, pages) keep flowing for the other browsers. + BlockingWorker routeWorker{4}; + BlockingWorker fileWorker{2}; std::function upgradeHandler; std::string bind(std::string_view address, std::string_view requestedPort) { @@ -580,9 +786,93 @@ class Server { } } + struct RouteMatch { + std::shared_ptr route; + std::string path, query; + }; + + // A request, other than a WebSocket upgrade, under a registered prefix. Every method under a prefix + // belongs to the route (405 for those it does not serve): its URLs never fall through to the providers. + std::optional matchRoute(const Request& request) const { + if (request.isUpgradeRequest("websocket")) return {}; + auto split = routing::splitTarget(request.uri); + if (!split) return {}; + auto route = routes.find(split->first); + if (!route) return {}; + return RouteMatch{std::move(route), std::move(split->first), std::move(split->second)}; + } + + // Sends a body read on the worker in chunks of at most emissionBufferSize bytes, each read after the + // previous one was sent (back-pressure). A failure cannot change the status line already sent: it is + // logged, and the caller closes the connection, which the client sees as a truncated body. + networking::Task streamBody(BlockingWorker& worker, typename Net::Socket& socket, std::function)> body, + std::optional length, std::string label) { + try { + std::vector chunk(Policy::emissionBufferSize); + std::uint64_t sent = 0; + for (;;) { + std::size_t count = 0; + co_await networking::ex::continues_on(worker.run([&] { count = body(chunk); }), Net::Scheduler(socket)); + if (count == 0) break; + if (count > chunk.size() || (length && count > *length - sent)) throw std::length_error("The body is longer than announced"); + sent += count; + std::vector buffers{Net::Buffer(static_cast(chunk.data()), count)}; + co_await Net::Send(socket, buffers); + } + if (length && sent != *length) throw std::length_error("The body is shorter than announced"); + } + catch (const std::exception& error) { + log::warn("{} ended its response early: {}", label, error.what()); + } + catch (...) { + log::warn("{} ended its response early: unknown exception", label); + } + } + + // Runs the handler on the worker, then streams its body in chunks of at most emissionBufferSize bytes, + // each read on the worker and sent before the next is read (back-pressure). Closing the connection + // fails the pending send and ends the response; the stop request of the server cancels the awaits. + networking::Task serveRoute(typename Net::Socket& socket, Request request, RouteMatch match) { + const bool head = request.method == Request::Method::Head; + RouteReply reply; + Response response; + try { + if (!head && request.method != Request::Method::Get) { + response = Response::getStatusResponse(Response::methodNotAllowed); + response.headers.emplace_back("Allow", "GET, HEAD"); + } else { + co_await networking::ex::continues_on(routeWorker.run([&] { + reply = match.route->handler(RouteRequest{request, match.path, match.query}); + routing::validateReply(reply); + }), Net::Scheduler(socket)); + response.statusCode = reply.status; + for (auto& [name, value] : reply.headers) response.headers.emplace_back(name, value); + if (reply.contentLength) response.headers.emplace_back("Content-Length", std::to_string(*reply.contentLength)); + else if (!reply.body) response.headers.emplace_back("Content-Length", "0"); + } + } + catch (const std::exception& error) { + log::warn("Route {} failed: {}", match.route->prefix, error.what()); + response = Response::getStatusResponse(Response::internalServerError); + reply.body = nullptr; + } + catch (...) { + log::warn("Route {} failed with an exception which is not a std::exception", match.route->prefix); + response = Response::getStatusResponse(Response::internalServerError); + reply.body = nullptr; + } + const bool streaming = !head && reply.body; // the built-in 405 has no reply.body + if (head) response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body + co_await Net::Send(socket, response.toBuffers()); + if (streaming) co_await streamBody(routeWorker, socket, std::move(reply.body), reply.contentLength, match.route->prefix); + socket.shutdown(Net::Socket::shutdown_both); + } + networking::Task serve(typename Net::Socket socket) { Request request; std::optional::Lease> lease; + std::unique_ptr streamed; + bool head = false; Response response; try { std::array buffer; @@ -592,6 +882,11 @@ class Server { request.parseSomeData(buffer.data(), buffer.data() + received); } log::info("Received request {} on {}", request.getMethodName(), request.uri); + if (auto match = matchRoute(request)) { + co_await serveRoute(socket, std::move(request), std::move(*match)); + co_return; + } + head = request.method == Request::Method::Head; auto prepared = requestHandler.prepareRequest(std::move(request)); if (prepared.needsDecode) { lease.emplace(co_await networking::ex::continues_on( @@ -605,6 +900,7 @@ class Server { prepared.response.headers.emplace_back("Vary", "Accept-Encoding"); } } + if (prepared.response.statusCode == Response::ok) streamed = std::move(prepared.file); response = std::move(prepared.response); } log::info(" responding http {}", static_cast(response.statusCode)); @@ -620,7 +916,14 @@ class Server { log::warn("HTTP asset request failed: {}", error.what()); response = Response::getStatusResponse(Response::internalServerError); } + catch (...) { + log::warn("HTTP asset request failed with an exception which is not a std::exception"); + response = Response::getStatusResponse(Response::internalServerError); + } + if (head) response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body co_await Net::Send(socket, response.toBuffers()); + if (streamed) + co_await streamBody(fileWorker, socket, [&file = *streamed](std::span out) { return file.read(out); }, streamed->knownSize(), "File response"); if (response.statusCode != Response::switchingProtocols || tasks.stopRequested()) socket.shutdown(Net::Socket::shutdown_both); // a stopped server hands nothing over: its drain would never end else if (upgradeHandler) diff --git a/include/webfront/system/FileSystem.hpp b/include/webfront/system/FileSystem.hpp index a484b212..0656d989 100644 --- a/include/webfront/system/FileSystem.hpp +++ b/include/webfront/system/FileSystem.hpp @@ -40,12 +40,16 @@ class File { File(RawData auto t) : File(decltype(t)::data, decltype(t)::dataSize) {} File(std::span input, size_t fileSize, std::string_view contentEncoding = "") : fileType{FileType::staticData}, data(input), size(fileSize), eofBit(fileSize==0), encoding(contentEncoding) {} - File(std::ifstream ifstream) : fileType{FileType::nativeFStream}, fstream{std::move(ifstream)} {} + File(std::ifstream ifstream) : fileType{FileType::nativeFStream}, fstream{std::move(ifstream)} { measureStream(); } [[nodiscard]] bool isEncoded() const { return !encoding.empty(); } [[nodiscard]] std::string_view getEncoding() const { return encoding; } [[nodiscard]] bool eof() const { return eofBit; } + /// The number of bytes this file yields, when known before reading it (always for embedded data, and for a + /// native file whose stream can seek). A server uses it to announce a length and stream the file in chunks. + [[nodiscard]] std::optional knownSize() const { return fileType == FileType::staticData ? std::optional{size} : streamSize; } + // Extracts characters from file into given buffer until buffer size or end of file is reached. // @param buffer buffer which will receive extracted data // @return bytes read @@ -58,6 +62,7 @@ class File { FileType fileType; std::span data; size_t readIndex{}, size{}; + std::optional streamSize; bool eofBit{false}; const std::string encoding{}; std::ifstream fstream; @@ -76,6 +81,17 @@ class File { return count; } + // The bytes left from the stream's current position, which the caller may have moved past a prefix. + void measureStream() { + if (!fstream.is_open()) return; + const auto start = fstream.tellg(); + fstream.seekg(0, std::ios::end); + const auto end = fstream.tellg(); + fstream.seekg(start); + if (start >= 0 && end >= start && fstream) streamSize = static_cast(end - start); + else fstream.clear(); + } + size_t readFStream(std::span buffer) { fstream.read(buffer.data(), static_cast(buffer.size())); if (fstream.eof()) { diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index b9c3373d..f44151a6 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -24,7 +24,7 @@ if(WEBFRONT_TEST_DOXYGEN) endif() set(TESTS_LIST) -list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) +list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp HTTPRoutesTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) diff --git a/test/unit/HTTPRoutesTests.cpp b/test/unit/HTTPRoutesTests.cpp new file mode 100644 index 00000000..193d4104 --- /dev/null +++ b/test/unit/HTTPRoutesTests.cpp @@ -0,0 +1,687 @@ +/// Dynamic routes of the HTTP server (#454): registration, priority, streamed replies, failures and shutdown. +#include "InjectableNetworking.hpp" +#include "Mocks.hpp" +#include "TemporaryDirectory.hpp" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef _WIN32 + #include +#endif + +using namespace webfront; +using namespace webfront::http; +using namespace std::chrono_literals; +using webfront::testing::InjectableSocket; + +namespace { + +/// One connection, accepted at once, whose request the test delivers once its routes are registered. +struct RouteNet : webfront::testing::InjectableNetworking { + static inline std::atomic accepts{0}; + static auto Accept(auto&) { + return networking::ex::then(networking::ex::just(), []() -> Socket { + if (accepts++ != 0) throw std::system_error(std::make_error_code(std::errc::operation_canceled)); + return Socket{}; + }); + } +}; + +struct ProviderFiles { + static inline std::list names{"webfront/services/files/provided.txt"}; +}; +using Files = MockFileSystem; +using Router = Server; + +template +bool waitFor(Condition condition, std::chrono::milliseconds limit = 10s) { + for (auto waited = 0ms; waited < limit; waited += 1ms) { + if (condition()) return true; + std::this_thread::sleep_for(1ms); + } + return false; +} + +void send(std::string_view request) { + std::vector bytes; + for (const char c : request) bytes.push_back(static_cast(c)); + InjectableSocket::receive(bytes); +} + +std::string get(std::string_view target, std::string_view method = "GET") { + return std::string(method) + " " + std::string(target) + " HTTP/1.1\r\nHost: localhost\r\n\r\n"; +} + +struct Fixture { + Fixture() { + InjectableSocket::reset(); + RouteNet::accepts = 0; + } + ~Fixture() { InjectableSocket::reset(); } + + /// Sends the request and waits for the end of the connection; returns what the server wrote. + std::string answer(std::string_view request) { + send(request); + REQUIRE(waitFor([] { return InjectableSocket::shutdownCount() > 0; })); + return InjectableSocket::writtenText(); + } +}; + +RouteReply text(std::string body) { + RouteReply reply; + reply.headers.emplace_back("Content-Type", "text/plain"); + reply.headers.emplace_back("Cache-Control", "no-store"); + reply.contentLength = body.size(); + reply.body = [body = std::move(body), position = std::size_t{0}](std::span out) mutable { + const auto count = std::min(out.size(), body.size() - position); + std::copy_n(body.data() + position, count, out.data()); + position += count; + return count; + }; + return reply; +} + +bool contains(const std::string& haystack, std::string_view needle) { return haystack.find(needle) != std::string::npos; } + +} // namespace + +SCENARIO("Route prefixes are validated when registered") { + RouteTable table; + const auto handler = [](const RouteRequest&) { return RouteReply{}; }; + GIVEN("prefixes that cannot be routes") { + for (const auto* prefix : {"", "/", "/files", "files/", "/a//b/", "/a/../b/", "/a/./b/", "/a b/", "/a?b/", "/a#/", "/a%2e/"}) { + THEN("'" << prefix << "' is refused") { REQUIRE_THROWS_AS(table.add(prefix, handler), std::invalid_argument); } + } + THEN("a route without handler is refused") { REQUIRE_THROWS_AS(table.add("/webfront/services/files/", nullptr), std::invalid_argument); } + } + GIVEN("a registered prefix") { + auto registration = table.add("/webfront/services/files/", handler); + THEN("the same prefix, a longer one and a shorter one collide") { + REQUIRE_THROWS_AS(table.add("/webfront/services/files/", handler), std::invalid_argument); + REQUIRE_THROWS_AS(table.add("/webfront/services/files/deep/", handler), std::invalid_argument); + REQUIRE_THROWS_AS(table.add("/webfront/services/", handler), std::invalid_argument); + } + THEN("a sibling prefix, even sharing the name's start, is accepted") { + REQUIRE_NOTHROW(table.add("/webfront/services/files2/", handler)); + REQUIRE_NOTHROW(table.add("/webfront/services/dialogs/", handler)); + } + THEN("lookup matches paths under the prefix only") { + REQUIRE(table.find("/webfront/services/files/token")); + REQUIRE_FALSE(table.find("/webfront/services/files")); + REQUIRE_FALSE(table.find("/webfront/services/filesX/token")); + REQUIRE_FALSE(table.find("/WebFront.js")); + } + THEN("unregistering frees the prefix and the lookup") { + registration.reset(); + REQUIRE_FALSE(table.find("/webfront/services/files/token")); + REQUIRE_NOTHROW(table.add("/webfront/services/files/", handler)); + } + THEN("a moved registration keeps the route until it is destroyed") { + auto moved = std::move(registration); + REQUIRE(table.find("/webfront/services/files/x")); + moved = {}; + REQUIRE_FALSE(table.find("/webfront/services/files/x")); + } + } + GIVEN("a registration outliving its table") { + RouteTable::Registration registration; + { + RouteTable shortLived; + registration = shortLived.add("/webfront/services/files/", handler); + } + THEN("destroying it is harmless") { REQUIRE_NOTHROW(registration.reset()); } + } +} + +SCENARIO("A route streams its reply in bounded chunks") { + Fixture fixture; + Router server("127.0.0.1", "0"); + GIVEN("a body several chunks long") { + std::string body; + for (std::size_t index = 0; index < 3 * DefaultBuffersPolicy::emissionBufferSize + 5; ++index) body.push_back(static_cast('a' + index % 26)); + std::size_t largestChunk = 0; + std::string target, query; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& request) { + target = std::string(request.path); + query = std::string(request.query); + auto reply = text(body); + reply.body = [inner = std::move(reply.body), &largestChunk](std::span out) { + largestChunk = std::max(largestChunk, out.size()); + return inner(out); + }; + return reply; + }); + WHEN("the browser requests it with a percent-encoded name and a query") { + const auto response = fixture.answer(get("/webfront/services/files/a%20b.txt?token=1")); + THEN("the headers describe the reply and the whole body follows") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(contains(response, "Content-Type: text/plain\r\n")); + REQUIRE(contains(response, "Cache-Control: no-store\r\n")); + REQUIRE(contains(response, "Content-Length: " + std::to_string(body.size()) + "\r\n")); + REQUIRE(contains(response, "Connection: close\r\n")); + REQUIRE(response.ends_with("\r\n\r\n" + body)); + } + THEN("the handler saw the decoded path and the raw query") { + REQUIRE(target == "/webfront/services/files/a b.txt"); + REQUIRE(query == "token=1"); + } + THEN("the body was never asked for more than the emission buffer at once") { + REQUIRE(largestChunk == DefaultBuffersPolicy::emissionBufferSize); + } + } + } +} + +SCENARIO("A route answers HEAD without reading its body") { + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic reads{0}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + auto reply = text("0123456789"); + reply.body = [&reads](std::span) { ++reads; return std::size_t{0}; }; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); + THEN("the headers announce the length and no body follows") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(contains(response, "Content-Length: 10\r\n")); + REQUIRE(response.ends_with("\r\n\r\n")); + REQUIRE(reads == 0); + } +} + +SCENARIO("A route precedes the file providers and refuses other methods") { + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic calls{0}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + ++calls; + return text("from the route"); + }); + GIVEN("a provider that also has a file under the prefix") { + const auto response = fixture.answer(get("/webfront/services/files/provided.txt")); + THEN("the route answers") { REQUIRE(response.ends_with("from the route")); } + } + GIVEN("a POST") { + const auto response = fixture.answer(get("/webfront/services/files/x", "POST")); + THEN("it is refused with the methods the route serves, without calling the handler") { + REQUIRE(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); + REQUIRE(contains(response, "Allow: GET, HEAD\r\n")); + REQUIRE(calls == 0); + } + } +} + +SCENARIO("A path outside every route, or after unregistering, goes to the providers") { + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { return text("x"); }); + GIVEN("a registration that was reset") { + route.reset(); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("the request is a 404") { REQUIRE(response.starts_with("HTTP/1.1 404 Not Found\r\n")); } + } +} + +SCENARIO("A failing handler answers 500 without leaking its error") { + Fixture fixture; + Router server("127.0.0.1", "0"); + GIVEN("a handler that throws") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { throw std::runtime_error("secret detail"); }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("the browser gets a bare 500") { + REQUIRE(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + REQUIRE_FALSE(contains(response, "secret detail")); + } + } + GIVEN("a handler whose header would split the response") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("X-Name", "a\r\nSet-Cookie: injected=1"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("it is refused") { + REQUIRE(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + REQUIRE_FALSE(contains(response, "injected")); + } + } + GIVEN("a handler setting a header the server owns") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("content-length", "1"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("it is refused") { REQUIRE(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); } + } +} + +SCENARIO("A body that breaks its promise closes the connection") { + Fixture fixture; + Router server("127.0.0.1", "0"); + GIVEN("a body shorter than its Content-Length") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("abc"); + reply.contentLength = 10; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("the client receives a truncated body, which it detects") { + REQUIRE(contains(response, "Content-Length: 10\r\n")); + REQUIRE(response.ends_with("\r\n\r\nabc")); + } + } + GIVEN("a body longer than its Content-Length") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("abcdef"); + reply.contentLength = 3; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("nothing past the announced length is sent") { REQUIRE(response.ends_with("\r\n\r\n")); } + } + GIVEN("a body that throws after a first chunk") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + RouteReply reply; + reply.contentLength = 100; + reply.body = [first = true](std::span out) mutable -> std::size_t { + if (!std::exchange(first, false)) throw std::runtime_error("disk gone"); + out[0] = 'x'; + return 1; + }; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("the connection ends after what was read") { REQUIRE(response.ends_with("\r\n\r\nx")); } + } +} + +SCENARIO("A slow handler does not block the server context") { + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic entered{false}, release{false}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + entered = true; + while (!release) std::this_thread::sleep_for(1ms); + return text("late"); + }); + send(get("/webfront/services/files/x")); + REQUIRE(waitFor([&] { return entered.load(); })); + THEN("the thread which sent the request has already returned, and the reply comes when the handler ends") { + REQUIRE(InjectableSocket::shutdownCount() == 0); + release = true; + REQUIRE(waitFor([] { return InjectableSocket::shutdownCount() > 0; })); + REQUIRE(InjectableSocket::writtenText().ends_with("late")); + } +} + +namespace { +// Peak resident set of the process in bytes, or 0 where it cannot be read. +std::uint64_t peakResidentBytes() { +#ifdef _WIN32 + return 0; +#else + rusage usage{}; + if (getrusage(RUSAGE_SELF, &usage) != 0) return 0; + #ifdef __APPLE__ + return static_cast(usage.ru_maxrss); // bytes + #else + return static_cast(usage.ru_maxrss) * 1024; // kilobytes + #endif +#endif +} +} // namespace + +SCENARIO("A large body is streamed without being held") { + Fixture fixture; + Router server("127.0.0.1", "0"); + constexpr std::uint64_t size = 128ull * 1024 * 1024; + std::size_t largestChunk = 0; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + RouteReply reply; + reply.contentLength = size; + reply.body = [&largestChunk, produced = std::uint64_t{0}](std::span out) mutable { + largestChunk = std::max(largestChunk, out.size()); + const auto count = static_cast(std::min(out.size(), size - produced)); + produced += count; + return count; + }; + return reply; + }); + InjectableSocket::discardWrites(); + const auto before = peakResidentBytes(); + send(get("/webfront/services/files/big")); + // 16384 chunks, each crossing to the worker thread: slow under Debug, coverage and sanitizers. The limit stays below + // the 60 s CTest timeout of the scenarios, so that a stall is reported by the test rather than by a kill. + REQUIRE(waitFor([] { return InjectableSocket::shutdownCount() > 0; }, 45s)); + THEN("the peak memory of the process did not grow with the size sent") { + // Holding the body would add its 128 MiB to the peak; ctest runs each scenario in its own process. + if (const auto after = peakResidentBytes()) REQUIRE(after - before < 48ull * 1024 * 1024); + } + THEN("every byte was sent through a buffer of the emission size") { + REQUIRE(InjectableSocket::discardedBytes() > size); + REQUIRE(largestChunk == DefaultBuffersPolicy::emissionBufferSize); + } +} + +SCENARIO("A connection which fails while a reply is streamed stops the reading") { + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic reads{0}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + RouteReply reply; + reply.body = [&reads](std::span out) { + if (++reads == 2) InjectableSocket::failWrites(std::make_error_code(std::errc::connection_reset)); + return out.size(); + }; + return reply; + }); + send(get("/webfront/services/files/endless")); + REQUIRE(waitFor([] { return InjectableSocket::shutdownCount() > 0; })); + THEN("the body is not read again") { + const auto seen = reads.load(); + std::this_thread::sleep_for(20ms); + REQUIRE(reads == seen); + REQUIRE(seen <= 3); + } +} + +SCENARIO("Stopping the server ends a reply being streamed") { + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + RouteReply reply; + reply.body = [](std::span out) { return out.size(); }; + return reply; + }); + InjectableSocket::deferWrites(); + send(get("/webfront/services/files/endless")); + REQUIRE(waitFor([] { return InjectableSocket::hasWrittenData(); })); + WHEN("the server is stopped and drained while a send is pending") { + server.stop(); + THEN("the drain returns") { REQUIRE_NOTHROW(server.drain()); } + } +} + +namespace { + +std::string pattern(std::size_t size) { + std::string bytes; + for (std::size_t index = 0; index < size; ++index) bytes.push_back(static_cast((index * 7 + 3) % 251)); + return bytes; +} + +// Serves, whatever the path, a file of fixed content: embedded data, or a native file when `native` names one. +struct ProvidedFile { + static inline std::string content; + static inline std::vector words; + static inline std::filesystem::path native; +}; +struct ProvidedFS { + explicit ProvidedFS(std::filesystem::path) {} + std::optional open(std::filesystem::path) { + if (!ProvidedFile::native.empty()) return fs::File(std::ifstream(ProvidedFile::native, std::ios::binary)); + auto& words = ProvidedFile::words; + words.assign((ProvidedFile::content.size() + 7) / 8, 0); + for (std::size_t index = 0; index < ProvidedFile::content.size(); ++index) + words[index / 8] |= static_cast(static_cast(ProvidedFile::content[index])) << ((7 - index % 8) * 8); + return fs::File(words, ProvidedFile::content.size()); + } +}; + +} // namespace + +SCENARIO("Files of a provider are announced by size and streamed") { + for (const bool native : {false, true}) { + GIVEN(std::string(native ? "a native file" : "an embedded file") << " of several chunks") { + webfront::test::TemporaryDirectory directory; + ProvidedFile::content = pattern(3 * DefaultBuffersPolicy::emissionBufferSize + 11); + ProvidedFile::native.clear(); + if (native) { + ProvidedFile::native = directory.path() / "file.bin"; + std::ofstream(ProvidedFile::native, std::ios::binary) << ProvidedFile::content; + } + Fixture fixture; + Server server("127.0.0.1", "0"); + WHEN("it is requested") { + const auto response = fixture.answer(get("/file.bin")); + THEN("the length is announced and the whole content follows") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(contains(response, "Content-Length: " + std::to_string(ProvidedFile::content.size()) + "\r\n")); + REQUIRE(response.ends_with("\r\n\r\n" + ProvidedFile::content)); + } + } + } + GIVEN(std::string(native ? "a native file" : "an embedded file") << " requested with HEAD") { + webfront::test::TemporaryDirectory directory; + ProvidedFile::content = pattern(20000); + ProvidedFile::native.clear(); + if (native) { + ProvidedFile::native = directory.path() / "file.bin"; + std::ofstream(ProvidedFile::native, std::ios::binary) << ProvidedFile::content; + } + Fixture fixture; + Server server("127.0.0.1", "0"); + const auto response = fixture.answer(get("/file.bin", "HEAD")); + THEN("the length is announced and no body follows") { + REQUIRE(contains(response, "Content-Length: 20000\r\n")); + REQUIRE(response.ends_with("\r\n\r\n")); + } + } + } + GIVEN("an empty file") { + ProvidedFile::content = ""; + ProvidedFile::native.clear(); + Fixture fixture; + Server server("127.0.0.1", "0"); + const auto response = fixture.answer(get("/file.bin")); + THEN("it is a 200 with a zero length") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(contains(response, "Content-Length: 0\r\n")); + } + } +} + +SCENARIO("A native file known by its size reports it") { + webfront::test::TemporaryDirectory directory; + const auto path = directory.path() / "known.bin"; + std::ofstream(path, std::ios::binary) << pattern(1234); + THEN("knownSize is the size on disk, whatever was read") { + fs::File file{std::ifstream(path, std::ios::binary)}; + REQUIRE(file.knownSize() == 1234); + std::array buffer{}; + REQUIRE(file.read(buffer) == 100); + REQUIRE(file.knownSize() == 1234); + } +} + +SCENARIO("Failed HEAD requests carry no body") { + Fixture fixture; + Router server("127.0.0.1", "0"); + GIVEN("a handler which throws") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { throw std::runtime_error("no"); }); + const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); + THEN("the 500 has its headers only") { + REQUIRE(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + REQUIRE(response.ends_with("\r\n\r\n")); + } + } + GIVEN("a handler with an invalid header") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("Bad Name", "v"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); + THEN("the 500 has its headers only") { REQUIRE(response.ends_with("\r\n\r\n")); } + } + GIVEN("a file which does not exist") { + const auto response = fixture.answer(get("/nothing.txt", "HEAD")); + THEN("the 404 has its headers only") { + REQUIRE(response.starts_with("HTTP/1.1 404 Not Found\r\n")); + REQUIRE(response.ends_with("\r\n\r\n")); + } + } +} + +SCENARIO("A file wrapped after a prefix yields the remaining bytes and their count") { + webfront::test::TemporaryDirectory directory; + const auto path = directory.path() / "prefixed.bin"; + std::ofstream(path, std::ios::binary) << "prefix:payload"; + std::ifstream stream(path, std::ios::binary); + stream.seekg(7); + fs::File file{std::move(stream)}; + THEN("only the payload is counted and read") { + REQUIRE(file.knownSize() == 7); + std::array buffer{}; + const auto count = file.read(buffer); + REQUIRE(std::string(buffer.data(), count) == "payload"); + } +} + +namespace { +struct Completes { + using receiver_concept = networking::ex::receiver_tag; + std::promise* done; + void set_value() noexcept { done->set_value(); } + void set_error(std::exception_ptr) noexcept { done->set_value(); } + void set_stopped() noexcept { done->set_value(); } +}; +} // namespace + +SCENARIO("A blocked job does not delay the others of a worker with several threads") { + BlockingWorker worker{2}; + std::promise release, blockedDone, quickDone; + auto shared = release.get_future().share(); + std::atomic blocked{false}; + auto blockedEnded = blockedDone.get_future(); + auto quickEnded = quickDone.get_future(); + auto slow = networking::ex::connect(worker.run([&] { blocked = true; shared.wait(); }), Completes{&blockedDone}); + auto fast = networking::ex::connect(worker.run([] {}), Completes{&quickDone}); + // The blocked job is released whatever happens: the worker's destructor waits for it. + struct Release { + std::promise& promise; + bool done = false; + void now() { + if (!std::exchange(done, true)) promise.set_value(); + } + ~Release() { now(); } + } releaseGuard{release}; + networking::ex::start(slow); + const bool started = waitFor([&] { return blocked.load(); }); + if (started) networking::ex::start(fast); + const bool quickDoneInTime = started && quickEnded.wait_for(5s) == std::future_status::ready; + const bool slowStillBlocked = blockedEnded.wait_for(10ms) == std::future_status::timeout; + releaseGuard.now(); + if (started) blockedEnded.wait(); + if (started) quickEnded.wait(); // `fast` and `worker` outlive any use of each other, even when an assertion fails + THEN("the quick job completes while the slow one still runs") { + REQUIRE(started); + REQUIRE(quickDoneInTime); + REQUIRE(slowStillBlocked); + } +} + +SCENARIO("A single-thread worker keeps the jobs in order") { + BlockingWorker worker; + std::promise firstDone, secondDone; + std::string order; + auto first = networking::ex::connect(worker.run([&] { order += 'a'; }), Completes{&firstDone}); + auto second = networking::ex::connect(worker.run([&] { order += 'b'; }), Completes{&secondDone}); + networking::ex::start(first); + networking::ex::start(second); + firstDone.get_future().wait(); + secondDone.get_future().wait(); + REQUIRE(order == "ab"); +} + +SCENARIO("A handler or a body throwing something else than a std::exception is contained") { + Fixture fixture; + Router server("127.0.0.1", "0"); + GIVEN("a handler which throws an int") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { throw 42; }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("the browser gets a 500") { REQUIRE(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); } + } + GIVEN("a body which throws an int after the headers") { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + RouteReply reply; + reply.contentLength = 10; + reply.body = [](std::span) -> std::size_t { throw 42; }; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("the connection ends after the headers") { REQUIRE(response.ends_with("\r\n\r\n")); } + } +} + +SCENARIO("Route matching sees the path as a URL path") { + Fixture fixture; + Router server("127.0.0.1", "0"); + std::string seen; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& request) { + seen = std::string(request.path); + return text("ok"); + }); + auto plus = server.addRoute("/a+b/", [&](const RouteRequest& request) { + seen = std::string(request.path); + return text("plus"); + }); + GIVEN("a prefix with a literal plus") { + const auto response = fixture.answer(get("/a+b/x+y")); + THEN("the plus stays a plus in the matching and in the path") { + REQUIRE(response.ends_with("plus")); + REQUIRE(seen == "/a+b/x+y"); + } + } + GIVEN("a percent-encoded plus") { + const auto response = fixture.answer(get("/a%2Bb/x")); + THEN("it matches the same route") { REQUIRE(response.ends_with("plus")); } + } + GIVEN("empty and dot segments before the prefix") { + const auto target = GENERATE(as{}, "/webfront//services/files/x", "/webfront/./services/files/x", "//webfront/services//files/./x"); + const auto response = fixture.answer(get(target)); + THEN("the route answers, not a file provider, with the normalized path") { + REQUIRE(response.ends_with("ok")); + REQUIRE(seen == "/webfront/services/files/x"); + } + } +} + +SCENARIO("A handler may answer 405 with a body of its own") { + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("not this path"); + reply.status = Response::methodNotAllowed; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("its body is streamed after its headers") { + REQUIRE(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); + REQUIRE(response.ends_with("\r\n\r\nnot this path")); + } +} + +SCENARIO("Header names are ASCII tokens whatever the locale") { + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("X-Caf\xC3\xA9", "v"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + THEN("a non-ASCII name is refused") { REQUIRE(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); } +} diff --git a/test/unit/InjectableNetworking.hpp b/test/unit/InjectableNetworking.hpp index 9a505666..72126b39 100644 --- a/test/unit/InjectableNetworking.hpp +++ b/test/unit/InjectableNetworking.hpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -14,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -100,13 +102,17 @@ class InjectableSocket : public networking::SocketBaseMock { error = writeError; return 0; } + if (discarding) { + discarded += input.size(); + return input.size(); + } const auto* first = static_cast(input.data()); written.insert(written.end(), first, first + input.size()); return input.size(); } void close() {} - void shutdown(shutdown_type) {} + void shutdown(shutdown_type) { ++shutdowns; } /// The read the WebSocket is waiting for: the test completes it, or the task is stopped. static ManualSender read(networking::buffers::MutableBuffer buffer) { @@ -139,7 +145,26 @@ class InjectableSocket : public networking::SocketBaseMock { deferring = false; deferred.clear(); readCalls = 0; + shutdowns = 0; + discarding = false; + discarded = 0; + } + + /// How many times the server shut a socket down: the end of a connection it answered. + static int shutdownCount() { return shutdowns; } + + /// Everything the server wrote. + static std::string writtenText() { + std::lock_guard lock(mutex); + return {reinterpret_cast(written.data()), written.size()}; + } + + /// Counts the written bytes instead of keeping them, to send more than the test may hold. + static void discardWrites() { + std::lock_guard lock(mutex); + discarding = true; } + static std::uint64_t discardedBytes() { return discarded; } static int readCallCount() { return readCalls; } @@ -216,6 +241,9 @@ class InjectableSocket : public networking::SocketBaseMock { inline static bool deferring = false; inline static std::vector> deferred; inline static int readCalls = 0; + inline static std::atomic shutdowns{0}; + inline static bool discarding = false; + inline static std::atomic discarded{0}; }; class InjectableNetworking : public networking::NetworkingMock { diff --git a/test/unit/StdnetShutdownTests.cpp b/test/unit/StdnetShutdownTests.cpp index e8107348..5e3952bf 100644 --- a/test/unit/StdnetShutdownTests.cpp +++ b/test/unit/StdnetShutdownTests.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -89,6 +90,11 @@ std::string readHeaders(Stdnet::Socket& socket, std::chrono::milliseconds timeou return received; } +webfront::Task cleanupReleasesHandler(http::Server& server, std::shared_ptr guard) { + static_cast(guard); // released when the cancelled task is destroyed, on the server context + co_await server.resumeAfter(1h); +} + const std::string upgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; @@ -294,3 +300,39 @@ SCENARIO("A rejected WebSocket Origin never reaches the server upgrade callback" serverThread.request_stop(); serverThread.join(); } + +SCENARIO("Draining pumps cancelled tasks while a route handler waits for their cleanup") { + const auto port = freePort(); + http::Server server("127.0.0.1", port); + std::promise released, entered; + std::atomic done{false}; + const auto release = [&] { + if (!done.exchange(true)) released.set_value(); + }; + auto route = server.addRoute("/webfront/services/wait/", [&, wait = released.get_future().share()](const http::RouteRequest&) { + entered.set_value(); + wait.wait(); + return http::RouteReply{}; + }); + { + std::shared_ptr guard(nullptr, [&](void*) { release(); }); + static_cast(server.startTask(cleanupReleasesHandler(server, std::move(guard)))); + } + std::thread serverThread([&server] { server.run(); }); + Stdnet::IoContext clientContext; + Stdnet::Socket client(clientContext); + connect(client, port); + const std::string request = "GET /webfront/services/wait/x HTTP/1.1\r\nHost: localhost\r\n\r\n"; + client.send(std::as_bytes(std::span(request))); + const bool handlerEntered = entered.get_future().wait_for(5s) == std::future_status::ready; + server.stop(); + serverThread.join(); // before any assertion: a joinable thread would terminate the process + REQUIRE(handlerEntered); + WHEN("the server is drained") { + auto drained = std::async(std::launch::async, [&server] { server.drain(); }); + const bool finished = drained.wait_for(5s) == std::future_status::ready; + release(); // never leave the test hanging if the drain waited for the cleanup it was to run + drained.wait(); + THEN("the drain ran the cleanup which released the handler") { REQUIRE(finished); } + } +} diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index 5f8e19cf..9b05aba6 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -104,6 +104,23 @@ class BrowserIntegrationTest { registerCallbacks(); registerBitsetCallbacks(); lifeReactSubscription = demo::installLifeReact(app); + streamRoute = app.addRoute("/webfront/services/test-stream/", [](const http::RouteRequest& request) { + if (request.query.find("fail=1") != std::string_view::npos) throw std::runtime_error("route failure requested by the spec"); + std::uint64_t size = 0; + if (const auto at = request.query.find("size="); at != std::string_view::npos) + size = std::stoull(std::string(request.query.substr(at + 5))); + http::RouteReply reply; + reply.headers.emplace_back("Content-Type", "application/octet-stream"); + reply.headers.emplace_back("Cache-Control", "no-store"); + reply.contentLength = size; + reply.body = [size, produced = std::uint64_t{0}](std::span out) mutable { + const auto count = static_cast(std::min(out.size(), size - produced)); + for (std::size_t index = 0; index < count; ++index) out[index] = static_cast((((produced + index) * 7) + 3) % 251); + produced += count; + return count; + }; + return reply; + }); } /// The status of `wf test` (the specs), unless the specs passed and C++ did not observe every call they make. @@ -157,6 +174,7 @@ class BrowserIntegrationTest { optional connectedUI; UISubscription uiSubscription; UISubscription lifeReactSubscription; + http::RouteTable::Registration streamRoute; std::map>> reactStores; UISubscription closedDomSubscription; std::map closedDocumentRejected; diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index 312b50c5..db0817c3 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -319,6 +319,44 @@ describe('WebFront browser integration', () => { }); }); +// A dynamic route of the HTTP server (#454): the reply is produced by C++ at run time and streamed in chunks. +describe('Dynamic HTTP routes', () => { + const url = '/webfront/services/test-stream/pattern.bin'; + const size = 100000; // several chunks of the server's emission buffer + const byteAt = index => (index * 7 + 3) % 251; + + it('streams a reply produced by C++', async () => { + const response = await fetch(`${url}?size=${size}`); + expect(response.status).toBe(200); + expect(response.headers.get('content-type')).toBe('application/octet-stream'); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(response.headers.get('content-length')).toBe(String(size)); + const bytes = new Uint8Array(await response.arrayBuffer()); + expect(bytes.length).toBe(size); + let wrong = -1; + for (let index = 0; index < size && wrong < 0; ++index) if (bytes[index] !== byteAt(index)) wrong = index; + expect(wrong).toBe(-1); + }); + + it('answers HEAD with the headers only', async () => { + const response = await fetch(`${url}?size=${size}`, {method: 'HEAD'}); + expect(response.status).toBe(200); + expect(response.headers.get('content-length')).toBe(String(size)); + expect((await response.arrayBuffer()).byteLength).toBe(0); + }); + + it('refuses the other methods and answers 500 when the handler fails', async () => { + expect((await fetch(url, {method: 'POST'})).status).toBe(405); + expect((await fetch(`${url}?fail=1`)).status).toBe(500); + }); + + it('leaves the embedded WebFront.js to the core', async () => { + const response = await fetch('/WebFront.js'); + expect(response.ok).toBeTrue(); + expect(response.headers.get('content-type')).toContain('javascript'); + }); +}); + // C++ also checks what it observed: it is told over this connection, after every call the specs sent. afterAll(async () => { await webFront.cppFunction('specsFinished')(); });