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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions docs/HTTP_ASSETS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/adr/ADR-002-systemes-de-fichiers-composables.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Comment thread
ambroise-leclerc marked this conversation as resolved.
Resolved

## É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
Expand Down
3 changes: 3 additions & 0 deletions docs/adr/ADR-020-services-systeme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions include/webfront/WebFront.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
168 changes: 168 additions & 0 deletions include/webfront/http/BlockingWorker.hpp
Original file line number Diff line number Diff line change
@@ -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 <condition_variable>
#include <deque>
#include <exception>
#include <functional>
#include <mutex>
#include <thread>
#include <utility>
#include <vector>

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<std::thread> 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<networking::ex::set_value_t(), networking::ex::set_error_t(std::exception_ptr), networking::ex::set_stopped_t()>;

BlockingWorker* worker;
std::function<void()> work;

template <typename Receiver>
struct Operation final : Job {
BlockingWorker* worker;
Receiver receiver;
std::function<void()> work;
Operation(BlockingWorker* owner, Receiver value, std::function<void()> 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 <typename Receiver>
auto connect(Receiver receiver) && {
return Operation<Receiver>(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<void()> work) { return {this, std::move(work)}; }

private:
std::mutex mutex;
std::condition_variable changed;
std::deque<Job*> queue;
bool stopping = false;
std::vector<std::thread> 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<Job*> 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
5 changes: 3 additions & 2 deletions include/webfront/http/Encodings.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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];
}
}
Expand Down
Loading
Loading